Legal Information

DirectX 7.0
Programmer's Reference

Information in this document, including URL and other Internet web site references, is subject to change without notice. The example companies, organizations, products, people and events depicted herein are fictitious. No association with any real company, organization, product, person or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property.

© 1995-1999 Microsoft Corporation. All rights reserved.

Microsoft, MS-DOS, Windows, Windows NT, ActiveX, Direct3D, DirectAnimation, DirectDraw, DirectInput, DirectMusic, DirectPlay, DirectShow, DirectSound, DirectX, Natural, and Win32 are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries.

Roland GS Sound Set/Microsoft (P) 1996 Roland Corporation U.S.

Roland is a registered trademark of the Roland Corporation.

The names of actual companies and products mentioned herein may be the trademarks of their respective owners.

Copyright Warning

Special Note and Warning The Roland GS Sound Set/Microsoft, the "Sample Set", incorporates the SoundCanvas Sound Set. Roland Corporation U.S. owns the Sample Set and all copyrights pertaining thereto and has licensed the Sample Set for use solely on Microsoft Operating Systems Products and Microsoft Application Products.

Roland reserves all rights to the Sample Set not expressly granted by Roland Corporation U.S. or by Microsoft under the terms of Microsoft's End User License Agreement.

The Sample Set may only be redistributed with your software application as an integral component of a Microsoft Operating System Product and under the terms of Microsoft's End User License Agreement. All other uses of the Sample Set require a separate written license from Roland Corporation U.S..

The Sample Set may not be used, copied or redistributed in hardware ROM or similar technology of any device without prior express written permission from an authorized representative of Roland Corporation U.S.. The Sample Set may not be redistributed with any Musical Instrument. A "Musical Instrument" is any device that is capable of generating musical sounds without being directly connected to a computer with a licensed Microsoft Operating System. You may not modify the Sample Set under any circumstances.

Built on Thursday, September 02, 1999


Introducing DirectX Foundation

Microsoft® DirectX® Foundation is a set of low-level application programming interfaces (APIs) for creating games and other high-performance multimedia applications. It includes support for two-dimensional (2-D) and three-dimensional (3-D) graphics, sound and music, input, force feedback, and network communication for applications such as multiplayer games.

This overview gives general introductory information about DirectX Foundation. Information is divided into the following sections:

  • About DirectX Help
  • What's New in DirectX Foundation?
  • Components of DirectX Foundation
  • DirectX Samples
  • DirectX Tutorials
  • DirectX Tools
  • C and C++ Programming Topics
  • Visual Basic Programming Topics
  • Further Information


About DirectX Help

This documentation includes information about developing Microsoft® DirectX® applications in C, C++, and Microsoft® Visual Basic®.

DirectX fully supports both C and C++. Although this document most often uses the C++ syntax, some of the examples and tutorials (as well as some of the sample applications) are in C. In addition, the following topics provide information on using C with DirectX:

  • Using Macro Definitions
  • Accessing COM Objects by Using C

For the sake of simplicity, this documentation generally uses "C++" to mean "C or C++" when presenting information for those languages, as opposed to Visual Basic. You can assume that discussions of C++ concepts are also valid for C, with the necessary changes in syntax.

To provide only the information that is relevant to your programming environment, this document implements language filtering. On the title bar of many topics (including this one) you will find a button for a pop-up language menu. This menu gives you the choice of seeing documentation tailored either to C++ (and C) or to Visual Basic. If you choose Show All, you will see the language-specific information for both languages. Regardless of your language selection, you will always see information (such as general concepts) that is relevant to all languages.

[C++]

This text appears only if you have selected C++ or Show All from the language menu.

[Visual Basic]

This text appears only if you have selected Visual Basic or Show All from the language menu.

The buttons that can appear on the title bar of topics are described as follows:

Button | Meaning
L | Shows when language filtering is in the topic. Select your programming language from those available on the menu.
+ | Denotes that additional information is available and provides links to those topics. This is called the See Also section.
! | Shows the Requirements (previously known as QuickInfo) for using reference material. The information may include operating system versions and header information.

The following conventions are used in the syntax of methods, functions, and other API elements, as well as typographic conventions used in explanatory material and sample code:

Convention | Meaning
Italic text | Denotes a placeholder or variable. You must provide the actual value. For example, the statement SetCursorPos(X, Y) requires you to substitute values for the X and Y parameters.
Bold text | Denotes a function, procedure, structure, macro, interface, method, data type, or other keyword in the programming interface or language.
[] | Encloses optional parameters.
... | Specifies that the preceding item may be repeated.
FULL BOLD CAPITALS | Used for most type and structure names.
FULL CAPITALS | Used for enumeration values, flags, and constants.
monospace | Sets off code examples and shows syntax spacing.
. . . | Represents an omitted portion of a sample application.


What's New in DirectX Foundation?

The following are some of the new features in DirectX 7.0:

  • A new Visual Basic type library makes key DirectX features available to applications developed in that environment.
  • Microsoft® Direct3D® Immediate Mode API offers many new features, including: device-state blocks, geometry blending, cubic environment mapping, user-defined clipping planes, and more. For details, see Immediate Mode Changes for DirectX 7.0.
  • A new Direct3DX Utility Library is available now as a helper layer that sits on top of Direct3D and Microsoft® DirectDraw® to simplify common tasks encountered by 3-D graphics developers.
  • Microsoft® DirectMusic® supports the Downloadable Sounds level 2 standard.
  • Microsoft® DirectInput® now supports up to eight mouse buttons, exclusive access to the keyboard, and delayed start for force-feedback effects. New methods allow reading and writing of force-feedback effect files, and a Force Editor application is provided for creating effects.
  • Improved hardware voice management is provided in Microsoft® DirectSound®.
  • New 3-D audio processing algorithms result in better CPU utilization in DirectSound.
  • DirectDraw stereo support has been added for active devices.
  • Ripple launching is provided for Microsoft® DirectPlay® lobbied applications.
  • Improved documentation includes dynamic filtering for language-specific information.
  • More sample applications are provided.

If you need to refer to information provided with a previous release of DirectX, the legacy documentation is available for download from http://www.microsoft.com/directx.


Components of DirectX Foundation

DirectX Foundation is made up of the following components:

  • Direct3D provides a high-level Retained Mode interface that allows applications to easily implement a complete 3-D graphical system, and a low-level Immediate Mode interface that lets applications take complete control over the rendering pipeline. For more information about Immediate Mode, see About Direct3D Immediate Mode. For more information about Retained Mode, which is not part of DirectX Foundation, see Direct3D Retained Mode.
  • Direct3D now includes a Direct3DX Utility Library that is a helper layer to simplify common tasks encountered by 3-D graphics developers. See About the Direct3DX Utility Library.
  • DirectDraw accelerates hardware and software animation techniques by providing direct access to bitmaps in off-screen display memory, as well as extremely fast access to the blitting and buffer-flipping capabilities of the hardware. For more information, see About DirectDraw.
  • DirectInput provides support for every kind of input and force-feedback device. For more information, see About DirectInput.
  • DirectMusic works with message-based data and provides a complete system for playing music and DLS-based sound effects with run-time composition and variation. For more information about this component of DirectX, see About DirectMusic.
  • DirectPlay makes connecting games over a modem link or network easy. For more information, see About DirectPlay.
  • DirectSetup provides a one-call installation procedure for DirectX. For more information, see About DirectSetup.
  • DirectSound enables playback of wave sounds and includes support for hardware and software mixing, 3-D positioning, and sound capture. For more information, see About DirectSound.


DirectX Samples

Studying code from working samples is one of the best ways to understand DirectX. Sample applications are located in the Dxf\Samples\Multimedia folder of the DirectX SDK or in the DirectX code samples under the Platform SDK References section.

A brief overview of the samples is provided under each component:

  • Direct3D Immediate Mode Tools and Samples
  • Direct3DX Utility Library Samples
  • DirectDraw Tools and Samples
  • DirectInput Tools and Samples
  • DirectMusic Samples
  • DirectPlay Tools and Samples
  • DirectSetup Samples
  • DirectSound Tools and Samples


DirectX Tutorials

The tutorials found throughout the DirectX components guide you step by step through the basics of implementing each component. Following the code path and explanations can help you understand how to use the APIs and avoid some of the pitfalls along the way.

The tutorials are listed under each component:

  • Direct3D Immediate Mode Tutorials
  • DirectDraw Tutorials
  • DirectInput Tutorials
  • DirectMusic Tutorials
  • DirectPlay Tutorials
  • DirectSound Tutorials


DirectX Tools

The following tools can be useful in developing and troubleshooting DirectX applications:

  • DirectX Caps Viewer
  • DirectX Diagnostic Tool
  • DirectX Property Sheet

See Also

  • Direct3D Immediate Mode Tools
  • DirectDraw Tools
  • DirectInput Tools
  • DirectPlay Tools


DirectX Caps Viewer

Description

The DirectX Caps Viewer tool enumerates devices and capabilities for all the components of DirectX.

Path

Executable: (SDK root)\Bin\DXUtils\DXCapsViewer.exe

User's Guide

Select items in the tree view. Information appears in the pane on the right.


DirectX Diagnostic Tool

Description

DirectX Diagnostic Tool gathers information on the system and the DirectX components installed on it, as well as providing a number of tests to ensure that components are working properly. A special version of this tool installed with the DirectX SDK allows developers to report problems directly to the DirectX development team.

Path

Executable: (SDK root)\Bin\DXUtils\Dxdiag.exe

User's Guide

DirectX Diagnostic Tool has its own Help file, which can be accessed by clicking the Help button.


DirectX Property Sheet

Description

This component of Control Panel can be used to obtain information about the DirectX components, drivers, and hardware features available on the system. It can also be used to set the amount of debugging output generated by the debug versions of the DirectX direct-link libraries (DLLs) and to disable hardware-acceleration features for testing purposes.

Path

Double-click the DirectX icon in Control Panel.


C and C++ Programming Topics

[Visual Basic]

This section pertains only to applications written in C++. For an introduction to programming for DirectX in Visual Basic, see Visual Basic Programming Topics.

[C++]

This section introduces some general topics that pertain to programming with any of the DirectX Foundation APIs. The following topics are discussed:

  • The Component Object Model
  • Using Callback Functions
  • Version Checking
  • Compiling DirectX Samples and Other DirectX Applications
  • Debugging DirectX Applications


The Component Object Model

[Visual Basic]

This topic pertains only to applications written in C++. For an introduction to programming for DirectX in Visual Basic, see Visual Basic Programming Topics.

[C++]

Most of the DirectX API is composed of objects and interfaces based on COM. COM is the foundation of an object-based system that focuses on reuse of interfaces. It is also an interface specification from which any number of interfaces can be built.

A DirectX application is built from instances of COM objects. You can consider an object to be a black box that represents hardware or data that you access through interfaces. Commands are sent to the object through methods of the COM interface. For example, the IDirectDraw7::GetDisplayMode method of the IDirectDraw7 interface is called to get the current display mode of the display adapter from the DirectDraw object.

Objects can bind to other objects at run time, and they can use the implementation of interfaces provided by the other object. If you know that an object is a COM object and you know which interfaces that object supports, your application (or another object) can determine which services the first object can perform. One of the methods that all COM objects inherit, the QueryInterface method, lets you determine which interfaces an object supports and creates pointers to these interfaces. For more information, see the IUnknown Interface.

More information about COM programming for DirectX is found in the following topics:

  • IUnknown Interface
  • C++ and the COM Interface
  • Retrieving Newer Interfaces
  • Interface Method Names and Syntax
  • Accessing COM Objects by Using C
  • Using Macro Definitions


IUnknown Interface

[Visual Basic]

This section pertains only to applications written in C++. For an introduction to programming for DirectX in Visual Basic, see Visual Basic Programming Topics.

[C++]

All COM objects support an interface called IUnknown. This interface provides DirectX with control of the object's lifetime and the ability to retrieve other interfaces implemented by the object. IUnknown has three methods:

  • AddRef increments the object's reference count by 1 when an interface or another application binds itself to the object.
  • QueryInterface queries the object about the features that it supports by requesting pointers to a specific interface.
  • Release decrements the object's reference count by 1. When the count reaches 0, the object is deallocated.

The AddRef and Release methods maintain an object's reference count. For example, if you create a DirectDrawSurface object, the object's reference count is set to 1. Every time a function returns a pointer to an interface for that object, the function then must call AddRef through that pointer to increment the reference count. Match each AddRef call with a call to Release. Before the pointer can be destroyed, you must call Release through that pointer. After an object's reference count reaches 0, the object is destroyed, and all interfaces to it become invalid.

The QueryInterface method determines whether an object supports a specific interface. If an object supports an interface, QueryInterface returns a pointer to that interface. You then can use the methods of that interface to communicate with the object. If QueryInterface successfully returns a pointer to an interface, it implicitly calls AddRef to increment the reference count, so your application must call Release to decrement the reference count before destroying the pointer to the interface.

Requirements

Windows NT/2000: Requires Windows NT 3.1 or later.
Windows 95/98: Requires Windows 95 or later.
Header: Declared in Unknwn.h.


IUnknown::AddRef

The IUnknown::AddRef method increases the reference count of the object by 1.

ULONG AddRef();

Parameters

There are no parameters.

Return Values

Returns the new reference count. This value is meant to be used for diagnostic and testing purposes only.

Remarks

When the object is created, its reference count is set to 1. Every time an application obtains an interface to the object or calls the AddRef method, the object's reference count is increased by 1. Use the Release method to decrease the object's reference count by 1.

Requirements

Windows NT/2000: Requires Windows NT 3.1 or later.
Windows 95/98: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in Unknwn.h.


IUnknown::QueryInterface

The IUnknown::QueryInterface method determines whether the object supports a particular COM interface. If it does, the system increases the object's reference count, and the application can use that interface immediately.

HRESULT QueryInterface(
  REFIID riid,
  LPVOID* obp
);

Parameters

riid
Reference identifier of the interface being requested.
obp
Address of a pointer to be filled with the interface pointer if the query succeeds.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value may be E_NOINTERFACE or E_POINTER. Some components also have their own definitions of these error values in their header files. In DirectInput, for example, DIERR_NOINTERFACE is equivalent to E_NOINTERFACE.

Remarks

If the application does not need to use the interface retrieved by a call to this method, it must call the Release method for that interface to free it. The QueryInterface method allows Microsoft and third parties to extend objects without interfering with existing or future functionality.

Requirements

Windows NT/2000: Requires Windows NT 3.1 or later.
Windows 95/98: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in Unknwn.h.


IUnknown::Release

The IUnknown::Release method decreases the reference count of the object by 1.

ULONG Release();

Parameters

There are no parameters.

Return Values

Returns the new reference count. This value is meant to be used for diagnostic and testing purposes only.

Remarks

The object deallocates itself when its reference count reaches 0. Use the AddRef method to increase the object's reference count by 1.

Applications must call this method to release only interfaces that it explicitly created in a previous call to IUnknown::AddRef, IUnknown::QueryInterface, or a creation function such as DirectDrawCreate.

Requirements

Windows NT/2000: Requires Windows NT 3.1 or later.
Windows 95/98: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in Unknwn.h.


C++ and the COM Interface

[Visual Basic]

This topic pertains only to applications written in C++. For an introduction to programming for DirectX in Visual Basic, see Visual Basic Programming Topics.

[C++]

To C++ programmers, a COM interface is like an abstract base class. That is, it defines a set of signatures and semantics but not the implementation, and no state data is associated with the interface. In a C++ abstract base class, all methods are defined as pure virtual, which means that they have no code associated with them.

Pure virtual C++ functions and COM interfaces both use a device called a vtable. A vtable contains the addresses of all functions that implement the interface. If you want an application or object to use these functions, use the QueryInterface method to verify that the interface exists on an object and to obtain a pointer to that interface. After sending QueryInterface, the object sends your application or object a pointer to the vtable, through which this method can call the interface methods implemented by the object. This mechanism isolates any private data that the object uses and the calling client process from one another .

Another similarity between COM objects and C++ objects is that a method's first argument is the name of the interface or class, called the this argument in C++. Because COM objects and C++ objects are completely binary-compatible, the compiler treats COM interfaces like C++ abstract classes and assumes the same syntax. This results in less complex code. For example, the this argument in C++ is treated as an understood parameter and not coded, and the indirection through the vtable is handled implicitly in C++.


Retrieving Newer Interfaces

[Visual Basic]

This topic pertains only to applications written in C++. For an introduction to programming for DirectX in Visual Basic, see Visual Basic Programming Topics.

[C++]

COM dictates that objects update their functionality, not by changing the methods within existing interfaces, but by extending new interfaces that encompass new features. By keeping existing interfaces static, an object built on COM can freely extend its services, while maintaining compatibility with older applications.

DirectX components follow this practice. For example, the DirectDraw component supports several interfaces to access a DirectDrawSurface object: IDirectDrawSurface, IDirectDrawSurface2, IDirectDrawSurface3, IDirectDrawSurface4, and IDirectDrawSurface7. Each version of the interface supports the methods provided by its ancestor but adds new methods to support new features.

If your application does not need these new features, it does not need to retrieve newer interfaces. To take advantage of features provided by a new interface, you must call the object's IUnknown::QueryInterface method, specifying the globally unique identifier (GUID) of the interface that you want to retrieve. Interface GUIDs are declared in the corresponding header file.

The following example shows how to query for a new interface:

LPDIRECTDRAW    lpDD1;
LPDIRECTDRAW2   lpDD2;

ddrval = DirectDrawCreate( NULL, &lpDD1, NULL );
if( FAILED(ddrval))
    goto ERROROUT;

// Query for the IDirectDraw2 interface.
ddrval = lpDD1->QueryInterface(IID_IDirectDraw2, (void **)&lpDD2);
if( FAILED(ddrval))
    goto ERROROUT;

// Now that you have an IDirectDraw2, release the original interface.
lpDD1->Release();

In some rare cases, a new interface does not support some methods provided in a previous interface version. The IDirect3DDevice2 interface is an example of this type of interface. If your application requires features provided by an earlier version of an interface, you can query for the earlier version as shown in the preceding example, using the GUID of the older interface to retrieve it.


Interface Method Names and Syntax

[Visual Basic]

This topic pertains only to applications written in C++. For an introduction to programming for DirectX in Visual Basic, see Visual Basic Programming Topics.

[C++]

All COM interface methods described in this document are shown using C++ class names. This naming convention is used for consistency and to differentiate between methods used for different DirectX objects that use the same name, such as QueryInterface, AddRef, and Release. This convention does not mean that you can use these methods only with C++.

The syntax for the methods also uses C++ conventions. It does not include the this pointer to the interface. When programming in C, the pointer to the interface must be included in each method. The following example shows the C++ syntax for the IDirectDraw7::GetCaps method:

HRESULT GetCaps(
  LPDDCAPS lpDDDriverCaps,
  LPDDCAPS lpDDHELCaps
);

The same example using C syntax would look like this:

HRESULT GetCaps(
  LPDIRECTDRAW7 lpDD,
  LPDDCAPS lpDDDriverCaps,
  LPDDCAPS lpDDHELCaps
);

The lpDD parameter is a pointer to the DirectDraw interface that represents the DirectDraw object.


Accessing COM Objects by Using C

[Visual Basic]

This topic pertains only to applications written in C. For an introduction to programming for DirectX in Visual Basic, see Visual Basic Programming Topics.

[C++]

Any COM interface method can be called from a C program. There are two things to remember when calling an interface method from C:

  • The first parameter of the method always refers to the object that has been created and that invokes the method (the this argument).
  • Each method in the interface is referenced through a pointer to the object's vtable.

The following example creates a surface associated with a DirectDraw object by calling the IDirectDraw7::CreateSurface method in C:

ret = lpDD->lpVtbl->CreateSurface (lpDD, &ddsd, &lpDDS,
      NULL);

The lpDD parameter references the DirectDraw object associated with the new surface. The method call fills a surface-description structure (&ddsd) and returns a pointer to the new surface (&lpDDS).

To call the IDirectDraw7::CreateSurface method, first dereference the DirectDraw object's vtable, and then dereference the method from the vtable. The first parameter supplied in the method is a reference to the DirectDraw object that has been created and that invokes the method.

To illustrate the difference between calling a COM object method in C and C++, the same method is shown in C++ (C++ implicitly dereferences the lpVtbl parameter and passes the this pointer):

ret = lpDD->CreateSurface(&ddsd, &lpDDS, NULL)


Using Macro Definitions

[Visual Basic]

This topic pertains only to applications written in C++. For an introduction to programming for DirectX in Visual Basic, see Visual Basic Programming Topics.

[C++]

Many of the header files for the DirectX interfaces include macro definitions for each method. These macros are included to simplify the use of the methods in your programming, and also have the advantage of expanding to appropriate calls in either C or C++ syntax, depending on whether or not __cplusplus is defined.

The following example uses the IDirectDraw7_CreateSurface macro to call the IDirectDraw7::CreateSurface method. The first parameter is a reference to the DirectDraw object that has been created and invokes the method:

ret = IDirectDraw7_CreateSurface (lpDD, &ddsd, &lpDDS,
    NULL);

To obtain a current list of the methods supported by macro definitions, see the appropriate header file for the DirectX component that you want to use.


Using Callback Functions

[Visual Basic]

This topic pertains only to applications written in C++. For an introduction to programming for DirectX in Visual Basic, see Visual Basic Programming Topics.

[C++]

DirectX contains many methods that are used to enumerate hardware resources or other items available to the application. These methods all work in fundamentally the same way.

Prototype callback functions are documented for each DirectX component. The application declares its own functions with the same return values and parameters as these prototypes. Callback functions are declared as type CALLBACK, WINAPI, or FAR PASCAL, which are all equivalent.

When the application calls an enumeration method, it supplies a pointer to the appropriate callback function that it has implemented. The method calls the function once for each item that qualifies for enumeration and passes in information about the item. Within the function, the application can use this information to perform any sort of task, such as building a list or looking for particular device capabilities. The enumeration method returns when all items have been enumerated or when the callback function returns a value indicating that enumeration can stop (either FALSE or a particular HRESULT, depending on the return type of the callback).

For an example, see DirectInput Device Enumeration.


Version Checking

In order to scale their functionality to the version of DirectX currently running on the user's system, applications may need to know what version of DirectX is currently installed.

The DirectX software development kit includes a sample application with source code at (SDK root) \Samples\Multimedia\DXMisc\Src\GetDXVer that determines whether DirectX is on the system and, if so, what version it is. Each new version of DirectX supports all the functionality that was in older versions, so be sure to test for the desired version or later, so that your application will continue to run on future versions.

You can also test for particular functionality by using QueryInterface. For example, suppose your application is designed to run on DirectX 3.0 or later, but has optional force-feedback effects supported only by DirectX 5.0 and later. You can determine whether support for force feedback is available by obtaining the IDirectInputDevice interface and then querying for IDirectInputDevice2.

For a variety of reasons applications may also want to determine what version of the operating system is present. To provide for easier migration to future versions of components or versions of the Windows operating system, applications should check for the earliest compliant version, and allow for installation and execution on later versions. Knowing that Windows 2000 will contain DirectX 7.0 functionality or greater means developers should write code that detects the presence of Windows 2000 or greater and allows the application to run if it is found. Conversely, if Windows NT 4.0 is the version detected, DirectX 7.0 functionality is not available.

The following sample function returns TRUE if the operating system is the same as or later than the one indicated in the parameters, which indicate the major version, minor version, and service pack.

BOOL bIsWindowsVersionOK(DWORD dwMajor, DWORD dwMinor, WORD dwSPMajor)
{
    OSVERSIONINFO osvi;

    // Initialize the OSVERSIONINFO structure.//
    ZeroMemory(&osvi, sizeof(OSVERSIONINFO));

    osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
    GetVersionEx((OSVERSIONINFO*)&osvi);

    // Check the major version.
    if (osvi.dwMajorVersion > dwMajor)
        return TRUE;
    else if (osvi.dwMajorVersion == dwMajor)
    {
        // Check the minor version.
        if (osvi.dwMinorVersion > dwMinor)
            return TRUE;
        else if (osvi.dwMinorVersion == dwMinor)
        {
            // Check the Service Pack.
            if (dwSPMajor && osvi.dwPlatformId ==
                    VER_PLATFORM_WIN32_NT)
            {
                HKEY    hKey;
                DWORD   dwCSDVersion;
                DWORD   dwSize;
                BOOL    fMeetsSPRequirement = FALSE;

                if (RegOpenKeyEx (HKEY_LOCAL_MACHINE,
                        "System\\CurrentControlSet\\Control\\Windows",
                        0,
                        KEY_QUERY_VALUE,
                        &hKey) == ERROR_SUCCESS)
                {
                    dwSize = sizeof(dwCSDVersion);
                    if (RegQueryValueEx (hKey,
                            "CSDVersion",
                            NULL,
                            NULL,
                            (unsigned char*)&dwCSDVersion,
                            &dwSize) == ERROR_SUCCESS)
                    {
                        fMeetsSPRequirement =
                                (LOWORD(dwCSDVersion)  >= dwSPMajor);
                    }
                    RegCloseKey(hKey);
                }

                return fMeetsSPRequirement;
            }
            return TRUE;
        }
    }
    return FALSE;
}


Compiling DirectX Samples and Other DirectX Applications

[Visual Basic]

This section pertains only to applications written in C++. For an introduction to programming for DirectX in Visual Basic, see Visual Basic Programming Topics.

[C++]

This section provides information about considerations specific to compiling DirectX applications. The following topics are discussed:

  • Preparing for Compilation
  • Component Version Constants


Preparing for Compilation

[Visual Basic]

This topic pertains only to applications written in C++. For an introduction to programming for DirectX in Visual Basic, see Visual Basic Programming Topics.

[C++]

The samples included in this SDK use Microsoft® Visual C++® project files (MDP files) that describe the appropriate source files, project resources, and linker settings for each sample. However, you might need to make additional preparations to ensure that the samples compile and link properly, or you might need to prepare settings for a new project of your own. (For the samples, developers that use other compilers can reference the generic makefiles included for information about the required libraries, then configure their environment appropriately.) The information provided here applies to the DirectX samples and the DirectX applications that you create.

After opening a project file in Visual C++, verify some settings before trying to compile the application. The following descriptions are valid for Microsoft Visual C++ 5.0 and 4.2. Other versions of Visual C++ and other compilers have equivalent settings. If you do not use these versions of Visual C++, refer to the documentation provided with your development environment for information on changing these settings.

Note The following discussion uses the default installation paths (C:\Mssdk\Include and C:\Mssdk\Lib) to describe file locations. Your installation paths might differ.

Include search paths

Be sure that the search path for header files is correct and the directory for DirectX header files is the first path that the compiler searches. To check the include path, choose Options from the Tools menu; then select the Directories tab. The following dialog box will appear.

The topmost path indicates the folder that contains the latest DirectX header files. The default path is C:\Mssdk\Include. If the path is not present, add it to the list, and move it to the top of the search list by using the toolbar controls within the Directories tab.

Linker search paths

Check the search paths and search order that the linker uses to search for link libraries. The link search paths are also listed on the Directories tab. Choose Options from the Tools menu; then select the Directories tab. When the dialog box appears, choose the Library files option in the Show directories for: drop-down list box. The topmost path should be the folder that contains the latest DirectX link libraries. The default path is C:\Mssdk\Lib. (Borland link libraries are provided in the Borland folder within the default folder.)

Project link libraries

If you are using the provided sample project files, you do not need to verify these settings; they are specified with the provided project files. For new applications, choose Settings from the Project menu to make the following dialog box appear. (In Visual C++ 4.2, this is the Settings item on the Build menu.)

All DirectX applications link to the Dxguid.lib include library, which defines the globally unique identifiers (GUIDs) for all DirectX Foundation COM interfaces. (You can also define INITGUID prior to all other include and define statements in a single source module.) In addition, verify that the application is linked to the appropriate standard DirectX link libraries. The following table shows the various DirectX foundation components that might be used and the corresponding link libraries for those components.

Component | Link library (*.lib)
Direct3D Immediate Mode | D3dim.lib, D3du.lib
Direct3DX Utility Library | D3dx.lib, D3dxd.lib (debug)
Direct3D Retained Mode | D3drm.lib, D3dxof.lib
DirectDraw | Ddraw.lib
DirectInput | Dinput.lib
DirectMusic | None
DirectPlay | Dplayx.lib
DirectSetup | Dsetup.lib
DirectSound | Dsound.lib
(All components) | Dxguid.lib


Component Version Constants

[Visual Basic]

This topic pertains only to applications written in C++. For an introduction to programming for DirectX in Visual Basic, see Visual Basic Programming Topics.

[C++]

For backward compatibility with previous versions of DirectX, some DirectX components include variable API element definitions in their header files. Affected elements are typically capability structures or flag sets that are version-specific. Parts of some header files are surrounded by preprocessor conditionals that cause the preprocessor to filter out unneeded definitions. The value of the defined constant identifies a specific version of the component; if no value is defined, the headers set a value that identifies the DirectX version for which the header file was written. An example from the DirectDraw header file, Ddraw.h, is shown here:

#ifndef   DIRECTDRAW_VERSION
#define   DIRECTDRAW_VERSION 0x0700
#endif /* DIRECTDRAW_VERSION */

You can define other values for these constants to use newer versions of the header files with previous versions of the components. For example, to use the latest headers to compile against the DirectX 3.0 version of DirectDraw, define DIRECTDRAW_VERSION to be 0x0300. You can set the value for the constant in your development environment, or you can change the value in the header file itself.


Debugging DirectX Applications

This section covers the following topics pertaining to debugging C and C++ applications:

  • Debug vs. Retail DLLs
  • Symbol Information


Debug vs. Retail DLLs

The DirectX SDK installation program provides the option of installing either debug or retail builds of the DirectX dynamic-link libraries (DLLs).

[Visual Basic]

If you are developing in Visual Basic, there is no advantage in installing the debug DLLs because your application would run more slowly.

[C++]

When developing software in C++, it is best to install the debug versions of the DLLs. The debug DLLs have additional code that validates internal data structures and output debug error messages (using the Microsoft® Win32® OutputDebugString function) while your program is executing. When an error occurs, the debug output gives you a more detailed description of the problem. The debug DLLs execute more slowly than the retail DLLs but are much more useful for debugging an application. Be sure to ship the retail version with your application.

To see the debug messages, configure your system so that debug output displays in a window or on a remote computer. A development environment such as Visual C++ allows you to do this. Consult the environment documentation for setup instructions.


Symbol Information

[Visual Basic]

This topic pertains only to applications written in C++. For an introduction to programming for DirectX in Visual Basic, see Visual Basic Programming Topics.

[C++]

To ensure that the debugger can find all the relevant symbolic information when using debug builds, locate the symbol files as follows:

OS | Debugger | Location for .pdb file | Location for .dbg file
Windows 95 Windows 98 | Visual C++ | Same directory as binary | Same directory as binary
Windows NT Windows 2000 | Visual C++ | Same directory as binary | %SystemRoot%\Symbols\<binary extension>\
Windows NT Windows 2000 | NTSD/KD | %SystemRoot%\Symbols\<binary extension>\ | %SystemRoot%\Symbols\<binary extension>\

Note When debugging with the Visual C++ development system on Microsoft® Windows NT®/Windows® 2000, do not use the WIN32API Splitsym development tool. WIN32API Splitsym copies private symbolic information from the <binary>.dbg file into the symbol directory under the binary extension (for example, %SystemRoot%\Symbols\Dll\ ), then deletes the original file from the binary directory. Visual C++ relies on finding a private symbolic information (<binary>.dbg) file in the same directory as the binary itself. Therefore, for debug builds, you must only copy the private symbolic information, and not delete it. This is an issue only when using Visual C++ with Windows NT/Windows 2000. Consult Visual C++ documentation and Windows 2000 Driver Development Kit (DDK) documentation for further debugging information.


Visual Basic Programming Topics

[C++]

This section pertains only to applications written in Visual Basic.

[Visual Basic]

This section is an introduction to developing applications with DirectX® for Visual Basic®.

The following topics are covered:

  • Referencing the Type Library
  • Creating DirectX Objects
  • Using GUIDs
  • Passing Arrays to Methods
  • Using Flags
  • Using Bitmasks
  • DirectX Enumerations
  • Visual Basic Error Trapping
  • DirectX Class Reference


Referencing the Type Library

[C++]

This topic pertains only to applications written in Visual Basic.

[Visual Basic]

In order to use DirectX for Visual Basic in a project, you must first ensure that the project has access to the type library.

In Visual Studio, choose References... from the Project menu. The References dialog box appears. Select the check box next to "DirectX 7 for Visual Basic Type Library", then click OK.


Creating DirectX Objects

[C++]

This topic pertains only to applications written in Visual Basic.

[Visual Basic]

Every DirectX for Visual Basic application must have a DirectX7 object. This is the parent object whose methods are used to create the principal objects for each DirectX component. DirectX7 also has many other methods, such as methods to perform calculations for Direct3D.

The DirectX7 object is obtained simply by declaration as a new object, as in the following example:

Public gObjDX As New DirectX7

To create a DirectX component such as DirectSound, you must first declare a variable for the object, and then set it to a created object by calling the appropriate DirectX7 creation method, as in the following example:

Public gObjDSound As DirectSound
Set gObjDSound = DirectX7.DirectSoundCreate

The following objects representing the principal components of DirectX are created by using methods of DirectX7:

Component | Objects | DirectX7 Creation Method
Direct3D Retained Mode | Direct3DRM | Direct3DRMCreate
DirectDraw | DirectDraw7 | DirectDrawCreate
DirectInput | DirectInput | DirectInputCreate
DirectMusic | DirectMusicComposer | DirectMusicComposerCreate
 | DirectMusicLoader | DirectMusicLoaderCreate
 | DirectMusicPerformance | DirectMusicPerformanceCreate
DirectPlay | DirectPlay4 | DirectPlayCreate
 | DirectPlayLobby | DirectPlayLobbyCreate
DirectSound | DirectSound | DirectSoundCreate
 | DirectSoundCapture | DirectSoundCaptureCreate

The other principal DirectX component, Direct3D Immediate Mode, is represented by a Direct3D7 object that must be obtained by calling the DirectDraw7.GetDirect3D method.


Using GUIDs

[C++]

This topic pertains only to applications written in Visual Basic.

[Visual Basic]

Globally unique identifiers (GUIDs), which are much used in the Component Object Model (COM) that underlies DirectX, are not usually visible in DirectX for Visual Basic. However, they do occur in a few places. When they do, they are treated as strings rather than numerical values.

When you need to obtain a new GUID, run Vbguidgen.exe (in the \Samples\Multimedia\VBSamples\DXMisc\Bin folder of the SDK) and click the Copy button. Paste the GUID into your Visual Basic application and place quotation marks around it.

You can also generate GUIDs at run time by using the DirectX7.CreateNewGuid method.

An application-defined GUID could be used in a DirectPlay program as follows (where SessionData is an initialized DirectPlaySessionData object):

Const guidApp = "{AC330441-9B71-11D2-9AAB-0020781461AC}"
Call SessionData.SetGuidApplication(guidApp)

Some DirectX methods return data types that contain GUID members. These GUIDs are in the same string format as in the example.

DirectX defines many GUIDs for particular properties or other entities, and some methods require you to pass in one of these predefined GUIDs. You can do so by passing in the actual value (from a C++ header file) as a string, as in the preceding example. Usually, however, you can more conveniently pass in a documented string alias. For example, the DirectInput.CreateDevice method allows you to create a device for the standard keyboard by passing in "GUID_SysKeyboard" rather than the actual GUID.


Passing Arrays to Methods

[C++]

This topic pertains only to applications written in Visual Basic.

[Visual Basic]

A few DirectX methods return data in parameters whose type is unspecified. For instance, the DirectSoundCaptureBuffer.ReadBuffer method takes a buffer parameter of type Any.

Typically you will want such methods to return their data as an array of bytes. Because Visual Basic arrays have extra information before the actual data, you cannot simply pass the name of the array to the method. Instead, you must pass the first element of the array, as in the following example, where dsCaptureBuffer is a DirectSoundCaptureBuffer object, buffer is a zero-based array of bytes, and nBytes is a Long containing the number of bytes to be read:

ReDim buffer(nBytes)
Call dsCaptureBuffer.ReadBuffer(0, nBytes, buffer(0), 0)

Note, however, that some methods do take an actual typed array as a parameter. (See, for example, DirectInputDevice.SetDataFormat.) In such cases you must pass in the array itself rather than its first element, as in the following example, where formatArray is an array of DIOBJECTDATAFORMAT types.

MyDevice.SetDataFormat(diDataFormat, formatArray())


Using Flags

[C++]

This topic pertains only to applications written in Visual Basic.

[Visual Basic]

Many object methods in DirectX for Visual Basic take a flags parameter, or a parameter with a similar name. Also, some types have a member containing flags. Flags are used to control miscellaneous aspects of the behavior of method calls or to report details about things like device capabilities.

A flag is a single bit of information. It dictates or reports whether a certain behavior or capability is present or absent. A set of related flags is represented by an enumeration whose members generally do not share any bits. (Some flags, however, may represent combinations of other flags.)

Because flags represent single bits, multiple flags can be combined in a single value. For example, suppose you wanted to set the cooperative level of a DirectInput device to both foreground and exclusive. You would do so by combining two flags, using a logical Or operation, as follows:

' diDevice is a DirectInputDevice object, and hwnd is a window handle
diDevice.SetCooperativeLevel(hwnd, _
    DISCL_FOREGROUND Or DISCL_EXCLUSIVE)

In most cases, combining two or more flags by using the Or operator is equivalent to summing them by using the addition operator. However, it is unwise to add flags together, because of the fact that some flags do represent combinations of bits. In the following hypothetical example, the flag CF_PURPLE represents a combination of CF_RED and CF_BLUE.

Enum COLORFLAGS
    CF_RED    = 1
    CF_BLUE   = 2
    CF_PURPLE = 3
    CF_GREEN  = 4
End Enum

Dim Color As Integer
Color = CF_RED Or CF_PURPLE

The value of Color is now 3. CF_RED is redundant, because CF_PURPLE already contains that value.

The following operation, on the other hand, sets an incorrect value:

' This is wrong!
Color = CF_RED + CF_PURPLE

The variable is now set to 4, which is equivalent to CF_GREEN.

When you retrieve a value for flags, you can extract the setting of an individual flag by using a logical And operation. If the flags value contains the bit represented by a flag constant, the And operation returns a nonzero value and that flag is "on". If the And operation returns zero, the flag is "off". For example, the following call determines whether an input device, whose capabilities have been retrieved in a variable of type DIDEVCAPS, is physically attached to the system:

Dim IsAttached As Boolean
IsAttached = diDevCaps.lFlags And DIDC_ATTACHED

Note that you should not test for equality, as in the following example:

' This is wrong!
IsAttached = (diDevCaps.lFlags = DIDC_ATTACHED)

The reason this won't work is that the value in lFlags might contain other bits as well, such as DIDC_FORCEFEEDBACK. (See CONST_DIDEVCAPSFLAGS.)


Using Bitmasks

Some DirectX types, such as DDSURFACEDESC2, have Long members that serve as bitmasks. It is usual to assign values to these members in hexadecimal form. However, Visual Basic normally attempts to convert hexadecimal constants to the shortest type, with the result that, for example, &HFF would be converted to an Integer with a value of -1. If this value is then passed back to DirectX for Visual Basic where a Long is expected, it is converted to &HFFFFFFFF.

In order to ensure that a hexadecimal bitmask is properly converted, place a second ampersand after the expression, as follows:

DDSD.ddpfPixelFormat.lRBitMask = &HFF&


DirectX Enumerations

[C++]

This topic pertains only to applications written in Visual Basic.

[Visual Basic]

Most DirectX applications have to perform enumerations of available resources, usually during the initialization stage. For example, an application that uses DirectDraw might need to find out what display modes are available, or an application using DirectInput might need to enumerate the available buttons and axes on a joystick.

In DirectX for Visual Basic, enumerations are handled automatically when the application obtains an enumeration object. When the enumeration object is created, it builds a collection. This collection exists as long as the object exists, and can be accessed by using methods of the enumeration object.

Some enumeration objects must be obtained from the DirectX7 object. For example, you enumerate DirectSound devices by calling the DirectX7.GetDSEnum method. Only after obtaining the GUID for a suitable device from the collection can you create the DirectSound object.

Other enumeration objects are obtained from DirectX component objects. Once you obtain a DirectInput object, for example, you can call the DirectInput.GetDIEnumDevices method to obtain an enumeration object for input devices.

The following sample code, where di is a DirectInput object, enumerates all input devices attached to the system:

Dim diEnum As DirectInputEnumDevices
Set diEnum = di.GetDIEnumDevices(0, DIEDFL_ATTACHEDONLY)

The two methods of the DirectInputEnumDevices object can now be used to iterate through the attached devices to look for one with particular capabilities or to perform some other task. In the following example, the names of the devices are put in a list box:

Dim diDevice As DirectInputDeviceInstance
Dim X As Integer

For X = 1 To diEnum.GetCount
    Set diDevice = diEnum.GetItem(X)
    Call List1.AddItem(diDevice.ProductName)
Next X

Note that all collections created by DirectX enumerations are 1-based.


Visual Basic Error Trapping

[C++]

This topic pertains only to applications written in Visual Basic.

[Visual Basic]

In C and C++, HRESULT values are returned by every method call. The application can choose to examine and act on return values, or it can ignore them.

Error handling in DirectX for Visual Basic is very different. In Visual Basic a method call either succeeds or it fails. Visual Basic has no success codes equivalent to positive HRESULT values such as S_FALSE. If the call fails, an error is raised, and unless the application has an error handler, execution terminates. The error number is set in the global Visual Basic Err object. Most of the possible errors for each method are listed on the reference page for the method in this documentation.

In the following example, gObjDPlay is a DirectPlay4 object. If the call to DirectPlay4.CreatePlayer fails, execution continues at the FAILEDCREATEPLAYER label.

Function GetPlayerID(PlayerName As String, PlayerHandle As String) _
        as Long

  On Error GoTo FAILEDCREATEPLAYER
  GetPlayerID = gObjDPlay.CreatePlayer(PlayerName, PlayerHandle, 0, 0)
  On Error GoTo 0

  ' Any code in this section is run only if CreatePlayer succeeded.
  .
  .
  .
  Exit Function

FAILEDCREATEPLAYER:

  If Err.Number = DPERR_INVALIDPLAYER Then
      MsgBox ("Not a valid player.")
  Else
      MsgBox("Unidentified player creation error.")
  End If
  GetPlayerID = 0

End Function


DirectX Class Reference

[C++]

This section pertains only to applications written in Visual Basic.

[Visual Basic]

This section contains references for the following classes that are common to all components of DirectX:

  • DirectX7
  • DirectXEvent


DirectX7

The DirectX7 class serves as a starting point for the DirectX component technologies. This class contains methods which create the main objects for the DirectDraw®, Direct3D®, DirectSound®, DirectInput®, DirectPlay®, and DirectMusic® application programming interfaces. It also contains global methods used by various DirectX components.

An instance of this class is usually the first object created in your DirectX application. It can be obtained by declaring an object variable as New, as in the following example:

Public objDX7 As New DirectX7

The methods of the DirectX7 class can be organized into the following groups:

Object creation | Direct3DRMCreate
 | DirectDrawCreate
 | DirectInputCreate
 | DirectMusicComposerCreate
 | DirectMusicLoaderCreate
 | DirectMusicPerformanceCreate
 | DirectPlayCreate
 | DirectPlayLobbyCreate
 | DirectSoundCaptureCreate
 | DirectSoundCreate
Enumeration | GetDDEnum
 | GetDSCaptureEnum
 | GetDSEnum
Color management | ColorGetAlpha
 | ColorGetBlue
 | ColorGetGreen
 | ColorGetRed
 | CreateColorRGB
 | CreateColorRGBA
Vector management | VectorAdd
 | VectorCopy
 | VectorCrossProduct
 | VectorDotProduct
 | VectorModulus
 | VectorNormalize
 | VectorRandom
 | VectorReflect
 | VectorRotate
 | VectorScale
 | VectorSubtract
Vertex management | CreateD3DLVertex
 | CreateD3DTLVertex
 | CreateD3DVertex
Matrix | CopyMatrix
 | IdentityMatrix
 | MatrixFromQuaternion
 | MatrixMultiply
 | ProjectionMatrix
 | QuaternionMultiply
 | QuaternionRotation
 | QuaternionSlerp
 | RotateXMatrix
 | RotateYMatrix
 | RotateZMatrix
 | ViewMatrix
 | ZeroMatrix
Miscellaneous | CreateEvent
 | CreateNewGuid
 | DestroyEvent
 | GetWindowRect
 | SetEvent
 | SystemBpp
 | TickCount


DirectX7.ColorGetAlpha

The DirectX7.ColorGetAlpha method retrieves the alpha component of a color.

object.ColorGetAlpha(color As Long) As Single

Parameters

object
Object expression that resolves to a DirectX7 object.
color
Color from which the alpha component is retrieved. A value between 0 and 255.

Return Values

If the method succeeds, the alpha value is returned if successful, or zero otherwise.

Error Codes

If the method fails, an error is raised and Err.Number is set.

See Also

DirectX7.ColorGetBlue, DirectX7.ColorGetGreen, DirectX7.ColorGetRed


DirectX7.ColorGetBlue

The DirectX7.ColorGetBlue method retrieves the blue component of a color.

object.ColorGetBlue(color As Long) As Single

Parameters

object
Object expression that resolves to a DirectX7 object.
color
Color from which the blue component is retrieved. A value between 0 and 255.

Return Values

If the method succeeds, the blue value is returned if successful, or zero otherwise.

Error Codes

If the method fails, an error is raised and Err.Number is set.

See Also

DirectX7.ColorGetAlpha, DirectX7.ColorGetGreen, DirectX7.ColorGetRed


DirectX7.ColorGetGreen

The DirectX7.ColorGetGreen method retrieves the green component of a color.

object.ColorGetGreen(color As Long) As Single

Parameters

object
Object expression that resolves to a DirectX7 object.
color
Color from which the green component is retrieved. A value between 0 and 255.

Return Values

If the method succeeds, the green value is returned if successful, or zero otherwise.

Error Codes

If the method fails, an error is raised and Err.Number is set.

See Also

DirectX7.ColorGetAlpha, DirectX7.ColorGetBlue, DirectX7.ColorGetRed


DirectX7.ColorGetRed

The DirectX7.ColorGetRed method retrieves the red component of a color.

object.ColorGetRed(color As Long) As Single

Parameters

object
Object expression that resolves to a DirectX7 object.
color
Color from which the red component is retrieved. A value between 0 and 255.

Return Values

If the method succeeds, the red value is returned if successful, or zero otherwise.

Error Codes

If the method fails, an error is raised and Err.Number is set.

See Also

DirectX7.ColorGetAlpha, DirectX7.ColorGetGreen, DirectX7.ColorGetBlue


DirectX7.CopyMatrix

The DirectX7.CopyMatrix method copies the source matrix into the destination matrix.

object.CopyMatrix(mDest As D3DMATRIX, _
    mSrc As D3DMATRIX)

Parameters

object
Object expression that resolves to a DirectX7 object.
mDest
A D3DMATRIX type to contain the copy of the matrix.
mSrc
A D3DMATRIX type that is the source to be copied.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX7.CreateColorRGB

The DirectX7.CreateColorRGB method creates an RGB color from supplied red, green, and blue components.

object.CreateColorRGB(r As Single, _
    g As Single, _
    b As Single) As Long

Parameters

object
Object expression that resolves to a DirectX7 object.
r, g, and b
Components of the RGB color.

Return Values

If the method succeeds, the new RGB value is returned, or zero otherwise.

Error Codes

If the method fails, an error is raised and Err.Number is set.

See Also

DirectX7.CreateColorRGBA


DirectX7.CreateColorRGBA

The DirectX7.CreateColorRGBA method creates an RGBA color from supplied red, green, blue, and alpha components.

object.CreateColorRGBA(r As Single, _
    g As Single, _
    b As Single, _
    a As Single) As Long

Parameters

object
Object expression that resolves to a DirectX7 object.
r, g, b, and a
Components of the RGBA color. Values between 0 and 1.

Return Values

If the method succeeds, the new RGBA value is returned, or zero otherwise.

Error Codes

If the method fails, an error is raised and Err.Number is set.

See Also

DirectX7.CreateColorRGB


DirectX7.CreateD3DLVertex

The DirectX7.CreateD3DLVertex method fills a D3DLVERTEX type using individual values that represent discrete vertex components.

object.CreateD3DLVertex(x As Single, _
    y As Single, _
    z As Single, _
    color As Long, _
    specular As Long, _
    tu As Single, _
    tv As Single, _
    v As D3DLVERTEX)

Parameters

object
Object expression that resolves to a DirectX7 object.
x, y, and z
Values describing the x-, y-, and z-coordinates of the vertex.
color and specular
Value specifying the RGBA representation of the diffuse and specular colors for the vertex. You can use the DirectX7.CreateColorRGBA method to generate desired color value from individual red, green, blue, and alpha components.
tu and tv
Values describing the u and v texture coordinates of the vertex.
v
Variable of type D3DLVERTEX that will be filled with the provided vertex component data.

Error Codes

If the method fails, an error is raised and Err.Number is set to an error code.

See Also

DirectX7.CreateD3DVertex, DirectX7.CreateD3DTLVertex


DirectX7.CreateD3DTLVertex

The DirectX7.CreateD3DTLVertex method fills a D3DTLVERTEX type using individual values that represent discrete vertex components.

object.CreateD3DTLVertex(sx As Single, _
    sy As Single, _
    sz As Single, _
    rhw As Single, _
    color As Long, _
    specular As Long, _
    tu As Single, _
    tv As Single, _
    v As D3DTLVERTEX)

Parameters

object
Object expression that resolves to a DirectX7 object.
sx, sy, and sz
Values describing the position of the vertex, in screen coordinates.
rhw
Reciprocal of homogeneous W for the vertex.
color and specular
Value specifying the RGBA representation of the diffuse and specular colors for the vertex. You can use the DirectX7.CreateColorRGBA method to generate desired color value from individual red, green, blue, and alpha components.
tu and tv
Values describing the u and v texture coordinates of the vertex.
v
Variable of type D3DTLVERTEX that will be filled with the provided vertex component data.

Error Codes

If the method fails, an error is raised and Err.Number is set to an error code.

See Also

DirectX7.CreateD3DVertex, DirectX7.CreateD3DTLVertex


DirectX7.CreateD3DVertex

The DirectX7.CreateD3DVertex method fills a D3DVERTEX type using individual values that represent discrete vertex components.

object.CreateD3DVertex(x As Single, _
    y As Single, _
    z As Single, _
    nx As Single, _
    ny As Single, _
    nz As Single, _
    tu As Single, _
    tv As Single, _
    v As D3DVERTEX)

Parameters

object
Object expression that resolves to a DirectX7 object.
x, y, and z
Values describing the x-, y-, and z-coordinates of the vertex.
nx, ny, and nz
Values describing the orientation of the vertex normal vector.
tu and tv
Values describing the u and v texture coordinates of the vertex.
v
Variable of type D3DVERTEX that will be filled with the provided vertex component data.

Error Codes

If the method fails, an error is raised and Err.Number is set to an error code.

See Also

DirectX7.CreateD3DLVertex, DirectX7.CreateD3DTLVertex


DirectX7.CreateEvent

The DirectX7.CreateEvent method returns a handle to the event object which is implemented in the form.

object.CreateEvent(event As DirectXEvent) As Long

Parameters

object
Object expression that resolves to a DirectX7 object.
event
The DirectXEvent object implemented in a form.

Return Values

If the method succeeds, a handle to the created event is returned.

Error Codes

If the method fails, an error is raised and Err.Number is set.

Remarks

The DirectXEvent object must be implemented by the form in order to receive notifications from DirectX. Generated event handles are used in notification methods of DirectSound, DirectMusic, DirectPlay and DirectInput.

DirectX automatically sets the event object to signaled when an appropriate event occurs. The DirectX7.SetEvent method can also be used to manually set the event. This might be done to test the event-handling code.

All created events must be explicitly destroyed by the creating application with a call to DirectX7.DestroyEvent. Failure to comply with the requirements can result in undefined behavior.

See Also

DirectX7.SetEvent; DirectX7.DestroyEvent; DirectSoundBuffer.SetNotificationPositions; DirectSoundCaptureBuffer.SetNotificationPositions; DirectInputDevice.SetEventNotification; DirectPlayLobby3.SetLobbyMessageEvent; DirectMusicPerformance.SetNotificationHandle


DirectX7.CreateNewGuid

The DirectX7.CreateNewGuid method generates a globally unique identifier.

object.CreateNewGuid() As String

Parameters

object
Object expression that resolves to a DirectX7 object.

Return Values

If the method succeeds, a GUID in string form is returned.

Error Codes

If the method fails, an error is raised and Err.Number is set.

See Also

Using GUIDs


DirectX7.DestroyEvent

The DirectX7.DestroyEvent method deletes an event handle created by the DirectX7.CreateEvent method.

object.DestroyEvent(eventid As Long)

Parameters

object
Object expression that resolves to a DirectX7 object.
eventid
The handle of an event returned from DirectX7.CreateEvent to be destroyed.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX7.Direct3DRMCreate

The DirectX7.Direct3DRMCreate method creates an instance of a Direct3DRM3 object.

object.Direct3DRMCreate() As Direct3DRM3

Parameters

object
Object expression that resolves to a DirectX7 object.

Return Values

If the method succeeds, a Direct3DRM3 object is returned.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX7.DirectDrawCreate

The DirectX7.DirectDrawCreate method creates a DirectDraw7 object.

object.DirectDrawCreate(guid As String) As DirectDraw7

Parameters

object
Object expression that resolves to a DirectX7 object.
guid
Address of the globally unique identifier (GUID) that represents the driver to be created. This can be an empty string to indicate the active display driver, or you can pass one of the following flags to restrict the active display driver's behavior for debugging purposes:
DDCREATE_EMULATIONONLY
The DirectDraw object will use emulation for all features; it will not take advantage of any hardware supported features.
DDCREATE_HARDWAREONLY
The DirectDraw object will never emulate features not supported by the hardware. Attempts to call methods that require unsupported features will fail, returning DDERR_UNSUPPORTED.

Return Values

If the method succeeds, a reference to a DirectDraw7 object is returned.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX7.DirectInputCreate

The DirectX7.DirectInputCreate method creates a DirectInput object.

object.DirectInputCreate() As DirectInput

Parameters

object
Object expression that resolves to a DirectX7 object.

Return Values

If the method succeeds, a DirectInput object is returned.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes:

DIERR_BETADIRECTINPUTVERSION
DIERR_INVALIDPARAM
DIERR_OLDDIRECTINPUTVERSION
DIERR_OUTOFMEMORY


DirectX7.DirectMusicComposerCreate

The DirectX7.DirectMusicComposerCreate method is used to create a composer object.

object.DirectMusicComposerCreate() As DirectMusicComposer

Parameters

object
Object expression that resolves to a DirectX7 object.

Return Values

The method returns a DirectMusicComposer object.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX7.DirectMusicLoaderCreate

The DirectX7.DirectMusicLoaderCreate method is used to create a loader object.

object.DirectMusicLoaderCreate() As DirectMusicLoader

Parameters

object
Object expression that resolves to a DirectX7 object.

Return Values

The method returns a DirectMusicLoader object.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX7.DirectMusicPerformanceCreate

The DirectX7.DirectMusicPerformanceCreate method is used to create a performance object.

object.DirectMusicPerformanceCreate() _
    As DirectMusicPerformance

Parameters

object
Object expression that resolves to a DirectX7 object.

Return Values

The method returns a DirectMusicPerformance object.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX7.DirectPlayCreate

The DirectX7.DirectPlayCreate method creates a DirectPlay4 object.

object.DirectPlayCreate(guid As String) As DirectPlay4

Parameters

object
Object expression that resolves to a DirectX7 object.
guid
A GUID that identifies the service provider to be bound to the DirectPlay4 object, or an empty string. See Remarks.

Return Values

If the method succeeds, a DirectPlay4 object is returned.

Error Codes

If the method fails, an error is raised and Err.Number is set.

Remarks

If the guid parameter is an empty string, the DirectPlay connection is not initialized and the application must call DirectPlay4.InitializeConnection.

See Also

Using GUIDs


DirectX7.DirectPlayLobbyCreate

The DirectX7.DirectPlayLobbyCreate method creates a DirectPlayLobby3 object.

object.DirectPlayLobbyCreate() As DirectPlayLobby3

Parameters

object
Object expression that resolves to a DirectX7 object.

Return Values

If the method succeeds, a DirectPlayLobby3 object is returned.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX7.DirectSoundCaptureCreate

The DirectX7.DirectSoundCaptureCreate method creates a DirectSoundCapture object.

object.DirectSoundCaptureCreate(guid As String) _
    As DirectSoundCapture

Parameters

object
Object expression that resolves to a DirectX7 object.
guid
A GUID that identifies the sound capture device. The value of this parameter must be a GUID returned by calling DirectX7.GetDSCaptureEnum. This parameter can also be an empty string for the default device.

Return Values

If the method succeeds, a reference to a DirectSoundCapture object is returned.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes:

DSERR_INVALIDPARAM
DSERR_NOAGGREGATION
DSERR_OUTOFMEMORY

Remarks

This method could fail on some sound cards that do not support full duplex. Calling DirectX7.DirectSoundCreate may set the capture device to an unsupported capture frequency which will cause DirectX7.DirectSoundCaptureCreate to fail.


DirectX7.DirectSoundCreate

The DirectX7.DirectSoundCreate method created a DirectSound object.

object.DirectSoundCreate(guid As String) As DirectSound

Parameters

object
Object expression that resolves to a DirectX7 object.
guid
A GUID that identifies the sound capture device. The value of this parameter must be a GUID returned by calling DirectSoundEnum.GetGuid. This parameter can also be an empty string for the default device.

Return Values

If the method succeeds, a reference to a DirectSound object is returned.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes:

DSERR_ALLOCATED
DSERR_INVALIDPARAM
DSERR_NOAGGREGATION
DSERR_NODRIVER
DSERR_OUTOFMEMORY


DirectX7.GetDDEnum

The DirectX7.GetDDEnum method creates a DirectDrawEnum object which is used to enumerate the primary DirectDraw display device and a non-display device (such as a 3-D accelerator that has no 2-D capabilities) if one is installed.

object.GetDDEnum() As DirectDrawEnum

Parameters

object
Object expression that resolves to a DirectX7 object.

Return Values

If the method succeeds, a reference to a DirectDrawEnum object is returned.

Error Codes

If the method fails, an error is raised and Err.Number may be set to the error value of DDERR_OUTOFMEMORY.


DirectX7.GetDSCaptureEnum

The DirectX7.GetDSCaptureEnum method creates a DirectSoundEnum object which is used to enumerate the DirectSoundCapture objects installed in the system.

object.GetDSCaptureEnum() As DirectSoundEnum

Parameters

object
Object expression that resolves to a DirectX7 object.

Return Values

If the method succeeds, a DirectSoundEnum object is returned.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_OUTOFMEMORY.

See Also

DirectX7.GetDSEnum


DirectX7.GetDSEnum

The DirectX7.GetDSEnum method creates a DirectSoundEnum object which is used to enumerate the DirectSound drivers installed in the system.

object.GetDSEnum() As DirectSoundEnum

Parameters

object
Object expression that resolves to a DirectX7 object.

Return Values

If the method succeeds, a DirectSoundEnum object is returned.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_OUTOFMEMORY.

See Also

DirectX7.GetDSCaptureEnum


DirectX7.GetWindowRect

The DirectX7.GetWindowRect method retrieves a rectangle that describes the client area of a window.

object.GetWindowRect(hwnd As Long, r As RECT)

Parameters

object
Object expression that resolves to a DirectX7 object.
hwnd
Window handle of the window for which the client-area rectangle will be retrieved.
r
A variable of type RECT that will be set to window's client area if the method succeeds.

Error Codes

If the method fails, an error is raised and Err.Number is set to an error code.


DirectX7.IdentityMatrix

The DirectX7.IdentityMatrix method creates an identity matrix.

object.IdentityMatrix(mDest As D3DMATRIX)

Parameters

object
Object expression that resolves to a DirectX7 object.
mDest
D3DMATRIX type that is the result of the operation.

Error Codes

If the method fails, an error is raised and Err.Number is set.

Remarks

The identity matrix is a matrix in which all coefficients are 0 except the [1,1][2,2][3,3][4,4] coefficients, which are set to 1. The identity matrix is special in that when it is applied to vertices, they are unchanged. The identity matrix is used as the starting point for matrices that will modify vertex values to create rotations, translations, and any other transformations that can be represented by a 4×4 matrix.


DirectX7.MatrixFromQuaternion

The DirectX7.MatrixFromQuaternion method calculates the matrix for the rotation that a unit quaternion represents.

object.MatrixFromQuaternion(matrix As D3DMATRIX, _
    quat As D3DRMQUATERNION)

Parameters

object
Object expression that resolves to a DirectX7 object.
matrix
The calculated matrix when the function returns.
quat
The D3DRMQUATERNION type.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX7.MatrixMultiply

The DirectX7.MatrixMultiply method determines the product of two matrices.

object.MatrixMultiply(mDest As D3DMATRIX, _
    mA As D3DMATRIX, _
    mB As D3DMATRIX)

Parameters

object
Object expression that resolves to a DirectX7 object.
mDest
D3DMATRIX type that holds the product of matrices mA and mB.
mA
D3DMATRIX type that serves as the multiplicand.
mB
D3DMATRIX type that serves as the multiplier.

Error Codes

If the method fails, an error is raised and Err.Number is set.

Remarks

In order for this to be conformable, the number of columns in mA must be equal to the number of rows in mB.


DirectX7.ProjectionMatrix

The DirectX7.ProjectionMatrix method sets the near and far clipping planes and the field of view angle.

object.ProjectionMatrix(mDest As D3DMATRIX, _
    nearPlane As Single, _
    farPlane As Single, _
    fov As Single)

Parameters

object
Object expression that resolves to a DirectX7 object.
mDest
Newly created projection matrix.
nearPlane
The distance to the near clipping plane. Units are application specific.
farPlane
The distance to the far clipping plane. Units are application specific.
fov
The field of view angle, in radians.

Error Codes

If the method fails, an error is raised and Err.Number is set.

Remarks

The fov can be determined by drawing a line from the middle of the projector to the middle of the front clipping plane and a line from the middle of the projector to the top of the front clipping plane and doubling the resulting angle.


DirectX7.QuaternionMultiply

The DirectX7.QuaternionMultiply method calculates the product of two quaternion types.

object.QuaternionMultiply(quat As D3DRMQUATERNION, _
    quatA As D3DRMQUATERNION, _
    quatB As D3DRMQUATERNION)

Parameters

object
Object expression that resolves to a DirectX7 object.
quat
The D3DRMQUATERNION type that will contain the product of the multiplication.
quatA and quatB
The D3DRMQUATERNION types that will be multiplied together.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX7.QuaternionRotation

The DirectX7.QuaternionRotation method retrieves a unit quaternion that represents a rotation of a specified number of radians around the given axis.

object.QuaternionRotatation(quat As D3DRMQUATERNION, _
    axis As D3DVECTOR, _
    theta As Single)

Parameters

object
Object expression that resolves to a DirectX7 object.
quat
A D3DRMQUATERNION type that will contain the result of the operation.
axis
A D3DVECTOR type specifying the axis of rotation.
theta
Number of radians to rotate around the axis specified by the axis parameter.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX7.QuaternionSlerp

The DirectX7.QuaternionSlerp method interpolated between two quaternion types, using spherical linear interpolation.

object.QuaternionSlerp(quat As D3DRMQUATERNION, _
    quatA As D3DRMQUATERNION, _
    quatB As D3DRMQUATERNION, _
    alpha As Single)

Parameters

object
Object expression that resolves to a DirectX7 object.
quat
The D3DRMQUATERNION type that will contain the interpolation.
quatA and quatB
The D3DRMQUATERNION types that are used as the starting and ending points for the interpolation, respectively.
alpha
Value between 0 and 1 that specifies how far to interpolate between quatA and quatB.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX7.RotateXMatrix

The DirectX7.RotateXMatrix method rotates the point (x,y,z) around the x-axis, generating a new point (x', y', z').

object.RotateXMatrix(mDest As D3DMATRIX, _
    radians As Single)

Parameters

object
Object expression that resolves to a DirectX7 object.
mDest
D3DMATRIX type that holds the result of the transformation.
radians
The angle of rotation in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Error Codes

If the method fails, an error is raised and Err.Number is set.

See Also

DirectX7.RotateYMatrix and DirectX7.RotateZMatrix.


DirectX7.RotateYMatrix

The DirectX7.RotateYMatrix method rotates the point (x,y,z) around the y-axis, generating a new point (x', y', z').

object.RotateYMatrix(mDest As D3DMATRIX, _
    radians As Single)

Parameters

object
Object expression that resolves to a DirectX7 object.
mDest
D3DMATRIX type that receives the result of the transformation.
radians
The angle of rotation in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Error Codes

If the method fails, an error is raised and Err.Number is set.

See Also

DirectX7.RotateXMatrix and DirectX7.RotateZMatrix.


DirectX7.RotateZMatrix

The DirectX7.RotateZMatrix method rotates the point (x,y,z) around the z-axis, generating a new point (x', y', z').

object.RotateZMatrix(mDest As D3DMATRIX, _
    radians As Single)

Parameters

object
Object expression that resolves to a DirectX7 object.
mDest
D3DMATRIX type that holds the result of the transformation.
radians
The angle of rotation in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Error Codes

If the method fails, an error is raised and Err.Number is set.

See Also

DirectX7.RotateYMatrix and DirectX7.RotateXMatrix.


DirectX7.SetEvent

The DirectX7.SetEvent sets the state of the event object to signaled.

object.SetEvent(eventid As Long)

Parameters

object
Object expression that resolves to a DirectX7 object.
eventid
The event handle to set as signaled.

Error Codes

If the method fails, an error is raised and Err.Number is set.

Remarks

This method must be called with an event handle created by DirectX7.CreateEvent.

DirectX automatically sets all created event objects to signaled when an appropriate event occurs. This method is primarily for testing purposes.


DirectX7.SystemBpp

The DirectX7.SystemBpp method returns the current bits per pixel for the system.

object.SystemBpp() As Long

Parameters

object
Object expression that resolves to a DirectX7 object.

Return Values

If the method succeeds, the current bits per pixel for the system is returned.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX7.TickCount

The DirectX7.TickCount method returns the system tick count.

object.TickCount() As Long

Parameters

object
Object expression that resolves to a DirectX7 object.

Return Values

If the method succeeds, the tick count on the system is returned.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX7.VectorAdd

The DirectX7.VectorAdd method adds two vectors.

object.VectorAdd(v As D3DVECTOR, _
    vA As D3DVECTOR, _
    vB As D3DVECTOR)

Parameters

object
Object expression that resolves to a DirectX7 object.
v
A D3DVECTOR type that will contain the result of the addition.
vA and vB
The D3DVECTOR types that will be added together.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX7.VectorCopy

The DirectX7.VectorCopy method copies a vector.

object.VectorCopy(vDest As D3DVECTOR, _
    vSrc As D3DVECTOR)

Parameters

object
Object expression that resolves to a DirectX7 object.
vDest
The destination D3DVECTOR for the copy.
vSrc
The source D3DVECTOR for the copy.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX7.VectorCrossProduct

The DirectX7.VectorCrossProduct method calculates the cross product of the two vector arguments.

object.VectorCrossProduct(v As D3DVECTOR, _
    vA As D3DVECTOR, _
    vB As D3DVECTOR)

Parameters

object
Object expression that resolves to a DirectX7 object.
v
A D3DVECTOR type that will contain the result of the cross product.
vA and vB
The D3DVECTOR types from which the cross product is produced.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX7.VectorDotProduct

The DirectX7.VectorDotProduct method returns the vector dot product.

object.VectorDotProduct(vA As D3DVECTOR, _
    vB As D3DVECTOR) As Single

Parameters

object
Object expression that resolves to a DirectX7 object.
vA and vB
The D3DVECTOR types from which the dot product is produced.

Return Values

If the method succeeds, the result of the dot product is returned, or zero otherwise.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX7.VectorModulus

The DirectX7.VectorModulus method returns the magnitude of a vector.

object.VectorModulus(vA As D3DVECTOR) As Single

Parameters

object
Object expression that resolves to a DirectX7 object.
vA
The D3DVECTOR type whose length is returned.

Return Values

If the method succeeds, the length of the D3DVECTOR type is returned, or zero otherwise.

Error Codes

If the method fails, an error is raised and Err.Number is set.

Remarks

This method uses the following formula to calculate the vector magnitude:


DirectX7.VectorNormalize

The DirectX7.VectorNormalize method scales a vector so that its modulus is 1.

object.VectorNormalize(v As D3DVECTOR)

Parameters

object
Object expression that resolves to a DirectX7 object.
v
A D3DVECTOR type that will contain the result of the scaling operation.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX7.VectorRandom

The DirectX7.VectorRandom method returns a random unit vector.

object.VectorRandom(v As D3DVECTOR)

Parameters

object
Object expression that resolves to a DirectX7 object.
v
A D3DVECTOR type that will contain a random unit vector.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX7.VectorReflect

The DirectX7.VectorReflect method reflects a ray about a given normal.

object.VectorReflect(vDest As D3DVECTOR, _
    vRay As D3DVECTOR, _
    vNormal As D3DVECTOR)

Parameters

object
Object expression that resolves to a DirectX7 object.
vDest
A D3DVECTOR type that will contain the result of the operation.
vRay
A D3DVECTOR type that will be reflected about a normal.
vNormal
A D3DVECTOR type specifying the normal about which the vector specified in vRay is reflected.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX7.VectorRotate

The DirectX7.VectorRotate method rotates a vector around a given axis. Returns a normalized vector if successful.

object.VectorRotate(vDest As D3DVECTOR, _
    vA As D3DVECTOR, _
    vAxis As D3DVECTOR, _
    theta As Single)

Parameters

object
Object expression that resolves to a DirectX7 object.
vDest
A D3DVECTOR type that will contain the normalized result of the operation.
vA
A D3DVECTOR type that will be rotated around the given axis.
vAxis
A D3DVECTOR type that is the axis of rotation.
theta
The amount of rotation in radians.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX7.VectorScale

The DirectX7.VectorScale method scales a vector uniformly in all three axes.

object.VectorScale(vDest As D3DVECTOR, _
    vA As D3DVECTOR, _
    factor As Single)

Parameters

object
Object expression that resolves to a DirectX7 object.
vDest
The D3DVECTOR type that will contain the result of the operation.
vA
The D3DVECTOR type that this method scales.
factor
Scaling factor. A value of 1 does not change the scaling; a value of 2 doubles it, and so on.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX7.VectorSubtract

The DirectX7.VectorSubtract method subtracts two vectors.

object.VectorSubtract(v As D3DVECTOR, _
    vA As D3DVECTOR, _
    vB As D3DVECTOR)

Parameters

object
Object expression that resolves to a DirectX7 object.
v
A D3DVECTOR type that will contain the result of the operation.
vA
A D3DVECTOR type from which vB is subtracted.
vB
A D3DVECTOR type that is subtracted from vA.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX7.ViewMatrix

The DirectX7.ViewMatrix method creates a view matrix based on the location of the camera passed to it.

object.ViewMatrix(mDest As D3DMATRIX, _
    vFrom As D3DVECTOR, _
    vTo As D3DVECTOR, _
    vUp As D3DVECTOR, _
    roll As Single)

Parameters

object
Object expression that resolves to a DirectX7 object.
mDest
The newly created view matrix.
vFrom
D3DVECTOR type that defines the camera location.
vTo
D3DVECTOR type that defines the camera look-at target.
vUp
D3DVECTOR type that defines the current world's up, usually [0, 1, 0].
roll
Clockwise roll around viewing direction, in radians.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectX7.ZeroMatrix

The DirectX7.ZeroMatrix method sets all members of a matrix to zero.

object.ZeroMatrix(mDest As D3DMATRIX)

Parameters

object
Object expression that resolves to a DirectX7 object.
mDest
D3DMATRIX type that holds the result of the operation.

Error Codes

If the method fails, an error is raised and Err.Number is set.


DirectXEvent

The DirectXEvent class creates event objects used in DirectSound, DirectMusic, DirectPlay and DirectInput. DirectXEvent objects are created by implementing the class in a form. The purpose of this class is to provide a callback method for handling notification events.

The DirectXEvent class has only one method, DirectXEvent.DXCallback.


DirectXEvent.DXCallback

The DirectXEvent.DXCallback method provides a callback routine for event handles.

object.DXCallback(eventid As Long)

Parameters

object
Object expression that resolves to a DirectXEvent object.
eventid
The handle to the event.

Error Codes

If the method fails, an error is raised and Err.Number is set.

Remarks

When you implement DirectXEvent in a form, you must also supply an implementation of the DirectXEvent.DXCallback method. The declaration and end of the method are automatically placed in the Code window when you select DirectXEvent in the Object box and DXCallback in the Procedures/Events box. The method takes the following form:

Private Sub DirectXEvent_DXCallBack(ByVal eventid as Long)
  ' Add your own event-handling code
  .
  .
  .
End Sub

The event handle passed to the method is one you created by using DirectX7.CreateEvent.

See Also

DirectX7.SetEvent


Further Information

Further explanation of the graphics and multimedia concepts and terms discussed throughout DirectX, as well as information on Windows programming in general, can be found in the following sources:

  • Bargen, Bradley and Peter Donnelly, Inside DirectX, Microsoft Press, 1998.
  • Begault, Durand R., 3-D Sound for Virtual Reality and Multimedia, Academic Press, 1994.
  • Blinn, James, Jim Blinn's Corner: A Trip Down the Graphics Pipeline, Morgan Kaufmann, 1996.
  • Foley, James D., Computer Graphics: Principles and Practice, Addison-Wesley, 1991 (2nd edition).
  • Hearn, Donald and M. Pauline Baker, Computer Graphics, Prentice-Hall, 1986.
  • Kientzle, Tim, A Programmer's Guide to Sound, Addison-Wesley Developers Press, 1998.
  • Petzold, Charles, Programming Windows 98, Microsoft Press, 1998 (5th edition).
  • Thompson, Nigel, 3D Graphics Programming for Windows 95, Microsoft Press, 1996.
  • Watt, Alan H., and Mark Watt, Advanced Animation and Rendering Techniques, Addison-Wesley, 1992.

Additional sources for the concepts and terms associated with COM can be found in the following sources:

  • Brockschmidt, Kraig, Inside OLE 2, Microsoft Press, 1995 (2nd edition).
  • Rogerson, Dale E., Inside COM, Microsoft Press, 1997.


Direct3D Immediate Mode

Direct3D® Immediate Mode application programming interface (API) is part of the three-dimensional (3-D) graphics component of DirectX®. The information on Direct3D Immediate Mode is organized into the following topics:

  • About Direct3D Immediate Mode
  • Why Use Direct3D Immediate Mode?
  • Getting Started with Immediate Mode
  • Direct3D Immediate Mode Architecture
  • Direct3D Immediate Mode Essentials
  • Direct3D Immediate Mode Tutorials
  • Direct3D Immediate Mode Reference
  • Direct3D Immediate Mode Tools and Samples


About Direct3D Immediate Mode

Direct3D is designed to enable world-class game and interactive three-dimensional (3-D) graphics on a computer running Microsoft® Windows®. It provides device-dependent access to 3-D video-display hardware in a device-independent manner. Direct3D is a drawing interface for 3-D hardware.

Direct3D has two modes: Immediate Mode and Retained Mode. Retained Mode is a high-level 3-D API for programmers who require rapid development or who want the help of the Retained Mode built-in support for hierarchies and animation.

Direct3D Immediate Mode is a low-level 3-D API that is ideal for developers who need to port games and other high-performance multimedia applications to the Windows operating system. Immediate Mode is a device-independent way for applications to communicate with accelerator hardware at a low level. Direct3D Retained Mode is built on top of Immediate Mode.

These are some of the advanced features of Direct3D:

  • Switchable depth buffering (using z-buffers or w-buffers)
  • Flat and Gouraud shading
  • Multiple light sources and types
  • Full material and texture support, including mipmapping
  • Robust software emulation drivers
  • Transformation and clipping
  • Hardware independence
  • Full support on Windows 95, Windows 98, and Windows 2000
  • Support for the Intel MMX architecture

Developers who use Immediate Mode instead of Retained Mode are typically experienced in high-performance programming issues and may also be experienced in 3-D graphics. Your best source of information about Immediate Mode is the sample code included with this SDK; it illustrates how to put Direct3D Immediate Mode to work in real-world applications.


Why Use Direct3D Immediate Mode?

The world management of Immediate Mode is based on vertices, polygons, and commands that control them. It allows immediate access to the transformation, lighting, and rasterization 3-D graphics pipeline. If hardware isn't present to accelerate rendering, Direct3D offers robust software emulation. Developers with existing 3-D applications and developers who need to achieve maximum performance by maintaining the thinnest possible layer between their application and the hardware should use Immediate Mode, instead of Retained Mode.

Direct3D Immediate Mode provides simple and straightforward methods to set up and render a 3-D scene. The key set of rendering methods are referred to as DrawPrimitive methods; they enable applications to render one or more objects in a scene with a single method call. For more information about these methods, see DrawPrimitive Methods.

Immediate Mode allows a low-overhead connection to 3-D hardware. This low-overhead connection comes at a price; you must provide explicit calls for transformations and lighting, you must provide all the necessary matrices, and you must determine what kind of hardware is present and what its capabilities are.


Getting Started with Immediate Mode

The following sections describe some of the technical concepts that you need to understand before you write programs that incorporate 3-D graphics. This is designed as a general overview. For information about specific topics, see Direct3D Immediate Mode Architecture and Direct3D Immediate Mode Essentials.

If you are already experienced in producing 3-D graphics, you can skim the following sections for information that is unique to Direct3D.

This section is divided into the following topics:

  • 3-D Coordinate Systems and Geometry
  • Matrices and Transformations


3-D Coordinate Systems and Geometry

Programming Direct3D applications requires a working familiarity with 3-D geometric principles. This section introduces the most important geometric concepts for creating 3-D scenes. The following topics are covered:

  • 3-D Coordinate Systems
  • 3-D Primitives
  • Triangle Rasterization Rules
  • Shading

The discussions in these topics provide you with a simple, high-level understanding of the basic concepts employed by a Direct3D application. For more information about these topics, see Further Information.


3-D Coordinate Systems

Typically 3-D graphics applications use two types of Cartesian coordinate systems: left-handed and right-handed. In both coordinate systems, the positive x-axis points to the right, and the positive y-axis points up. You can remember which direction the positive z-axis points by pointing the fingers of either your left or right hand in the positive x-direction and curling them into the positive y-direction. The direction your thumb points, either toward or away from you, is the direction the positive z-axis points for that coordinate system.

Direct3D uses a left-handed coordinate system. If you are porting an application that is based on a right-handed coordinate system, you must make two changes to the data passed to Direct3D.

  • Flip the order of triangle vertices so that the system traverses them clockwise from the front. In other words, if the vertices are v0, v1, v2, pass them to Direct3D as v0, v2, v1.
  • Use the view matrix to scale world space by –1 in the z-direction. To do this, flip the sign of the _31, _32, _33, and _34 member of the D3DMATRIX structure that you use for your view matrix. (Likewise, Visual Basic applications can perform this operation on the corresponding members of the D3DMATRIX type.)

There are a wide variety of other coordinate systems used in 3-D software. Left- and right-handed coordinates are the most common. However, it is not unusual for 3-D modeling programs to use a coordinate system in which the y-axis points toward or away from the viewer, and the z-axis points up. In this case, right-handedness is defined as any positive axis (x, y, or z) pointing toward the viewer. Left-handedness is defined as any positive axis (x, y, or z) pointing away from the viewer. If you are porting a left-handed modeling application where the z-axis points up, you must do a rotation on all of the vertex data in addition to the previous steps.

The essential operations performed on objects defined in a 3-D coordinate system are translation, rotation, and scaling. You can combine these basic transformations to create a transform matrix. For details, see 3-D Transformations.

When you combine these operations, the results are not commutative—the order in which you multiply matrices is important.


3-D Primitives

A 3-D primitive is a collection of vertices that form a single 3-D entity. The simplest primitive is a collection of points in a 3-D coordinate system, which is called a point list.

Often, 3-D primitives are polygons. A polygon is a closed 3-D figure delineated by at least three vertices. The simplest polygon is a triangle. Direct3D uses triangles to compose most of its polygons because all three of the vertices in a triangle are guaranteed to be coplanar. Rendering non-planar vertices is inefficient. You can combine triangles to form large, complex polygons and meshes.

The following illustration shows a cube. Two triangles form each face of the cube. The entire set of triangles taken together forms one cubic primitive. You can apply textures and materials to the surfaces of primitives to make them appear to be a single solid form. For details, see Materials and Textures.

You can also use triangles to create primitives whose surfaces appear to be smooth curves. The following illustration shows how a sphere can be simulated with triangles. After a material is applied, it looks curved when it is rendered. This is especially true if you use Gouraud shading. For details, see Gouraud Shading.


Triangle Rasterization Rules

Often, the points specified for vertices do not precisely match the pixels on the screen. When this happens, Direct3D applies triangle rasterization rules to decide which pixels apply to a given triangle.

Direct3D uses a top-left filling convention for filling geometry. This is the same convention that is used for rectangles in GDI and OpenGL. In Direct3D, the center of the pixel is the decisive point. If the center is inside a triangle, the pixel is part of the triangle. Pixel centers are at integer coordinates.

This description of triangle-rasterization rules used by Direct3D does not necessarily apply to all available hardware. Your testing may uncover minor variations in the implementation of these rules.

The following illustration shows a rectangle whose upper-left corner is at (0, 0) and whose lower-right corner is at (5, 5). This rectangle fills 25 pixels, just as you would expect. The width of the rectangle is defined as right minus left. The height is defined as bottom minus top.

In the top-left filling convention, top refers to the vertical location of horizontal spans, and left refers to the horizontal location of pixels within a span. An edge cannot be a top edge unless it is horizontal—in general, most triangles have only left and right edges.

The top-left filling convention determines the action taken by Direct3D when a triangle passes through the center of a pixel. The following illustration shows two triangles, one at (0, 0), (5, 0), and (5, 5), and the other at (0, 5), (0, 0), and (5, 5). The first triangle in this case gets 15 pixels, whereas the second gets only 10 because the shared edge is the left edge of the first triangle.

If you define a rectangle with its upper-left corner at (0.5, 0.5) and its lower-right corner at (2.5, 4.5), the center point of this rectangle is at (1.5, 2.5). When the Direct3D rasterizer tessellates this rectangle, the center of each pixel is unambiguously inside each of the four triangles, and the top-left filling convention is not needed. The following illustration shows this. The pixels in the rectangle are labeled according to the triangle in which Direct3D includes them.

If you move the rectangle in the previous example so that its upper-left corner is at (1.0, 1.0), its lower-right corner at (3.0, 5.0), and its center point at (2.0, 3.0), Direct3D applies the top-left filling convention. Most of the pixels in this rectangle straddles the border between two or more triangles, as the next illustration shows.

For both rectangles, the same pixels are affected.


Shading

This section describes techniques used in Direct3D to control the shading of 3-D polygons.

  • Shading Modes
  • Comparing Shading Modes
  • Setting the Shading Mode
  • Face and Vertex Normal Vectors
  • Triangle Interpolants


Shading Modes

The shading mode used to render a polygon has a profound effect on its appearance. Shading modes determine the intensity of color and lighting at any point on a polygon face. Direct3D currently supports two shading modes:

  • Flat Shading
  • Gouraud Shading


Flat Shading

In the flat shading mode, the Direct3D rendering pipeline renders a polygon, using the color of the polygon material at its first vertex as the color for the entire polygon. 3-D objects that are rendered with flat shading have visibly sharp edges between polygons if they are not coplanar.

The following figure shows a teapot rendered with flat shading. The outline of each polygon is clearly visible. Flat shading is computationally the least expensive form of shading.


Gouraud Shading

When Direct3D renders a polygon using Gouraud shading, it computes a color for each vertex by using the vertex normal and lighting parameters. Then, it interpolates the color across the face of the polygons (See Face and Vertex Normal Vectors). The interpolation is done linearly. For example, if the red component of the color of vertex 1 is 0.8 and the red component of vertex 2 is 0.4, utilizing the Gouraud shading mode and the RGB color model, the Direct3D lighting module would assign a red component of 0.6 to the pixel at the midpoint of the line between these vertices.

The following figure demonstrates Gouraud shading. This teapot is composed of many flat, triangular polygons. However, Gouraud shading makes the surface of the object appear curved and smooth.

Gouraud shading can also be used to display objects with sharp edges. For details, see Face and Vertex Normal Vectors.


Comparing Shading Modes

In the flat shading mode, the following pyramid would be displayed with a sharp edge between adjoining faces. In the Gouraud shading mode, however, shading values would be interpolated across the edge, and the final appearance would be of a curved surface.

Gouraud shading lights flat surfaces more realistically than flat shading. A face in the flat shading mode is a uniform color, but Gouraud shading allows light to fall across a face more correctly. This effect is particularly obvious if there is a nearby point source.

Gouraud shading smooths out the sharp edges between polygons that are visible with flat shading. However, it can result in Mach bands, which are bands of color or light that are not smoothly blended across adjacent polygons. Your application can reduce the appearance of Mach bands by increasing the number of polygons in an object, increasing screen resolution, or increasing the color depth of the application.

Gouraud shading can miss some details. One example is the case shown by the following illustration, in which a spotlight is completely contained within a polygon face.

In this case, Gouraud shading, which interpolates between vertices, would miss the spotlight altogether; the face would be rendered as though the spotlight did not exist.


Setting the Shading Mode

[C++]

Direct3D allows one shading mode to be selected at a time. By default, Gouraud shading is selected. In C++, the shading mode can be changed by calling the IDirect3DDevice7::SetRenderState method. Set the dwRenderStateType parameter to D3DRENDERSTATE_SHADEMODE. The dwRenderState parameter must be set to a member of the D3DSHADEMODE enumeration. The following sample code fragments illustrate how the current shading mode of a Direct3D application can be set to flat or Gouraud shading mode.

// Set to flat shading.
// This code fragment assumes that lpDev is a valid pointer to
// an IDirect3DDevice7 interface.
hr = lpDev->SetRenderState(D3DRENDERSTATE_SHADEMODE, D3DSHADE_FLAT);
if(FAILED(hr))
{
    // Code to handle the error goes here.
}

// Set to Gouraud shading (this is the default for Direct3D).
hr = lpDev->SetRenderState(D3DRENDERSTATE_SHADEMODE,
                            D3DSHADE_GOURAUD);
if(FAILED(hr))
{
    // Code to handle the error goes here.
}
[Visual Basic]

Direct3D allows one shading mode to be selected at a time. By default, Gouraud shading is selected. In Visual Basic, the shading mode can be changed by calling the Direct3DDevice7.SetRenderState method. Set the state parameter to D3DRENDERSTATE_SHADEMODE. The renderstate parameter must be set to a member of the CONST_D3DSHADEMODE enumeration. The following code fragment illustrates how the current shading mode of a Direct3D application can be set to flat or Gouraud shading mode.

'  Set to flat shading.
'  This code fragment assumes that d3dDev is a valid reference to
'  a Direct3DDevice7 object.
On Local Error Resume Next
Call d3dDev.SetRenderState(D3DRENDERSTATE_SHADEMODE, _
                           D3DSHADE_FLAT)

' Check for an error.
If Err.Number <> DD_OK Then
    ' Handle the error.
End If

' Set to Gouraud shading (this is the default for Direct3D).
Call d3dDev.SetRenderState(D3DRENDERSTATE_SHADEMODE, _
                           D3DSHADE_GOURAUD)

If Err.Number <> DD_OK Then
    ' Handle the error.
End If


Face and Vertex Normal Vectors

Each face in a mesh has a perpendicular normal vector. The vector's direction is determined by the order in which the vertices are defined and by whether the coordinate system is right- or left-handed. The face normal points away from the front side of the face. In Direct3D, only the front side of a face is visible. A front face is one in which vertices are defined in clockwise order.

Any face that is not a front face is a back face. Direct3D does not always render back faces; therefore, back faces are said to be culled. (You can change the culling mode to render back faces if you want. See Culling State for more information.)

Direct3D applications do not need to specify face normals; the system calculates them automatically when they are needed. The system uses face normals in the flat shading mode. In the Gouraud shading mode, Direct3D uses the vertex normal. It also uses the vertex normal for controlling lighting and texturing effects.

[C++]

Direct3D applications written in C++ typically use the D3DVERTEX structure for their vertices. The members of the D3DVERTEX structure describe the position and orientation of the vertex. The orientation is indicated by a vertex normal vector. The following code fragment demonstrates how vertex values, including the vertex normal, can be set. The normal vectors point toward the viewport, which is at the origin of the world coordinate system. The vertex positions in this example are specified in world coordinates.

D3DVERTEX lpVertices[3];

// A vertex can be specified one structure member at a time.
lpVertices[0].x = 0;
lpVertices[0].y = 5;
lpVertices[0].z = 5;
lpVertices[0].nx = 0;    // X component of the normal vector.
lpVertices[0].ny = 0;    // Y component of the normal vector.
lpVertices[0].nz = -1;   // Points the normal back at the origin.
lpVertices[0].tu = 0;    // Only used if a texture is being used.
lpVertices[0].tv = 0;    // Only used if a texture is being used.

// Vertices can also by specified on one line of code for each vertex
// by using some of the D3DOVERLOADS macros.
lpVertices[1] = D3DVERTEX(D3DVECTOR(-5,-5,5),D3DVECTOR(0,0,-1),0,0);
lpVertices[2] = D3DVERTEX(D3DVECTOR(5,-5,5),D3DVECTOR(0,0,-1),0,0);
[Visual Basic]

Direct3D applications written in Visual Basic typically use the D3DVERTEX type for their vertices. The members of the D3DVERTEX type describe the position and orientation of the vertex. The orientation is indicated by a vertex normal vector. The following code fragment demonstrates how vertex values, including the vertex normal, can be set. The normal vectors point toward the viewport, which is at the origin of the world coordinate system. The vertex positions in this example are specified in world coordinates.

D3DVERTEX Vertices(3)

' A vertex can be specified one structure member at a time.
Vertices(0).x = 0
Vertices(0).y = 5
Vertices(0).z = 5
Vertices(0).nx = 0    ' X component of the normal vector.
Vertices(0).ny = 0    ' Y component of the normal vector.
Vertices(0).nz = -1   ' Points the normal back at the origin.
Vertices(0).tu = 0    ' Only used if a texture is being used.
Vertices(0).tv = 0    ' Only used if a texture is being used.

When applying Gouraud shading to a polygon, Direct3D uses the vertex normals to calculate the angle between the light source and the surface. It calculates the color and intensity values for the vertices and interpolates them for every point across all of the primitive's surfaces. Direct3D calculates the light intensity value by using the angle. The greater the angle, the less light is shining on the surface.

If you are creating an object that is flat, set the vertex normals to point perpendicular to the surface, as shown in the following illustration. A flat surface composed of two triangles is defined.

It is more likely, however, that your object is made up of triangle strips and the triangles are not coplanar. One simple way to get smooth shading across all of the triangles in the strip is to first calculate the surface normal vector for each polygonal face with which the vertex is associated. The vertex normal can be set to make an equal angle with each of the surface normals. However, this method may not be efficient enough for complex primitives.

This method is illustrated by the following figure, which shows two surfaces, S1 and S2 seen edge-on from above. The normal vectors for S1 and S2 are shown in blue. The vertex normal vector is shown in red. The angle that the vertex normal vector makes with the surface normal of S1 is the same as the angle between the vertex normal and the surface normal of S2. When these two surfaces are lit and shaded with Gouraud shading, the result is a smoothly shaded, smoothly rounded edge between them.

If the vertex normal leans toward one of the faces with which it is associated, it causes the light intensity to increase or decrease for points on that surface, depending on the angle it makes with the light source. An example is shown in the following figure. Again, these surfaces are seen edge-on. The vertex normal leans toward S1, causing it to have a smaller angle with the light source than it would if the vertex normal had equal angles with the surface normals.

You can use Gouraud shading to display some of the objects in a 3-D scene with sharp edges. To do so, duplicate the vertex normal vectors at any intersection of faces where a sharp edge is required, as shown in the following illustration.

[C++]

If you are using the IDirect3DDevice7::DrawPrimitive or IDirect3DDevice7::DrawIndexedPrimitive methods to render your scene, define the object with sharp edges as a triangle list, rather than a triangle strip. When you define an object as a triangle strip, Direct3D treats it as a single polygon composed of multiple triangular faces. Gouraud shading is applied both across each face of the polygon and between adjacent faces. The result is an object that is smoothly shaded from face to face. Since a triangle list is a polygon composed of a series of disjoint triangular faces, Direct3D applies Gouraud shading across each face of the polygon. However, it is not applied from face to face. If two or more triangles of a triangle list are adjacent, they appear to have a sharp edge between them.

[Visual Basic]

If you are using the Direct3DDevice7.DrawPrimitive or Direct3DDevice7.DrawIndexedPrimitive methods to render your scene, define the object with sharp edges as a triangle list, rather than a triangle strip. When you define an object as a triangle strip, Direct3D treats it as a single polygon composed of multiple triangular faces. Gouraud shading is applied both across each face of the polygon and between adjacent faces. The result is an object that is smoothly shaded from face to face. Since a triangle list is a polygon composed of a series of disjoint triangular faces, Direct3D applies Gouraud shading across each face of the polygon. However, it is not applied from face to face. If two or more triangles of a triangle list are adjacent, they appear to have a sharp edge between them.

Another alternative is to change to flat shading when rendering objects with sharp edges. This is computationally the most efficient method, but it may result in objects in the scene that are not rendered as realistically as the objects that are Gouraud-shaded.


Triangle Interpolants

The system interpolates the characteristics of a triangle's vertices across the triangle when it renders a face. These are the triangle interpolants:

  • Color
  • Specular
  • Alpha

All the triangle interpolants are modified by the current shading mode:

Flat | No interpolation is done. Instead, the color of the first vertex in the triangle is applied across the entire face.
Gouraud | Linear interpolation is performed between all three vertices.

The color and specular interpolants are treated differently, depending on the color model. In the RGB color model, the system uses the red, green, and blue color components in the interpolation. In the monochromatic or ramp model, the system uses only the blue component of the vertex color.

The alpha component of a color is treated as a separate interpolant because device drivers can implement transparency in two different ways: by using texture blending or by using stippling.

A C++ application uses the dwShadeCaps member of the D3DPRIMCAPS structure to determine what forms of interpolation the current device driver supports. Similarly, a Visual Basic application accesses this information through the lShadeCaps member of the D3DPRIMCAPS type.


Matrices and Transformations

Use matrices in Direct3D to define world, view, and projection transformations. If you haven't programmed for 3-D graphics before, this section will help you familiarize yourself with the key concepts you need to understand to get started. If you have prior experience in 3-D programming, skip this section, or skim the following topics:

  • Matrices
  • 3-D Transformations


Matrices

You a basic knowledge of matrices to work with Direct3D. For more information, see 3-D Transformations.

Matrices in Direct3D are represented by a 4×4 homogenous matrix, defined by the D3DMATRIX structure in C++, and by the D3DMATRIX type in Visual Basic.

[C++]

The D3D_OVERLOADS implementation of the D3DMATRIX structure (D3DMATRIX (D3D_OVERLOADS)) implements a parentheses ("()") operator. This operator offers convenient access to values in the matrix for C++ programmers. Instead of having to refer to the structure members by name, C++ programmers can refer to them by row and column number and index these numbers as needed. These indices are zero-based, so, for example, the element in the third row, second column would be M(2, 1). To use the D3D_OVERLOADS operators, define D3D_OVERLOADS before including the D3dtypes.h header file.

The D3dutil.cpp source file also provides helper functions for creating and concatenating matrices. You can use these functions as they are or as a basis to write your own matrix manipulation functions.

[C++,Visual Basic]


3-D Transformations

Direct3D uses matrices to perform 3-D transformations. This section explains how matrices create 3-D transformations, describes some common uses for transformations, and details how you can combine matrices to produce a single matrix that encompasses multiple transformations. Information is divided into the following topics:

  • About 3-D Transformations
  • Translation
  • Rotation
  • Scaling
  • Matrix Concatenation

For more information about transformations in Direct3D Immediate Mode, see Geometry Pipeline.


About 3-D Transformations

In programs that work with 3-D graphics, you can use geometrical transformations to:

  • Express the location of an object relative to another object.
  • Rotate and size objects.
  • Change viewing positions, directions, and perspectives.

You can transform any point into another point by using a 4×4 matrix. In the following example, a matrix is used to reinterpret the point (x, y, z), producing the new point (x', y', z'):

Perform the following operations on (x, y, z) and the matrix to produce the point (x', y', z'):

The most common transformations are translation, rotation, and scaling. You can combine the matrices that produce these effects into a single matrix to calculate several transformations at once. For example, you can build a single matrix to translate and rotate a series of points. For more information, see Matrix Concatenation.

Matrices are written in row-column order. A matrix that evenly scales vertices along each axis (known as uniform scaling) is represented by the following matrix (using mathematical notation):

[C++]

In C++, Direct3D Immediate Mode declares matrices as a two-dimensional array, using the D3DMATRIX structure. The following example shows how to initialize a D3DMATRIX structure to act as a uniform scaling matrix:

D3DMATRIX scale = {
    D3DVAL(s),    0,            0,            0,
    0,            D3DVAL(s),    0,            0,
    0,            0,            D3DVAL(s),    0,
    0,            0,            0,            D3DVAL(1)
};
[Visual Basic]

In Visual Basic, Direct3D Immediate Mode uses matrices declared as a two-dimensional array, using the D3DMATRIX type. The following example shows how to initialize a variable of type D3DMATRIX to act as a uniform scaling matrix:

    Dim ScaleMatrix As D3DMATRIX

    ' In this example, s is a variable of type Single.
    With ScaleMatrix
        .rc11 = s
        .rc22 = s
        .rc33 = s
        .rc44 = 1
    End With


Translation

The following transformation translates the point (x, y, z) to a new point (x', y', z'):

[C++]

You can create a translation matrix by hand in C++. The following example shows the source code for a function that creates a matrix to translate vertices:

D3DMATRIX Translate(const float dx, const float dy, const float dz)
{
    D3DMATRIX ret = D3DUtil_SetIdentityMatrix(); // declared in d3dutil.h
    ret(3, 0) = dx;
    ret(3, 1) = dy;
    ret(3, 2) = dz;
    return ret;
}    // End of Translate
[Visual Basic]

In Visual Basic, you can create a translation matrix by hand, or you can use the TranslateMatrix helper subroutine in the Math.bas file that is included with this SDK. The following example shows the source code for the TranslateMatrix subroutine:

Sub TranslateMatrix(m As D3DMATRIX, v As D3DVECTOR)
    Call dx.IdentityMatrix(m) ' Method of the DirectX7 object
    m.rc41 = v.x
    m.rc42 = v.y
    m.rc43 = v.z
End Sub


Rotation

The transformations described here are for left-handed coordinate systems, and so may be different from transformation matrices that you have seen elsewhere. For more information, see 3-D Coordinate Systems.

The following transformation rotates the point (x, y, z) around the x-axis, producing a new point (x', y', z')

The following transformation rotates the point around the y-axis:

The following transformation rotates the point around the z-axis:

In these example matrices, the Greek letter theta (θ) stands for the angle of rotation, in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

[C++]

In a C++ application, use the D3DUtil_SetRotateXMatrix, D3DUtil_SetRotateYMatrix, and D3DUtil_SetRotateZMatrix helper functions in the D3dutil.cpp file to create rotation matrices. (The D3dutil.cpp file is included with this SDK.) The following is the sample code for the D3DUtil_SetRotateXMatrix helper function:

VOID D3DUtil_SetRotateXMatrix( D3DMATRIX& mat, FLOAT fRads )
{
    D3DUtil_SetIdentityMatrix( mat );
    mat._22 =  cosf( fRads );
    mat._23 =  sinf( fRads );
    mat._32 = -sinf( fRads );
    mat._33 =  cosf( fRads );
}v
[Visual Basic]

Visual Basic applications can use the DirectX7.RotateXMatrix, DirectX7.RotateYMatrix, and DirectX7.RotateZMatrix methods to create rotation matrices.

If you manually created a matrix for rotation about an axis—in this case, the x-axis—the source code would look something like the following:

Sub CreateXRotation(ret As D3DMATRIX, rads As Single)
    Dim cosine As Single
    Dim sine As Single
    cosine = Cos(rads)
    sine = Sin(rads)

    Call dx.IdentityMatrix(ret) ' Method of the DirectX7 object.

    ret.rc22 = cosine
    ret.rc23 = sine
    ret.rc32 = -sine
    ret.rc33 = cosine
End Sub


Scaling

The following transformation scales the point (x, y, z) by arbitrary values in the x-, y-, and z-directions to a new point (x', y', z'):


Matrix Concatenation

One of the primary advantages of using matrices is that you can combine the effects of two or more matrices by multiplying them. This means that, to rotate a model and then translate it to some location, you don't need to apply two matrices. Instead, you multiply the rotation and translation matrices to produce a composite matrix that contains all their effects. This process, called matrix concatenation, can be written with the following formula:

In this formula, C is the composite matrix being created, and M1 through Mn are the individual transformations that matrix C contains. In most cases, only two or three matrices are concatenated, but there is no limit.

C++ applications can use the D3dmath.cpp source file that is included with the DirectX SDK. It contains the D3DMath_MatrixMultiply helper function to perform matrix multiplication. Visual Basic applications can use the MatrixMult subroutine from the Math.bas file that is included with this SDK.

Notice the order in which the matrix multiplication is performed—the order is crucial. The preceding formula reflects the left-to-right rule of matrix concatenation. That is, the visible effects of the matrices that you use to create a composite matrix occur in left-to-right order. A typical world transformation matrix is the following example. Imagine that you are creating the world transformation matrix for a stereotypical flying saucer. You would probably want to spin the UFO around its center (the y-axis of model space) and translate it to some other place in your scene. To accomplish this effect, you would first create a rotation matrix, then multiply it by a translation matrix, as in the following formula:

In this formula, Ry is a matrix for rotation about the y-axis, and Tw is a translation to some position in world coordinates.

The order in which you multiply the matrices is important because, unlike multiplying two scalar values, matrix multiplication is not commutative. Multiplying the matrices in the opposite order would have the visual effect of translating the UFO to its world space position, then rotating it around the world origin.

No matter what type of matrix you are creating, remember the left-to-right rule to ensure that you achieve the expected effects.


Direct3D Immediate Mode Architecture

This section provides high-level information about the organization of the Direct3D® Immediate Mode documentation. Information is divided into the following topics:

  • Architectural Overview of Immediate Mode
  • Immediate Mode Object Types
  • Immediate Mode COM Interfaces


Architectural Overview of Direct3D Immediate Mode

DirectX SDK

Architectural Overview of Immediate Mode

Direct3D applications communicate with graphics hardware in a similar fashion whether they use Retained Mode or Immediate Mode. They may or may not take advantage of software emulation before interacting with the hardware emulation layer (HAL). Since Direct3D is an interface to a DirectDraw® object, the HAL is referred to as the DirectDraw/Direct3D HAL.

Direct3D is tightly integrated with the DirectDraw component of DirectX. DirectDraw surfaces are used as rendering targets (front and back surfaces) and as z-buffers. The Direct3D interface is actually an interface to a DirectDraw object.


Immediate Mode Object Types

Direct3D Immediate Mode is made up of a series of objects. When programming with C++, you work directly with these objects to manipulate your virtual world and build a Direct3D application. A Visual Basic application ultimately accesses these objects as well, although DirectX for Visual Basic exposes a slightly different object model.

[C++]
DirectDraw Object
A DirectDraw object provides the functionality of Direct3D; IDirect3D, IDirect3D2, IDirect3D3, and IDirect3D7 are interfaces to a DirectDraw object. Since a DirectDraw object represents the display device and the display device implements many of the most important features of Direct3D, the abilities of Direct3D are incorporated into DirectDraw. The IDirect3D7 interface is an interface to an entirely different object than its predecessors. For more information, see Direct3D Interfaces. Like Direct3D, the method by which you create the DirectDraw object determines what interfaces you can use.

Create a DirectDraw object that can support the newest Direct3D interface by calling the DirectDrawCreateEx function. For more information, see Direct3D Interfaces.

DirectDrawSurface Object
A DirectDrawSurface object that was created with 3-D capabilities (DDSCAPS_3DDEVICE) can be used to create a Direct3D device object that uses the surface as its rendering target. Applications create a device from a surface by calling the IDirect3D7::CreateDevice method.

A DirectDrawSurface object that was created with texture-mapping capabilities contains the bitmap(s) that your Direct3D application uses for texturing objects in a scene. Applications use a pointer to the surface's IDirectDrawSurface7 interface to identify the texture to Direct3D. Applications create a texture and retrieve its interface pointer by calling the IDirectDraw7::CreateSurface method. (This is a change from the method by which applications previously created textures, retrieving the IDirect3DTexture2 interface for the surface by calling the IUnknown::QueryInterface method, and specifying the IID_IDirect3DTexture2 reference identifier.)

For more information, see Textures.

Direct3DDevice Object
A Direct3DDevice object encapsulates and stores the rendering state for an Immediate Mode application. Direct3D devices are independent of the surfaces they use as rendering targets, and devices can be used to render to several render-target surfaces (prior to DirectX 5.0, this was not the case). In DirectX 7.0, the recommended device object exposes the IDirect3DDevice7 interface. Direct3D applications can create a device and retrieve a pointer to its IDirect3DDevice7 interface by calling the IDirect3D7::CreateDevice method. A device object created in this manner only exposes the most recent interface. For details, see Device Interfaces and Direct3D Devices.

Unlike its predecessors, a device object that exposes the IDirect3DDevice7 interface does not employ separate objects for materials, lights, and viewports; these objects are effectively obsolete with DirectX 7.0. Rather, the new interface includes methods that provides the functionality of these legacy objects as part of the internal data structures for the device.

Direct3DVertexBuffer Object
A Direct3DVertexBuffer object is a memory buffer that contains vertices to be rendered with the vertex-buffer rendering methods offered in the IDirect3DDevice7 interface. Vertex buffers are not to be confused with the legacy execute buffer architecture. A vertex buffer contains only vertex data to be processed by a Direct3DDevice object and offers features to improve performance during rendering. To create a vertex buffer and retrieve an interface for it, call the IDirect3D7::CreateVertexBuffer method.

For more information, see Vertex Buffers.

[Visual Basic]

DirectX for Visual Basic exposes the following classes for Direct3D Immediate Mode programming:

DirectX7 Class
The DirectX7 class defines the object that is used to create all other component-level objects, such as the Direct3D7 or DirectDraw7 object.
DirectDraw7 Class
The DirectDraw7 class represents the display device, spawns the Direct3D7 class, and creates the texture and rendering target surfaces used for rendering. To create an object of the DirectDraw7 class, call the DirectX7.DirectDrawCreate method.
DirectDrawSurface7 Class
The DirectDrawSurface7 class represents memory that is used to contain image data for display, texturing, or as a rendering target for a Direct3D device. Call the DirectDraw7.CreateSurface method to create an empty surface, or call the DirectDraw7.CreateSurfaceFromFile method to create a surface and load it with image data from a bitmap file.
Direct3D7 Class
The Direct3D7 class defines an object that provides the functionality of Direct3D, used to create and manipulate the objects that you need to render a scene. To create an object of the Direct3D7 class, call the DirectDraw7.GetDirect3D method.
Direct3DDevice7 Class
The Direct3DDevice7 class defines an object that encapsulates and stores the rendering state, lighting and material states, and viewport parameters for an Immediate Mode application written in Visual Basic. To create an object of this class, call the Direct3D7.CreateDevice method. For more information, see Direct3D Devices, Lighting and Materials, and Viewports and Clipping.
Direct3DEnumDevices Class
The Direct3DEnumDevices class defines an object that can enumerate the rendering devices present on a system. To create an object of the Direct3DEnumDevices class, call the Direct3D7.GetDevicesEnum method.
Direct3DEnumPixelFormats Class
The Direct3DEnumPixelFormats class defines an object that can enumerate the pixel formats supported for a given device on a system. To create an object of the Direct3DEnumPixelFormats class, call the Direct3D7.GetEnumZBufferFormats or Direct3DDevice7.GetTextureFormatsEnum methods.
Direct3DVertexBuffer7 Class
The Direct3DVertexBuffer7 class defines an object that acts as a memory buffer for vertices. Vertices in a vertex buffer can be rendered with the vertex-buffer rendering methods offered in the Direct3DDevice7 class. Call the Direct3D7.CreateVertexBuffer method to create a vertex buffer.

For more information, see Vertex Buffers.


Immediate Mode COM Interfaces

[Visual Basic]

Note The information in this topic applies only to applications written in C++. DirectX for Visual Basic does not expose COM interfaces.

[C++]

The Direct3D Immediate Mode API consists primarily of the following interfaces:

IDirect3D7 | Root interface, used to obtain other interfaces
IDirect3DDevice7 | 3-D Device for DrawPrimitive-based programming
IDirect3DVertexBuffer7 | Interface used to work with vertex buffers.

For backward compatibility with previous versions of DirectX, all objects that supported former interface versions still support them in DirectX 7.0. However, new objects may only support the latest interfaces. For more information, see Direct3D Interfaces and Device Interfaces.


Direct3D Immediate Mode Essentials

Direct3D Immediate Mode consists of a relatively small number of API elements that create objects, fill them with data, and link them together. The API is based on COM. The Immediate Mode API is a very thin layer over the Direct3D drivers.

This section provides technical information about the components of Direct3D Immediate Mode. Information is divided into the following topics.

  • Immediate Mode Changes for DirectX 7.0
  • Direct3D and DirectDraw
  • Direct3D Devices
  • Geometry Pipeline
  • Lighting and Materials
  • Vertex Formats
  • Textures
  • Depth Buffers
  • Stencil Buffers
  • Vertex Buffers
  • Common Techniques and Special Effects
  • GUIDs
  • Performance Optimization
  • Troubleshooting


Immediate Mode Changes for DirectX 7.0

[Visual Basic]
Support for Visual Basic applications
Like the other components in DirectX 7.0, Direct3D Immediate Mode now offers its services to Visual Basic applications. This is made possible by a set of classes that marshal data from the Visual Basic application to the DirectX run time. In addition, the documentation provided with this SDK has been expanded to include the Visual Basic developer.
[C++]

DirectX 7.0 maintains backward compatibility by exposing and supporting objects and interfaces offered by previous releases of DirectX. However, two key Direct3D interfaces have been added as part of DirectX 7.0: IDirect3D7 and IDirect3DDevice7. They are interfaces to new objects that are distinct from those in previous releases. These new objects provide several new features, performance improvements, and ease-of-use enhancements over their counterparts from previous versions of DirectX:

Hardware-accelerated transformation and lighting
Direct3D can now take advantage of 3-D accelerators to accelerate transformation and lighting operations in hardware. If compliant hardware is available, the IDirect3D7::EnumDevices method sets the D3DDEVCAPS_HWTRANSFORMANDLIGHT capability flag in the dwDevCaps member of the associated D3DDEVICEDESC7 structure. For more information, see TnLHAL Device.
Environment mapping with cubic environment maps
Direct3D and DirectDraw now support a special type of texture map used in environment mapping, called a cubic environment map. Cubic environment mapping involves the use of a six-sided texture that can contain images to be applied to objects in a scene. Cubic environment maps provide realistic environment mapping in your applications, are easy to use, and even allow you to implement dynamic environment mapping.
API Changes
Direct3D for DirectX 7.0 moves lighting, material, and viewport parameters into the device interface. Therefore, separate objects to handle these parameters are no longer needed, nor are their interfaces. Several methods have been included in the IDirect3DDevice7 interface to manipulate these parameters.

Vertex buffers can now be used with strided vertices, made possible by the addition of the IDirect3DVertexBuffer7::ProcessVerticesStrided method to the new IDirect3DVertexBuffer7 interface.

Geometry Blending
Applications that use the Direct3D geometry pipeline can take advantage of new support for geometry blending. Geometry blending can be used to perform "skinning" effects to increase the realism of segmented objects in a scene, especially characters. For more information, see Geometry Blending.
Device-state blocks
Applications that target the new IDirect3DDevice7 interface can take advantage of its support for programmable sets of state changes, called state blocks. State blocks make it possible for a Direct3D application to record common sequences of device state changes into a construct that has a unique identifier, or block handle. Applications can use the block handle to execute previously recorded state blocks in a single method call. Besides minimizing the calls required to change device states, state blocks enable devices to cache precompiled sets of state changes for optimal execution, often resulting in improved performance. For details, see State Blocks.
Improved texture management
The Direct3D texture manager has been expanded to allow applications to prioritize managed textures. Direct3D uses texture priorities to determine which textures to keep in memory, and which to remove.
Support for Visual Basic applications
Like the other components in DirectX 7.0, Direct3D Immediate Mode now offers its services to Visual Basic applications. This is made possible by a set of classes that marshal data from the Visual Basic application to the DirectX run time. In addition, the documentation provided with this SDK has been expanded to include the Visual Basic developer.
Enhanced software emulation
Direct3D has been optimized to use any special instructions supported by the CPU. Supported instruction sets include the AMD 3D-Now! instruction set on some AMD processors and the MMX instruction set supported by many Intel processors. Where available, Direct3D utilizes the 3D-Now! instruction set to accelerate transformation and lighting operations and the MMX instruction set to accelerate rasterization. Applications that use the Direct3D transformation and lighting pipeline with software devices automatically benefit from this feature.

Migrating to the new set of Direct3D objects comes at a small price. Despite the names of the interfaces that they support, these objects are separate from their counterparts in previous releases, and they do not support the same interfaces. You cannot use IUnknown::QueryInterface to retrieve a legacy interface from an object that supports the new interfaces, nor can you query for a new interface from a legacy object. Attempts to do so fail, returning E_NOINTERFACE.

Existing applications that use execute buffers for rendering cannot use the new objects unless they abandon the execute buffer architecture. Otherwise, they must use the legacy objects (which will continue to be supported). In fact, execute-buffer rendering is generally considered obsolete. Therefore, no information covering the use of execute buffers is included in this documentation. Documentation about execute-buffer rendering is still available in the legacy documentation that ships with this SDK and is available for download from http://www.microsoft.com/directx.


Direct3D and DirectDraw

This section describes the close relation between Direct3D and DirectDraw. It offers information on the following topics:

  • The DirectDraw Object and Direct3D
  • Direct3D Interfaces
  • Accessing Direct3D
  • Creating Objects Subordinate to Direct3D
  • DirectDraw Cooperative Levels and FPU Precision


The DirectDraw Object and Direct3D

Direct3D is implemented through COM objects and interfaces. Applications written in C++ directly access these interfaces and objects, whereas Visual Basic application interact with a layer of code—visible as the DirectX for Visual Basic Classes—that marshals data from a Visual Basic application to the DirectX run time. The information specific to C++ in this topic describes important relationships between DirectDraw and Direct3D. The discussion is followed by details about similar relationships between the classes exposed by DirectX for Visual Basic.

[C++]

The Direct3D interfaces are actually interfaces to the DirectDraw object. DirectDraw presents programmers with a single, unified object that encapsulates both the DirectDraw and Direct3D states. The DirectDraw object is the first object that your application creates and the last object that your application releases. Since the DirectDraw object represents the display device and the display device implements many of the most important features of Direct3D, the abilities of Direct3D are incorporated into DirectDraw.

Note For DirectX 7.0, there are two ways to create the DirectDraw object from which you access Direct3D: the new DirectDrawCreateEx function and the legacy DirectDrawCreate function used in previous releases of DirectX. The DirectDrawCreateEx function creates a DirectDraw object that is capable of exposing the newest set of Direct3D interfaces offered in DirectX 7.0. The DirectDrawCreate function, on the other hand, creates a DirectDraw object that is incapable of spawning a Direct3D interface that supports the features of DirectX 7.0. This documentation assumes that all applications will create their DirectDraw objects by using the DirectDrawCreateEx function. For more information, see Direct3D Interfaces and Device Interfaces.

This means that the lifetime of the Direct3D driver state is the same as that of the DirectDraw object. Releasing the Direct3D interface does not destroy the Direct3D driver state. That state is not destroyed until all references to that object—whether they are DirectDraw or Direct3D references—have been released. Therefore, if you release a Direct3D interface while holding a reference to a DirectDraw driver interface and then query the Direct3D interface again, the Direct3D state is preserved.

The DirectDraw object created by the DirectDrawCreateEx function contains a single Direct3D interface, IDirect3D7. (DirectDraw objects created with the legacy DirectDrawCreate function support the legacy interfaces IDirect3D, IDirect3D2, and IDirect3D3. These interfaces are obsolete and are provided for backward compatibility.) New applications should use the IDirect3D7 interface to create other Direct3D objects. For details, see Direct3D Interfaces.

[Visual Basic]

Although the DirectDraw and Direct3D share much of the same code—in fact, they are basically the same root object—DirectX for Visual Basic exposes them according to how you will use them: as functionally separate classes. DirectX for Visual Basic uses the DirectDraw7 and Direct3D7 classes from which your application can create objects. The underlying relationship (as described in the C++ portion of this topic) between DirectDraw and Direct3D is apparent even from within Visual Basic. The global DirectX7 class contains a method to create a DirectDraw7 object, but no equivalent method for Direct3D. Rather, the DirectDraw7 class defines a method to retrieve the Direct3D7 class, called DirectDraw7.GetDirect3D because these two classes actually refer to the same object within DirectX.

The GetDirect3D method does not create a new object. Rather, the method creates a new class that exposes the Direct3D-related features offered by the DirectDraw object that created it.

The DirectDraw7 class provides the two-dimensional features for a display device, whereas the Direct3D7 class offers the 3-D features for the device. Use the DirectDraw7 class to create the surfaces that the Direct3D class uses for rendering targets, depth buffers, and textures. The Direct3D class is then used to create the subordinate objects that Direct3D requires, such as vertex buffers and enumeration classes.


Direct3D Interfaces

[Visual Basic]

Note The information in this topic applies only to applications written in C++. DirectX for Visual Basic does not directly expose COM interfaces to applications.

[C++]

The functionality of Direct3D objects is accessed by C++ applications through the interfaces IDirect3D, IDirect3D2, IDirect3D3, and IDirect3D7. This section presents general information on all three of these interfaces, working backward from the IDirect3D7 interface introduced with DirectX 7.0 to the first interface, IDirect3D.

IDirect3D7 Interface
The IDirect3D7 interface, although named similarly to its predecessors, represents an interface to an entirely new Direct3D object. This object supports and expands upon the DrawPrimitive architecture, but it does not support the legacy interfaces mentioned previously in this topic. Applications retrieve a pointer to the IDirect3D7 interface by calling the QueryInterface method of a DirectDraw object that was created by calling the DirectDrawCreateEx function.

The IDirect3D7 interface supports many of the same features as the IDirect3D3 interface, enabling applications to create rendering devices and vertex buffers, as well as enumerating pixel formats. This interface adds the ability to create textures, rendering obsolete the need to query a DirectDraw surface for a texture interface.

A notable difference between IDirect3D7 and its ancestors is the absence of methods to create light, material, or viewport objects. This difference reflects the approach taken in the IDirect3DDevice7 interface to incorporate lighting, material, and viewport parameters as part of the device's internal data structures, rather than separate objects.

The IDirect3D7 object supports the features described in Immediate Mode Changes for DirectX 7.0.

Applications obtain a pointer to the IDirect3D7 interface by using the QueryInterface method of the new IDirectDraw7 interface. For details, see Accessing Direct3D.

IDirect3D2 and IDirect3D3 Interfaces
Applications get a pointer to the legacy IDirect3D2 and IDirect3D3 interfaces from a DirectDraw object that was created by the DirectDrawCreate function (as opposed to the new DirectDrawCreateEx function.) The interfaces are retrieved by calling the QueryInterface method for the DirectDraw object. Using these interface, your applications could find and enumerate the types of Direct3D devices supported by a particular DirectDraw object. They also exposed methods needed to create other Direct3D Immediate Mode objects, such as viewports, materials and lights. (The concept of lights, materials, and viewports as discrete objects is abandoned by the IDirect3D7 interface.)

One of the most important differences between IDirect3D2 and its predecessor, IDirect3D, is that IDirect3D2 implements an IDirect3D2::CreateDevice method. This method creates a Direct3D device that supports the DrawPrimitive methods. For more information about the devices created by the IDirect3D2::CreateDevice method, see Direct3D Devices.

Like the IDirect3D2 interface, the IDirect3D3 interface supports the DrawPrimitive style of Direct3D programming. In addition, the IDirect3D3 interface extends the functionality of DrawPrimitive-style programming by introducing the IDirect3DDevice3 interface. This interface introduced the concepts of flexible vertex formats, vertex buffers, and new texturing capabilities. For additional information, see Vertex Formats, Textures, Vertex Buffers and Rendering.

Applications obtain a pointer to the IDirect3D3 interface from a DirectDraw object, using the QueryInterface method.

IDirect3D Interface
The legacy IDirect3D interface supports the use of execute buffers. It is provided for compatibility with existing code. New applications should use the IDirect3D7 interface. If your application uses execute buffers, it cannot migrate to the features offered by DirectX 7.0. For more information, see Immediate Mode Changes for DirectX 7.0.


Accessing Direct3D

[C++]

When a Direct3D application written in C++ starts up, it must obtain a pointer to an IDirect3D7 interface to access the latest Direct3D functionality. Use the following steps to obtain a pointer to the IDirect3D7 interface:

To obtain a pointer to the IDirect3D7 interface

  1. Call DirectDrawCreateEx to create a DirectDraw device. Applications must use the DirectDrawCreateEx function to create a DirectDraw object capable of supporting IDirect3D7; a DirectDraw object created by the legacy DirectDrawCreate function does not support the IDirect3D7 interface.
  2. Call the IUnknown::QueryInterface method to get a pointer to an IDirect3D7 interface.

The following illustration shows these steps and relates this process to the one required for legacy applications:

Note As shown in the preceding figure, the DirectDraw component is comprised of two COM objects. The newest object—called DirectDraw7 and created by calling the DirectDrawCreateEx function—is the only object that exposes the IDirect3D7 interface. The DirectDraw7 object does not expose legacy Direct3D interfaces. Applications that require previous iterations of the Direct3D must use the DirectDrawCreate method to create a DirectDraw object, and then query for a legacy interface.

The following code fragment demonstrates how to create a DirectDraw7 object and query for an IDirect3D7 interface:

LPDIRECTDRAW7   lpDD;               // IDirectDraw7 Interface
LPDIRECT3D7     lpD3D;              // IDirect3D7 Interface
HRESULT hr;

// Get an IDirectDraw7 interface.
// Use the current display driver.
hr = DirectDrawCreateEx (NULL, (void **)&lpDD, IID_IDirectDraw7, NULL);
if (FAILED (hr))
{
    // Code to handle an error goes here.
}

// Get D3D interface
hr = lpDD->QueryInterface (IID_IDirect3D7, (void **)&lpD3D);
if (FAILED (hr))
{
    // Code to handle the error goes here.
}
[Visual Basic]

When a Direct3D application written in Visual Basic starts up, it must obtain a reference to the Direct3D7 class to access Direct3D functionality. Use the following steps to obtain such a reference:

To obtain a reference to the Direct3D7 class

  1. Call DirectX7.DirectDrawCreate to create a DirectDraw7 class object.
  2. Call the DirectDraw7.GetDirect3D method to retrieve the DirectDraw object's reference to the Direct3D7 class.

The following illustration shows these steps:

The following code fragment demonstrates how to retrieve the Direct3D7 class from a DirectDraw7 class object:

' Retrieve a reference to the Direct3D7 class.
'
' For this example, dx is a valid reference to the DirectX7 class.
On Local Error Resume Next
Dim ddraw As DirectDraw7
Dim d3d As Direct3D7

' Create a default DirectDraw7 object.
Set ddraw = dx.DirectDrawCreate("")
If (Err.Number <> DD_OK) Then
    ' Handle error.
End If

' Retrieve the Direct3D7 reference from the DirectDraw7 object.
Set d3d = ddraw.GetDirect3D
If (Err.Number <> DD_OK) Then
    ' Handle error.
End If


Creating Objects Subordinate to Direct3D

[C++]

Applications written in C++ use the IDirect3D7 interface to create Direct3D rendering devices and vertex buffers. A Direct3D application creates a rendering device by invoking the IDirect3D7::CreateDevice method. For details, see Direct3D Devices. The rendering device encompasses the rendering, lighting, material, and viewport states.

Call the IDirect3D7::CreateVertexBuffer method to create a vertex buffer. Vertex buffers contain vertex data specially prepared for faster rendering than simple arrays of vertex data. For more information, see Vertex Buffers.

[Visual Basic]

Applications written in Visual Basic use the methods of the Direct3D7 class to create Direct3D rendering devices and vertex buffers. A Direct3D application creates a rendering device by invoking the Direct3D7.CreateDevice method. For details, see Direct3D Devices. The rendering device encompasses the rendering, lighting, material, and viewport states.

Call the Direct3D7.CreateVertexBuffer method to create a vertex buffer. Vertex buffers contain vertex data specially prepared for faster rendering than simple arrays of vertex data. For more information, see Vertex Buffers.


DirectDraw Cooperative Levels and FPU Precision

[Visual Basic]

Note The information in this topic applies only to applications written in C++. DirectX for Visual Basic does not support changing floating-point unit (FPU) precision.

[C++]

Direct3D always uses single-precision floating-point calculations to increase the performance of rendering a 3-D scene. By default, when you create a rendering device that supports the IDirect3DDevice7 interface, Direct3D sets the FPU to single-precision, round-to-nearest mode with exceptions disabled. From that point on, the system assumes that the state of the FPU does not change until the device is released; it then resets the FPU to double-precision mode.

Note This behavior is different from that of the legacy IDirect3DDevice3 interface. Devices that expose IDirect3DDevice3 check FPU mode on each rendering pass unless the DDSCL_FPUSETUP flag was used when the DirectDraw cooperative level was set in a prior call to IDirectDraw4::SetCooperative method.

Applications that require double-precision accuracy can include the DDSCL_FPUPRESERVE flag when calling the IDirectDraw7::SetCooperativeLevel method to set the DirectDraw cooperative level. When the DDSCL_FPUPRESERVE flag is used, the system still uses single-precision mode, but it saves the state of the FPU prior to changing the precision mode, then restores the mode when it returns control to the application. (Calling the method again using the DDSCL_FPUSETUP flag returns Direct3D to its default behavior.) Obviously, this check, save, then restore process takes time and can noticeably affect performance. This flag should only be used when the application must have double-precision accuracy and you do not want to include code to manually set and restore the FPU mode as the application requires.

Floating-point precision is thread-specific, so when developing multithreaded applications, be careful to check the FPU precision state to ensure that it is set and reset as appropriate for each thread.

Important Loading some dynamic-link libraries (DLLs) at run time can cause the FPU to be reset to double-precision mode. Some compilers, such as Visual C++, set the default DLL entry point to _DllMainCrtStartup, a function that the compiler supplies to initialize the C/C++ run-time components. This function also sets the FPU precision mode to double precision. If an application sets the DDSCL_FPUSETUP cooperative level, then loads a DLL, Direct3D does not detect that the FPU has been reset, and performance suffers.

If your application loads DLLs at run time, it should check and reset the FPU precision mode immediately after the LoadLibrary Win32 function returns, and before calling any Direct3D functions. You can reset the precision mode explicitly or by calling the IDirectDraw7::SetCooperativeLevel method again with the DDSCL_FPUSETUP flag set. Using SetCooperativeLevel to set the FPU precision mode can also cause DirectDraw surfaces to be lost.

You can explicitly set the entry point for DLLs that you compile by using the /ENTRY: linker switch. However, if you do, the C/C++ run time is not initialized automatically.

The following is a sample source file for a console application that checks and sets the FPU precision setting by using inline assembly language:

#include <windows.h>
#include <math.h>

// This function evaluates whether the floating-point
// control Word is set to single precision/round to nearest/
// exceptions disabled. If not, the
// function changes the control Word to set them and returns
// TRUE, putting the old control Word value in the passback
// location pointed to by pwOldCW.
BOOL MungeFPCW( WORD *pwOldCW )
{
    BOOL ret = FALSE;
    WORD wTemp, wSave;

    __asm fstcw wSave
    if (wSave & 0x300 ||            // Not single mode
        0x3f != (wSave & 0x3f) ||   // Exceptions enabled
        wSave & 0xC00)              // Not round to nearest mode
    {
        __asm
        {
            mov ax, wSave
            and ax, not 300h    ;; single mode
            or  ax, 3fh         ;; disable all exceptions
            and ax, not 0xC00   ;; round to nearest mode
            mov wTemp, ax
            fldcw   wTemp
        }
        ret = TRUE;
    }
    *pwOldCW = wSave;
    return ret;
}

void RestoreFPCW(WORD wSave)
{
    __asm fldcw wSave
}

void __cdecl main()
{
    WORD wOldCW;
    BOOL bChangedFPCW = MungeFPCW( &wOldCW );
    // Do something with control Word, as set by MungeFPCW.
    if ( bChangedFPCW )
        RestoreFPCW( wOldCW );
}


Direct3D Devices

This section provides an overview of Direct3D devices. The overview is divided into the following topics:

  • What Is a Direct3D Device?
  • Direct3D Device Types
  • Device Interfaces
  • Device States
  • Using Devices
  • AGP Surfaces and Direct3D Devices


What Is a Direct3D Device?

A Direct3D device is the rendering component of Direct3D. It encapsulates and stores the rendering state. In addition, a Direct3D device performs transformations and lighting operations and rasterizes an image to a DirectDraw surface. Architecturally, Direct3D devices contain a transformation module, a lighting module, and a rasterizing module, as the following illustration shows.

Direct3D enables applications that use custom transformation and lighting models to bypass the Direct3D device's transformation and lighting modules. For details, see Vertex Formats.

[C++]

In C++, there are four COM interfaces that can be used for rendering: IDirect3DDevice, IDirect3DDevice2, IDirect3DDevice3, and IDirect3DDevice7. In this documentation, it is assumed that applications target the latest interface version. For more information, see Device Interfaces.

[Visual Basic]

In DirectX for Visual Basic, you access Direct3D Immediate Mode devices through the Direct3DDevice7 class. The Direct3DDevice7 class supports the DrawPrimitive family of scene-rendering methods. The Direct3DDevice7 object can use various DirectDraw surfaces as render targets at different times if the application requires it. For more information, see Direct3DDevice7.SetRenderTarget.


Direct3D Device Types

This section introduces Direct3D devices and presents information for each type of device. The following topics are discussed:

  • About Device Types
  • HAL Device
  • TnLHAL Device
  • RGB Device
  • Reference Rasterizer
  • Legacy Device Types


About Device Types

Direct3D currently supports four types of Direct3D devices: the HAL device, a HAL device with accelerated tranformation and lighting support, software-emulated RGB device, and the reference rasterizer. The first two types of devices can be used for shipping applications, and the reference rasterizer is supported for feature testing.

[C++]

Note Previous releases of DirectX exposed additional device types—the MMX and Ramp devices—that are now obsolete. These are still available to C++ applications that target older versions of Direct3D but are not supported through the latest interfaces. For more information, see Legacy Device Types.

The Direct3D device that an application creates must correspond to the capabilities of the hardware on which the application is running. Direct3D provides rendering capabilities, either by accessing 3-D hardware that is installed in the computer or by emulating the capabilities of 3-D hardware in software. Therefore, Direct3D provides devices for both hardware access and software emulation.

Hardware-accelerated devices give better performance than software-emulated devices. In most cases, applications target computers that have hardware acceleration of some kind and fall back on software emulation to accommodate lower-end computers.

With the exception of the reference rasterizer, software devices do not always support the same features as a hardware device. For example, software devices do not support assigning a texture to more than one texture stage at a time. Applications should always query for device capabilities to determine which features are supported.

[C++,Visual Basic]


HAL Device

If the computer on which your application is running is equipped with a display adapter that supports Direct3D, your application should use it for 3-D operations. Direct3D HAL devices implement all or part of the transformation, lighting, and rasterizing modules in hardware.

Applications do not access 3-D cards directly. They call Direct3D functions and methods. Direct3D access the hardware through the hardware abstraction layer (HAL). If the computer that your application is running on supports the HAL, it will gain the best performance by using a HAL device.

[C++]

To create a HAL device from C++, call the IDirect3D7::CreateDevice method, and pass the IID_IDirect3DHALDevice value as the first parameter. For details, see Creating a Direct3D Device.

[Visual Basic]

To create a HAL device from Visual Basic, call the Direct3D7.CreateDevice method, and pass the "IID_IDirect3DHALDevice" string constant as the first parameter. For details, see Creating a Direct3D Device.

Note Unlike the software-emulation RGB device, hardware devices cannot render to 8-bit render-target surfaces.


TnLHAL Device

Some new 3-D hardware is capable of performing hardware-accelerated for transformation and lighting operations, freeing the CPU of most of its workload. Where available, your application can use devices like these for optimal performance. Direct3D TnLHAL devices implement all of the transformation, lighting, and rasterizing modules in hardware.

Applications do not access 3-D cards directly. They call Direct3D functions and methods. Direct3D access the hardware through the hardware abstraction layer (HAL). If the computer that your application is running on supports the TnLHAL, it will gain the best performance by using a TnLHAL device.

[C++]

Hardware devices capable of hardware-accelerated transformation and lighting expose the D3DDEVCAPS_HWTRANSFORMANDLIGHT device capability. To create a TnLHAL device from C++, call the IDirect3D7::CreateDevice method, and pass the IID_IDirect3DTnLHALDevice value as the first parameter. For details, see Creating a Direct3D Device.

[Visual Basic]

Hardware devices capable of hardware-accelerated transformation and lighting expose the D3DDEVCAPS_HWTRANSFORMANDLIGHT device capability. To create a TnLHAL device from Visual Basic, call the Direct3D7.CreateDevice method, and pass the "IID_IDirect3DTnLHALDevice" string constant as the first parameter. For details, see Creating a Direct3D Device.


RGB Device

If the user's computer provides no special hardware acceleration for 3-D operations, your application may emulate 3-D hardware in software. RGB devices emulate the functions of color 3-D hardware in software. Because an RGB device is emulated in software, it runs more slowly than a HAL device. However, RGB devices take advantage of any special instructions supported by the user's CPU to increase performance. Supported instruction sets include the AMD 3D-Now! instruction set on some AMD processors and the MMX instruction set supported by many Intel processors. Direct3D uses the 3D-Now! instruction set to accelerate transformation and lighting operations and the MMX instruction set to accelerate rasterization.

[C++]

Applications written in C++ create an RGB device with the IDirect3D7::CreateDevice method. Pass the value IID_IDirect3DRGBDevice as the first parameter. For more information, see Creating a Direct3D Device.

[Visual Basic]

Applications written in Visual Basic create an RGB device with the Direct3D7.CreateDevice method. Pass the "IID_IDirect3DRGBDevice" string constant as the first parameter. For more information, see Creating a Direct3D Device.


Reference Rasterizer

Direct3D supports an additional device type called the reference rasterizer. Unlike an RGB device, the reference rasterizer supports every Direct3D feature. Because these features are implemented for accuracy, rather than speed, and are implemented in software, the results are not very fast. The reference rasterizer does make use of special CPU instructions whenever it can, but it is not intended for retail applications. Use the reference rasterizer only for feature testing or demonstration purposes.

The reference rasterizer is not normally enumerated by Direct3D; set the EnumReference named value in the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Direct3D\Drivers registry key to a nonzero DWORD value to enable its enumeration.

[C++]

Applications written in C++ create a reference device with the IDirect3D7::CreateDevice method. Pass the value IID_IDirect3DRefDevice as the first parameter. For more information, see Creating a Direct3D Device.

[Visual Basic]

Visual Basic applications create a reference device with the Direct3D7.CreateDevice method. Pass the "IID_IDirect3DRefDevice" string constant as the first parameter. For more information, see Creating a Direct3D Device.


Legacy Device Types

[Visual Basic]

Note The information in this topic applies only to applications written in C++. DirectX for Visual Basic does not support these device types.

[C++]

Previous releases of DirectX supported two additional types of device, called the MMX device and the Ramp device. These devices are superseded in the current version of DirectX, but can still be accessed through legacy interfaces.

MMX Device

MMX is a special instruction set that some microprocessors support. It provides increased performance for multimedia and 3-D processing. Direct3D uses MMX support, if it is installed, to increase rendering speed.

MMX devices are not hardware-accelerated devices like HAL devices. The transformation, lighting, and rasterizing modules are completely implemented in software. However, MMX devices provide much better performance than other types of software-emulated Direct3D devices.

If your application uses the IDirect3D2 interface, it must explicitly create an MMX device. However, beginning with the IDirect3D3 interface, MMX and RGB devices implement exactly the same feature set (see RGB Device). If an application attempts to create an RGB device and the microprocessor supports MMX technology, Direct3D automatically creates an MMX device.

Your application creates an MMX device by invoking the IDirect3D3::CreateDevice method and passing the value IID_IDirect3DMMXDevice in the first parameter. For more information, see Creating a Direct3D Device. If the application explicitly requests that an MMX device is created and the user's computer does not support MMX technology, CreateDevice fails.

Ramp Device

You cannot create a Direct3D ramp device by using the IDirect3D3 or IDirect3D7 interfaces, nor can you query an existing ramp device for the IDirect3DDevice3 or IDirect3DDevice7 interfaces. In short, ramp devices do not support any multiple texture blending options. For emulation of these features, use the MMX or RGB software emulation devices.

A ramp device is a software-emulated device that provides monochrome lighting. Applications can select it when the user's computer does not have sufficient processing power to support any other type of Direct3D devices. Ramp mode uses the full range of the transformation module but does not support colored lighting. A ramp mode device uses the Direct3D lighting module for monochrome gray-scale lighting only. Therefore, lights in ramp mode have intensity but no color. The gray-scale value is stored in the blue component of the light color.

Colored materials and textures can be used in ramp mode. Direct3D uses the material or texture color as its base color. If white light (full-intensity light) is shining on the material or texture, the base color is used. However, if the light strength is less than full intensity, Direct3D mixes gray or black into the color of the material or texture. If your application uses textures in ramp mode, it must set the D3DLIGHTSTATE_MATERIAL member of the legacy D3DLIGHTSTATETYPE enumerated type. Only 8-bit textures can be used in ramp mode.

To control the number of color values available for a material or texture in ramp mode, your application must set the dwRampSize member of the legacy D3DMATERIAL structure when it creates its materials. Direct3D uses the material and texture color as the base color. The value in the dwRampSize member determines how many gradients of the base color are available, depending on the brightness of the light. Direct3D creates a color palette with the number of entries (1-based) specified in the dwRampSize member. Since the maximum possible number of palette entries is less than 256 (256 minus the reserved colors that Windows uses), your application should specify the minimum number of gray-scale values required for the application.

For best results, make the ramp size for most or all of your application's materials the same value. When Direct3D runs out of palette entries, it searches through the existing materials to find the closest color match. Only materials with the same ramp size can be considered a match.

Ramp devices are provided primarily for backward compatibility with legacy applications. In general, computers that do not have sufficient processing power to support RGB devices are not suited to 3-D applications.

An application creates a ramp device by invoking the IDirect3D2::CreateDevice method and passing the value IID_IDirect3DRampDevice as the first parameter. For more information, see Creating a Direct3D Device.


Device Interfaces

[Visual Basic]

Note The information in this topic applies only to applications written in C++. DirectX for Visual Basic does not use COM interfaces, nor does it support rendering with execute-buffers.

[C++]

Applications written in C++ use a device interface to manipulate a Direct3DDevice object's rendering states, lighting states, and to perform rendering operations. There are four COM interfaces for devices in Direct3D: IDirect3DDevice, IDirect3DDevice2, IDirect3DDevice3, and IDirect3DDevice7. Underlying these interfaces is one of two possible COM objects that expose either all of the first three interfaces or only the IDirect3DDevice7 interface. The device object—and thus the interfaces—that your application uses depends entirely on the method by which the device is created. For more information, see Creating a Direct3D Device. Devices that expose the legacy IDirect3DDevice, IDirect3DDevice2, and IDirect3DDevice3 interfaces represent features and rendering capabilities exposed in versions of DirectX earlier than DirectX 7.0. This documentation refers to these objects as old devices. Objects that expose the IDirect3DDevice7 interface, which this documentation refers to as new devices, represent the latest set of rendering features. Applications cannot migrate across this interface boundary by using the IUnknown::QueryInterface method because the old device object is unaware of the newest features and the new device object is designed for optimal performance, rather than backward compatibility. Direct3D requires that you choose which interface your application will use ahead of time.

This documentation largely assumes that you will use the latest interface. However, some knowledge of previous implementations might be useful. The IDirect3DDevice interface exposed in previous versions of DirectX provides methods used for programming with execute buffers. However, execute buffers were provided primarily for backward compatibility. Subsequent versions of DirectX abandoned execute buffers in favor of the much simpler DrawPrimitive model, greatly simplifying the code required to render a scene. The DrawPrimitive rendering approach is employed by all interfaces later than the IDirect3DDevice interface. Direct3D Immediate Mode in DirectX 7.0 introduces the IDirect3DDevice7 interface, which provices greater simplicity and hardware acceleration. The device object that exposes IDirect3DDevice7 is capable of performing hardware-accelerated transformation and lighting operations when running on certain hardware. For more information, see Immediate Mode Changes for DirectX 7.0. These interfaces share some common methods, especially the interfaces that perform DrawPrimitive rendering. For more information, see Rendering.

Prior to the introduction of the IDirect3DDevice2 interface in DirectX 5.0, Direct3D devices were actually interfaces to DirectDrawSurface objects. The IDirect3DDevice2 and IDirect3DDevice3 interfaces implement a device-object model in which a Direct3DDevice object is entirely separate from DirectDraw surfaces, and concepts such as lights, materials, and viewports are objects that can be associated with one or more devices to render a scene. On the other hand, the IDirect3DDevice7 interface simplifies the Direct3D object-model further by moving lighting, material, and viewport parameters from separate objects, into the device itself.

Note There are no interface version numbers between IDirect3DDevice3 and IDirect3DDevice7.

Because devices are separated from DirectDraw surfaces and have independent lifetimes, Direct3D device objects can use various DirectDraw surfaces as render targets at different times if the application requires it. For more information, see IDirect3DDevice7::SetRenderTarget.


Device States

A Direct3D device is a state machine; applications set up the state of the lighting, rendering, and transformation modules and then pass data through them during rendering. This section describes render states, provides details about each of the render states used in Direct3D Immediate Mode, and contains information about device state blocks, which applications can use to manipulate groups of devices states in a single call. The following topics are discussed:

  • Render States
  • State Blocks
[C++]

C++ applications set most device states through the IDirect3DDevice7::SetRenderState method.

[Visual Basic]

Applications developed in Visual Basic set most device states through the Direct3DDevice7.SetRenderState method.

Note Device states also include user-defined clip planes, transformations, and lighting states. For more information, see User-defined Clip Planes, the Geometry Pipeline, and Lighting and Materials.


Render States

This section introduces the concept of render states, contrasts them to texture stage states, and discusses the various render states in detail. Information in this section is organized into the following topics:

  • About Render States
  • Current Texture
  • Antialiasing States
  • Texture Addressing State
  • Texture Wrapping State
  • Texture Borders
  • Texture Perspective State
  • Texture Filtering State
  • Outline and Fill States
  • Shading State
  • Fog States
  • Alpha-blending States
  • Alpha-testing States
  • Texture Blending State
  • Culling State
  • Depth Buffering State
  • Ramp State
  • Subpixel Correction State
  • Plane Masking State
  • Color Keying State
  • Render Command Batching State
  • Stencil Buffer State
  • Primitive Clipping State
  • Lighting State
  • Extent Update State
  • Ambient Lighting State
  • Per-vertex Color States


About Render States

Device render states control the behavior of the Direct3D device's rasterization module. By altering the attributes of the rendering state, what type of shading is used, fog attributes, and many other rasterizer operations.

[C++]

Applications written in C++ control the other characteristics of the rendering state by invoking the IDirect3DDevice7::SetRenderState method. The D3DRENDERSTATETYPE enumerated type specifies all of the possible rendering states. Your application passes a value from the D3DRENDERSTATETYPE enumeration as the first parameter to the IDirect3DDevice7::SetRenderState method.

Render states also can control the style of texturing and how texture filtering is done. For DirectX 6.0 and later, all texture-related render states are superseded by corresponding features offered by the IDirect3DDevice7::SetTextureStageState method. Attempts to use the superseded render states with the IDirect3DDevice7 interface will fail.

D3DRENDERSTATE_TEXTUREADDRESS, D3DRENDERSTATE_TEXTUREADDRESSU and D3DRENDERSTATE_TEXTUREADDRESSV
Superseded by the D3DTSS_ADDRESS, D3DTSS_ADDRESSU, D3DTSS_ADDRESSV texture stage states.
D3DRENDERSTATE_BORDERCOLOR
Superseded by the D3DTSS_BORDERCOLOR texture stage state.
D3DRENDERSTATE_TEXTUREMAG
Superseded by the D3DTSS_MAGFILTER texture stage state.
D3DRENDERSTATE_TEXTUREMIN
Superseded by the D3DTSS_MINFILTER texture stage state. Mipmap minification filtering is superseded by D3DTSS_MIPFILTER.
D3DRENDERSTATE_TEXTUREMAPBLEND
Superseded by the D3DTSS_COLOROP and D3DTSS_ALPHAOP texture stage states.
[Visual Basic]

Visual Basic applications control the characteristics of the rendering state by invoking the Direct3DDevice7.SetRenderState method. The CONST_D3DRENDERSTATETYPE enumerated type specifies all of the possible rendering states. Your application passes a value from the CONST_D3DRENDERSTATETYPE enumeration as the first parameter to the Direct3DDevice7.SetRenderState method.


Current Texture

[Visual Basic]

Note Information in this topic pertains only to applications written in C++. DirectX for Visual Basic uses surface objects and the Direct3DDevice7.SetTexture method to assign current textures to a device.

[C++]

The D3DRENDERSTATE_TEXTUREHANDLE render state is obsolete. Applications set the current textures by calling the IDirect3DDevice7::SetTexture method.


Antialiasing States

Antialiasing is a method of making lines and edges appear smoother on the screen. Direct3D supports two ways to perform antialiasing, called edge antialiasing and full-scene antialiasing. For details about these techniques, see Antialiasing in the Common Techniques and Special Effects section.

[C++]

By default, Direct3D default doesn't perform antialiasing. The D3DRENDERSTATE_ANTIALIAS render state can be set to one of the members of D3DANTIALIASMODE to enable full-scene antialiasing. (The default value, D3DANTIALIAS_NONE disables full-scene antialiasing.)

To enable edge-antialiasing (which requires a second rendering pass), set the D3DRENDERSTATE_EDGEANTIALIAS render state to TRUE. To disable it, set D3DRENDERSTATE_EDGEANTIALIAS to FALSE.

[Visual Basic]

By default, Direct3D default doesn't perform antialiasing. The D3DRENDERSTATE_ANTIALIAS render state can be set to one of the members of the CONST_D3DANTIALIASMODE enumeration to enable full-scene antialiasing. (The default value, D3DANTIALIAS_NONE disables full-scene antialiasing.)

To enable edge-antialiasing (which requires a second rendering pass), set the D3DRENDERSTATE_EDGEANTIALIAS render state to nonzero. To disable it, set D3DRENDERSTATE_EDGEANTIALIAS to zero.


Texture Addressing State

[Visual Basic]

Note Information in this topic pertains only to applications written in C or C++. DirectX for Visual Basic requires applications to set the texture addressing state by way of the Direct3DDevice7.SetTextureStageState method.

[C++]

The D3DRENDERSTATE_TEXTUREADDRESS, D3DRENDERSTATE_TEXTUREADDRESSU, and D3DRENDERSTATE_TEXTUREADDRESSV render states are obsolete, and are superseded by the D3DTSS_ADDRESS, D3DTSS_ADDRESSU, and D3DTSS_ADDRESSV texture stage states.

Note The IDirect3DDevice7 interface does not recognize the legacy D3DRENDERSTATE_TEXTUREADDRESS, D3DRENDERSTATE_TEXTUREADDRESSU, and D3DRENDERSTATE_TEXTUREADDRESSV render states. Attempts to use these render states will fail.


Texture Wrapping State

[C++]

Note The u- and v-wrapping render states D3DRENDERSTATE_WRAPU and D3DRENDERSTATE_WRAPV are obsolete and have been superseded by the D3DRENDERSTATE_WRAP0 through D3DRENDERSTATE_WRAP7 render states.

These wrapping render states enable and disable u- and v-wrapping for various textures in the device's multitexture cascade. Set these render states to a combination of the D3DWRAPCOORD_0, D3DWRAPCOORD_1, D3DWRAPCOORD_2, and D3DWRAPCOORD_3 flags to enable wrapping in first, second, third, and fourth directions of the texture, use a value of zero to disable wrapping altogether. Texture wrapping is disabled in all directions for all texture stages by default. For a conceptual overview, see Texture Wrapping.

Although D3DRENDERSTATE_WRAPU and D3DRENDERSTATE_WRAPV are superseded, the IDirect3DDevice7 interface still recognizes them. These older render states, when passed to the IDirect3DDevice7::SetRenderState affect u- and v-texture wrapping for the first texture stage (stage 0).

[Visual Basic]

The D3DRENDERSTATE_WRAP0 through D3DRENDERSTATE_WRAP7 render states control texture wrapping for various textures in the device's multitexture cascade. Set these render states to a combination of the D3DWRAPCOORD_0, D3DWRAPCOORD_1, D3DWRAPCOORD_2, and D3DWRAPCOORD_3 values from the CONST_D3D enumeration to enable wrapping in first, second, third, and fourth directions of the texture, use a value of zero to disable wrapping altogether. Texture wrapping is disabled in all directions for all texture stages by default. For a conceptual overview, see Texture Wrapping.


Texture Borders

[Visual Basic]

Note Information in this topic pertains only to applications written in C++. DirectX for Visual Basic requires applications to set texture border behavior by setting the D3DTSS_BORDERCOLOR texture stage state with the Direct3DDevice7.SetTextureStageState method.

[C++]

The D3DRENDERSTATE_BORDERCOLOR render state is obsolete, superseded by the D3DTSS_BORDERCOLOR texture stage state supported by the IDirect3DDevice7::SetTextureStageState method. For more information, see About the Border Color Texture Address Mode.

Note The D3DRENDERSTATE_BORDERCOLOR render state is not recognized by the IDirect3DDevice7 interface. Attempts to use this render state with the IDirect3DDevice7 interface will fail.


Texture Perspective State

[C++]

Applications can apply perspective correction to textures to make them fit properly onto primitives that diminish in size as they get farther away from the viewer. See D3DRENDERSTATE_TEXTUREPERSPECTIVE.

The following code fragment illustrates the process of enabling texture perspective correction:

// This code fragment assumes that lpD3DDevice is a valid pointer to
// an IDirect3DDevice7 interface.

// Enable texture perspective.
lpD3DDevice7->SetRenderState(D3DRENDERSTATE_TEXTUREPERSPECTIVE,
                             TRUE);

For the IDirect3DDevice3 and IDirect3DDevice7 interfaces, the default value is TRUE to enable perspective correct texture mapping. For earlier interfaces, the default is FALSE. Note that many 3-D adapters apply texture perspective correction unconditionally. Perspective correction must be enabled to use w-based fog, and w-buffers. For more information, see Eye-relative vs. Z-Based Depth in the Fog section, and Enabling Depth Buffering in the Depth Buffers section.

[Visual Basic]

Applications can apply perspective correction to textures to make them fit properly onto primitives that diminish in size as they get farther away from the viewer. See D3DRENDERSTATE_TEXTUREPERSPECTIVE.

The following code fragment illustrates the process of enabling texture perspective correction:

' This code fragment assumes that d3dD3DDevice is a valid reference to
' a Direct3DDevice7 object.

' Enable texture perspective.
Call d3dDevice7.SetRenderState(D3DRENDERSTATE_TEXTUREPERSPECTIVE, _
                               True)

The default value is True to enable perspective correct texture mapping.

Note that many 3-D adapters apply texture perspective correction unconditionally. Perspective correction must be enabled to use w-based fog, and w-buffers. For more information, see Eye-relative vs. Z-Based Depth in the Fog section, and Enabling Depth Buffering in the Depth Buffers section.


Texture Filtering State

[Visual Basic]

Note Information in this topic pertains only to applications written in C++. DirectX for Visual Basic requires applications to set texture-filtering behavior by using the Direct3DDevice7.SetTextureStageState method.

[C++]

Note The legacy render states, D3DRENDERSTATE_TEXTUREMAG, D3DRENDERSTATE_TEXTUREMIN, and D3DRENDERSTATE_ANISOTROPY, are obsolete with the release of DirectX 7.0.

Applications must use the D3DTSS_MAGFILTER, D3DTSS_MINFILTER, and D3DTSS_MAXANISOTROPY texture-stage states to control texture filtering.


Outline and Fill States

[C++]

Primitives that have no textures are rendered with the color specified by their material, or with the colors specified for the vertices, if any. The method used to fill them can be selected with the D3DFILLMODE enumerated type. See D3DRENDERSTATE_FILLMODE.

If you want your application to enable dithering, it must pass the D3DRENDERSTATE_DITHERENABLE enumerated value as the first parameter to IDirect3DDevice7::SetRenderState. It must set the second parameter to TRUE to enable dithering, and FALSE to disable it.

At times, drawing the last pixel in a line can cause unsightly overlap with surrounding primitives. This can be controlled using the D3DRENDERSTATE_LASTPIXEL enumerated value. However, this setting should not be altered without some forethought. Under some conditions, suppressing the rendering of the last pixel can cause unsightly gaps between primitives.

By default, Direct3D devices use a solid outline for primitives. The outline pattern can be changed using the D3DLINEPATTERN structure. See D3DRENDERSTATE_LINEPATTERN.

Note The legacy render states D3DRENDERSTATE_ROP2, D3DRENDERSTATE_STIPPLEENABLE, and D3DRENDERSTATE_STIPPLEPATTERN00 through D3DRENDERSTATE_STIPPLEPATTERN31 are obsolete with the release of DirectX 7.0.

[Visual Basic]

Primitives that have no textures are rendered with the color specified by their material, or with the colors specified for the vertices, if any. The method used to fill them can be selected with the CONST_D3DFILLMODE enumerated type. See D3DRENDERSTATE_FILLMODE.

If you want your application to enable dithering, it must pass the D3DRENDERSTATE_DITHERENABLE enumerated value as the first parameter to Direct3DDevice7.SetRenderState. It must set the second parameter to True to enable dithering, and False to disable it.

At times, drawing the last pixel in a line can cause unsightly overlap with surrounding primitives. This can be controlled using the D3DRENDERSTATE_LASTPIXEL enumerated value. However, this setting should not be altered without some forethought. Under some conditions, suppressing the rendering of the last pixel can cause unsightly gaps between primitives.

DirectX for Visual Basic does not support the D3DRENDERSTATE_LINEPATTERN render state.


Shading State

[C++]

Direct3D supports both flat and Gouraud shading. The default is Gouraud shading. To control the current shading mode, your C++ application uses the D3DSHADEMODE enumerated type. See D3DRENDERSTATE_SHADEMODE.

The following C++ code fragment demonstrates the process of setting the shading state to flat shading mode:

// This code fragment assumes that lpD3DDevice is a valid pointer to
// a IDirect3DDevice7 interface.

// Set the shading state.
lpD3DDevice->SetRenderState(D3DRENDERSTATE_SHADEMODE,
                            D3DSHADE_FLAT);
[Visual Basic]

Direct3D supports both flat and Gouraud shading. The default is Gouraud shading. To control the current shading mode from a Visual Basic application, use the CONST_D3DSHADEMODE enumerated type. See D3DRENDERSTATE_SHADEMODE.

The following Visual Basic code fragment demonstrates the process of setting the shading state to flat shading mode:

' This example assumes that D3DDevice is a valid reference
' to a Direct3DDevice7 object.

' Set the shading state.
Call D3DDevice.SetRenderState(D3DRENDERSTATE_SHADEMODE, D3DSHADE_FLAT)


Fog States

Fog effects can give a 3-D scene greater realism. Fog effects can be used for more than simulating fog. They can also be used to decrease the clarity of a scene with distance. This mirrors what happens in the real world. As objects get more distant from the viewer, their detail becomes less distinct. For more information about using fog in your application, see Fog.

[C++]

A C++ application controls fog through device rendering states. The D3DRENDERSTATETYPE enumerated type includes states to control whether pixel (table) or vertex fog is used, what color it is, the fog formula the system applies, and the parameters to the formula.

You enable fog by setting the D3DRENDERSTATE_FOGENABLE render state to TRUE. The fog color can be set to any D3DCOLOR value (the alpha component of the fog color is ignored). See D3DRENDERSTATE_FOGCOLOR.

The D3DRENDERSTATE_FOGTABLEMODE and D3DRENDERSTATE_FOGVERTEXMODE render states control the fog formula applied for fog calculations, and indirectly control which type of fog is applied at all. Both render states can be set to one of the members of the D3DFOGMODE enumerated type. Setting either render state to D3DFOG_NONE disables pixel or vertex fog, respectively. If both render states are set to valid modes, the system will apply only pixel fog effects.

The D3DRENDERSTATE_FOGSTART and D3DRENDERSTATE_FOGEND render states control fog formula parameters for the D3DFOG_LINEAR mode. The D3DRENDERSTATE_FOGDENSITY render state controls fog density in the exponential fog modes.

For more information, see Fog Parameters.

[Visual Basic]

In Visual Basic, applications control fog through device rendering states. The CONST_D3DRENDERSTATETYPE enumerated type includes states to control whether pixel (table) or vertex fog is used, what color it is, the fog formula the system applies, and the parameters to that formula.

You enable fog by setting the D3DRENDERSTATE_FOGENABLE render state to True. The fog color can be set to any value of type Long returned by the DirectX7.CreateColorRGB method. See D3DRENDERSTATE_FOGCOLOR.

The D3DRENDERSTATE_FOGTABLEMODE and D3DRENDERSTATE_FOGVERTEXMODE render states control the fog formula that the system applies for fog calculations, and indirectly control which type of fog is applied at all. Both render states can be set to one of the members of the CONST_D3DFOGMODE enumeration. Setting either render state to D3DFOG_NONE disables pixel or vertex fog, respectively. If both render states are set to valid modes, the system will apply only pixel fog effects.

The D3DRENDERSTATE_FOGSTART and D3DRENDERSTATE_FOGEND render states control fog formula parameters for the D3DFOG_LINEAR mode. The D3DRENDERSTATE_FOGDENSITY render state controls fog density in the exponential fog modes.

For more information, see Fog Parameters.


Alpha-Blending States

The alpha value of a color controls its transparency. Enabling alpha blending allows colors, materials, and textures on a surface to be blended with transparency onto another surface. For more information, see Alpha Texture Blending and Multipass Texture Blending.

[C++]

Applications written in C++ use the D3DRENDERSTATE_ALPHABLENDENABLE render state to enable alpha transparency blending. The Direct3D API allows many types of alpha blending. However, it is important to note the user's 3-D hardware may not support all of the blending states allowed by Direct3D.

The type of alpha blending that is done depends on the D3DRENDERSTATE_SRCBLEND and D3DRENDERSTATE_DESTBLEND render states. Source and destination blend states are used in pairs. The following code fragment demonstrates how the source blend state is set to D3DBLEND_SRCCOLOR and the destination blend state is set to D3DBLEND_INVSRCCOLOR.

// This code fragment assumes that lpD3DDevice is a valid pointer to
// an IDirect3DDevice7 interface.

// Set the source blend state.
lpD3DDevice->SetRenderState(D3DRENDERSTATE_SRCBLEND,
                            D3DBLEND_SRCCOLOR);

// Set the destination blend state.
lpD3DDevice->SetRenderState(D3DRENDERSTATE_DESTBLEND,
                            D3DBLEND_INVSRCCOLOR);

As a result of the calls in the preceding code fragment, Direct3D performs a linear blend between the source color (the color of the primitive being rendered at the current location) and the destination color (the color at the current location in the frame buffer). This gives an appearance similar to tinted glass. Some of the color of the destination object seems to be transmitted through the source object. The rest of it appears to be absorbed.

Altering the source and destination blend states can give the appearance of emissive objects in a foggy or dusty atmosphere. For instance, if your application models flames, force fields, plasma beams, or similarly radiant objects in a foggy environment, set the source and destination blend states to D3DBLEND_ONE.

Another application of alpha blending is controlling the lighting in a 3-D scene, also called light mapping. Setting the source blend state to D3DBLEND_ZERO and the destination blend state to D3DBLEND_SRCALPHA darkens a scene according to the source alpha information. The source primitive is used as a light map that scales the contents of the frame buffer to darken it when appropriate. This produces monochrome light mapping.

Color light mapping can be achieved by setting the source alpha blending state to D3DBLEND_ZERO and the destination blend state to D3DBLEND_SRCCOLOR.

Direct3D devices provide alpha value stippling if it is supported by the display hardware. See D3DRENDERSTATE_STIPPLEDALPHA. If your application creates an RGB or ramp software emulation device, Direct3D ignores this enumerated value.

[Visual Basic]

Visual Basic applications use the D3DRENDERSTATE_ALPHABLENDENABLE render state to enable alpha transparency blending. The Direct3D API allows many types of alpha blending. However, it is important to note the user's 3-D hardware may not support all of the blending states allowed by Direct3D.

The type of alpha blending that is done depends on the D3DRENDERSTATE_SRCBLEND and D3DRENDERSTATE_DESTBLEND render states. Source and destination blend states are used in pairs. The following code fragment demonstrates how the source blend state is set to D3DBLEND_SRCCOLOR and the destination blend state is set to D3DBLEND_INVSRCCOLOR.

' This code fragment assumes that D3DDevice contains a
' reference to a Direct3DDevice7 object.

' Set the source blend state.
Call D3DDevice.SetRenderState(D3DRENDERSTATE_SRCBLEND, _
                              D3DBLEND_SRCCOLOR);

' Set the destination blend state.
Call D3DDevice.SetRenderState(D3DRENDERSTATE_DESTBLEND, _
                              D3DBLEND_INVSRCCOLOR);

As a result of the calls in the preceding code fragment, Direct3D performs a linear blend between the source color (the color of the primitive being rendered at the current location) and the destination color (the color at the current location in the frame buffer). This gives an appearance similar to tinted glass. Some of the color of the destination object seems to be transmitted through the source object. The rest of it appears to be absorbed.

Altering the source and destination blend states can give the appearance of emissive objects in a foggy or dusty atmosphere. For instance, if your application models flames, force fields, plasma beams, or similarly radiant objects in a foggy environment, set the source and destination blend states to D3DBLEND_ONE.

Another application of alpha blending is controlling the lighting in a 3-D scene, also called light mapping. Setting the source blend state to D3DBLEND_ZERO and the destination blend state to D3DBLEND_SRCALPHA darkens a scene according to the source alpha information. The source primitive is used as a light map that scales the contents of the frame buffer to darken it when appropriate. This produces monochrome light mapping.

Color light mapping can be achieved by setting the source alpha blending state to D3DBLEND_ZERO and the destination blend state to D3DBLEND_SRCCOLOR.

Direct3D devices provide alpha value stippling if it is supported by the display hardware. See D3DRENDERSTATE_STIPPLEDALPHA. If your application creates an RGB or ramp software emulation device, Direct3D ignores this enumerated value.


Alpha-Testing States

[C++]

C++ applications can use alpha testing to control when pixels are written to the render-target surface. By using the D3DRENDERSTATE_ALPHATESTENABLE enumerated value, your application sets the current Direct3D device so that it tests each pixel according to an alpha test function. If the test succeeds, the pixel is written to the surface. If it doesn't, Direct3D ignores it. Select the alpha test function with the D3DRENDERSTATE_ALPHAFUNC enumerated value. Your application can set a reference alpha value for all pixels to be compared against by using the D3DRENDERSTATE_ALPHAREF render state.

The most common use for alpha testing is to improve performance when rasterizing objects that are nearly transparent. If the color data being rasterized is more opaque than the color already at a given pixel (D3DPCMPCAPS_GREATEREQUAL) then the pixel is written, otherwise the rasterizer ignores the pixel altogether, saving the processing required to blend the two colors. The following example checks to see if a given comparison function is supported and, if so, it sets the comparison function parameters required to improve performance during rendering.

// This example assumes that pd3dDeviceDesc is a
// D3DDEVICEDESC7 structure that was filled with a
// previous call to IDirect3DDevice7::GetCaps.
if (pd3dDeviceDesc.dpcTriCaps.dwAlphaCmpCaps & D3DPCMPCAPS_GREATEREQUAL)
{
    dev->SetRenderState( D3DRENDERSTATE_ALPHAREF, (DWORD)0x00000001);
    dev->SetRenderState( D3DRENDERSTATE_ALPHATESTENABLE, TRUE );
    dev->SetRenderState( D3DRENDERSTATE_ALPHAFUNC, D3DCMP_GREATEREQUAL );
}

// If the comparison isn't supported, render anyway.
// The only drawback is no performance gain.

Not all hardware supports all alpha testing features. You can check the device capabilities by calling the IDirect3DDevice7::GetCaps method. After retrieving the device capabilities, check the dwAlphaCmpCaps member of the D3DPRIMCAPS structure (contained by the associated D3DDEVICEDESC7 structure) for the desired comparison function. If the dwAlphaCmpCaps member contains only the D3DPCMPCAPS_ALWAYS capability or only the D3DPCMPCAPS_NEVER capability, the driver does not support alpha tests at all.

[Visual Basic]

Applications written in Visual Basic use alpha testing to control when pixels are written to the render-target surface. By using the D3DRENDERSTATE_ALPHATESTENABLE enumerated value, your application sets the current Direct3D device so that it tests each pixel according to an alpha test function. If the test succeeds, the pixel is written to the surface. If it doesn't, Direct3D ignores it. Select the alpha test function with the D3DRENDERSTATE_ALPHAFUNC render state. Your application can set a reference alpha value for all pixels to be compared against by using the D3DRENDERSTATE_ALPHAREF render state.

The most common use for alpha testing is to improve performance when rasterizing objects that are nearly transparent. If the color data being rasterized is more opaque than the color already at a given pixel (D3DPCMPCAPS_GREATEREQUAL) then the pixel is written, otherwise the rasterizer ignores the pixel altogether, saving the processing required to blend the two colors. The following example checks to see if a given comparison function is supported and, if so, it sets the comparison function parameters required to improve performance during rendering.

' This example assumes that d3dDeviceDesc is a
' D3DDEVICEDESC7 type that was filled with a
' previous call to Direct3DDevice7.GetCaps.
If (d3dDeviceDesc.dpcTriCaps.lAlphaCmpCaps And D3DPCMPCAPS_GREATEREQUAL) Then
        Call dev.SetRenderState(D3DRENDERSTATE_ALPHAREF, &H1)
        Call dev.SetRenderState(D3DRENDERSTATE_ALPHATESTENABLE, True)
        Call dev.SetRenderState(D3DRENDERSTATE_ALPHAFUNC, D3DCMP_GREATEREQUAL)
End If

' If the comparison isn't supported, render anyway.
' The only drawback is no performance gain.

Not all hardware supports all alpha testing features. You can check the device capabilities by calling the Direct3DDevice7.GetCaps method. After retrieving the device capabilities, check the lAlphaCmpCaps member of the D3DPRIMCAPS type (contained by the associated D3DDEVICEDESC7 type) for the desired comparison function. If the lAlphaCmpCaps member contains only the D3DPCMPCAPS_ALWAYS capability or only the D3DPCMPCAPS_NEVER capability, the driver does not support alpha tests at all.


Texture Blending State

[Visual Basic]

Note Information in this topic pertains only to applications written in C++. DirectX for Visual Basic requires applications to control texture blending by using the Direct3DDevice7.SetTextureStageState method with the D3DTSS_COLOROP and D3DTSS_ALPHAOP texture stage states.

[C++]

The D3DRENDERSTATE_TEXTUREMAPBLEND render state is superseded by the texture blending states available through the D3DTSS_COLOROP and D3DTSS_ALPHAOP texture stage states. For more information, see Multiple Texture Blending.

Note The D3DRENDERSTATE_TEXTUREMAPBLEND render state is obsolete, and is not recognized by the IDirect3DDevice7 interface. Attempts to use this render state with the IDirect3DDevice7 interface will fail.


Culling State

As Direct3D renders primitives, it culls those primitives that are facing away from the viewer.

[C++]

You can set the culling mode from a C++ application by using the D3DCULL enumerated type. See D3DRENDERSTATE_CULLMODE. By default, Direct3D culls back faces with counterclockwise vertices.

The following code sample illustrates the process of setting the culling mode to cull back faces with clockwise vertices.

// This code fragment assumes that lpD3DDevice is a valid pointer to
// an IDirect3DDevice interface.

// Set the culling state.
lpD3DDevice->SetRenderState(D3DRENDERSTATE_CULLMODE,
                            D3DCULL_CW);
[Visual Basic]

Visual Basic applications set the culling mode by using D3DRENDERSTATE_CULLMODE render state, which can be set to a member of the CONST_D3DCULL enumeration. By default, Direct3D culls back faces with counterclockwise vertices.

The following code sample illustrates the process of setting the culling mode to cull back faces with clockwise vertices.

' This code fragment assumes that D3DDevice  contains a valid
' reference to a Direct3DDevice object.

' Set the culling state.
Call D3DDevice.SetRenderState(D3DRENDERSTATE_CULLMODE, _
                              D3DCULL_CW)


Depth Buffering State

Depth buffering is a method of removing hidden lines and surfaces. For a conceptual overview, see What Are Depth Buffers?. By default, Direct3D does not use depth buffering.

[C++]

C++ applications update the depth buffering state with the D3DRENDERSTATE_ZENABLE render state, using one of the members of the D3DZBUFFERTYPE enumeration to specify the new state value.

If, for some reason, your application needs to prevent Direct3D from writing to the depth buffer, it can use the D3DRENDERSTATE_ZWRITEENABLE enumerated value, specifying FALSE as the second parameter for the call to IDirect3DDevice7::SetRenderState.

The following code fragment shows how the depth buffer state is set to enable z-buffering:

// This code fragment assumes that lpD3DDevice is a valid pointer to
// a and IDirect3DDevice7 interface.

// Enable z-buffering.
lpD3DDevice->SetRenderState(D3DRENDERSTATE_ZENABLE,
                            D3DZB_TRUE); // D3DZB_TRUE is the same as TRUE

Your application can also use the D3DRENDERSTATE_ZFUNC render state to control the comparison function that Direct3D uses when performing depth buffering.

Z-biasing is a method of displaying one surface in front of another even if their depth values are the same. You can use this technique for a variety of effects. A common example is rendering shadows on walls. Both the shadow and the wall have the same depth value. However, you want your application to show the shadow on the wall. Giving a z-bias to the shadow makes Direct3D display them properly (see D3DRENDERSTATE_ZBIAS).

[Visual Basic]

You can update the depth buffering state from a Visual Basic application with the D3DRENDERSTATE_ZENABLE render state, using one of the members of the CONST_D3DZBUFFERTYPE enumeration to specify the new state value.

If, for some reason, your application needs to prevent Direct3D from writing to the depth buffer, it can use the D3DRENDERSTATE_ZWRITEENABLE render state, specifying D3DZB_FALSE as the second parameter for the call to Direct3DDevice7.SetRenderState.

The following Visual Basic code fragment shows how the depth buffer state is set to enable z-buffering:

' This code fragment assumes that D3DDevice contains a valid
' reference to a Direct3DDevice7 object.

' Enable z-buffering.
Call D3DDevice.SetRenderState(D3DRENDERSTATE_ZENABLE, _
                              D3DZB_TRUE)

Your application can also use the D3DRENDERSTATE_ZFUNC render state to control the comparison function that Direct3D uses when performing depth buffering.

Z-biasing is a method of displaying one surface in front of another even if their depth values are the same. You can use this technique for a variety of effects. A common example is rendering shadows on walls. Both the shadow and the wall have the same depth value. However, you want your application to show the shadow on the wall. Giving a z-bias to the shadow makes Direct3D display them properly (see D3DRENDERSTATE_ZBIAS).


Ramp State

The D3DRENDERSTATE_MONOENABLE render state is not currently used. Ramp lighting is automatically enabled when an application uses a ramp device. For more information, see Legacy Device Types.


Subpixel Correction State

The D3DRENDERSTATE_SUBPIXEL and D3DRENDERSTATE_SUBPIXELX render states are not used, and are ignored by the system.


Plane Masking State

[Visual Basic]

Note Information in this topic pertains only to applications written in C++.

[C++]

Note The D3DRENDERSTATE_PLANEMASK render state is obsolete with the release of DirectX 7.0. To disable writes to the color buffer by using alpha blending, set D3DRENDERSTATE_SRCBLEND to D3DBLEND_ZERO and D3DRENDERSTATE_DESTBLEND to D3DBLEND_ONE.


Color Keying State

Setting a color key instructs Direct3D to treat the key color as transparent. When Direct3D applies a texture that was created with the DDSD_CKSRCBLT flag to a primitive, all texels that match the key color are not rendered on the primitive. Note that any textures that were not created with the DDSD_CKSRCBLT flag will not display color-key effects, even if they contain the color key.

[C++]

C++ applications set color keys with the IDirectDrawSurface7::SetColorKey method for the surface that will be using the color key (in this case, the render-target surface). However, color keying can be toggled on and off by calling the IDirect3DDevice7::SetRenderState method. Set the first parameter to D3DRENDERSTATE_COLORKEYENABLE. Your application should set the second parameter to TRUE to enable color keying and FALSE to disable it. The default is FALSE.

// This code fragment assumes that lpD3DDevice is a valid pointer to
// an IDirect3DDevice7 interface.

// Disable color keying.
lpD3DDevice->SetRenderState(D3DRENDERSTATE_COLORKEYENABLE,
                            FALSE);
[Visual Basic]

Applications written in Visual Basic set color keys with the DirectDrawSurface7.SetColorKey method for the surface that will be using the color key (in this case, the render-target surface). However, color keying can be toggled on and off by calling the Direct3DDevice7.SetRenderState method. Set the first parameter to D3DRENDERSTATE_COLORKEYENABLE. Your application should set the second parameter to True to enable color keying and False to disable it. The default is False.

' This code fragment assumes that D3DDevice contains a valid reference
' to a Direct3DDevice7 object.

' Disable color keying.
Call D3DDevice.SetRenderState(D3DRENDERSTATE_COLORKEYENABLE, _
                              FALSE)


Render Command Batching State

[Visual Basic]

Information in this topic pertains only to applications in C++.

[C++]

Note This render state obsolete, and is only useful to legacy applications that render with texture handles (using the IDirect3DDevice2 interface). Batched primitives are implicitly flushed when rendering with the IDirect3DDevice7 interface.


Stencil Buffer State

Applications use the stencil buffer to determine whether or not a pixel is written to the rendering target surface. For details, see Stencil Buffers.

[C++]

Applications written in C++ enable or disable stenciling by calling the IDirect3DDevice7::SetRenderState method. Pass D3DRENDERSTATE_STENCILENABLE as the value of the first parameter. Set the value of the second parameter to TRUE or FALSE to enable or disable it respectively.

Set the comparison function that Direct3D uses to perform the stencil test by invoking the IDirect3DDevice7::SetRenderState method. Set the value of the first parameter to D3DRENDERSTATE_STENCILFUNC. Pass a member of the D3DCMPFUNC enumerated type as the value of the second parameter.

The stencil reference value is the value in the stencil buffer that the stencil function uses for its test. By default, the stencil reference value is zero. Your application can set it by calling the IDirect3DDevice7::SetRenderState method. Pass D3DRENDERSTATE_STENCILREF as the value of the first parameter. Set the value of the second parameter to the new reference value.

Before Direct3D module performs the stencil test for any pixel, it does a bitwise AND of the stencil reference value and a stencil mask value. The result is then compared against the contents of the stencil buffer using the stencil comparison function. Your application can set the stencil mask. Use the IDirect3DDevice7::SetRenderState method, and pass D3DRENDERSTATE_STENCILMASK as the value of the first parameter. Set the value of the second parameter to the new stencil mask.

To set the action that Direct3D takes when the stencil test fails, invoke the IDirect3DDevice7::SetRenderState method and pass D3DRENDERSTATE_STENCILFAIL as the first parameter. The second parameter must be a member of the D3DSTENCILOP enumerated type.

Your application can also control how Direct3D responds when the stencil test passes but the z-buffer test fails. Call the IDirect3DDevice7::SetRenderState method and pass D3DRENDERSTATE_STENCILZFAIL as the first parameter and use a member of the D3DSTENCILOP enumerated type for the second parameter.

In addition, your program can control what Direct3D does when both the stencil test and the z-buffer test pass. Use the IDirect3DDevice7::SetRenderState method and pass D3DRENDERSTATE_STENCILPASS as the first parameter. Again, the second parameter must be a member of the D3DSTENCILOP enumerated type.

[Visual Basic]

You enable or disable stenciling in Visual Basic by calling the Direct3DDevice7.SetRenderState method. Pass D3DRENDERSTATE_STENCILENABLE as the value of the first parameter. Set the value of the second parameter to True or False to enable or disable it respectively.

Set the comparison function that Direct3D uses to perform the stencil test by invoking the Direct3DDevice7.SetRenderState method. Set the value of the first parameter to D3DRENDERSTATE_STENCILFUNC. Pass a member of the CONST_D3DCMPFUNC enumeration type as the value of the second parameter.

The stencil reference value is the value in the stencil buffer that the stencil function uses for its test. By default, the stencil reference value is zero. Your application can set it by calling the Direct3DDevice7.SetRenderState method. Pass D3DRENDERSTATE_STENCILREF as the value of the first parameter. Set the value of the second parameter to the new reference value.

Before Direct3D module performs the stencil test for any pixel, it performs a bitwise And operation of the stencil reference value and a stencil mask value. The result is then compared against the contents of the stencil buffer using the stencil comparison function. Your application can set the stencil mask by using the D3DRENDERSTATE_STENCILMASK render state. Set the render state value to the new stencil mask.

To set the action that Direct3D takes when the stencil test fails, invoke the Direct3DDevice7.SetRenderState method and pass D3DRENDERSTATE_STENCILFAIL as the first parameter. The second parameter must be a member of the CONST_D3DSTENCILOP enumeration.

Your application can also control how Direct3D responds when the stencil test passes but the z-buffer test fails. Call the Direct3DDevice7.SetRenderState method and pass D3DRENDERSTATE_STENCILZFAIL as the first parameter and use a member of the D3DSTENCILOP enumeration for the second parameter.

In addition, your program can control what Direct3D does when both the stencil test and the z-buffer test pass. Use the Direct3DDevice7.SetRenderState method and pass D3DRENDERSTATE_STENCILPASS as the first parameter. Again, the second parameter must be a member of the D3DSTENCILOP enumeration.


Primitive Clipping State

[C++]

Direct3D can clip primitives that render partially outside the viewport. When using C++, Direct3D clipping is controlled by the D3DRENDERSTATE_CLIPPING render state. Set this render state to TRUE (the default value) to enable primitive clipping. Set it to FALSE to disable Direct3D clipping services.

The primitive clipping render state is entirely independent of clipping operations that can be performed on vertices within a vertex buffer. The IDirect3DVertexBuffer7::ProcessVertices and IDirect3DVertexBuffer7::ProcessVerticesStrided methods accept their own flags to control primitive clipping during vertex processing.

Note This render state is analogous, albeit reciprocal, to the D3DDP_DONOTCLIP flag used in legacy rendering methods. This render state supersedes the D3DDP_DONOTCLIP flag for DirectX 7.0. Where the D3DDP_DONOTCLIP flag disabled clipping on a per-call basis, this render state affects all rendering calls until the state value is again changed by the application.

[Visual Basic]

Direct3D can clip primitives that render partially outside the viewport. In a Visual Basic application, Direct3D clipping is controlled by the D3DRENDERSTATE_CLIPPING render state. Set this render state to True (the default value) to enable primitive clipping. Set it to False to disable Direct3D clipping services.

The primitive clipping render state is entirely independent of clipping operations that can be performed on vertices within a vertex buffer. The Direct3DVertexBuffer7.ProcessVertices method accepts flags to control primitive clipping during vertex processing.


Lighting State

Applications that use the Direct3D geometry pipeline can enable or disable lighting calculations. Only vertices that contain a vertex normal will be properly lit; vertices with no normal will use a dot product of 0 in all lighting computations. This means that a vertex that doesn't use a normal will effectively receive no light. For more information, see Mathematics of Direct3D Lighting.

[C++]

Applications enable Direct3D lighting by setting the D3DRENDERSTATE_LIGHTING render state to TRUE, which is the default setting, and they disable Direct3D lighting by setting the render state to FALSE.

The lighting render state is entirely independent of lighting computations that can be performed on vertices within a vertex buffer. The IDirect3DVertexBuffer7::ProcessVertices and IDirect3DVertexBuffer7::ProcessVerticesStrided methods accept their own flags to control lighting calculations during vertex processing.

Note This render state is analogous, albeit reciprocal, to the D3DDP_DONOTLIGHT flag used in legacy rendering methods. This render state supersedes the D3DDP_DONOTLIGHT flag for DirectX 7.0. Where the D3DDP_DONOTLIGHT flag disabled lighting on a per-call basis, this render state affects all rendering calls until the state value is again changed by the application.

[Visual Basic]

Applications enable Direct3D lighting by setting the D3DRENDERSTATE_LIGHTING render state to True, which is the default setting, and they disable Direct3D lighting by setting the render state to False.

The lighting render state is entirely independent of lighting computations that can be performed on vertices within a vertex buffer. The IDirect3DVertexBuffer7::ProcessVertices and IDirect3DVertexBuffer7::ProcessVerticesStrided methods accept their own flags to control lighting calculations during vertex processing.

Note This render state is analogous, albeit reciprocal, to the D3DDP_DONOTLIGHT flag used in legacy rendering methods. This render state supersedes the D3DDP_DONOTLIGHT flag for DirectX 7.0. Where the D3DDP_DONOTLIGHT flag disabled lighting on a per-call basis, this render state affects all rendering calls until the state value is again changed by the application.


Extent Update State

[C++]

Direct3D supports updating the viewport extents to reflect the area of the viewport affected by rendering methods. In an application written with C++, the D3DRENDERSTATE_EXTENTS render state controls extents updates made by the system. The default setting for this state, FALSE, disables extent updates. Applications that intend to use the IDirect3DDevice7::GetClipStatus and IDirect3DDevice7::SetClipStatus methods to manipulate the viewport extents can enable extents updates by setting D3DRENDERSTATE_EXTENTS to TRUE.

The extents updates render state is entirely independent of extents updates that can be performed with a vertex buffer. The IDirect3DVertexBuffer7::ProcessVertices and IDirect3DVertexBuffer7::ProcessVerticesStrided methods accept their own flags to control extents updates during vertex processing.

Note This render state is analogous, albeit reciprocal, to the D3DDP_DONOTUPDATEEXTENTS flag used in legacy rendering methods. This render state supersedes the D3DDP_DONOTUPDATEEXTENTS flag for DirectX 7.0. Where the D3DDP_DONOTUPDATEEXTENTS flag disabled extent updates on a per-call basis, this render state affects all rendering calls until the state value is again changed by the application.

[Visual Basic]

Direct3D supports updating the viewport extents to reflect the area of the viewport affected by rendering methods. A Visual Basic application can use the D3DRENDERSTATE_EXTENTS render state to control extents updates made by the system. The default setting for this state, False, disables extent updates. Applications that intend to use the Direct3DDevice7.GetClipStatus and Direct3DDevice7.SetClipStatus methods to manipulate the viewport extents can enable extents updates by setting D3DRENDERSTATE_EXTENTS to True.

The extents updates render state is entirely independent of extents updates that can be performed with a vertex buffer. The Direct3DVertexBuffer7.ProcessVertices method accepts its own flags to control extents updates during vertex processing.


Ambient Lighting State

Ambient light is the surrounding light that comes from all directions. For specific information on how Direct3D used ambient light, see Direct Light vs. Ambient Light, and Mathematics of Direct3D Lighting.

[C++]

Your C++ application sets the color of the ambient lighting by invoking the IDirect3DDevice7::SetRenderState method and passing the enumerated value D3DRENDERSTATE_AMBIENT as the first parameter. The second parameter is a color in RGBA format. The default is zero.

// This code fragment assumes that lpD3DDevice is a valid pointer to
// an IDirect3DDevice7 interface.

// Set the ambient light.
D3DCOLOR d3dclrAmbientLightColor = D3DRGBA(1.0f,1.0f,1.0f,1.0f);
lpD3DDevice->SetRenderState(D3DRENDERSTATE_AMBIENT,
                            d3dclrAmbientLightColor);
[Visual Basic]

A Visual Basic application sets the color of the ambient lighting by invoking the Direct3DDevice7.SetRenderState method and passing the enumerated value D3DRENDERSTATE_AMBIENT as the first parameter. The second parameter is a color in RGBA format. The default is zero.

' This code fragment assumes that D3DDevice contains a valid
' reference to a Direct3DDevice7 object, and dx contains a
' valid reference to a DirectX7 object.
Dim AmbientLightColor As Long

' Set the ambient light.
AmbientLightColor = dx.CreateColorRGBA(1#, 1#, 1#, 1#)
Call D3DDevice.SetRenderState(D3DRENDERSTATE_AMBIENT, _
                              AmbientLightColor)


Per-vertex Color States

[C++]

Vertices of type D3DVERTEX, D3DLVERTEX, and D3DTLVERTEX cannot contain both color and normal information. Because the default shading mode is Gouraud shading, which depends on both vertex color and normal information, Direct3D did not use vertex color in the lighting calculations.

With the introduction of the flexible vertex format in DirectX 5.0, vertices can contain both vertex color and vertex normal information. By default, Direct3D uses this information when it calculates lighting. If you want your application to disable the use of vertex color lighting information, invoke the IDirect3DDevice7::SetRenderState method and pass D3DRENDERSTATE_COLORVERTEX as the first parameter. Set the second parameter to FALSE to disable vertex color lighting, or TRUE to enable it.

If per-vertex color is enabled, applications can configure the source from which the system retrieves color information for a vertex. The D3DRENDERSTATE_DIFFUSEMATERIALSOURCE, D3DRENDERSTATE_SPECULARMATERIALSOURCE, D3DRENDERSTATE_AMBIENTMATERIALSOURCE, and D3DRENDERSTATE_EMISSIVEMATERIALSOURCE render states control color sources for the diffuse, specular, ambient, and emissive color component sources. Each of these states can be set to members of the D3DMATERIALCOLORSOURCE enumerated type, which defines constants that instruct the system to use the current material, diffuse color, or specular color as the source for the specified color component.

[Visual Basic]

Vertices of type D3DVERTEX, D3DLVERTEX, and D3DTLVERTEX cannot contain both color and normal information. Because the default shading mode is Gouraud shading, which depends on both vertex color and normal information, Direct3D did not use vertex color in the lighting calculations.

When using flexible vertex formats, as opposed to the aforementioned vertex types, vertices can contain both vertex color and vertex normal information. By default, Direct3D uses this information when it calculates lighting. If you want your application to disable the use of vertex color lighting information, invoke the Direct3DDevice7.SetRenderState method and pass D3DRENDERSTATE_COLORVERTEX as the first parameter. Set the second parameter to False to disable vertex color lighting, or True to enable it.

If per-vertex color is enabled, applications can configure the source from which the system retrieves color information for a vertex. The D3DRENDERSTATE_DIFFUSEMATERIALSOURCE, D3DRENDERSTATE_SPECULARMATERIALSOURCE, D3DRENDERSTATE_AMBIENTMATERIALSOURCE, and D3DRENDERSTATE_EMISSIVEMATERIALSOURCE render states control color sources for the diffuse, specular, ambient, and emissive color component sources. Each of these states can be set to members of the CONST_D3DMATERIALCOLORSOURCE enumerated type, which defines constants that instruct the system to use the current material, diffuse color, or specular color as the source for the specified color component.


State Blocks

A state block in Direct3D Immediate Mode is a group of device states—render states, lighting and material parameters, transformation states, texture stage states, and current texture information—taken as a snapshot of the device's current state or explicitly recorded, that can be applied to a device in a single call. Device-state blocks can be optimized by the rendering device to accelerate the common sequences of state changes that your application requires, or can simply make applying device states easier.

The following topics in this section describe the key concepts of device state blocks, and provide information about how applications use them:

  • State Block Handles
  • Recording State Blocks
  • Capturing State Blocks
  • Applying State Blocks
  • Creating Predefined State Blocks
  • Deleting State Blocks


State Block Handles

State block handles are 32-bit values that uniquely identify a cached group of device states, and the associated state values, within the rendering device. These handles are used to apply states to the device, to capture the current state of the rendering device, and to delete the cached states when they are no longer needed.

[C++]

In C++, you receive a state-block handle when you finish recording a state block by calling the IDirect3DDevice7::EndStateBlock method, and when you capture a predefined set of device state data by calling the IDirect3DDevice7::CreateStateBlock method.

[Visual Basic]

In Visual Basic, you receive a state-block handle when you finish recording a state block by calling the Direct3DDevice7.EndStateBlock method, and when you capture a predefined set of device state data by calling the Direct3DDevice7.CreateStateBlock method.


Recording State Blocks

[C++]

The IDirect3DDevice7 interface offers the IDirect3DDevice7::BeginStateBlock method to record device states into a state block, as your application calls for them. The BeginStateBlock method causes the system to start recording device state changes into a state block, rather than applying them to the device. After you call BeginStateBlock, calls to any of the following methods will be recorded into a device state block:

  • IDirect3DDevice7::LightEnable
  • IDirect3DDevice7::SetClipPlane
  • IDirect3DDevice7::SetLight
  • IDirect3DDevice7::SetMaterial
  • IDirect3DDevice7::SetRenderState
  • IDirect3DDevice7::SetTexture
  • IDirect3DDevice7::SetTextureStageState
  • IDirect3DDevice7::SetTransform
  • IDirect3DDevice7::SetViewport

When you're done recording the state block, notify the system to stop recording by calling the IDirect3DDevice7::EndStateBlock method. The EndStateBlock method places the handle of the state block you recorded into the variable whose address you pass in the lpdwBlockHandle parameter. Your application will use this handle to apply the state block to the device as needed, to capture new state data into the block, and to delete the state block when it is no longer required.

[Visual Basic]

The Direct3DDevice7 object offers the Direct3DDevice7.BeginStateBlock method to record device states into a state block, as your application calls for them. The BeginStateBlock method causes the system to start recording device state changes into a state block, rather than applying them to the device. After you call BeginStateBlock, calls to any of the following methods will be recorded into a device state block:

  • Direct3DDevice7.LightEnable
  • Direct3DDevice7.SetClipPlane
  • Direct3DDevice7.SetLight
  • Direct3DDevice7.SetMaterial
  • Direct3DDevice7.SetRenderState
  • Direct3DDevice7.SetTexture
  • Direct3DDevice7.SetTextureStageState
  • Direct3DDevice7.SetTransform
  • Direct3DDevice7.SetViewport

When you're done recording the state block, notify the system to stop recording by calling the Direct3DDevice7.EndStateBlock method. The EndStateBlock method places the handle of the state block you recorded into the variable you pass in the blockHandle parameter. Your application will use this handle to apply the state block to the device as needed, to capture new state data into the block, and to delete the state block when it is no longer required.

Performance Note For best results, group all state changes tightly between an BeginStateBlock/EndStateBlock pair.

It is important to check the error code from the EndStateBlock method. If it fails, it is most likely because the display mode has changed (error code DDERR_SURFACELOST). Design your application to recover from this type of failure by recreating its surfaces and recording the state block again.


Capturing State Blocks

[C++]

The IDirect3DDevice7::CaptureStateBlock method updates the values within an existing state block to reflect the current state of the device. The method accepts a single parameter, dwBlockHandle, that identifies the state block which will receive the current state of the device if the call succeeds.

The IDirect3DDevice7::CaptureStateBlock method is especially useful to update a state block that your application has already recorded to include slightly different state settings. To do so, apply the existing state block, change the necessary settings, then capture the state of the system back into the state block. The following pseudo-code illustrates:

// The dwMyBlock variable contains a handle to a device-state block for
// a previously-recorded set of device states.

// Set the current state block.
d3dDevice->ApplyStateBlock(dwMyBlock);

// Change device states as needed.
.
.
.

// Capture the modified device state data back-into the existing block.
d3dDevice->CaptureStateBlock(dwMyBlock);

The CaptureStateBlock method doesn't capture the entire state of the device, it only updates the values for the states already within the state block. For example, imagine a state block that contains the following two operations, represented by psuedo-code:

SetRenderState(D3DRENDERSTATE_SHADEMODE, D3DSHADE_GOURAUD);
SetTexture(0, lpd3dAnyTexture);

If your application changed either of the preceding two settings since the state block was originally recorded, the IDirect3DDevice7::CaptureStateBlock method will update the states within the block—and only those states—to their new values.

[Visual Basic]

The Direct3DDevice7.CaptureStateBlock method updates the values within an existing state block to reflect the current state of the device. The method accepts a single parameter, blockHandle, that identifies the state block which will receive the current state of the device if the call succeeds.

The Direct3DDevice7.CaptureStateBlock method is especially useful to update a state block that your application has already recorded to include slightly different state settings. To do so, apply the existing state block, change the necessary settings, then capture the state of the system back into the state block. The following pseudo-code illustrates:

' The MyBlock variable contains a handle to a device-state block for
' a previously-recorded set of device states.

' Set the current state block.
Call d3dDevice.ApplyStateBlock(MyBlock)

' Change device states as needed.
.
.
.

' Capture the modified device state data back-into the existing block.
Call d3dDevice.CaptureStateBlock(MyBlock)

The CaptureStateBlock method doesn't capture the entire state of the device, it only updates the values for the states already within the state block. For example, imagine a state block that contains the following two operations, represented by psuedo-code:

Call SetRenderState(D3DRENDERSTATE_SHADEMODE, D3DSHADE_GOURAUD)
Call SetTexture(0, d3dAnyTexture)

If your application changed either of the preceding two settings since the state block was originally recorded, the Direct3DDevice7.CaptureStateBlock method will update the states within the block—and only those states—to their new values.


Applying State Blocks

[C++]

The IDirect3DDevice7::ApplyStateBlock method applies an existing state block to the device. The ApplyStateBlock method accepts a single parameter, dwBlockHandle, that identifies the state block to be applied.

Note You cannot apply a state block while recording another state block (that is, between calls to IDirect3DDevice7::BeginStateBlock and IDirect3DDevice7::EndStateBlock). Attempts to do so will fail, returning D3DERR_INBEGINSTATEBLOCK.

[Visual Basic]

The Direct3DDevice7.ApplyStateBlock method applies an existing state block to the device. The ApplyStateBlock method accepts a single parameter, blockHandle, that identifies the state block to be applied.

Note You cannot apply a state block while recording another state block (that is, between calls to Direct3DDevice7.BeginStateBlock and Direct3DDevice7.EndStateBlock). Attempts to do so will fail, returning D3DERR_INBEGINSTATEBLOCK.


Creating Predefined State Blocks

[C++]

The IDirect3DDevice7::CreateStateBlock method creates a new state block that contains the entire set of device states, or just those device-states related to vertex or pixel processing. The CreateStateBlock method accepts two parameters. The first parameter identifies the type of state information to be captured into the new state block, and the second parameter is the address of a variable that will receive a valid state-block handle if the call succeeds.

Valid values for the first parameter are defined by the D3DSTATEBLOCKTYPE enumerated type, which includes members that you can use to capture the entire set of device states (D3DSBT_ALL), or only those states that pertain to vertex or pixel processing (D3DSBT_VERTEX or D3DSBT_PIXEL). The following list summarizes the states that the system captures when you pass the D3DSBT_VERTEX or D3DSBT_PIXEL values:

  • Vertex-related States (D3DSBT_VERTEX)

    State (enabled or disabled) of all lights

    Transformation matrices

    User-defined clipping planes

    The values set for the following render states:
    D3DRENDERSTATE_AMBIENT

    D3DRENDERSTATE_AMBIENTMATERIALSOURCE

    D3DRENDERSTATE_CLIPPING

    D3DRENDERSTATE_CLIPPLANEENABLE

    D3DRENDERSTATE_COLORVERTEX

    D3DRENDERSTATE_CULLMODE

    D3DRENDERSTATE_DIFFUSEMATERIALSOURCE

    D3DRENDERSTATE_EMISSIVEMATERIALSOURCE

    D3DRENDERSTATE_EXTENTS

    D3DRENDERSTATE_FOGCOLOR

    D3DRENDERSTATE_FOGDENSITY

    D3DRENDERSTATE_FOGENABLE

    D3DRENDERSTATE_FOGEND

    D3DRENDERSTATE_FOGSTART

    D3DRENDERSTATE_FOGTABLEMODE

    D3DRENDERSTATE_FOGVERTEXMODE

    D3DRENDERSTATE_LIGHTING

    D3DRENDERSTATE_LOCALVIEWER

    D3DRENDERSTATE_NORMALIZENORMALS

    D3DRENDERSTATE_RANGEFOGENABLE

    D3DRENDERSTATE_SHADEMODE

    D3DRENDERSTATE_SPECULARENABLE

    D3DRENDERSTATE_SPECULARMATERIALSOURCE

    D3DRENDERSTATE_VERTEXBLEND

    The values set for the following texture-stage states:
    D3DTSS_TEXCOORDINDEX

    D3DTSS_TEXTURETRANSFORMFLAGS

  • Pixel-related States (D3DSBT_PIXEL)
    The values set for the following render states:
    D3DRENDERSTATE_ALPHABLENDENABLE

    D3DRENDERSTATE_ALPHAFUNC

    D3DRENDERSTATE_ALPHAREF

    D3DRENDERSTATE_ALPHATESTENABLE

    D3DRENDERSTATE_ANTIALIAS

    D3DRENDERSTATE_COLORKEYENABLE

    D3DRENDERSTATE_DESTBLEND

    D3DRENDERSTATE_DITHERENABLE

    D3DRENDERSTATE_EDGEANTIALIAS

    D3DRENDERSTATE_FILLMODE

    D3DRENDERSTATE_FOGDENSITY

    D3DRENDERSTATE_FOGEND

    D3DRENDERSTATE_FOGSTART

    D3DRENDERSTATE_LASTPIXEL

    D3DRENDERSTATE_LINEPATTERN

    D3DRENDERSTATE_SHADEMODE

    D3DRENDERSTATE_SRCBLEND

    D3DRENDERSTATE_STENCILENABLE

    D3DRENDERSTATE_STENCILFAIL

    D3DRENDERSTATE_STENCILFUNC

    D3DRENDERSTATE_STENCILMASK

    D3DRENDERSTATE_STENCILPASS

    D3DRENDERSTATE_STENCILREF

    D3DRENDERSTATE_STENCILWRITEMASK

    D3DRENDERSTATE_STENCILZFAIL

    D3DRENDERSTATE_STIPPLEDALPHA

    D3DRENDERSTATE_TEXTUREFACTOR

    D3DRENDERSTATE_TEXTUREPERSPECTIVE

    D3DRENDERSTATE_WRAP0 through D3DRENDERSTATE_WRAP7

    D3DRENDERSTATE_ZBIAS

    D3DRENDERSTATE_ZENABLE

    D3DRENDERSTATE_ZFUNC

    D3DRENDERSTATE_ZWRITEENABLE

    The values set for the following texture-stage states:
    D3DTSS_ADDRESS

    D3DTSS_ADDRESSU

    D3DTSS_ADDRESSV

    D3DTSS_ALPHAARG1

    D3DTSS_ALPHAARG2

    D3DTSS_ALPHAOP

    D3DTSS_BORDERCOLOR

    D3DTSS_BUMPENVLOFFSET

    D3DTSS_BUMPENVLSCALE

    D3DTSS_BUMPENVMAT00

    D3DTSS_BUMPENVMAT01

    D3DTSS_BUMPENVMAT10

    D3DTSS_BUMPENVMAT11

    D3DTSS_COLORARG1

    D3DTSS_COLORARG2

    D3DTSS_COLOROP

    D3DTSS_MAGFILTER

    D3DTSS_MAXANISOTROPY

    D3DTSS_MAXMIPLEVEL

    D3DTSS_MINFILTER

    D3DTSS_MIPFILTER

    D3DTSS_MIPMAPLODBIAS

    D3DTSS_TEXCOORDINDEX

    D3DTSS_TEXTURETRANSFORMFLAGS

[Visual Basic]

The Direct3DDevice7.CreateStateBlock method creates a new state block that contains the entire set of device states, or just those device-states related to vertex or pixel processing. The CreateStateBlock method accepts two parameters. The first parameter identifies the type of state information to be captured into the new state block, and the second parameter is the address of a variable that will receive a valid state-block handle if the call succeeds.

Valid values for the first parameter are defined by the CONST_D3DSTATEBLOCKTYPE enumeration, which includes members that you can use to capture the entire set of device states (D3DSBT_ALL), or only those states that pertain to vertex or pixel processing (D3DSBT_VERTEX or D3DSBT_PIXEL). The following list summarizes the states that the system captures when you pass the D3DSBT_VERTEX or D3DSBT_PIXEL values:

  • Vertex-related States (D3DSBT_VERTEX)

    State (enabled or disabled) of all lights

    Transformation matrices

    User-defined clipping planes

    The values set for the following render states:
    D3DRENDERSTATE_AMBIENT

    D3DRENDERSTATE_AMBIENTMATERIALSOURCE

    D3DRENDERSTATE_CLIPPING

    D3DRENDERSTATE_CLIPPLANEENABLE

    D3DRENDERSTATE_COLORVERTEX

    D3DRENDERSTATE_CULLMODE

    D3DRENDERSTATE_DIFFUSEMATERIALSOURCE

    D3DRENDERSTATE_EMISSIVEMATERIALSOURCE

    D3DRENDERSTATE_EXTENTS

    D3DRENDERSTATE_FOGCOLOR

    D3DRENDERSTATE_FOGDENSITY

    D3DRENDERSTATE_FOGENABLE

    D3DRENDERSTATE_FOGEND

    D3DRENDERSTATE_FOGSTART

    D3DRENDERSTATE_FOGTABLEMODE

    D3DRENDERSTATE_FOGVERTEXMODE

    D3DRENDERSTATE_LIGHTING

    D3DRENDERSTATE_LOCALVIEWER

    D3DRENDERSTATE_NORMALIZENORMALS

    D3DRENDERSTATE_RANGEFOGENABLE

    D3DRENDERSTATE_SHADEMODE

    D3DRENDERSTATE_SPECULARENABLE

    D3DRENDERSTATE_SPECULARMATERIALSOURCE

    D3DRENDERSTATE_VERTEXBLEND

    The values set for the following texture-stage states:
    D3DTSS_TEXCOORDINDEX

    D3DTSS_TEXTURETRANSFORMFLAGS

  • Pixel-related States (D3DSBT_PIXEL)
    The values set for the following render states:
    D3DRENDERSTATE_ALPHABLENDENABLE

    D3DRENDERSTATE_ALPHAFUNC

    D3DRENDERSTATE_ALPHAREF

    D3DRENDERSTATE_ALPHATESTENABLE

    D3DRENDERSTATE_ANTIALIAS

    D3DRENDERSTATE_COLORKEYENABLE

    D3DRENDERSTATE_DESTBLEND

    D3DRENDERSTATE_DITHERENABLE

    D3DRENDERSTATE_EDGEANTIALIAS

    D3DRENDERSTATE_FILLMODE

    D3DRENDERSTATE_FOGDENSITY

    D3DRENDERSTATE_FOGEND

    D3DRENDERSTATE_FOGSTART

    D3DRENDERSTATE_LASTPIXEL

    D3DRENDERSTATE_LINEPATTERN

    D3DRENDERSTATE_SHADEMODE

    D3DRENDERSTATE_SRCBLEND

    D3DRENDERSTATE_STENCILENABLE

    D3DRENDERSTATE_STENCILFAIL

    D3DRENDERSTATE_STENCILFUNC

    D3DRENDERSTATE_STENCILMASK

    D3DRENDERSTATE_STENCILPASS

    D3DRENDERSTATE_STENCILREF

    D3DRENDERSTATE_STENCILWRITEMASK

    D3DRENDERSTATE_STENCILZFAIL

    D3DRENDERSTATE_STIPPLEDALPHA

    D3DRENDERSTATE_TEXTUREFACTOR

    D3DRENDERSTATE_TEXTUREPERSPECTIVE

    D3DRENDERSTATE_WRAP0 through D3DRENDERSTATE_WRAP7

    D3DRENDERSTATE_ZBIAS

    D3DRENDERSTATE_ZENABLE

    D3DRENDERSTATE_ZFUNC

    D3DRENDERSTATE_ZWRITEENABLE

    The values set for the following texture-stage states:
    D3DTSS_ADDRESS

    D3DTSS_ADDRESSU

    D3DTSS_ADDRESSV

    D3DTSS_ALPHAARG1

    D3DTSS_ALPHAARG2

    D3DTSS_ALPHAOP

    D3DTSS_BORDERCOLOR

    D3DTSS_BUMPENVLOFFSET

    D3DTSS_BUMPENVLSCALE

    D3DTSS_BUMPENVMAT00

    D3DTSS_BUMPENVMAT01

    D3DTSS_BUMPENVMAT10

    D3DTSS_BUMPENVMAT11

    D3DTSS_COLORARG1

    D3DTSS_COLORARG2

    D3DTSS_COLOROP

    D3DTSS_MAGFILTER

    D3DTSS_MAXANISOTROPY

    D3DTSS_MAXMIPLEVEL

    D3DTSS_MINFILTER

    D3DTSS_MIPFILTER

    D3DTSS_MIPMAPLODBIAS

    D3DTSS_TEXCOORDINDEX

    D3DTSS_TEXTURETRANSFORMFLAGS

Note It is important to check the error code from the CreateStateBlock method. If it fails, it is most likely because the display mode has changed (error code DDERR_SURFACELOST). Your application should recover from this type of failure by recreating its surfaces, then recreating the state block.


Deleting State Blocks

[C++]

The IDirect3DDevice7::DeleteStateBlock deletes an existing state block, deallocating the memory used to contain it. The DeleteStateBlock method accepts the handle to the state block to be deleted at its only parameter. After deleting a state block, any handles to it are considered invalid, and can no longer be used.

[Visual Basic]

The Direct3DDevice7.DeleteStateBlock deletes an existing state block, deallocating the memory used to contain it. The DeleteStateBlock method accepts the handle to the state block to be deleted at its only parameter. After deleting a state block, any handles to it are considered invalid, and can no longer be used.


Using Devices

This section provides information about using Direct3D devices in a Direct3D Immediate Mode application. Information is divided into the following topics:

  • Enumerating Direct3D Devices
  • Creating a Direct3D Device
  • Setting Transformations
  • Rendering


Enumerating Direct3D Devices

Applications can query the hardware that they run on to detect which types of Direct3D devices it supports. This section contains information on two primary tasks involved in enumerating Direct3D Devices. Information is organized into the following topics:

  • Starting Device Enumeration
  • Selecting an Enumerated Device


Starting Device Enumeration

[C++]

A C++ application begins device enumeration by calling the IDirect3D7::EnumDevices method, which enumerates all the Direct3D devices that the hardware supports. Direct3D invokes the D3DEnumDevicesCallback7 function to select the device to be used. You supply the D3DEnumDevicesCallback7 function in your application. Because this callback function is supplied by your application, you can call it anything that you want.

The following code fragment illustrates the process of enumerating Direct3D devices. In this example, the device enumeration callback function is named EnumDeviceCallback. The code passes a pointer to EnumDeviceCallback to the IDirect3D7::EnumDevices method, which in turn calls EnumDeviceCallback for each device being enumerated, then returns. The callback can stop the enumeration before all devices have been enumerated by returning D3DENUMRET_CANCEL.

// In this code fragment, the variable lpd3d contains a valid
// pointer to the IDirect3D7 interface that the application obtained
// prior to executing this code.

BOOL fDeviceFound = FALSE;
hRes = lpd3d->EnumDevices(EnumDeviceCallback, &fDeviceFound);
if (FAILED(hRes))
{
    // Code to handle the error goes here.
}

if (!fDeviceFound)
{
    // Code to handle the error goes here.
}
[Visual Basic]

A Visual Basic application begins device enumeration by retrieving a reference to the Direct3DEnumDevices class by calling the Direct3D7.GetDevicesEnum method. The Direct3DEnumDevices class defines methods that retrieve the number of enumerated devices and information about each device.

The following code fragment illustrates the process of retrieving the Direct3DEnumDevices class:

' In this example, the d3d variable is a valid reference to a
' Direct3D7 class.
Dim d3dEnum As Direct3DEnumDevices

' Retrieve the enumerator class.
Set d3dEnum = d3d.GetDevicesEnum


Selecting an Enumerated Device

[C++]

In C++, Direct3D invokes the D3DEnumDevicesCallback7 function provided by the caller for each Direct3D device installed on the system. When it is called, its first and second parameters are strings that describe the device and provide the user-friendly device name.

The third parameter is a pointer to a D3DDEVICEDESC7 structure containing information about the hardware capabilities of the device. Even if the device being enumerated is a HAL device, the particular hardware may not support all the capabilities that Direct3D allows. The last parameter is a programmer-defined value. Your application passes this value to the IDirect3D7::EnumDevices method. It in turn passes this value to the D3DEnumDevicesCallback7 function.

The following code fragment illustrates how to create a D3DEnumDevicesCallback7 function. In this example, the application-supplied callback function is named EnumDeviceCallback. The EnumDeviceCallback function uses the following algorithm to choose an appropriate Direct3D device:

  1. Discard any devices that don't match the current display depth.
  2. Discard any devices that can't do Gouraud-shaded triangles.
  3. If a hardware device is found that passes the tests in points 1 and 2, use it. However, if the application is running in debug mode, it does not use the hardware device.

The code for the EnumDeviceCallback function is shown in the following example:

// This function is written with the assumption that the following
// global variables are declared in the program.
// DWORD                   g_dwDeviceBitDepth          = 0;
// GUID                    g_guidDevice;
// char                    g_szDeviceName[MAX_PATH];
// char                    g_szDeviceDesc[MAX_PATH];
// D3DDEVICEDESC7          g_d3dDeviceDesc;

static HRESULT WINAPI
EnumDeviceCallback(LPSTR            lpszDeviceDesc,
                   LPSTR            lpszDeviceName,
                   LPD3DDEVICEDESC7 lpd3dEnumDeviceDesc,
                   LPVOID           lpUserArg)
{
    BOOL fIsHardware = FALSE;

    fIsHardware = (lpd3dEnumDeviceDesc->dwDevCaps & D3DDEVCAPS_HWRASTERIZATION);

    // Does the device render at the depth we want?
    if ((lpd3dEnumDeviceDesc->dwDeviceRenderBitDepth & g_dwDeviceBitDepth) == 0)
    {
        // If not, skip this device.

        return D3DENUMRET_OK;
    }

    // The device must support Gouraud-shaded triangles.
    if (!(lpd3dEnumDeviceDesc->dpcTriCaps.dwShadeCaps &
          D3DPSHADECAPS_COLORGOURAUDRGB))
    {
        // No Gouraud shading. Skip this device.

        return D3DENUMRET_OK;
    }

    //
    // This device has the necessary capabilities. Save the details.
    //
    *(BOOL*)lpUserArg = TRUE;
    CopyMemory(&g_guidDevice, &lpd3dEnumDeviceDesc->deviceGUID, sizeof(GUID));
    strcpy(g_szDeviceDesc, lpszDeviceDesc);
    strcpy(g_szDeviceName, lpszDeviceName);
    CopyMemory(&g_d3dDeviceDesc, lpd3dEnumDeviceDesc,
               sizeof(D3DDEVICEDESC7));

    // If this is a hardware device, it has
    // the necessary capabilities.
    if (fIsHardware)
        return D3DENUMRET_CANCEL;

    // Otherwise, keep looking.

    return D3DENUMRET_OK;
}
[Visual Basic]

In Visual Basic, the Direct3DEnumDevices class enumerates the Direct3D devices installed on the system. Retrieve information about each device by querying the class, identifying devices enumerated within the class by their index. The first device is at index 1, the second is at 2, and so on. The Direct3DEnumDevices.GetCount method reports the number of enumerated devices and, therefore, the highest allowable index value.

Call the Direct3DEnumDevices.GetGuid method to retrieve the GUID for an enumerated device as a text string. The string differs from one device to another.

Call the Direct3DEnumDevices.GetName and Direct3DEnumDevices.GetDescription methods to retrieve text strings that contain the name and user-friendly description of the device.

Call the Direct3DEnumDevices.GetDesc methods to retrieve a description of the capabilities of the device, in the form of the D3DDEVICEDESC7 type. Even if the device being enumerated is a hardware device, the particular hardware might not support all of the capabilities that the Direct3D API allows.

The following code fragment illustrates how to create a function that calls the methods of the Direct3DEnumDevices class to determine device capabilities. In this example, the application-defined function uses the following algorithm to choose an appropriate Direct3D device:

  1. Discard any devices that don't match the current display depth.
  2. Discard any devices that can't do Gouraud-shaded triangles.
  3. If a hardware device is found that passes the tests in points 1 and 2, use it.
Private Sub EnumerateDevices(d3denum As Direct3DEnumDevices)
' For this example, the following global variables are assumed to be defined:
    '   g_lDeviceBitDepth is the desired bit depth (combination of CONST_DDBITDEPTHFLAGS constants).
    '   g_DeviceDesc contains the D3DDEVICEDESC7 for device capabilities.
    '   g_strDeviceGUID contains the GUID string for the device.
    '   g_strDeviceDescription contains the string for the device description text.
    '   g_strDeviceName contains the string for the device name.

    ' Local variables used to enumerate devices.
    Dim iDevice As Integer
    Dim DevDesc As D3DDEVICEDESC7
    Dim bIsHardware As Boolean

    ' Begin enumerating the devices.
    For iDevice = 1 To d3denum.GetCount
        Dim checkDesc As D3DDEVICEDESC7
        Call d3denum.GetDesc(iDevice, DevDesc)

        ' If there is no hardware support for this device
        bIsHardware = (DevDesc.lDevCaps Or D3DDEVCAPS_HWRASTERIZATION)

        ' Does the device render at the depth you want? If not, stop
        ' checking, and get the next device.
        If checkDesc.lDeviceRenderBitDepth And Not g_lDeviceBitDepth Then
            GoTo NEXT_DEVICE
        End If

        ' The device must support Gouraud-shaded triangles.
        If (Not checkDesc.dpcTriCaps.lShadeCaps And D3DPSHADECAPS_COLORGOURAUDRGB) Then
            ' No Gouraud shading in RGB mode. Skip this device.
            GoTo NEXT_DEVICE
        End If

        '
        ' By the time you get here, you know that this is a device you
        ' are interested in. Place the results in the global variables.
        '
        g_strDeviceGUID = d3denum.GetGuid(iDevice)
        g_strDeviceDescription = d3denum.GetDescription(iDevice)
        g_strDeviceName = d3denum.GetName(iDevice)
        g_DeviceDesc = DevDesc

        ' If this current device is hardware accelerated,
        ' you have found what you are looking for.
        If bIsHardware = True Then Exit For

        ' Otherwise, keep looking.
NEXT_DEVICE:
    Next iDevice
End Sub ' EnumerateDevices


Creating a Direct3D Device

Important Performance Note All rendering devices created by a given Direct3D object share the same physical resources. Although your application can create multiple rendering devices from a single Direct3D object, because they share the same hardware, extreme performance penalties will be incurred.

[C++]

To create a Direct3D device in a C++ application, your application must first create a DirectDraw object by calling the DirectDrawCreateEx function and obtain a pointer to the IDirect3D7 interface. For details, see Accessing Direct3D. It must then call the IDirect3D7::CreateDevice method to create a Direct3D device. This method passes a pointer to the IDirect3DDevice7 interface to your application.

The following illustration shows the process for creating a Direct3D device in C++.

Note As discussed in Accessing Direct3D, the DirectDraw component comprises two COM objects. The newest object—called DirectDraw7 and created by calling the DirectDrawCreateEx function—is the only object that exposes the IDirect3D7 interface. It is the only object capable of spawning a Direct3D device that exposes the IDirect3DDevice7 interface. The Direct3DDevice object created in this manner does not expose legacy Direct3D interfaces. Applications that require previous iterations of the Direct3D device interface must use the DirectDrawCreate method to create a DirectDraw object, and then create the desired legacy objects.

This code fragment illustrates the process of creating a Direct3D rendering device that supports the IDirect3Device7 interface:

LPDIRECTDRAW7    lpDD;              // IDirectDraw7 Interface
LPDIRECT3D7     lpD3D;              // IDirect3D7 Interface
LPDIRECTDRAWSURFACE7  lpddsRender;  // Rendering surface
LPDIRECT3DDEVICE7     lpd3dDevice;  // D3D Device
HRESULT hr;

// Create DirectDraw interface.
// Use the current display driver.
hr = DirectDrawCreateEx (NULL, (void **)&lpDD, IID_IDirectDraw7, NULL);
if (FAILED (hr))
{
    // Code to handle the error goes here.
}

// Get an IDirect3D7 interface
hr =
    lpDD->QueryInterface (IID_IDirect3D7, (void **)&lpD3D);
if (FAILED (hr))
{
    // Code to handle the error goes here.
}

//
// Code for the following tasks is omitted for clarity.
//
// Applications must set the cooperative level at this point.
// Full-screen applications probably need to set the display
// mode.
// The primary surface should be created here.
// The rendering surface must be created at this point. It is
// assumed in this code fragment that, once created, the rendering
// surface is pointed to by the variable lpddsRender.
// If a z-buffer is being used, it should be created here.
// Direct3D device enumeration can be done at this point.

hr = lpD3D->CreateDevice (IID_IDirect3DHALDevice,
                               lpddsRender,
                               &lpd3dDevice,
                               NULL);

The preceding sample invokes the IDirect3D7::CreateDevice method to create the Direct3D device. In the case of this sample, a Direct3D HAL device is created if the call is successful.

The target DirectDraw rendering surface that your application creates must be created to be used as a Direct3D rendering target. To do this, it must pass a DDSURFACEDESC2 structure to the IDirectDraw7::CreateSurface method. The DDSURFACEDESC2 structure has a member called ddsCaps, which is a structure of type DDSCAPS2. The DDSCAPS2 structure contains a member named dwCaps, which must be set to DDSCAPS_3DDEVICE when IDirectDraw7::CreateSurface is invoked.

When it is used with a hardware-accelerated rendering device, the render-target surface that you use must be created in display memory (with the DDSCAPS_VIDEOMEMORY flag). Otherwise, it must be created in system memory (using the DDSCAPS_SYSTEMMEMORY flag).

Note Some popular hardware devices require that the render target and depth buffer surfaces use the same bit depth. On such hardware, if your application uses a 16-bit render-target surface, the attached depth buffer must also be 16 bits. For a 32-bit render-target surface, the depth buffer must be 32 bits, of which 8 bits can be used for stencil buffering (if needed).

If the hardware upon which your application is running has this requirement and your application fails to meet it, any attempts to create a rendering device that uses the noncompliant surfaces fail. Use the DirectDraw method, IDirectDraw7::GetDeviceIdentifier to track hardware that imposes this limitation.

[Visual Basic]

To create a Direct3D device, your application must first initialize the DirectDraw object in the normal manner and obtain a reference to the Direct3D7 class. For details, see Accessing Direct3D. It must then call the Direct3D7.CreateDevice method to create a Direct3D device. The method returns a reference to a Direct3DDevice7 class object.

The following figure illustrates the process for creating a Direct3D device from a Visual Basic application:

The following code fragment illustrates this process:

' For this example, the g_dx variable contains a valid
' reference to a DirectX7 object.
Private Sub Test()
    On Local Error Resume Next

    Dim ddraw As DirectDraw7        ' DirectDraw7 class
    Dim d3d As Direct3D7            ' Direct3D3 class
    Dim ddsRender As DirectDrawSurface7 ' Rendering surface
    Dim d3dDev As Direct3DDevice7   '  Direct3D Device

    ' Create DirectDraw7 object.
    ' Use the current display driver.
    Set ddraw = g_dx.DirectDrawCreate("")
    If Err.Number <> DD_OK Then
        ' Code to handle the error goes here.
    End If

    ' Get a Direct3D7 object.
    Set d3d = ddraw.GetDirect3D
    If Err.Number <> DD_OK Then
        ' Code to handle the error goes here.
    End If

    '
    ' Code for the following tasks is omitted for clarity.
    '
    ' + Applications need to set the cooperative level at this point.
    ' + Full-screen applications probably need to set the display
    '   mode.
    ' + The primary surface should be created here.
    ' + The rendering surface must be created at this point. It is
    '   assumed in this code fragment that, once created, the
    '   rendering surface is referred to by the variable ddsRender.
    ' + If a depth-buffer is being used, it should be created here.
    ' + Direct3D device enumeration can be done at this point.

    Set d3dDev = d3d.CreateDevice("IID_IDirect3DHALDevice", ddsRender)
End Sub

This code fragment invokes the Direct3D7.CreateDevice method to create the Direct3D device. In this case, a Direct3D HAL device is created if the call is successful.

The target DirectDraw rendering surface that your application creates must be created for use as a Direct3D rendering target. To do this, it must pass a DDSURFACEDESC2 variable to the DirectDraw7.CreateSurface method. The DDSURFACEDESC2 type has a member called ddsCaps, which is of type DDSCAPS2. The DDSCAPS2 type contains a member named lCaps, which must be set to DDSCAPS_3DDEVICE when DirectDraw7.CreateSurface is invoked.

To be used with a hardware-accelerated rendering device, the render-target surface that you use must be created in display memory (with the DDSCAPS_VIDEOMEMORY flag). Otherwise, it must be created in system memory (using the DDSCAPS_SYSTEMMEMORY flag).

Note Some popular hardware devices require that the render target and depth buffer surfaces use the same bit depth. On such hardware, if your application uses a 16-bit render-target surface, the attached depth buffer must also be 16 bits. For a 32-bit render-target surface, the depth buffer must be 32 bits, of which 8 bits can be used for stencil buffering, if needed.

If the hardware upon which your application is running has this requirement and your application fails to meet it, any attempts to create a rendering device that uses the noncompliant surfaces fail.


Setting Transformations

[C++]

In C++, transformations are applied by using the IDirect3DDevice7::SetTransform method. For example, you can use code like the following to set the view transformation:

    HRESULT hr
    D3DMATRIX  view;

    // Fill in the view matrix.

    hr = lpDev->SetTransform(D3DTRANSFORMSTATE_VIEW, &view);

    if(FAILED(hr)){
        // Code to handle the error goes here.
    }

There are several possible settings for the first parameter in a call to IDirect3DDevice7::SetTransform. The most common are D3DTRANSFORMSTATE_WORLD, D3DTRANSFORMSTATE_VIEW, and D3DTRANSFORMSTATE_PROJECTION. These transformation states are defined in the D3DTRANSFORMSTATETYPE enumerated type. This enumeration also contains values to set transformations to be applied to texture coordinates: the D3DTRANSFORMSTATE_TEXTURE1 through D3DTRANSFORMSTATE_TEXTURE7 states.

[Visual Basic]

In Visual Basic, transformations are applied by using the Direct3DDevice7.SetTransform method. For example, you could use code like the following to set the view transformation:

    On Local Error Resume Next
    Dim view As D3DMATRIX

    ' Fill in the view matrix.
    Call d3dDev.SetTransform(D3DTRANSFORMSTATE_VIEW, view)

    If Err.Number <> DD_OK Then
        ' Code to handle the error goes here.
    End If

There are several possible settings for the first parameter in a call to Direct3DDevice7.SetTransform. The most common are D3DTRANSFORMSTATE_WORLD, D3DTRANSFORMSTATE_VIEW, and D3DTRANSFORMSTATE_PROJECTION. These transformation states are defined in the CONST_D3DTRANSFORMSTATETYPE enumeration. This enumeration also contains values to set transformations to be applied to texture coordinates: the D3DTRANSFORMSTATE_TEXTURE1 through D3DTRANSFORMSTATE_TEXTURE7 states.


Rendering

Applications use the DrawPrimitive family of methods to render a 3-D scene. The DrawPrimitive architecture is recommended over the legacy execute-buffer rendering model. As a result, the following topics discuss rendering with DrawPrimitive:

  • Grouping Vertices
  • Beginning and Ending a Scene
  • Clearing Surfaces
  • Rendering Primitives
  • Primitive Types
  • Render States


Grouping Vertices

You can group vertices for a primitive in two basic ways:

  • In an array that includes all vertices for the primitive in order.
  • In an unordered array of vertices, accompanied by an ordered array of values, where each value is the index of a vertex in the unordered array. Primitives of this type are sometimes referred to as indexed primitives.

The DrawPrimitive architecture makes it possible to render groups of vertices that define a primitive in a single call or to render the vertices that comprise a primitive one by one. For more information, see Rendering Primitives.


Beginning and Ending a Scene

[C++]

Applications written in C++ notify Direct3D that scene rendering is about to begin by calling the IDirect3DDevice7::BeginScene method. BeginScene causes the system to check its internal data structures, the availability and validity of rendering surfaces, and sets an internal flag to signal that a scene is in progress. After you begin a scene, you can call the various rendering methods to render the primitives or individual vertices that make up the objects in the scene. Attempts to call rendering methods when a scene is not in progress fail, returning D3DERR_SCENE_NOT_IN_SCENE. For more information, see Rendering Primitives.

After you complete the scene, call the IDirect3DDevice7::EndScene method. The EndScene method clears an internal flag that signals when a scene is in progress, flushes cached data, and verifies the integrity of the rendering surfaces.

All rendering methods must be bracketed by calls to the BeginScene and EndScene methods. If surfaces are lost or internal errors occur, the scene methods return error values. If BeginScene fails, the scene does not begin, and subsequent calls to EndScene will fail. When surfaces are lost during rendering, EndScene will return DDERR_SURFACELOST. If surfaces were not successfully restored before calling BeginScene, then BeginScene will also return DDERR_SURFACELOST.

To summarize these cases:

  • If BeginScene returns any error, you must not call EndScene because the scene has not successfully begun.
  • If BeginScene succeeds, but you get an error while rendering of the scene, you must call EndScene.
  • If EndScene fails, for any reason, you need not call it again.

For example, some simple scene code might look like this:

HRESULT hr;

if(SUCCEEDED(lpDevice->BeginScene()))
{
    // Render primitives only if the scene
    // starts successfully.

    // Close the scene.
    hr = lpDevice->EndScene();
    if(FAILED(hr))
        return hr;
}

You cannot embed scenes; that is, you must complete rendering a scene before you can begin another one. Calling IDirect3DDevice7::EndScene when IDirect3DDevice7::BeginScene has not been called returns the D3DERR_SCENE_NOT_IN_SCENE error value. Likewise, calling BeginScene when a previous scene has not been completed (with the EndScene method) results in the D3DERR_SCENE_IN_SCENE error.

Do not attempt to call GDI functions on DirectDraw surfaces, such as the render target or textures, while a scene is being rendered (between BeginScene and EndScene calls). Attempts to do so can prevent the results of the GDI operations from being visible. If your application uses GDI functions, be sure that all GDI calls are made outside the scene functions.

[Visual Basic]

Visual Basic applications notify Direct3D that scene rendering is about to begin by calling the Direct3DDevice7.BeginScene method. BeginScene causes the system to check its internal data structures, the availability and validity of rendering surfaces, and sets an internal flag to signal that a scene is in progress. After you begin a scene, you can call the various rendering methods to render the primitives or individual vertices that make up the objects in the scene. Attempts to call rendering methods when a scene is not in progress fail, returning the D3DERR_SCENE_NOT_IN_SCENE error. For more information, see Rendering Primitives.

After you complete the scene, call the Direct3DDevice7.EndScene method. The EndScene method clears an internal flag that signals when a scene is in progress, flushes cached data, and verifies the integrity of the rendering surfaces.

All rendering methods must be bracketed by calls to the BeginScene and EndScene methods. If surfaces are lost or internal errors occur, the scene methods fail and Err.Number will be set to an error code. If BeginScene fails, the scene does not begin, and subsequent calls to EndScene will fail. When surfaces are lost during rendering, EndScene will fail, raising the DDERR_SURFACELOST error. If surfaces were not successfully restored before calling BeginScene, then BeginScene will also return DDERR_SURFACELOST.

To summarize these cases:

  • If BeginScene returns any error, you must not call EndScene because the scene has not successfully begun.
  • If BeginScene succeeds, but you get an error while rendering of the scene, you must call EndScene.
  • If EndScene fails, for any reason, you need not call it again.

For example, some simple scene code might look like this:

On Local Error Resume Next

Call d3dDev.BeginScene
If Err.Number = DD_OK Then
    ' Render primitives only if the scene
    ' starts successfully.

    ' Close the scene.
    Call d3dDev.EndScene
    If Err.Number <> DD_OK Then
        ' Code to handle error goes here.
    End If
End If

You cannot embed scenes; that is, you must complete rendering a scene before you can begin another one. Calling Direct3DDevice7.EndScene when Direct3DDevice7.BeginScene has not been called causes a D3DERR_SCENE_NOT_IN_SCENE error. Likewise, calling BeginScene when a previous scene has not been completed (with the EndScene method) results in the D3DERR_SCENE_IN_SCENE error.

Do not attempt to call GDI functions on DirectDraw surfaces, such as the render target or textures, while a scene is being rendered (between BeginScene and EndScene calls). Attempts to do so can prevent the results of the GDI operations from being visible. If your application uses GDI functions, make sure that all GDI calls are made outside the scene functions.


Clearing Surfaces

Before rendering objects in a scene, clear the viewport on the render-target surface (or a subset of the viewport). Clearing the viewport causes the system to set the desired portion of the render-target surface and any attached depth or stencil buffers to a desired state. This resets the areas of the surface that will be rendered again and resets the corresponding areas of the depth and stencil buffers, if any are in use. Clearing a render-target surface can set the desired region to a default color or texture. For depth and stencil buffers, this can set a depth or stencil value.

[C++]

The IDirect3DDevice7 interface offers the IDirect3DDevice7::Clear method to clear the viewport. For more information about using these methods, see Clearing a Viewport in the Viewports and Clipping section.

[Visual Basic]

The Direct3DDevice7 Visual Basic class offers the Direct3DDevice7.Clear method to clear the viewport. For more information about using these methods, see Clearing a Viewport in the Viewports and Clipping section.

Optimization Note Applications that render scenes covering the entire area of the render-target surface can improve performance by clearing the attached depth and stencil buffer surfaces (if any) instead of the render target. In this case, clearing the depth buffer causes Direct3D to rewrite the render target on the next rendered frame, making an explicit clear operation on the render target redundant. However, if your application renders only to a portion of the render-target surface, explicit clear operations are required.


Rendering Primitives

The following topics introduce the DrawPrimitive rendering methods and provides information about using them in your application:

  • DrawPrimitive Methods
  • Rendering Strided Vertices


DrawPrimitive Methods

[C++]

Direct3D offers several methods to render primitives and indexed primitives in a single call. All rendering methods in the IDirect3DDevice7 interface accept a combination of flexible vertex format flags that describe the vertex type your application uses; these flags also determine which parts of the geometry pipeline the system will apply. (This differs from the version of the methods in the IDirect3DDevice2, which accept only the concrete vertex formats identified by members of the D3DPRIMITIVETYPE enumeration.) For more information about these descriptors, see Vertex Formats.

The DrawPrimitive family of rendering methods offers the following rendering methods, organized into the following groups:

Basic rendering
IDirect3DDevice7::DrawPrimitive and IDirect3DDevice7::DrawIndexedPrimitive
Vertex buffer rendering
IDirect3DDevice7::DrawPrimitiveVB and IDirect3DDevice7::DrawIndexedPrimitiveVB
Strided vertices
IDirect3DDevice7::DrawPrimitiveStrided and IDirect3DDevice7::DrawIndexedPrimitiveStrided. Vertex buffers can be used to render strided vertices, but the vertices must be processed with the IDirect3DVertexBuffer7::ProcessVerticesStrided method.

When you render a primitive, the associated methods accept parameters that describe the type of primitive being rendered (such as a triangle strip, a triangle list, or another primitive type), the vertex format, rendering behavior flags, and vertex information. These flags and their effects are documented in the references for the rendering methods.

Note that the number of vertices you need to provide for the methods depends on the type of primitive you are rendering. For instance, if you're rendering a line list, you must provide at least two vertices to define a single line, and the total number must be an even value. Likewise for a triangle list, you must include at least three vertices, with the total evenly divisible by three. For information about vertex counts for other types of primitives, see Primitive Types and D3DPRIMITIVETYPE.

Vertex buffers, and the methods to render from them, provide performance and ease-of-use enhancements that improve upon rendering vertices from your own data structures. For more information, see Vertex Buffers.

[Visual Basic]

Direct3D offers Visual Basic applications several methods to render primitives in a single call. All rendering methods in the Direct3DDevice7 class accept a combination of flexible vertex format flags that describe the vertex type your application uses; these flags also determine which parts of the geometry pipeline the system will apply. For more information about these descriptors, see Vertex Formats.

The DrawPrimitive family of rendering methods offers the following rendering methods, organized into the following groups:

Basic rendering
Direct3DDevice7.DrawPrimitive and Direct3DDevice7.DrawIndexedPrimitive
Vertex buffer rendering
Direct3DDevice7.DrawPrimitiveVB and Direct3DDevice7.DrawIndexedPrimitiveVB

When you render a primitive, the associated methods accept parameters that describe the type of primitive being rendered (such as a triangle strip, a triangle list, or another primitive type), the vertex format, rendering behavior flags, and vertex information. These flags and their effects are documented in the references for the rendering methods.

Note that the number of vertices you need to provide for the methods depends on the type of primitive you are rendering. For instance, if you're rendering a line list, you must provide at least two vertices to define a single line, and the total number must be an even value. Likewise for a triangle list, you must include at least three vertices, with the total evenly divisible by three. For information about vertex counts for other types of primitives, see Primitive Types and CONST_D3DPRIMITIVETYPE.

Vertex buffers, and the methods to render from them, provide performance and ease-of-use enhancements that improve upon rendering vertices from your own data structures. For more information, see Vertex Buffers.

Note DirectX for Visual Basic does not support rendering strided vertices.


Rendering Strided Vertices

[Visual Basic]

Note The information in this topic applies only to applications written in C++. DirectX for Visual Basic does not support rendering with strided vertices.

[C++]

Because of the indirection provided by strided vertices—detailed in the Strided Vertex Format section—applications must take care to set up the vertices properly. Often, developers forget to include a vertex component in the associated D3DDRAWPRIMITIVESTRIDEDDATA structures. This oversight doesn't necessarily cause the rendering methods to fail, but can result in "missing" geometry that is difficult to troubleshoot.

The following code shows one way that you might set up and render strided vertices:

//---------------------------------------------
// A custom vertex format that includes XYZ, a
// diffuse color & two sets of texture coords.
//---------------------------------------------
struct MTVERTEX
{
    FLOAT x, y, z;
    DWORD dwColor;
    FLOAT tuBase, tvBase;
    FLOAT tuLightMap, tvLightMap;
};

// Make an array of custom vertices.
MTVERTEX g_avVertices[36];
// Fill the array.
//  (vertex at index 0)
//  .
//  .
//  .
//  (vertex at index 35)

// Construct strided vertices vertex using the array of
// custom vertices already defined.
D3DDRAWPRIMITIVESTRIDEDDATA g_StridedData;

// Assign the addresses of the various interleaved components
// to their corresponding strided members.
g_StridedData.position.lpvData          = &g_avWallVertices[24].x;
g_StridedData.diffuse.lpvData           = &g_avWallVertices[24].dwColor;
g_StridedData.textureCoords[0].lpvData  = &g_avWallVertices[24].tuBase;
g_StridedData.textureCoords[1].lpvData  = &g_avWallVertices[24].tuLightMap;
g_StridedData.position.dwStride         = sizeof(MTVERTEX);
g_StridedData.diffuse.dwStride          = sizeof(MTVERTEX);
g_StridedData.textureCoords[0].dwStride = sizeof(MTVERTEX);
g_StridedData.textureCoords[1].dwStride = sizeof(MTVERTEX);

// Render the vertices with multiple texture blending (Modulate).
g_pd3dDevice->SetTextureStageState( 1, D3DTSS_COLOROP, D3DTOP_MODULATE );
g_pd3dDevice->SetTexture( 0, g_BaseTextureMap);
g_pd3dDevice->SetTexture( 1, g_LightMap);
g_pd3dDevice->DrawPrimitiveStrided( D3DPT_TRIANGLELIST,
                        D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX2,
                        &g_StridedData, 12, NULL );


Primitive Types

Direct3D can create and manipulate the following types of primitives:

  • Point Lists
  • Line Lists
  • Line Strips
  • Triangle Lists
  • Triangle Strips
  • Triangle Fans
[C++]

You can render these primitive types from a C++ application with any of the rendering methods of the IDirect3DDevice7 interface. For more information, see Rendering. (Note that you cannot render point lists with the indexed-primitive rendering methods.)

[Visual Basic]

You can render all of these primitive types from a Visual Basic application with any of the rendering methods of the Direct3DDevice7 interface. For more information, see Rendering.


Point Lists

A point list is a collection of vertices that are rendered as isolated points. Your application can use them in 3-D scenes for star fields, or dotted lines on the surface of a polygon. Applications create a point list by filling an array of vertices.

[C++]

The following C++ code fragment illustrates the process of constructing a point list:

const DWORD TOTAL_VERTS=6;
D3DVERTEX lpVerts[TOTAL_VERTS];

lpVerts[0] = D3DVERTEX(D3DVECTOR(-5,-5,0),D3DVECTOR(0,0,-1),0,0);
lpVerts[1] = D3DVERTEX(D3DVECTOR(0,5,0),D3DVECTOR(0,0,-1),0,0);
lpVerts[2] = D3DVERTEX(D3DVECTOR(5,-5,0),D3DVECTOR(0,0,-1),0,0);
lpVerts[3] = D3DVERTEX(D3DVECTOR(10,5,0),D3DVECTOR(0,0,-1),0,0);
lpVerts[4] = D3DVERTEX(D3DVECTOR(15,-5,0),D3DVECTOR(0,0,-1),0,0);
lpVerts[5] = D3DVERTEX(D3DVECTOR(20,5,0),D3DVECTOR(0,0,-1),0,0);

Render the point list using the IDirect3DDevice7::DrawPrimitive method. The following code fragment illustrates the use of IDirect3DDevice7::DrawPrimitive for drawing the point list in the preceding example. All calls to IDirect3DDevice7::DrawPrimitive must occur between IDirect3DDevice7::BeginScene and IDirect3DDevice7::EndScene.

HRESULT hResult;
// This code fragment assumes that lpDirect3DDevice is a valid
// pointer to an IDirect3DDevice7 interface.
hResult =
    lpDirect3DDevice->DrawPrimitive(D3DPT_POINTLIST,
                                     D3DFVF_VERTEX,
                                     lpVerts,
                                     TOTAL_VERTS,
                                     D3DDP_WAIT);
[Visual Basic]

An application written in Visual Basic creates a point list by filling an array of vertices, as in the following code fragment:

' This code fragment assumes that dx is a valid reference
' to a DirectX7 object.
On Local Error Resume Next
Const TOTAL_VERTS As Integer = 6
Dim Verts(TOTAL_VERTS) As D3DVERTEX

Verts(0) = dx.CreateD3DVertex(-5, -5, 0, 0, 0, -1, 0, 0)
Verts(1) = dx.CreateD3DVertex(0, 5, 0, 0, 0, -1, 0, 0)
Verts(2) = dx.CreateD3DVertex(5, -5, 0, 0, 0, -1, 0, 0)
Verts(3) = dx.CreateD3DVertex(10, 5, 0, 0, 0, -1, 0, 0)
Verts(4) = dx.CreateD3DVertex(15, -5, 0, 0, 0, -1, 0, 0)
Verts(5) = dx.CreateD3DVertex(20, 5, 0, 0, 0, -1, 0, 0)

Render the point list using the Direct3DDevice7.DrawPrimitive method. The following code fragment illustrates the use of Direct3DDevice7.DrawPrimitive for drawing the point list in the preceding example. All calls to Direct3DDevice7.DrawPrimitive must occur between Direct3DDevice7.BeginScene and Direct3DDevice7.EndScene.

' This code fragment assumes that d3ddev is a valid
' reference to an Direct3DDevice7 object.
Call d3ddev.DrawPrimitive(D3DPT_POINTLIST, _
                          D3DFVF_VERTEX, _
                          Verts(0), _
                          TOTAL_VERTS, _
                          D3DDP_WAIT)

If Err.Number <> DD_OK Then
    ' Code to handle error goes here.
End If

The following illustration shows the resulting points.

Your application can apply materials and textures to a point list. The colors in the material or texture only appear at the points drawn, and not anywhere between the points.


Line Lists

A line list is a list of isolated, straight line segments. Line lists are useful for such tasks as adding sleet or heavy rain to a 3-D scene. Applications create a line list by filling an array of vertices. The number of vertices in a line list must be greater than or equal to two, and it must be even.

[C++]

The following code fragment illustrates how this task is accomplished from C++:

const DWORD TOTAL_VERTS=6;
D3DVERTEX lpVerts[TOTAL_VERTS];

lpVerts[0] = D3DVERTEX(D3DVECTOR(-5,-5,0),D3DVECTOR(0,0,-1),0,0);
lpVerts[1] = D3DVERTEX(D3DVECTOR(0,5,0),D3DVECTOR(0,0,-1),0,0);
lpVerts[2] = D3DVERTEX(D3DVECTOR(5,-5,0),D3DVECTOR(0,0,-1),0,0);
lpVerts[3] = D3DVERTEX(D3DVECTOR(10,5,0),D3DVECTOR(0,0,-1),0,0);
lpVerts[4] = D3DVERTEX(D3DVECTOR(15,-5,0),D3DVECTOR(0,0,-1),0,0);
lpVerts[5] = D3DVERTEX(D3DVECTOR(20,5,0),D3DVECTOR(0,0,-1),0,0);

Render the line list using the IDirect3DDevice7::DrawPrimitive method. The following code fragment illustrates the use of IDirect3DDevice7::DrawPrimitive for drawing the line list in the preceding example. Remember that all calls to IDirect3DDevice7::DrawPrimitive must occur between IDirect3DDevice7::BeginScene and IDirect3DDevice7::EndScene.

HRESULT hResult;
// This code fragment assumes that lpDirect3DDevice is a valid
// pointer to an IDirect3DDevice7 interface.
hResult =
    lpDirect3DDevice->DrawPrimitive(D3DPT_LINELIST,
                                      D3DFVF_VERTEX,
                                      lpVerts,
                                      TOTAL_VERTS,
                                      D3DDP_WAIT);
[Visual Basic]

A Visual Basic application could fill the array as shown in the following code fragment:

' This code fragment assumes that dx is a valid reference
' to a DirectX7 object.
On Local Error Resume Next
Const TOTAL_VERTS As Integer = 6
Dim Verts(TOTAL_VERTS) As D3DVERTEX

Verts(0) = dx.CreateD3DVertex(-5, -5, 0, 0, 0, -1, 0, 0)
Verts(1) = dx.CreateD3DVertex(0, 5, 0, 0, 0, -1, 0, 0)
Verts(2) = dx.CreateD3DVertex(5, -5, 0, 0, 0, -1, 0, 0)
Verts(3) = dx.CreateD3DVertex(10, 5, 0, 0, 0, -1, 0, 0)
Verts(4) = dx.CreateD3DVertex(15, -5, 0, 0, 0, -1, 0, 0)
Verts(5) = dx.CreateD3DVertex(20, 5, 0, 0, 0, -1, 0, 0)

Render the point list using the Direct3DDevice7.DrawPrimitive method. The following code fragment illustrates the use of Direct3DDevice7.DrawPrimitive for drawing the line list in the preceding example. All calls to Direct3DDevice7.DrawPrimitive must occur between Direct3DDevice7.BeginScene and Direct3DDevice7.EndScene.

' This code fragment assumes that d3ddev is a valid
' reference to an Direct3DDevice7 object.
Call d3ddev.DrawPrimitive(D3DPT_LINELIST, _
                          D3DFVF_VERTEX, _
                          Verts(0), _
                          TOTAL_VERTS, _
                          D3DDP_WAIT)

If Err.Number <> DD_OK Then
    ' Code to handle error goes here.
End If

The following illustration shows the resulting lines.

You can apply materials and textures to a line list. The colors in the material or texture only appear along the lines drawn, not at any point in between the lines.


Line Strips

A line strip is a primitive that is composed of connected line segments. Your application can use line strips for creating polygons that are not closed. A closed polygon is a polygon whose last vertex is connected to its first vertex by a line segment. If your application makes polygons based on line strips, the vertices are not guaranteed to be coplanar. You create a line strip by filling an array of vertices.

[C++]

The following code fragment illustrates this process using C++:

const DWORD TOTAL_VERTS=6;
D3DVERTEX lpVerts[TOTAL_VERTS];

lpVerts[0] = D3DVERTEX(D3DVECTOR(-5,-5,0),D3DVECTOR(0,0,-1),0,0);
lpVerts[1] = D3DVERTEX(D3DVECTOR(0,5,0),D3DVECTOR(0,0,-1),0,0);
lpVerts[2] = D3DVERTEX(D3DVECTOR(5,-5,0),D3DVECTOR(0,0,-1),0,0);
lpVerts[3] = D3DVERTEX(D3DVECTOR(10,5,0),D3DVECTOR(0,0,-1),0,0);
lpVerts[4] = D3DVERTEX(D3DVECTOR(15,-5,0),D3DVECTOR(0,0,-1),0,0);
lpVerts[5] = D3DVERTEX(D3DVECTOR(20,5,0),D3DVECTOR(0,0,-1),0,0);

Render the line list using the IDirect3DDevice7::DrawPrimitive method. The following code fragment illustrates the use of IDirect3DDevice7::DrawPrimitive for drawing the line strip in the preceding example. Remember that all calls to IDirect3DDevice7::DrawPrimitive must occur between IDirect3DDevice7::BeginScene and IDirect3DDevice7::EndScene.

HRESULT hResult;
// This code fragment assumes that lpDirect3DDevice is a valid
// pointer to an IDirect3DDevice7 interface.
hResult =
    lpDirect3DDevice->DrawPrimitive(D3DPT_LINESTRIP,
                                      D3DFVF_VERTEX,
                                      lpVerts,
                                      TOTAL_VERTS,
                                      D3DDP_WAIT);
[Visual Basic]

This code fragment illustrates this process using Visual Basic.

' This code fragment assumes that dx is a valid reference
' to a DirectX7 object.
On Local Error Resume Next
Const TOTAL_VERTS As Integer = 6
Dim Verts(TOTAL_VERTS) As D3DVERTEX

Verts(0) = dx.CreateD3DVertex(-5, -5, 0, 0, 0, -1, 0, 0)
Verts(1) = dx.CreateD3DVertex(0, 5, 0, 0, 0, -1, 0, 0)
Verts(2) = dx.CreateD3DVertex(5, -5, 0, 0, 0, -1, 0, 0)
Verts(3) = dx.CreateD3DVertex(10, 5, 0, 0, 0, -1, 0, 0)
Verts(4) = dx.CreateD3DVertex(15, -5, 0, 0, 0, -1, 0, 0)
Verts(5) = dx.CreateD3DVertex(20, 5, 0, 0, 0, -1, 0, 0)

Render the line list using the Direct3DDevice7.DrawPrimitive method. The following code fragment illustrates the use of Direct3DDevice7.DrawPrimitive for drawing the line strip in the preceding example. Remember that all calls to Direct3DDevice7.DrawPrimitive must occur between Direct3DDevice7.BeginScene and Direct3DDevice7.EndScene.

' This code fragment assumes that d3ddev is a valid
' reference to an Direct3DDevice7 object.
Call d3ddev.DrawPrimitive(D3DPT_LINESTRIP, _
                          D3DFVF_VERTEX, _
                          Verts(0), _
                          TOTAL_VERTS, _
                          D3DDP_WAIT)

If Err.Number <> DD_OK Then
    ' Code to handle error goes here.
End If

The following illustration shows the line strip that the previous code produces.


Triangle Lists

A triangle list is a list of isolated triangles. They may or may not be near each other. A triangle list must have at least three vertices. The total number of vertices must be divisible by three.

Use triangle lists when you want to create an object that is composed of disjoint pieces. For instance, one way to create a force field wall in a 3-D game is to specify a large list of small, unconnected triangles. Then apply a material and texture to the triangle list that appears to emit light. Each triangle in the wall appears to glow. The scene behind the wall becomes partially visible through the gaps between the triangles, as players might expect when looking at a force field.

Triangle lists are also useful for creating primitives that have sharp edges and are shaded with Gouraud shading. See Face and Vertex Normal Vectors.

[C++]

Create a triangle list in C++ by filling an array of vertices, as in the following code fragment:

const DWORD TOTAL_VERTS=6;
D3DVERTEX lpVerts[TOTAL_VERTS];

lpVerts[0] = D3DVERTEX(D3DVECTOR(-5,-5,0),D3DVECTOR(0,0,-1),0,0);
lpVerts[1] = D3DVERTEX(D3DVECTOR(0,5,0),D3DVECTOR(0,0,-1),0,0);
lpVerts[2] = D3DVERTEX(D3DVECTOR(5,-5,0),D3DVECTOR(0,0,-1),0,0);
lpVerts[3] = D3DVERTEX(D3DVECTOR(10,5,0),D3DVECTOR(0,0,-1),0,0);
lpVerts[4] = D3DVERTEX(D3DVECTOR(15,-5,0),D3DVECTOR(0,0,-1),0,0);
lpVerts[5] = D3DVERTEX(D3DVECTOR(20,5,0),D3DVECTOR(0,0,-1),0,0);

Render a triangle list using the IDirect3DDevice7::DrawPrimitive method. The following code fragment illustrates the use of IDirect3DDevice7::DrawPrimitive for drawing the triangle list in the preceding example. Remember that all calls to IDirect3DDevice7::DrawPrimitive must occur between IDirect3DDevice7::BeginScene and IDirect3DDevice7::EndScene.

HRESULT hResult;
// This code fragment assumes that lpDirect3DDevice is a valid
// pointer to an IDirect3DDevice7 interface.
hResult =
    lpDirect3DDevice->DrawPrimitive(D3DPT_TRIANGLELIST,
                                      D3DFVF_VERTEX,
                                      lpVerts,
                                      TOTAL_VERTS,
                                      D3DDP_WAIT);
[Visual Basic]

Create a triangle list in Visual Basic by filling an array of vertices, as in the following code fragment:

' This code fragment assumes that dx is a valid reference
' to a DirectX7 object.
On Local Error Resume Next
Const TOTAL_VERTS As Integer = 6
Dim Verts(TOTAL_VERTS) As D3DVERTEX

Verts(0) = dx.CreateD3DVertex(-5, -5, 0, 0, 0, -1, 0, 0)
Verts(1) = dx.CreateD3DVertex(0, 5, 0, 0, 0, -1, 0, 0)
Verts(2) = dx.CreateD3DVertex(5, -5, 0, 0, 0, -1, 0, 0)
Verts(3) = dx.CreateD3DVertex(10, 5, 0, 0, 0, -1, 0, 0)
Verts(4) = dx.CreateD3DVertex(15, -5, 0, 0, 0, -1, 0, 0)
Verts(5) = dx.CreateD3DVertex(20, 5, 0, 0, 0, -1, 0, 0)

Render a triangle list using the Direct3DDevice7.DrawPrimitive method. The following code fragment illustrates the use of Direct3DDevice7.DrawPrimitive for drawing the triangle list in the preceding example. Remember that all calls to Direct3DDevice7.DrawPrimitive must occur between Direct3DDevice7.BeginScene and Direct3DDevice7.EndScene.

' This code fragment assumes that d3ddev is a valid
' reference to an Direct3DDevice7 object.
Call d3ddev.DrawPrimitive(D3DPT_TRIANGLELIST, _
                          D3DFVF_VERTEX, _
                          Verts(0), _
                          TOTAL_VERTS, _
                          D3DDP_WAIT)

If Err.Number <> DD_OK Then
    ' Code to handle error goes here.
End If

The following illustration depicts the resulting triangles.


Triangle Strips

A triangle strip is a series of connected triangles. Because the triangles are connected, the application does not need to repeatedly specify all three vertices for each triangle. For example, you only need seven vertices to define the following triangle strip.

The system uses vertices v1, v2, and v3 to draw the first triangle, v2, v4, and v3 to draw the second triangle, v3, v4, and v5 to draw the third, v4, v6, and v5 to draw the fourth, and so on. Notice that the vertices of the second and fourth triangles are out of order; this is required to make sure that all of the triangles are drawn in a clockwise orientation.

Most objects in 3-D scenes are composed of triangle strips. This is because triangle strips can be used to specify complex objects in a way that makes efficient use of memory and processing time. You create a triangle strip by filling an array of vertices.

[C++]

The following C++ code fragment fills an array of vertices for use as a triangle strip:

const DWORD TOTAL_VERTS=6;
D3DVERTEX lpVerts[TOTAL_VERTS];

lpVerts[0] = D3DVERTEX(D3DVECTOR(-5,-5,0),D3DVECTOR(0,0,-1),0,0);
lpVerts[1] = D3DVERTEX(D3DVECTOR(0,5,0),D3DVECTOR(0,0,-1),0,0);
lpVerts[2] = D3DVERTEX(D3DVECTOR(5,-5,0),D3DVECTOR(0,0,-1),0,0);
lpVerts[3] = D3DVERTEX(D3DVECTOR(10,5,0),D3DVECTOR(0,0,-1),0,0);
lpVerts[4] = D3DVERTEX(D3DVECTOR(15,-5,0),D3DVECTOR(0,0,-1),0,0);
lpVerts[5] = D3DVERTEX(D3DVECTOR(20,5,0),D3DVECTOR(0,0,-1),0,0);

Your application can then render the triangle strip using the IDirect3DDevice7::DrawPrimitive method. The following code fragment illustrates the use of IDirect3DDevice7::DrawPrimitive for drawing the triangle strip in the preceding example. Remember that all calls to IDirect3DDevice7::DrawPrimitive must occur between IDirect3DDevice7::BeginScene and IDirect3DDevice7::EndScene.

HRESULT hResult;
// This code fragment assumes that lpDirect3DDevice7 is a valid
// pointer to an IDirect3DDevice7 interface.
hResult =
    lpDirect3DDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP,
                                      D3DFVF_VERTEX,
                                      lpVerts,
                                      TOTAL_VERTS,
                                      D3DDP_WAIT);
[Visual Basic]

Applications written in Visual Basic could use code like the following to setup a triangle strip:

' This code fragment assumes that dx is a valid reference
' to a DirectX7 object.
On Local Error Resume Next
Const TOTAL_VERTS As Integer = 6
Dim Verts(TOTAL_VERTS) As D3DVERTEX

Verts(0) = dx.CreateD3DVertex(-5, -5, 0, 0, 0, -1, 0, 0)
Verts(1) = dx.CreateD3DVertex(0, 5, 0, 0, 0, -1, 0, 0)
Verts(2) = dx.CreateD3DVertex(5, -5, 0, 0, 0, -1, 0, 0)
Verts(3) = dx.CreateD3DVertex(10, 5, 0, 0, 0, -1, 0, 0)
Verts(4) = dx.CreateD3DVertex(15, -5, 0, 0, 0, -1, 0, 0)
Verts(5) = dx.CreateD3DVertex(20, 5, 0, 0, 0, -1, 0, 0)

Your application can then render the triangle strip using the Direct3DDevice7.DrawPrimitive method. The following code fragment illustrates the use of Direct3DDevice7.DrawPrimitive for drawing the triangle strip in the preceding example. Remember that all calls to Direct3DDevice7.DrawPrimitive must occur between Direct3DDevice7.BeginScene and Direct3DDevice7.EndScene.

' This code fragment assumes that d3ddev is a valid
' reference to an Direct3DDevice7 object.
Call d3ddev.DrawPrimitive(D3DPT_TRIANGLESTRIP, _
                          D3DFVF_VERTEX, _
                          Verts(0), _
                          TOTAL_VERTS, _
                          D3DDP_WAIT)

If Err.Number <> DD_OK Then
    ' Code to handle error goes here.
End If

The following illustration shows the resulting triangle strip.


Triangle Fans

A triangle fan is similar to a triangle strip, except that all of the triangles share one vertex, as shown in the following illustration.

The system uses vertices v2, v3, and v1 to draw the first triangle, v3, v4, and v1 to draw the second triangle, v4, v5, and v1 to draw the third triangle, and so on. (When flat shading is enabled, the system shades the triangle with the color from its first vertex.)

[C++]

Your C++ application can create a triangle fan by filling an array of vertices, as shown in the following code fragment:

const DWORD TOTAL_VERTS=6;
D3DVERTEX lpVerts[TOTAL_VERTS];

lpVerts[0] = D3DVERTEX(D3DVECTOR(0,0,0),D3DVECTOR(0,0,-1),0,0);
lpVerts[1] = D3DVERTEX(D3DVECTOR(-5,-5,0),D3DVECTOR(0,0,-1),0,0);
lpVerts[2] = D3DVERTEX(D3DVECTOR(-3,7,0),D3DVECTOR(0,0,-1),0,0);
lpVerts[3] = D3DVERTEX(D3DVECTOR(0,10,0),D3DVECTOR(0,0,-1),0,0);
lpVerts[4] = D3DVERTEX(D3DVECTOR(3,7,0),D3DVECTOR(0,0,-1),0,0);
lpVerts[5] = D3DVERTEX(D3DVECTOR(5,5,0),D3DVECTOR(0,0,-1),0,0);

It can then render the triangle fan using the IDirect3DDevice7::DrawPrimitive method. The following code fragment illustrates the use of IDirect3DDevice7::DrawPrimitive for drawing the triangle fan in the preceding example. Remember that all calls to IDirect3DDevice7::DrawPrimitive must occur between IDirect3DDevice7::BeginScene and IDirect3DDevice7::EndScene.

HRESULT hResult;
// This code fragment assumes that lpDirect3DDevice is a valid
// pointer to an IDirect3DDevice7 interface.
hResult =
    lpDirect3DDevice->DrawPrimitive(D3DPT_TRIANGLEFAN,
                                     D3DFVF_VERTEX,
                                     lpVerts,
                                     TOTAL_VERTS,
                                     D3DDP_WAIT);
[Visual Basic]

A Visual Basic application can create a triangle fan by setting up an array of vertices as shown in the following code fragment:

' This code fragment assumes that dx is a valid reference
' to a DirectX7 object.
On Local Error Resume Next
Const TOTAL_VERTS As Integer = 6
Dim Verts(TOTAL_VERTS) As D3DVERTEX

Verts(0) = dx.CreateD3DVertex(0, 0, 0, 0, 0, -1, 0, 0)
Verts(1) = dx.CreateD3DVertex(-5, -5, 0, 0, 0, -1, 0, 0)
Verts(2) = dx.CreateD3DVertex(-3, 7, 0, 0, 0, -1, 0, 0)
Verts(3) = dx.CreateD3DVertex(0, 10, 0, 0, 0, -1, 0, 0)
Verts(4) = dx.CreateD3DVertex(3, 7, 0, 0, 0, -1, 0, 0)
Verts(5) = dx.CreateD3DVertex(5, 5, 0, 0, 0, -1, 0, 0)

It can then render the triangle fan using the Direct3DDevice7.DrawPrimitive method. The following code fragment illustrates the use of Direct3DDevice7.DrawPrimitive for drawing the triangle fan in the preceding example. Remember that all calls to Direct3DDevice7.DrawPrimitive must occur between Direct3DDevice7.BeginScene and Direct3DDevice7.EndScene.

' This code fragment assumes that d3ddev is a valid
' reference to an Direct3DDevice7 object.
Call d3ddev.DrawPrimitive(D3DPT_TRIANGLEFAN, _
                          D3DFVF_VERTEX, _
                          Verts(0), _
                          TOTAL_VERTS, _
                          D3DDP_WAIT)

If Err.Number <> DD_OK Then
    ' Code to handle error goes here.
End If

This illustration depicts the resulting triangle fan.


AGP Surfaces and Direct3D Devices

Using textures in 3-D applications can greatly enhance the appearance of realism in 3-D images. Memory for storing textures never seems as abundant as developers would like. DirectDraw and Direct3D support the Accelerated Graphics Port (AGP) architecture. The AGP architecture gives computers the ability to create DirectDraw surfaces in applications' memory spaces. This significantly extends the amount of memory available for storing textures.

Only the Direct3D HAL device supports the use of the AGP architecture. For more information on the use of the AGP architecture, see Using Non-local Video Memory Surfaces.


Geometry Pipeline

When you design a 3-D application, you define the world in any units you find convenient, from microns to parsecs. Your application passes a description of that world to Direct3D. This description includes the sizes and relative positions of all of the objects in your world and the position and orientation of the viewer. Direct3D transforms this description into a series of pixels on the screen. This process—the transformation of the geometry you supply into a two-dimensional image—is the geometry pipeline, sometimes called the transformation pipeline.

This section provides a Direct3D-centered approach to discussing the geometry pipeline. The following topics introduce key concepts and make parallels from those concepts to their counterparts in the Direct3D API:

  • Overview of the Pipeline
  • The World Transformation
  • The View Transformation
  • The Projection Transformation
  • Viewports and Clipping
  • The Rasterizer


Overview of the Pipeline

The part of Direct3D that pushes geometry through the geometry pipeline is the transformation engine. It locates the model and viewer in the world, projects vertices for display on the screen, and clips vertices to the viewport. (The transformation engine also performs lighting computations to determine diffuse and specular components at each vertex. For more information, see Lighting and Materials.)

The geometry pipeline takes vertices as input. The transformation engine applies three transformations to the vertices (the world, view, and projection transformations), clips the result, and passes everything on to the rasterizer. The sequence of steps looks like this:

At the head of the pipeline, no transformations have been applied, so all of a model's vertices are declared relative to a local coordinate system (this is a local origin and an orientation). This orientation of coordinates is often referred to as model space, and individual coordinates are called model coordinates.

The first stage of the geometry pipeline transforms a model's vertices from their local coordinate system to a coordinate system that is used by all the objects in a scene. The process of reorienting the vertices is called the world transformation. This new orientation is commonly referred to as world space, and each vertex in world space is declared using world coordinates. This transformation is discussed in The World Transformation.

In the next stage, the vertices that describe your 3-D world are oriented with respect to a camera. That is, your application chooses a point-of-view for the scene, and world space coordinates are relocated and rotated around the camera's view, turning world space into camera space. This is the view transformation. For more information, see The View Transformation.

The next stage is the projection transformation. In this part of the pipeline, objects are usually scaled with relation to their distance from the viewer in order to give the illusion of depth to a scene; close objects are made to appear larger than distant objects, and so on. This transformation is discussed in The Projection Transformation. For simplicity, this documentation refers to the space in which vertices exist after the projection transformation as projection space. (Some graphics books might refer to projection space as post-perspective homogeneous space.) Not all projection transformations scale the size of objects in a scene. A projection such as this is sometimes called an affine or orthogonal projection.

In the final part of the pipeline, any vertices that will not be visible on the screen are removed, so that the rasterizer doesn't take the time to calculate the colors and shading for something that will never be seen. This process is called clipping, and is discussed in Viewports and Clipping. After clipping, the remaining vertices are scaled according to the viewport parameters and converted into screen coordinates. The resulting vertices—seen on the screen when the scene is rasterized—exist in screen space.


The World Transformation

The discussion of the world transformation introduces basic concepts and provides details on how to set up a world transformation matrix in a Direct3D application. This information is organized into the following topics:

  • What Is the World Transformation?
  • Setting Up a World Matrix


What Is the World Transformation?

The world transformation changes coordinates from model space, where vertices are defined relative to a model's local origin, to world space, where vertices are defined relative to an origin common to all of the objects in a scene. In essence, the world transformation places a model into the world; hence its name. The following illustration provides a graphical representation of the relationship between the world coordinate system and a model's local coordinate system:

The world transformation can include any combination of translations, rotations, and scalings. For a discussion of the mathematics of transformations, see 3-D Transformations.


Setting Up a World Matrix

Like any other transformation, you create the world transformation by concatenating a series of transformation matrices into a single matrix that contains the sum total of their effects. In the simplest case, when a model is at the world origin and its local coordinate axes are oriented the same as world space, the world matrix is the identity matrix. More commonly, the world matrix is a combination of a translation into world space, and possibly one or more rotations to "turn" the model as needed.

[C++]

The following example, from a fictitious 3-D model class written in C++, uses the helper functions in the D3dutil.cpp and D3dmath.cpp files (included with the DirectX SDK) to create a world matrix that includes three rotations to orient a model and a translation to relocate it relative to its position in world space.

/*
 * For the purposes of this example, the following variables
 * assumed to be valid and initialized.
 *
 * The m_vPos variable is a D3DVECTOR that contains the model's
 * location in world coordinates.
 *
 * The m_fPitch, m_fYaw, and m_fRoll variables are D3DVALUEs that
 * contain the model's orientation in terms of pitch, yaw, and roll
 * angles (in radians).
 */

D3DMATRIX C3DModel::MakeWorldMatrix(void)
{
    D3DMATRIX matWorld, // World matrix being constructed.
      matTemp,  // Temp matrix for rotations.
      matRot;   // Final rotation matrix (applied to matWorld).

    // Using the left-to-right order of matrix concatenation,
    // apply the translation to the object's world position
    // before applying the rotations.
    D3DUtil_SetTranslateMatrix(matWorld, m_vPos);
    D3DUtil_SetIdentityMatrix(matRot);

    //
    // Now, apply the orientation variables into the
    // world matrix
    //
    if(m_fPitch || m_fYaw || m_fRoll)
    {
// Produce and combine the rotation matrices.
D3DUtil_SetRotateXMatrix(matTemp, m_fPitch);    // pitch
D3DMath_MatrixMultiply(matRot,matRot,matTemp);
D3DUtil_SetRotateYMatrix(matTemp, m_fYaw);      // yaw
D3DMath_MatrixMultiply(matRot,matRot,matTemp);
D3DUtil_SetRotateZMatrix(matTemp, m_fRoll);     // roll
D3DMath_MatrixMultiply(matRot,matRot,matTemp);

// Apply the rotation matrices to complete the world matrix.
D3DMath_MatrixMultiply(matWorld, matRot, matWorld);
    }
    return (matWorld);
}

After you prepare the world transformation matrix, call the IDirect3DDevice7::SetTransform method to set it, specifying the D3DTRANSFORMSTATE_WORLD flag in the first parameter. For more information, see Setting Transformations.

[Visual Basic]

The following example, from a fictitious 3-D model class, uses the functions offered by the DirectX7 class to create a world matrix that includes three rotations to orient a model and a translation to relocate it relative to its position in world space.

'
' For the purposes of this example, the following variables
' assumed to be valid and initialized.
'
'   The g_dx variable contains a valid reference to a DirectX7 object.
'
'   The m_vPos variable is a D3DVECTOR that contains the model's
'   location in world coordinates.
'
'   The m_sPitch, m_sYaw, and m_sRoll variables are Singles that
'   contain the model's orientation in terms of pitch, yaw, and roll
'   angles (in radians).
'
Public Function MakeWorldMatrix() As D3DMATRIX
    Dim matWorld As D3DMATRIX   ' World matrix to be returned.
    Dim matTemp As D3DMATRIX    ' Temp matrix to hold rotations.
    Dim matRot As D3DMATRIX     ' Temp rotation matrix.

    ' Modify matWorld to create a translation matrix.
    Call g_dx.IdentityMatrix(matWorld)
    matWorld.rc41 = m_vPos.x
    matWorld.rc42 = m_vPos.y
    matWorld.rc43 = m_vPos.z

    Call g_dx.IdentityMatrix(matRot) ' Sets up the rotation matrix

    '
    ' Using the left-to-right order of matrix concatenation,
    ' apply the translation to the object's world position
    ' before applying the rotations.
    '

    ' Produce and combine the rotation matrices.
    If (m_sPitch <> 0) Or (m_sYaw <> 0) Or (m_sRoll <> 0) Then
' First, pitch.
Call g_dx.RotateXMatrix(matTemp, m_sPitch)
Call g_dx.MatrixMultiply(matRot, matRot, matTemp)

' Then, yaw.
Call g_dx.RotateYMatrix(matTemp, m_sYaw)
Call g_dx.MatrixMultiply(matRot, matRot, matTemp)

' Finally, roll.
Call g_dx.RotateZMatrix(matTemp, m_sRoll)
Call g_dx.MatrixMultiply(matRot, matRot, matTemp)

' Apply the rotation matrices to the translation already in
' matWorld to complete the world matrix.
Call g_dx.MatrixMultiply(matWorld, matRot, matWorld)
    End If

    MakeWorldMatrix = matWorld
End Function

After you prepare the world transformation matrix, call the Direct3DDevice7.SetTransform method to set it, specifying the D3DTRANSFORMSTATE_WORLD flag in the first parameter. For more information, see Setting Transformations.

Performance Optimization Direct3D uses the world and view matrices that you set to configure several of its internal data structures. Each time you set a new world or view matrix, the system recalculates the associated internal structures. Setting these matrices frequently—for example, thousands of times per frame—is computationally expensive. You can minimize the number of required calculations by concatenating your world and view matrices into a proverbial "world-view" matrix that you set as the world matrix, then set the view matrix to the identity. Keep cached copies of individual world and view matrices that you can modify, concatenate, and reset the world matrix as needed. (For clarity, Direct3D samples rarely employ this optimization.)


The View Transformation

This section introduces the basic concepts of the view transformation and provides details on how you can set up a view transformation matrix in a Direct3D application. This information is organized into the following topics:

  • What Is the View Transformation?
  • Setting Up a View Matrix


What Is the View Transformation?

The view transformation locates the viewer in world space, transforming vertices into camera space. In camera space, the camera (or "viewer") is at the origin, looking in the positive z-direction. (Recall that Direct3D uses a left-handed coordinate system, so z is positive into a scene.) The view matrix relocates the objects in the world around a camera's position (the origin of camera space) and orientation.

There are many ways to create a view matrix. In all cases, the camera has some logical position and orientation in world space that is used as a starting point to create a view matrix that will be applied to the models in a scene. The view matrix translates and rotates objects to place them in camera space, where the camera is at the origin. One way to create a view matrix is to combine a translation matrix with rotation matrices for each axis. In this approach, the following general matrix formula applies:

In this formula, V is the view matrix being created, T is a translation matrix that repositions objects in the world, and Rx through Rz are rotation matrices that rotate objects along the x-, y-, and z-axis. The translation and rotation matrices are based on the camera's logical position and orientation in world space. So, if the camera's logical position in the world <10,20,100>, the aim of the translation matrix is to move objects -10 units along the x-axis, -20 units along the y-axis, and -100 along the z-axis. The rotation matrices in the formula are based on the camera's orientation, in terms of how the much the axes of camera space are rotated out of alignment with world space. For example, if the camera mentioned earlier is pointing straight down, its z-axis is 90 degrees (pi/2 radians) out of alignment with the z-axis of world space, as shown in the following illustration.

The rotation matrices apply rotations of equal, but opposite, magnitude to the models in the scene. The view matrix for this camera would include a rotation of -90 degrees around the x-axis. The rotation matrix is combined with the translation matrix to create a view matrix that adjusts the position and orientation of the objects in the scene so that their top is facing toward the camera, giving the appearance that the camera is above the model.

Another approach involves creating the composite view matrix directly. (The D3DUTIL_SetViewMatrix helper function in the D3dutil.cpp source file uses this technique, as does the DirectX7.ViewMatrix method used by Visual Basic applications). This approach uses the camera's world space position and a "look-at point" within the scene to derive vectors that describe the orientation of the camera space coordinate axes. The camera position is subtracted from the look-at point to produce a vector for the camera's direction vector (vector n). Then the cross product of the vector n and the y-axis of world space is taken and normalized to produce a "right" vector (vector u). Next, the cross product of the vectors u and n is taken to determine an "up" vector (vector v). The right (u), up (v), and view-direction (n) vectors describe the orientation of the coordinate axes for camera space in terms of world space. The x, y, and z translation factors are computed by taking the negative of the dot product between the camera position and the u, v, and n vectors.

These values are put into the following matrix to produce the view matrix:

In this matrix, u, v, and n are the up, right and view-direction vectors, and c is the camera's world space position. This matrix contains all the elements needed to translate and rotate vertices from world space to camera space. After creating this matrix, you can also apply a matrix for rotation around the z-axis to allow the camera to roll.

For information on implementing this technique, see Setting Up a View Matrix.


Setting Up a View Matrix

[C++]

The D3DUtil_SetViewMatrix helper function, from the D3dutil.cpp source file that is included with this SDK, creates a view matrix based on the camera location and a look-at point passed to it. It uses the Magnitude, CrossProduct, and DotProduct D3D_OVERLOADS helper functions.

HRESULT D3DUtil_SetViewMatrix( D3DMATRIX& mat, D3DVECTOR& vFrom,
       D3DVECTOR& vAt, D3DVECTOR& vWorldUp )
{
    // Get the z basis vector, which points straight ahead. This is the
    // difference from the eyepoint to the lookat point.
    D3DVECTOR vView = vAt - vFrom;

    FLOAT fLength = Magnitude( vView );
    if( fLength < 1e-6f )
return E_INVALIDARG;

    // Normalize the z basis vector
    vView /= fLength;

    // Get the dot product, and calculate the projection of the z basis
    // vector onto the up vector. The projection is the y basis vector.
    FLOAT fDotProduct = DotProduct( vWorldUp, vView );

    D3DVECTOR vUp = vWorldUp - fDotProduct * vView;

    // If this vector has near-zero length because the input specified a
    // bogus up vector, let's try a default up vector
    if( 1e-6f > ( fLength = Magnitude( vUp ) ) )
    {
vUp = D3DVECTOR( 0.0f, 1.0f, 0.0f ) - vView.y * vView;

// If we still have near-zero length, resort to a different axis.
if( 1e-6f > ( fLength = Magnitude( vUp ) ) )
{
    vUp = D3DVECTOR( 0.0f, 0.0f, 1.0f ) - vView.z * vView;

    if( 1e-6f > ( fLength = Magnitude( vUp ) ) )
return E_INVALIDARG;
}
    }

    // Normalize the y basis vector
    vUp /= fLength;

    // The x basis vector is found simply with the cross product of the y
    // and z basis vectors
    D3DVECTOR vRight = CrossProduct( vUp, vView );

    // Start building the matrix. The first three rows contains the basis
    // vectors used to rotate the view to point at the lookat point
    D3DUtil_SetIdentityMatrix( mat );
    mat._11 = vRight.x;    mat._12 = vUp.x;    mat._13 = vView.x;
    mat._21 = vRight.y;    mat._22 = vUp.y;    mat._23 = vView.y;
    mat._31 = vRight.z;    mat._32 = vUp.z;    mat._33 = vView.z;

    // Do the translation values (rotations are still about the eyepoint)
    mat._41 = - DotProduct( vFrom, vRight );
    mat._42 = - DotProduct( vFrom, vUp );
    mat._43 = - DotProduct( vFrom, vView );

    return S_OK;
}

As with the world transformation, you call the IDirect3DDevice7::SetTransform method to set the view transformation, specifying the D3DTRANSFORMSTATE_VIEW flag in the first parameter. See Setting Transformations, for more information.

[Visual Basic]

Visual Basic applications use the DirectX7.ViewMatrix method to create view matrix based on the camera location, a look-at point, an "up" vector (usually 0,1,0), and a roll value specified in radians.

The following example code, written in Visual Basic, shows how the ViewMatrix method can be used.

' For this example, the g_dx variable contains a valid reference
' to a global DirectX7 object.
Dim matView  As D3DMATRIX
Dim vFrom As D3DVECTOR, _
    vTo As D3DVECTOR, _
    vUp As D3DVECTOR

    vFrom.x = 0: vFrom.y = 0: vFrom.z = -15
    vTo.x = 0: vTo.y = 0: vTo.z = 0
    vUp.x = 0: vUp.y = 1: vUp.z = 0

' Initialize the matrix to the identity.
g_dx.IdentityMatrix matView

' Create a view matrix with a camera at 0,0,-15, that points at the
' world-origin, with no rotation around the vFrom->vTo vector.
Call g_dx.ViewMatrix(matView, vFrom, vTo, vUp, 0)

As with the world transformation, you call the Direct3DDevice7.SetTransform method to set the view transformation, specifying the D3DTRANSFORMSTATE_VIEW flag in the first parameter. See Setting Transformations, for more information.

Performance Optimization Direct3D uses the world and view matrices that you set to configure several of its internal data structures. Each time you set a new world or view matrix, the system recalculates the associated internal structures. Setting these matrices frequently—for example, 20000 times per frame—is computationally expensive. You can minimize the number of required calculations by concatenating your world and view matrices into a proverbial "world-view" matrix that you set as the world matrix, then set the view matrix to the identity. Keep cached copies of individual world and view matrices that you can modify, concatenate, and reset the world matrix as needed. (For clarity, Direct3D samples rarely employ this optimization.)


The Projection Transformation

You can think of the projection transformation as controlling the camera's internals; it is analogous to choosing a lens for the camera. This is the most complicated of the three transformation types. This discussion of the projection transformation is organized into the following topics:

  • The Viewing Frustum
  • What Is the Projection Transformation?
  • Setting Up a Projection Matrix
  • A W-Friendly Projection Matrix


The Viewing Frustum

A viewing frustum is 3-D volume in a scene positioned relative to the viewport's camera. The shape of the volume affects how models are projected from camera space onto the screen. The most common type of projection, a perspective projection, is responsible for making objects near the camera appear bigger than objects in the distance. For perspective viewing, the viewing frustum can be visualized as a pyramid, with the camera positioned at the tip. This pyramid is intersected by a front and back clipping plane. The volume within the pyramid between the front and back clipping planes is the viewing frustum. Objects are visible only when they are in this volume.

If you imagine that you are standing in a dark room and looking out through a square window, you are visualizing a viewing frustum. In this analogy, the near-clipping plane is the window, and the back clipping plane is whatever finally interrupts your view—the skyscraper across the street, the mountains in the distance, or nothing at all. You can see everything inside the truncated pyramid that starts at the window and ends with whatever interrupts your view, and you can see nothing else.

The viewing frustum is defined by fov (field of view) and by the distances of the front and back clipping planes, specified in z-coordinates.

In this illustration, the variable D is the distance from the camera to the origin of the space that was defined in the last part of the geometry pipeline—the viewing transformation. This is the space around which you arrange the limits of your viewing frustum. For information about how this D variable is used to build the projection matrix, see What Is the Projection Transformation?


What Is the Projection Transformation?

The projection matrix is typically a scale and perspective projection. The projection transformation converts the viewing frustum into a cuboid shape. Because the near end of the viewing frustum is smaller than the far end, this has the effect of expanding objects that are near to the camera; this is how perspective is applied to the scene.

In The Viewing Frustum, the distance between the camera required by the projection transformation and the origin of the space defined by the viewing transformation is defined as D. A beginning for a matrix defining the perspective projection might use this D variable like this:

The viewing matrix puts the camera at the origin of the scene. Since the projection matrix needs to have the camera at (0, 0, -D), it translates the vector by -D in the z-direction, by using the following matrix:

Multiplying these two matrices gives the following composite matrix:

The following illustration shows how the perspective transformation converts a viewing frustum into a new coordinate space. Notice that the frustum becomes cuboid and also that the origin moves from the upper-right corner of the scene to the center.

In the perspective transformation, the limits of the x- and y-directions are -1 and 1. The limits of the z-direction are 0 for the front plane and 1 for the back plane.

This matrix translates and scales objects based on a specified distance from the camera to the near clipping plane, but it doesn't consider the field-of-view (fov), and the z-values that it produces for objects in the distance can be nearly identical, making depth comparisons difficult. The following matrix addresses these issues, and adjusts vertices to account for the aspect ratio of the viewport, making it a good choice for the perspective projection:

In this matrix, Zn is the z-value of the near clipping plane. The variables w, h, and Q have the following meanings (noting that fovw and fovh represent the viewport's horizontal and vertical fields-of-view, in radians):

For your application, using field-of-view angles to define the x and y scaling coefficients might not be as convenient as using the viewport's horizontal and vertical dimensions (in camera space). As the math works-out, the following two formulas for w and h use the viewport's dimensions, and are equivalent to the preceding formulas:

In these formulas, Zn represents the position of the near clipping plane, and the Vw and Vh variables represent the width and height of the viewport, in camera space.

[C++]

For a C++ application, these two dimensions correspond directly to the dwWidth and dwHeight members of the D3DVIEWPORT7 structure.

Whatever formula you decide to use, it's important that you set Zn to as large a value as you can, as z-values extremely close to the camera don't vary by much, making depth comparisons using 16-bit z-buffers tricky.

As with the world and view transformations, you call the IDirect3DDevice7::SetTransform method to set the projection transformation; for more information, see Setting Transformations.

[Visual Basic]

For a Visual Basic application, these two dimensions correspond directly to the lWidth and lHeight members of the D3DVIEWPORT7 type.

Whatever formula you decide to use, it's important that you set Zn to as large a value as you can, as z-values extremely close to the camera don't vary by much, making depth comparisons using 16-bit z-buffers tricky.

As with the world and view transformations, you call the Direct3DDevice7.SetTransform method to set the projection transformation; for more information, see Setting Transformations.


Setting Up a Projection Matrix

[C++]

The following ProjectionMatrix sample function—written in C++—takes four input parameters that set the front and back clipping planes, as well as the horizontal and vertical field of view angles. (This code parallels the approach discussed in the What Is the Projection Transformation? topic.) The fields-of-view should be less than pi radians.

D3DMATRIX
ProjectionMatrix(const float near_plane,
     // distance to near clipping plane
 const float far_plane,
     // distance to far clipping plane
 const float fov_horiz,
     // horizontal field of view angle, in radians
 const float fov_vert)
     // vertical field of view angle, in radians
{
    float    h, w, Q;

    w = (float)cot(fov_horiz*0.5);
    h = (float)cot(fov_vert*0.5);
    Q = far_plane/(far_plane - near_plane);

    D3DMATRIX ret = ZeroMatrix();
    ret(0, 0) = w;
    ret(1, 1) = h;
    ret(2, 2) = Q;
    ret(3, 2) = -Q*near_plane;
    ret(2, 3) = 1;
    return ret;
}   // end of ProjectionMatrix()

When you have created the matrix, you need set it in a call to the IDirect3DDevice7::SetTransform method, specifying D3DTRANSFORMSTATE_PROJECTION in the first parameter. For details, see Setting Transformations.

[Visual Basic]

Applications written in Visual Basic can create a projection matrix "by hand" as described in the What Is the Projection Transformation? topic. However, the DirectX7 object includes an implementation of this approach, offered through the DirectX7.ProjectionMatrix method.

The following Visual Basic code fragment shows how this DirectX7.ProjectionMatrix is commonly used.

'
' For this example, the g_dx variable contains a reference to a global
' DirectX7 object.
'
' The pi variable is a variable of type Single that loosely approximates
' the trigonometric constant of the same name (3.141592).
Dim matProj As D3DMATRIX

' Initialize the matrix to the identity.
g_dx.IdentityMatrix matProj

' Create a projection matrix that reflects a viewing frustum with the
' front and rear clipping planes at 1 and 1000, and a field-of-view
' angle of pi/2 radians (90 degrees).
Call g_dx.ProjectionMatrix(matProj, 1, 1000, pi / 2)

When you have created the matrix, you need set it in a call to the Direct3DDevice7.SetTransform method, specifying D3DTRANSFORMSTATE_PROJECTION in the first parameter. For details, see Setting Transformations.


A W-Friendly Projection Matrix

Direct3D Immediate Mode can utilize the W component of a vertex that has been transformed by the world, view, and projection matrices to perform depth-based calculations in depth-buffer or fog effects. Computations such as these require that your projection matrix normalize W to be equivalent to world-space Z. In short, if your projection matrix includes a (3,4) coefficient that is not 1, you must scale all the coefficients by the inverse of the (3,4) coefficient to make a proper matrix. If you don't provide a compliant matrix, fog effects and depth buffering will not be applied correctly. (The projection matrix recommended in What Is the Projection Transformation? is compliant with w-based calculations.)

The following illustration shows a non-compliant projection matrix, and the same matrix scaled so that eye-relative fog will be enabled.

In the preceding matrices, all variables are assumed to be nonzero. For more information about eye-relative fog, see Eye-Relative vs. Z-based Depth. For information about w-based depth buffering, see What Are Depth Buffers?

Note Direct3D uses the currently set projection matrix in its w-based depth calculations. As a result, applications must set a compliant projection matrix to receive the desired w-based features, even if they do not use the Direct3D transformation pipeline.


Viewports and Clipping

This section discusses the last stage of the geometry pipeline: clipping. The discussion is organized into the following topics:

  • What Is a Viewport?
  • Viewport Rectangle
  • Clipping Volumes
  • Viewport Scaling
  • Using Viewports

Direct3D implements clipping by way of a set of viewport parameters set in the device.

[C++]

The IDirect3DDevice7 interface exposes methods that enable C++ applications to manipulate the viewport parameters for a device. (In previous releases of DirectX, viewports were implemented as a separate COM object that exposed its own interface.)

[Visual Basic]

The Direct3DDevice7 class offers methods that enable applications written in Visual Basic to manipulate the viewport parameters for a device.


What Is a Viewport?

Conceptually, a viewport is a 2-D rectangle into which a three dimensional scene is projected. (In Direct3D, the rectangle exists as coordinates within a DirectDraw surface that the system uses as a rendering target.) The projection transformation converts vertices into the coordinate system used for the viewport.

You use a viewport in Direct3D to specify the following features in your application:

  • The screen-space viewport to which the rendering will be confined.
  • The range of depth values on a render-target surface into which a scene will be rendered (usually 0.0 to 1.0).


Viewport Rectangle

[C++]

Note The viewport structure used in DirectX 7.0 is much different than the structure recommended in previous releases (the legacy D3DVIEWPORT2 structure). Please read this information carefully to ensure that your application uses viewport parameters properly.

You define the viewport rectangle in C++ by using the D3DVIEWPORT7 structure. The D3DVIEWPORT7 structure is used with the viewport manipulation methods offered by the IDirect3DDevice7 interface: IDirect3DDevice7::SetViewport and IDirect3DDevice7::GetViewport. The D3DVIEWPORT7 structure contains four members—dwX, dwY, dwWidth, and dwHeight—that define the area of the render-target surface into which a scene will be rendered, called the "viewport rectangle".

These values correspond to the destination rectangle, or viewport rectangle, as shown in the following illustration.

The values you specify for the dwX, dwY, dwWidth, and dwHeight members of the D3DVIEWPORT7 structure are screen coordinates relative to the upper-left corner of the render-target surface. The structure defines two additional members (dvMinZ and dvMaxZ) indicate the depth-ranges into which the scene will be rendered.

The viewport structure used in DirectX 7.0 is much different than the structure recommended in previous releases (the legacy D3DVIEWPORT2 structure). In short, the D3DVIEWPORT7 structure simplifies the legacy structure by omitting the members that were used describe the size and dimensions of the viewport, in 3-D projection space. The vast majority of applications always set the now absent members to the same values, while a few used them to scale geometry to adjust for the viewport's aspect ratio. This effect was difficult to perform accurately and reliably.

Direct3D assumes that the viewport clipping volume ranges from -1.0 to 1.0 in X, and from 1.0 to -1.0 in Y (these were the settings used most often by applications in the past). In DirectX 7.0, as in previous releases of DirectX, you can adjust for viewport aspect ratio before clipping, during the projection transformation. This task is covered by topics in The Projection Transformation section.

Note The D3DVIEWPORT7 structure members dvMinZ and dvMaxZ are interpreted in a manner completely different than in previous versions of DirectX. The dvMinZ and dvMaxZ members now indicate the depth-ranges into which the scene will be rendered, and are not used for clipping. Most applications will set these members to 0.0 and 1.0 to enable the system to render to the entire range of depth values in the depth buffer. In some cases, you can achieve special effects by using other depth ranges. For instance, if you wanted to render a heads-up display in a game, you could set both values to 0.0 to force the system to render objects in a scene in the foreground, or you might set them both to 1.0 to render an object that should always be in the background.

[Visual Basic]

Within a Visual Basic application, you define the viewport rectangle by using the D3DVIEWPORT7 type. The D3DVIEWPORT7 type is used with the viewport manipulation methods offered by the Direct3DDevice7 class: Direct3DDevice7.SetViewport and Direct3DDevice7.GetViewport. The D3DVIEWPORT7 type contains four members—lX, lY, lWidth, and lHeight—that define the area of the render-target surface into which a scene will be rendered, called the "viewport rectangle".

These values correspond to the destination rectangle, or viewport rectangle, as shown in the following illustration.

The values you specify for the lX, lY, lWidth, and lHeight members of the D3DVIEWPORT7 type are screen coordinates relative to the upper-left corner of the render-target surface. The type defines two additional members (minz and maxz) indicate the depth-ranges into which the scene will be rendered.

Direct3D assumes that the viewport clipping volume ranges from -1.0 to 1.0 in x, and from 1.0 to -1.0 in y (these were the settings used most often by applications in the past). In DirectX 7.0, as in previous releases of DirectX, you can adjust for viewport aspect ratio before clipping, during the projection transformation. This task is covered by topics in the The Projection Transformation section.


Clipping Volumes

The results of the projection matrix determine the clipping volume, in projection space. Direct3D defines the clipping volume in projection space as:

In the preceding formulas, Xc, Yc, Zc, and Wc represent the vertex coordinates after the projection transformation is applied. Any vertices that have an x, y, or z component outside these ranges are clipped, if clipping is enabled (the default behavior).

[C++]

With the exception of vertex buffers, applications enable or disable clipping by way of the D3DRENDERSTATE_CLIPPING render state. Clipping information for vertex buffers is generated during processing, for more information see Processing Vertices.

[Visual Basic]

With the exception of vertex buffers, applications enable or disable clipping by way of the D3DRENDERSTATE_CLIPPING render state. Clipping information for vertex buffers is generated during processing, for more information see Processing Vertices.


Viewport Scaling

[C++]

The dimensions used in the dwX, dwY, dwWidth, and dwHeight members of the D3DVIEWPORT7 structure for a viewport define the location and dimensions of the viewport on the render-target surface. These values are in screen coordinates, relative to the upper-left corner of the surface.

Direct3D uses the viewport location and dimensions to scale the vertices to fit a rendered scene into the appropriate location on the target surface. Internally, Direct3D inserts these values into a matrix that is applied to each vertex:

This matrix simply scales vertices according to the viewport dimensions and desired depth range and translates them to the appropriate location on the render-target surface. (The matrix also "flips" the y-coordinate to reflect a screen origin at the top-left corner with y increasing downward.) After this matrix is applied, vertices are still homogeneous—that is, they still exist as [x,y,z,w] vertices—and they must be converted to non-homogeneous coordinates before being sent to the rasterizer. This is performed by way of simple division, as discussed in The Rasterizer.

Note The viewport scaling matrix in by DirectX 7.0 incorporates the dvMinZ and dvMaxZ members of the D3DVIEWPORT7 structure to scale vertices to fit the depth range [dvMinZ, dvMaxZ]. This represents different semantics from previous releases of DirectX, in which these members were used for clipping. For more information, see Viewport Rectangle and Clipping Volumes. Applications typically set dvMinZ and dvMaxZ to 0.0 and 1.0 to cause the system to render to the entire depth range. However, you can use other values to achieve certain affects. You might set both values to 0.0 to force all objects into the foreground, or set both to 1.0 to render all objects into the background.

[Visual Basic]

The dimensions used in the lX, lY, lWidth, and lHeight members of the D3DVIEWPORT7 type for a viewport define the location and dimensions of the viewport on the render-target surface. These values are in screen coordinates, relative to the upper-left corner of the surface.

Direct3D uses the viewport location and dimensions to scale the vertices to fit a rendered scene into the appropriate location on the target surface. Internally, Direct3D inserts these values into a matrix that is applied to each vertex:

This matrix simply scales vertices according to the viewport dimensions and desired depth range and translates them to the appropriate location on the render-target surface. (The matrix also "flips" the y-coordinate to reflect a screen origin at the top-left corner with y increasing downward.) After this matrix is applied, vertices are still homogeneous—that is, they still exist as [x,y,z,w] vertices—and they must be converted to non-homogeneous coordinates before being sent to the rasterizer. This is performed by way of simple division, as discussed in The Rasterizer.


Using Viewports

This section provides details about working with viewports. Information is divided into the following topics:

  • Setting the Viewport Clipping Volume
  • Clearing a Viewport
  • Manually Transforming Vertices


Setting the Viewport Clipping Volume

The only thing required to configure the viewport parameters for a rendering device is to set the viewport's clipping volume. To do this, you initialize and set clipping values for the clipping volume and for the render-target surface. Viewports are commonly set up to render to the full area of the render-target surface, but this isn't a requirement.

[C++]

You could use the following settings for the members of the D3DVIEWPORT7 structure to achieve this from C++:

    memset(&viewData, 0, sizeof(D3DVIEWPORT7));
    viewData.dwX = 0;
    viewData.dwY = 0;
    viewData.dwWidth  = width;
    viewData.dwHeight = height;
    viewData.dvMinZ = 0.0f;
    viewData.dvMaxZ = 1.0f;

After setting values in the D3DVIEWPORT7 structure, simply apply the viewport parameters to the device by calling its IDirect3DDevice7::SetViewport method. The following examples shows what this call might look like:

    HRESULT hr;

    hr = lpD3DDevice->SetViewport(&viewData);
    if(FAILED(hr))
return hr;

If the call succeeds, the viewport parameters are set and will take effect the next time a rendering method is called. If you need to make changes to the viewport parameters, just update the values in the D3DVIEWPORT7 structure and call SetViewport again.

Note The D3DVIEWPORT7 structure members dvMinZ and dvMaxZ are interpreted in a manner completely different than in previous versions of DirectX. The dvMinZ and dvMaxZ members now indicate the depth-ranges into which the scene will be rendered, and are not used for clipping. Most applications will set these members to 0.0 and 1.0 to enable the system to render to the entire range of depth values in the depth buffer. In some cases, you can achieve special effects by using other depth ranges. For instance, if you wanted to render a heads-up display in a game, you could set both values to 0.0 to force the system to render objects in a scene in the foreground, or you might set them both to 1.0 to render an object that should always be in the background.

[Visual Basic]

The following Visual Basic code creates settings in a D3DVIEWPORT7 type to achieve this:

Dim viewData As D3DVIEWPORT7

With viewData
    .lX = 0: .lY = 0
    .lWidth = Width: .lHeight = Height
    .minz = 0#: .maxz = 1#
End With

After setting values in the D3DVIEWPORT7 type, simply apply the viewport parameters to the device by calling its Direct3DDevice7.SetViewport method.

' The dev variable contains a valid reference to a Direct3DDevice7 object.
Call dev.SetViewport(viewData)

After the call, the viewport parameters are set and will take effect the next time a rendering method is called. If you need to make changes to the viewport parameters, just update the values in the D3DVIEWPORT7 type and call SetViewport again.


Clearing a Viewport

Clearing the viewport resets the contents of the viewport rectangle on the render-target surface as well as the rectangle in the depth and stencil buffer surfaces (if specified). Typically, you will clear the viewport before rendering a new frame to ensure that graphics and other data is ready to accept new rendered objects without displaying artifacts.

[C++]

The IDirect3DDevice7 interface offers C++ developers the IDirect3DDevice7::Clear method to clear the viewport. The method accepts one or more rectangles that define the area or areas on the surfaces being cleared. In cases where the scene being rendered includes motion throughout the entire viewport rectangle—in a first-person perspective game, perhaps—you might want to clear the entire viewport each frame. In this situation, you would set the dwCount parameter to 1, and the lpRects parameter to the address of a single rectangle that covers the entire viewport area. If you find it more convenient, you can set the lpRects parameter to NULL and the dwCount parameter to 0 to indicate that the entire viewport rectangle should be cleared.

The Clear method is flexible, and provides support for clearing stencil bits within a depth buffer. The dwFlags parameter accepts three flags that determine how it clears the render target and any associated depth or stencil buffers. If you include the D3DCLEAR_TARGET flag, the method clears the viewport using an arbitrary RGBA color that you provide in the dwColor parameter (not the material color). If you include the D3DCLEAR_ZBUFFER flag, the method clears the depth buffer to an arbitrary depth you specify in dvZ: 0.0 is the closest distance, and 1.0 is the farthest. Including the D3DCLEAR_STENCIL flag causes the method to reset the stencil bits to the value you provide in the dwStencil parameter. You can use integers that range from 0 to 2n-1, where n is the stencil buffer bit depth.

Note DirectX 5.0 allowed background materials to have associated textures, making it possible to clear the viewport to a texture, rather than a simple color. This feature was little used, and not particularly efficient. Interfaces for DirectX 6.0 and later do not accept texture handles, meaning that you can no longer clear the viewport to a texture. Rather, applications must now draw backgrounds manually. As a result, there is rarely a need to clear the viewport on the render-target surface. So long as your application clears the depth buffer, all pixels on the render-target surface will be overwritten anyway.

In some situations, you might only be rendering to small portions of the render target and depth buffer surfaces. The clear methods also allow you to clear multiple areas of your surfaces in a single call. Do this by setting the dwCount parameter to the number of rectangles you want cleared, and specify the address of the first rectangle in an array of rectangles in the lpRects parameter.

[Visual Basic]

The Direct3DDevice7 Visual Basic class offers the Direct3DDevice7.Clear method to clear the viewport. The method accepts one or more rectangles that define the area or areas on the surfaces being cleared. In cases where the scene being rendered includes motion throughout the entire viewport rectangle—in a first-person perspective game, perhaps—you might want to clear the entire viewport each frame. In this situation, you would set the count parameter to 1, and the recs() parameter to a single-element array of D3DRECT variables (where the first and only element describes a rectangle that covers the entire area of the render-target surface).

The Clear method is flexible, and provides support for clearing stencil bits within a depth buffer. The flags parameter accepts three flags that determine how it clears the render target and any associated depth or stencil buffers. If you include the D3DCLEAR_TARGET flag, the method clears the viewport using an arbitrary RGBA color that you provide in the color parameter (not the material color). If you include the D3DCLEAR_ZBUFFER flag, the method clears the depth buffer to an arbitrary depth you specify in z: 0.0 is the closest distance, and 1.0 is the farthest. Including the D3DCLEAR_STENCIL flag causes the method to reset the stencil bits to the value you provide in the stencil parameter. You can use integers that range from 0 to 2n-1, where n is the stencil buffer bit depth.

In some situations, you might only be rendering to small portions of the render target and depth buffer surfaces. The clear methods also allow you to clear multiple areas of your surfaces in a single call. Do this by setting the count parameter to the number of rectangles you want cleared, and an array of rectangles in the recs() parameter.


Manually Transforming Vertices

You can use three different kinds of vertices in your Direct3D application. Read Vertex Formats for more details on the vertex formats:

[C++]
Untransformed, unlit vertices
Vertices that your application doesn't light or transform. C++ applications that neither transform nor light vertices before rendering a scene can use D3DVERTEX vertices (or an equivalent flexible vertex format). Although you specify lighting parameters and transformation matrices, Direct3D does the math.
Untransformed, lit vertices
Vertices that your application lights but does not transform. C++ applications that use customized lighting effects might use D3DLVERTEX vertices (or an equivalent flexible vertex format).
Transformed, lit, vertices
Vertices that your application both lights and transforms. C++ applications that transform and light vertices on their own might use D3DTLVERTEX vertices (or an equivalent flexible vertex format). These vertices skip the transformations in the geometry pipeline altogether but they can be clipped by the system if needed. If your application clips vertices itself, you can get the best performance by specifying the D3DDP_DONOTCLIP flag when calling a rendering method. If you want Direct3D to clip vertices, omit the D3DDP_DONOTCLIP flag. Note that if you request Direct3D clipping on transformed and lit vertices, the system back-transforms them to camera space for clipping, then transforms them back to screen space, incurring processing overhead.

In DirectX 7.0, you can change from simple to complex vertex types by using vertex buffers. (In previous releases of DirectX, applications could call the TransformVertices method of the legacy IDirect3DViewport3 interface. With the advent of vertex buffers in DirectX 6.0 and the abandonment of discrete viewport objects in DirectX 7.0, this method became obsolete.) Vertex buffers are objects used to efficiently contain and process batches of vertices for rapid rendering, and are optimized to exploit processor-specific features. Vertex buffers offer the IDirect3DVertexBuffer7::ProcessVertices and IDirect3DVertexBuffer7::ProcessVerticesStrided methods to perform vertex transformations for you; this is usually much faster than the TransformVertices method. The ProcessVertices family of methods method accepts only untransformed vertices, and can optionally light and clip vertices as well. Lighting is performed at the time you call the ProcessVertices methods, but clipping is actually performed at render time.

After processing the vertices, you can use special rendering methods to render the vertices, or you can access them directly by locking the vertex buffer memory. For more information about using vertex buffers, see Vertex Buffers.

[Visual Basic]
Untransformed, unlit vertices
Vertices that your application doesn't light or transform. Visual Basic applications that neither transform nor light vertices before rendering a scene can use D3DVERTEX vertices (or an equivalent flexible vertex format). Although you specify lighting parameters and transformation matrices, Direct3D does the math.
Untransformed, lit vertices
Vertices that your application lights but does not transform. Visual Basic applications that use customized lighting effects might use D3DLVERTEX vertices (or an equivalent flexible vertex format).
Transformed, lit, vertices
Vertices that your application both lights and transforms. Visual Basic applications that transform and light vertices on their own might use D3DTLVERTEX vertices (or an equivalent flexible vertex format). These vertices skip the transformations in the geometry pipeline altogether but they can be clipped by the system if needed. If your application clips vertices itself, you can get the best performance by specifying the D3DDP_DONOTCLIP flag when calling a rendering method. If you want Direct3D to clip vertices, omit the D3DDP_DONOTCLIP flag. Note that if you request Direct3D clipping on transformed and lit vertices, the system back-transforms them to camera space for clipping, then transforms them back to screen space, incurring processing overhead.

You can change from simple to complex vertex types by using vertex buffers. Vertex buffers are objects used to efficiently contain and process batches of vertices for rapid rendering, and are optimized to exploit processor-specific features. Vertex buffers offer the Direct3DVertexBuffer7.ProcessVertices method to perform vertex transformations for you; this is usually much faster than the TransformVertices method. The ProcessVertices method accepts only untransformed vertices, and can optionally light and clip vertices as well. Lighting is performed at the time you call ProcessVertices, but clipping is actually performed at render time.

After processing the vertices, you can use special rendering methods to render the vertices, or you can access them directly by locking the vertex buffer memory. For more information about using vertex buffers, see Vertex Buffers.


The Rasterizer

After passing through the Direct3D geometry pipeline, vertices have been transformed, clipped, and scaled to fit in the viewport on the render-target surface, making them almost ready to be sent to the rasterizer to be painted on the screen. However, the vertices are still homogeneous, and the rasterizer expects to receive vertices in terms of their x-, y-, and z-locations, as well as the reciprocal-of-homogeneous-w (RHW). Direct3D converts the homogeneous vertices to non-homogeneous vertices by dividing the x-, y-, and z-coordinates by the w-coordinate, and produces an RHW value by inverting the w-coordinate, as in the following formulas:

The resulting values are passed to the rasterizer for display. The rasterizer uses the x- and y-coordinates as the screen coordinates for the vertex, and uses the z-coordinate for depth comparisons in the depth buffer, when z-buffering is enabled. The RHW value is used in multiple ways: for calculating fog, for performing perspective-correct texture mapping, and for w-buffering (an alternate form of depth buffering).


Lighting and Materials

This section describes illumination in Direct3D Immediate Mode scenes, using ambient light levels, and applying lights and materials to objects in your 3-D scenes. The following topics are discussed:

  • Introduction to Lighting and Materials

    Describes, in general terms, the roles of light sources and materials in a Direct3D Immediate Mode scene.

  • Direct3D Light Model vs. Nature

    Describes the Direct3D illumination model in more detail, and contrasts it with the behavior of light in the natural world.

  • Color Values for Lights and Materials

    Describes the RGBA color values used with both light sources and materials in Direct3D Immediate Mode.

  • Direct Light vs. Ambient Light

    Compares and contrasts the roles of true light sources and ambient light levels.

  • Enabling and Disabling the Lighting Engine

    Describes how to enable or disable the Direct3D lighting engine.

  • Lights

    Describes lights in Direct3D and provides information on how to use them in a scene.

  • Materials

    Describes materials in Direct3D Immediate Mode and provides information about how to use them in a scene.

  • Mathematics of Direct3D Lighting

    Provides details about the math behind the Direct3D light model.


Introduction to Lighting and Materials

When lighting is enabled, as Direct3D rasterizes a scene in the final stage of rendering, it determines the color of each rendered pixel based on a combination of the current material color (and the texels in an associated texture map), the diffuse and specular colors at the vertex, if specified, as well as the color and intensity of light produced by light sources in the scene or the scene's ambient light level. When you use Direct3D lighting and materials, you are allowing Direct3D to handle the details of illumination for you, but advanced users can perform lighting on their own if necessary.

How you work with lighting and materials makes a huge difference in the appearance of the rendered scene. Materials define how light reflects off of a surface. Direct light and ambient light levels define the light that is being reflected. You must use materials to render a scene if you are letting Direct3D handle lighting. Lights are not actually required to render a scene, but you'll be hard pressed to see much in a scene rendered without light. At best, rendering an unlit scene will result in a silhouette of the objects in the scene—not enough detail for most purposes.


Direct3D Light Model vs. Nature

In nature, when light is emitted from a source, it reflects off hundreds (if not thousands or millions) of objects before reaching the viewer's eye. Each time it reflects, parts of the light are absorbed by a surface, parts are scattered in random directions, and the rest goes on to another surface or to the viewer. This process continues until the light attenuates to nothing or a viewer perceives the light—but, who knows how many times the light will bounce? It could be once, a hundred times, or millions of times.

Obviously, the calculations required to perfectly simulate the natural behavior of light are, by far, too time consuming to be used for real-time 3-D graphics. Therefore, with the interest of speed in mind, the Direct3D light model approximates the way light works in the natural world. Direct3D describes light in terms of red, green, and blue components that combine to create a final color. For more information, see Color Values for Lights and Materials. In Direct3D, when light reflects off a surface, the light color interacts mathematically with the surface itself to create the color eventually drawn to the screen. For specific information about the algorithms Direct3D uses, see Mathematics of Direct3D Lighting.

The Direct3D Immediate Mode light model generalizes light into two types: ambient light and direct light. Each has different attributes, and each interacts with the material of a surface in different ways. Ambient light is light that has been scattered so much that its direction and source are indeterminate: it maintains a low-level of intensity everywhere. The indirect lighting used by photographers is a good example of ambient light. Ambient light in Direct3D, as in nature, has no real direction or source, only a color and intensity. In fact, the ambient light level is completely independent of any objects in a scene that generate light. Ambient light does not contribute to specular reflection.

Direct light is the light generated by a source within a scene; it always has color and intensity, and travels in a specified direction. Direct light interacts with the material of a surface to create specular highlights, and its direction is used as a factor in shading algorithms, including Gouraud shading. When direct light is reflected, it does not contribute to the ambient light level in a scene. The sources in a scene that generate direct light have different characteristics that affect how they illuminate a scene. For more information, see Lights.

Additionally, a polygon's material has properties that affect how that polygon reflects the light it receives. You set a single reflectance trait that describes how the material reflects ambient light, and you set individual traits to determine the material's specular and diffuse reflectance. For more information, see Materials.


Color Values for Lights and Materials

Direct3D Immediate Mode describes color in terms the four components (red, green, blue, and alpha) that combine to make a final color. The D3DCOLORVALUE C++ structure is defined to contain values for each component. (Visual Basic applications use the D3DCOLORVALUE type.) Each member is a floating point value that typically ranges from 0.0 to 1.0, inclusive. Although both lights and materials use the same structure to describe color, the values within the structure are used a little differently by each.

Color values for light sources represent the amount of a particular light component it emits. Lights don't use an alpha component, so you only need to think about the red, green, and blue components of the color. You can visualize the three components as the red, green, and blue lenses on a projection television. Each lens might be off (a 0.0 value in the appropriate member), it might be as bright as possible (a 1.0 value), or some level in between. The colors coming from each lens combine to make the light's final color. A combination like R: 1.0, G: 1.0, B: 1.0 creates a white light, where R: 0.0, G: 0.0, B: 0.0 results in a light that doesn't emit light at all. You can make a light that emits only one component, resulting in a purely red, green, or blue light, or, the light could use combinations to emit colors like yellow or purple. You can even set negative values color component values to create a "dark light" that actually removes light from a scene. Or, you might set the components to some value larger than 1.0 to create an extremely bright light.

With materials, on the other hand, color values represent how much of a given light component is reflected by a surface that is rendered with that material. A material whose color components are R: 1.0, G: 1.0, B: 1.0, A: 1.0 will reflect all the light that comes its way. Likewise, a material with R: 0.0, G: 1.0, B: 0.0, A: 1.0 will reflect all of the green light that is directed at it. Materials have multiple reflectance values to create various types of effects; for more information, see Material Properties.

Color values for ambient light are different than those used for direct light sources and materials. For more information, see Direct Light vs. Ambient Light.


Direct Light vs. Ambient Light

Although both direct and ambient light illuminate objects in a scene, they are independent of one another, they have very different effects, and they require that you work with them in completely different ways.

[C++]

Direct light is just that: direct. Direct light always has direction and color, and it is a factor for shading algorithms, such as Gouraud shading. Different types of lights emit direct light in different ways, creating special attenuation effects. You create a sets of light parameters for direct light by calling the IDirect3DDevice7::SetLight method. For more information, see Lights.

Ambient light is effectively everywhere in a scene. You can think of it as a general level of light that fills an entire scene, regardless of the objects and their locations within that scene. Ambient light, being everywhere, has no position or direction, only color and intensity. Set the ambient light level with a call to the IDirect3DDevice7::SetRenderState method, specifying D3DRENDERSTATE_AMBIENT as the dwRenderStateType parameter, and the desired RGBA color as the dwRenderState parameter.

Ambient light color takes the form of an RGBA value, where each component is an integer value from 0 to 255. (This is unlike most color values in Direct3D Immediate Mode. For more information, see Color Values for Lights and Materials.) You can use the RGBA_MAKE macro to generate RGBA values from integers. The red, green, and blue components combine to make the final color of the ambient light. The alpha component controls the transparency of the color. In ramp emulation, ambient light doesn't have color, so the alpha component is used for brightness. When using hardware acceleration or RGB emulation, the alpha component is ignored.

[Visual Basic]

Direct light is just that: direct. Direct light always has direction and color, and it is a factor for shading algorithms, such as Gouraud shading. Different types of lights emit direct light in different ways, creating special attenuation effects. You create a sets of light parameters for direct light by calling the Direct3DDevice7.SetLight method. For more information, see Lights.

Ambient light is effectively everywhere in a scene. You can think of it as a general level of light that fills an entire scene, regardless of the objects and their locations within that scene. Ambient light, being everywhere, has no position or direction, only color and intensity. Set the ambient light level with a call to the Direct3DDevice7.SetRenderState method, specifying D3DRENDERSTATE_AMBIENT as the state parameter, and the desired RGBA color as the renderstate parameter.

You can use the DirectX7.CreateColorRGBA method to generate RGBA values from values of type Single. The red, green, and blue components combine to make the final color of the ambient light. The alpha component controls the transparency of the color. In ramp emulation, ambient light doesn't have color, so the alpha component is used for brightness. When using hardware acceleration or RGB emulation, the alpha component is ignored.


Enabling and Disabling the Lighting Engine

[C++]

By default, Direct3D performs lighting calculations on all vertices, even those without vertex normals. (This is different from the behavior in previous releases of DirectX, where lighting was performed only on vertices that contained a vertex normal.) However, you can disable lighting through the D3DRENDERSTATE_LIGHTING render state. Call the IDirect3DDevice7::SetRenderState method, passing D3DRENDERSTATE_LIGHTING as the first parameter, and TRUE or FALSE as the second parameter. Setting the state to TRUE enables lighting (the default) and setting it to FALSE disables lighting operations.

If your application uses vertex buffers, the process is slightly different, but it's just as simple: include or omit the D3DVOP_LIGHT flag when calling the IDirect3DVertexBuffer7::ProcessVertices or IDirect3DVertexBuffer7::ProcessVerticesStrided methods to enable or disable lighting for that vertex buffer.

[Visual Basic]

By default, Direct3D performs lighting calculations on all vertices, even those without vertex normals. However, you can disable lighting through the D3DRENDERSTATE_LIGHTING render state. Call the Direct3DDevice7.SetRenderState method, passing D3DRENDERSTATE_LIGHTING as the first parameter, and True or False as the second parameter. Setting the state to True enables lighting (the default) and setting it to False disables lighting operations.

If your application uses vertex buffers, the process is slightly different, but it's just as simple: include or omit the D3DVOP_LIGHT flag when calling the Direct3DVertexBuffer7.ProcessVertices method to enable or disable lighting for that vertex buffer.


Lights

Lights are used to illuminate objects in a scene. This section describes lights and how they are used in Direct3D Immediate Mode. The following topics are discussed:

  • Introduction to Light Objects
  • Light Properties
  • Using Lights


Introduction to Light Objects

Direct3D employs three types of lights: point lights, spotlights, and directional lights. You choose the type of light you want when you create a set of light properties. The illumination properties and the resulting computational overhead varies with each type of light source. The following types of light sources, supported by the Direct3D lighting module, are discussed:

  • Point lights
  • Spotlights
  • Directional lights

Note DirectX 7.0 does not use the parallel-point light type offered in previous releases of DirectX.

Do not confuse light sources in a scene with the concept of an ambient light level. For more information, see Direct Light vs. Ambient Light, Light Properties and Using Lights.


Point Lights

Point lights have color and position within a scene, but no single direction. They give off light equally in all directions, as shown in the following illustration.

A light bulb would be a good example of a point light. Point lights are affected by attenuation and range, and illuminate a mesh on a vertex-by-vertex basis. During lighting, Direct3D uses the point light's position in world space and the coordinates of the vertex being lit to derive a vector for the direction of the light, and the distance that the light has traveled. Both of these are used (along with the vertex normal) to calculate the contribution of the light to the illumination of the surface.


Spotlights

Spotlights have color, position, and direction in which they emit light. Light emitted from a spotlight is made up of a bright inner cone, and a larger outer cone, with the light intensity diminishing between the two, as shown in the following illustration, along with the related members from the D3DLIGHT7 C++ structure (the D3DLIGHT7 Visual Basic type parallels this structure).

Spotlights are affected by falloff, attenuation, and range. These factors, as well as the distance light travels to each vertex, are figured in while computing lighting effects for objects in a scene. Computing all these effects for each vertex makes spotlights the most computationally expensive of all lights in Direct3D Immediate Mode.


Directional Lights

Directional lights have only color and direction, not position. They give off parallel light, meaning that all light generated by it travels through scene in the same direction. You can imagine a directional light as a light source at near infinite distance, such as the sun. Directional lights are not affected by attenuation or range, so the direction and color you specify are the only factors considered when Direct3D calculates vertex colors. Because of the small number of illumination factors, these are the least computationally intensive lights to use.


Light Properties

Light properties describe a light source's type and color. Depending on the type of light being used, a light can have properties for attenuation and range, or for spotlight effects. But, not all types of lights will use all properties. Direct3D Immediate Mode uses the D3DLIGHT7 structure (for C++) and the D3DLIGHT7 type (for Visual Basic) to carry information about light properties for all types of light sources. This section contains information for all light properties. Information is divided into the following groups:

  • Light Type
  • Light Color
  • Light Position, Range and Attenuation
  • Light Direction
  • Spotlight Properties

Light properties affect how a light source illuminates objects in a scene. For more information, see Using Lights, Setting Light Properties, and Mathematics of Direct3D Lighting.


Light Type

[C++]

The light type property defines which type of light source you're using. The light type is set by using a value from the D3DLIGHTTYPE C++ enumeration in the dltType member of the light's D3DLIGHT7 structure. There are three types of lights in Direct3D Immediate Mode—point lights, spotlights, and directional lights. Each type illuminates objects in a scene differently, with varying levels of computational overhead. For general information about how each type of light works, see Introduction to Light Objects.

[Visual Basic]

The light type property defines which type of light source you're using. The light type is set by using a value from the CONST_D3DLIGHTTYPE Visual Basic enumeration in the dltType member of the light's D3DLIGHT7 type. There are three types of lights in Direct3D Immediate Mode—point lights, spotlights, and directional lights. Each type illuminates objects in a scene differently, with varying levels of computational overhead. For general information about how each type of light works, see Introduction to Light Objects.


Light Color

Lights in Direct3D emit three colors that are used independently in the system's lighting computations: a diffuse color, an ambient color, and a specular color. Each is incorporated by the Direct3D lighting module, interacting with a counterpart from the current material, to produce a final color used in rendering. The diffuse color interacts with the diffuse reflectance property of the current material, the specular color with the material's specular reflectance property, and so on. (For specifics about how Direct3D applies these colors, see Mathematics of Direct3D Lighting.)

[C++]

In a C++ application, the D3DLIGHT7 structure includes three members for these colors—dcvDiffuse, dcvAmbient, and dcvSpecular—each one is a D3DCOLORVALUE structure that defines the color being emitted.

[Visual Basic]

The D3DLIGHT7 Visual Basic type includes three members for these colors—dcvDiffuse, dcvAmbient, and dcvSpecular—each one is a D3DCOLORVALUE type that defines the color being emitted.

The type of color that applies most heavily to the system's computations is the diffuse color. The most common diffuse color is white (R:1.0 G:1.0 B:1.0), but you can create colors as needed to achieve desired effects. For example, you could use red light for a fireplace, or you could use green light for a traffic signal set to "Go."

Generally, you set the light color components to values between 0.0 and 1.0, inclusive, but this isn't a requirement. For example, you might set all the components to 2.0, creating a light that was "brighter than white." This type of setting can be especially useful when you use attenuation settings other than constant.

Note that although Direct3D uses RGBA values for lights, the alpha color component is not used. For more information, see Color Values for Lights and Materials.


Light Position, Range and Attenuation

[C++]

The position, range, and attenuation properties are used to define a light's location in world space, and how the light it emits behaves over distance. Like all light the properties you use in C++, these are carried within a light's D3DLIGHT7 structure.

Position

Light position is described using a D3DVECTOR structure in the dvPosition member of the D3DLIGHT7 structure. The x-, y-, and z-coordinates are assumed to be in world space. Directional lights are the only type of light that don't use the position property.

Range

A light's range property determines the distance, in world space, at which meshes in a scene no longer receive light emitted by that object. The dvRange member contains a floating-point value that represents the light's maximum range, in world space. Most applications set the range to the maximum possible value, D3DLIGHT_RANGE_MAX, which is defined in D3d.h. Directional lights don't use the range property.

Attenuation

Attenuation controls how a light's intensity decreases toward the maximum distance specified by the range property. Light attenuation is represented by three D3DLIGHT7 structure members: dvAttenuation0, dvAttenuation1, and dvAttenuation2. These members contain floating point values typically ranging from 0.0 to 1.0, controlling a light's constant, linear, and quadratic attenuation. Many applications set the dvAttenuation1 member to 1.0 and the others to 0.0, resulting in light intensity that attenuates evenly over distance—from maximum intensity at the source, to zero intensity at the light's range. You can combine attenuation values to get more complex attenuation effects. Or, you might set them to values outside of the normal range to create even stranger attenuation effects; negative attenuation values make a light that gets brighter over distance. For more information about the mathematical model that Direct3D uses to calculate attenuation, see Light Attenuation Over Distance. Like the range property, directional lights don't use the attenuation property.

[Visual Basic]

The D3DLIGHT7 type includes members that your Visual Basic application uses to define a light's position, range, and attenuation properties. These describe a light's location in world space, and how the light it emits behaves over distance.

Position

Light position is described using a D3DVECTOR type in the position member of the D3DLIGHT7 type. The x-, y-, and z-coordinates are assumed to be in world space. Directional lights are the only type of light that don't use the position property.

Range

A light's range property determines the distance, in world space, at which meshes in a scene no longer receive light emitted by that object. The range member contains a floating-point value that represents the light's maximum range, in world space. Most applications set the range to the maximum possible value (18.446+e18). Directional lights don't use the range property.

Attenuation

Attenuation controls how a light's intensity decreases toward the maximum distance specified by the range property. Light attenuation is represented by three D3DLIGHT7 members: attenuation0, attenuation1, and attenuation2. These members contain floating point values typically ranging from 0.0 to 1.0, controlling a light's constant, linear, and quadratic attenuation. Many applications set the attenuation1 member to 1.0 and the others to 0.0, resulting in light intensity that attenuates evenly over distance—from maximum intensity at the source, to zero intensity at the light's range. You can combine attenuation values to get more complex attenuation effects. Or, you might set them to values outside of the normal range to create even stranger attenuation effects; negative attenuation values make a light that gets brighter over distance. For more information about the mathematical model that Direct3D uses to calculate attenuation, see Light Attenuation Over Distance. Like the range property, directional lights don't use the attenuation property.


Light Direction

A light's direction property determines the direction that the light emitted by the object travels, in world space. Direction is only used by directional and spotlights, and is described with a vector.

[C++]

An application that uses C++ employs the the dvDirection member (a D3DVECTOR structure) of the D3DLIGHT7 structure. Direction vectors are described as distances from a logical origin, regardless of the light's position within a scene. Therefore, a spotlight that points straight into a scene (along the positive z-axis) would have a direction vector of <0,0,1> no matter where its position is defined to be. Similarly, you could simulate sunlight shining directly down on a scene by using a directional light whose direction is <0,-1,0>. Obviously, you don't have to create lights that shine along the coordinate axes; you can mix and match values to create lights that shine at more interesting angles.

[Visual Basic]

Visual Basic applications set the light direction in the direction member of the light's D3DLIGHT7 type. The direction member is of type D3DVECTOR. Direction vectors are described as distances from a logical origin, regardless of the light's position within a scene. Therefore, a spotlight that points straight into a scene (along the positive z-axis) would have a direction vector of <0,0,1> no matter where its position is defined to be. Similarly, you could simulate sunlight shining directly down on a scene by using a directional light whose direction is <0,-1,0>. Obviously, you don't have to create lights that shine along the coordinate axes; you can mix and match values to create lights that shine at more interesting angles.

Note Although you don't need to normalize a light's direction vector, always be sure that it has magnitude. In other words, don't use a <0,0,0> direction vector.


Spotlight Properties

[C++]

The D3DLIGHT7 C++ structure contains three members that are used only by spotlights. These members (dvFalloff, dvTheta, and dvPhi) control how large or small a spotlight object's inner and outer cones are, and how light decreases between them. For general information about these characteristics, see Spotlights.

The dvTheta value is the radian angle of the spotlight's inner cone and the dvPhi value is the angle for the outer cone of light. The dvFalloff value controls how light intensity decreases between the outer edge of the inner cone and in the inner edge of the outer cone. Most applications will set dvFalloff to 1.0 to create falloff that occurs evenly between the two cones, but you can set other values as needed. For more information about the mathematical model used by Direct3D for calculating falloff, see Spotlight Falloff Model.

The following illustration shows the relationship between the values for these members, and how they can affect a spotlight's inner and outer cones of light.

[Visual Basic]

The D3DLIGHT7 Visual Basic type contains three members that are used only by spotlights. These members (falloff, theta, and phi) control how large or small a spotlight object's inner and outer cones are, and how light decreases between them. For general information about these characteristics, see Spotlights.

The theta value is the radian angle of the spotlight's inner cone and the phi value is the angle for the outer cone of light. The falloff value controls how light intensity decreases between the outer edge of the inner cone and in the inner edge of the outer cone. Most applications will set falloff to 1.0 to create falloff that occurs evenly between the two cones, but you can set other values as needed. For more information about the mathematical model used by Direct3D for calculating falloff, see Spotlight Falloff Model.

The following illustration shows the relationship between the values for these members, and how they can affect a spotlight's inner and outer cones of light.


Using Lights

This section provides information about using lights in a Direct3D Immediate Mode application. Information is divided into the following topics:

  • Setting Light Properties
  • Enabling and Disabling Lights
  • Retrieving Light Properties


Setting Light Properties

[C++]

You set lighting properties in a C++ application by preparing a D3DLIGHT7 structure and then calling the IDirect3DDevice7::SetLight method. The SetLight method accepts the index at which the device should place the set of light properties to its internal list of light properties, and the address of a prepared D3DLIGHT7 structure that defines those properties. You can call SetLight with new information as needed to update the light's illumination properties.

The system allocates memory to accommodate a set of lighting properties each time you call the SetLight method with an index that has never been assigned properties. Applications can set a very large number of lights, with only a subset of the assigned lights enabled at a time. Check the dwMaxActiveLights member of the D3DDEVICEDESC7 structure when you retrieve device capabilities to determine the maximum number of active lights supported by that device. If you do not need to use a particular light anymore, you can disable it, or overwrite it with a new set of light properties.

The following C++ code prepares and sets properties for a white point-light whose emitted light will not attenuate over distance:

    /*
     * For the purposes of this example, the g_lpd3dDev variable
     * is a valid pointer to an IDirect3DDevice7 interface.
     */
    D3DLIGHT7 d3dLight;
    HRESULT   hr;

    // Initialize the structure.
    ZeroMemory(&d3dLight, sizeof(D3DLIGHT7));

    // Set up for a white point light.
    d3dLight.dltType = D3DLIGHT_POINT;
    d3dLight.dcvDiffuse.r = 1.0f;
    d3dLight.dcvDiffuse.g = 1.0f;
    d3dLight.dcvDiffuse.b = 1.0f;
    d3dLight.dcvAmbient.r = 1.0f;
    d3dLight.dcvAmbient.g = 1.0f;
    d3dLight.dcvAmbient.b = 1.0f;
    d3dLight.dcvSpecular.r = 1.0f;
    d3dLight.dcvSpecular.g = 1.0f;
    d3dLight.dcvSpecular.b = 1.0f;

    // Position it high in the scene, and behind the viewer.
    // (Remember, these coordinates are in world space, so
    //  the "viewer" could be anywhere in world space, too.
    //  For the purposes of this example, assume the viewer
    //  is at the origin of world space.)
    d3dLight.dvPosition.x = 0.0f;
    d3dLight.dvPosition.y = 1000.0f;
    d3dLight.dvPosition.z = -100.0f;

    // Don't attenuate.
    d3dLight.dvAttenuation0 = 1.0f;
    d3dLight.dvRange = D3DLIGHT_RANGE_MAX;

    // Set the property info for the first light.
    hr = g_lpd3dDev->SetLight(0, d3dLight);
    if (FAILED(hr))
    {
// Code to handle the error goes here.
    }

You can update a set of light properties with another call to SetLight at any time. Just specify the index of the set of light properties you want to update and the address of the D3DLIGHT7 structure that contains the new properties.

Note Assigning a set of light properties to the device does not enable the light source whose properties are being added. Enable a light source by calling the IDirect3DDevice7::LightEnable method for the device.

[Visual Basic]

Your Visual Basic application sets lighting properties by preparing a D3DLIGHT7 type and then calling the Direct3DDevice7.SetLight method. The SetLight method accepts the index at which the device should place the set of light properties to its internal list of light properties, and the address of a prepared D3DLIGHT7 type that defines those properties. You can call SetLight with new information as needed to update the light's illumination properties.

The system allocates memory to accommodate a set of lighting properties each time you call the SetLight method with an index that has never been assigned properties. Applications can set a very large number of lights, with only a subset of the assigned lights enabled at a time. Check the lMaxActiveLights member of the D3DDEVICEDESC7 type when you retrieve device capabilities to determine the maximum number of active lights supported by that device. If you do not need to use a particular light anymore, you can disable it, or overwrite it with a new set of light properties.

The following code, written in Visual Basic, prepares and sets properties for a white point-light whose emitted light will not attenuate over distance:

'
' For this example, the d3dDevice variable contains a valid reference
' to a Direct3DDevice7 object.
'
Dim LightDesc As D3DLIGHT7
Dim c As D3DCOLORVALUE
Dim vPos As D3DVECTOR

' Use the same color settings for all emitted light color.
With c
    .r = 1#: .g = 1#: .b = 1#
    .a = 1# ' The alpha component isn't used for lights.
End With

With vPos
    .x = 0: .y = 1000: .z = -100
End With

With LightDesc
    .dltType = D3DLIGHT_POINT
    .position = vPos
    .Ambient = c: .diffuse = c: .specular = c
    .attenuation0 = 1# ' Don't attenuate the light
End With

d3dDevice.SetLight 0, LightDesc

You can update a set of light properties with another call to SetLight at any time. Just specify the index of the set of light properties you want to update and the address of the D3DLIGHT7 type that contains the new properties.

Note Assigning a set of light properties to the device does not enable the light source whose properties are being added. Enable a light source by calling the Direct3DDevice7.LightEnable method for the device.


Enabling and Disabling Lights

[C++]

Once you assign a set of light properties for a light source in a scene, the light source can be activated by calling the IDirect3DDevice7::LightEnable method for the device. New light sources are disabled by default. The LightEnable method accepts two parameters. Set the first parameter to the zero-based index of the light source to be affected by the method, and set the second parameter to TRUE to enable the light or FALSE to disable it.

The following code fragment illustrates the use of this method by enabling the first light source in the device's list of light source properties:

/*
 * For the purposes of this example, the g_lpd3dDev variable
 * is a valid pointer to an IDirect3DDevice7 interface.
 */
HRESULT hr;

hr = g_lpd3dDev->LightEnable(0, TRUE);
if (FAILED(hr))
{
    // Code to handle the error goes here.
}
[Visual Basic]

Once you assign a set of light properties for a light source in a scene, the light source can be activated by calling the Direct3DDevice7.LightEnable method for the device. New light sources are disabled by default. The LightEnable method accepts two parameters. Set the first parameter to the zero-based index of the light source to be affected by the method, and set the second parameter to True to enable the light or False to disable it.

The following code fragment illustrates the use of this method by enabling the first light source in the device's list of light source properties:

'
' For the purposes of this example, the d3dDevice variable contains
' a valid reference to Direct3DDevice7 object.
'
On Local Error Resume Next

Call d3dDevice.LightEnable(0, True)
If Err.Number <> DD_OK Then
    'Code to handle the error goes here.
End If

If you enable a light that has no properties, or supply an index outside the range of the light property sets assigned within the device, the LightEnable method creates a light source with the following properties and enables or disables it:

Member | Default
dltType | D3DLIGHT_DIRECTIONAL
dcvDiffuse | (R:1, G:1, B:1, A:0)
dcvSpecular | (R:0, G:0, B:0, A:0)
dcvAmbient | (R:0, G:0, B:0, A:0)
dvPosition | (0, 0, 0)
dvDirection | (0, 0, 1)
dvRange | 0
dvFalloff | 0
dvAttenuation0 | 0
dvAttenuation1 | 0
dvAttenuation2 | 0
dvTheta | 0
dvPhi | 0


Retrieving Light Properties

[C++]

You can retrieve all the properties for an existing light source from C++ by calling the IDirect3DDevice7::GetLight method for the device. When calling the GetLight method, pass in the first parameter the zero-based index of the light source for which the properties will be retrieved, and supply the address of a D3DLIGHT7 structure in the second parameter. The device will fill the D3DLIGHT7 structure to describe the lighting properties it uses for the light source at that index.

The following C++ code illustrates this process:

    /*
     * For the purposes of this example, the g_lpd3dDev variable
     * is a valid pointer to an IDirect3DDevice7 interface.
     */
    HRESULT hr;
    D3DLIGHT7 light;

    // Get the property info for the first light.
    hr = g_lpd3dDev->GetLight(0, light);
    if (FAILED(hr))
    {
// Code to handle the error goes here.
    }

If you supply an index outside the range of the light sources assigned within the device, the GetLight method will fail, returning DDERR_INVALIDPARAMS.

[Visual Basic]

A Visual Basic application retrieves the properties for an existing light source by calling the Direct3DDevice7.GetLight method for the device. When calling the GetLight method, pass in the first parameter the zero-based index of the light source for which the properties will be retrieved, and a variable of type D3DLIGHT7 as the second parameter. The device will fill the D3DLIGHT7 type to describe the lighting properties it uses for the light source at that index.

The following Visual Basic code fragment illustrates this process:

'
' For the purposes of this example, the d3dDevice variable contains
' a valid reference to a Direct3DDevice7 object.
'
Dim lightDesc As D3DLIGHT7

' Get the property info for the first light.
Call d3dDevice.GetLight(0, lightDesc)
If Err.Number <> DD_OK Then
    ' Code to handle the error goes here.
End If

If you supply an index outside the range of the light sources assigned within the device, the GetLight method will fail, and the value of Err.Number will be DDERR_INVALIDPARAMS.


Materials

This section describes materials and how they are used in Direct3D Immediate Mode applications. The following topics are discussed:

  • What Are Materials?
  • Material Properties
  • Using Materials

Default Material Properties If your application does not specify material properties for rendering, the system uses a default material. The default material reflects all diffuse light (white, you might say), with no ambient or specular reflection, and no emissive color.


What Are Materials?

Materials describe how polygons reflect light or appear to emit light in a 3-D scene. Essentially, a material is a set of properties that tell Direct3D the following things about the polygons it is rendering:

  • How they reflect ambient and diffuse light
  • What their specular highlights look like
  • Whether or not the polygons appear to emit light
[C++]

Direct3D Immediate Mode applications written in C++ use the D3DMATERIAL7 structure to describe material properties. For more information, see Material Properties.

[Visual Basic]

Direct3D Immediate Mode applications written in Visual Basic use the D3DMATERIAL7 type to describe material properties. For more information, see Material Properties.


Material Properties

[C++]

Material properties detail a material's diffuse reflection, ambient reflection, light emission, and specular highlighting characteristics. Direct3D uses the D3DMATERIAL7 structure to carry all material property information. Material properties affect the colors Direct3D uses to rasterize polygons that use the material. With the exception of the specular property, each of the properties is described as an RGBA color that represents how much of the red, green, and blue parts of a given type of light it reflects, and an alpha blending factor (the alpha component of the RGBA color). The material's specular property is described in two parts: color and power. For more information, see Color Values for Lights and Materials.

Diffuse and Ambient Reflection

The dcvDiffuse and dcvAmbient members of the D3DMATERIAL7 structure describe how a material reflects the ambient and diffuse light in a scene. Because most scenes contain much more diffuse light than ambient light, diffuse reflection plays the largest part in determining color. Additionally, because diffuse light is directional, the angle of incidence for diffuse light affects the overall intensity of the reflection. Diffuse reflection is greatest when the light strikes a vertex parallel to the vertex normal. As the angle increases, the effect of diffuse reflection diminishes. The amount of light reflected is the cosine of the angle between the incoming light and the vertex normal, as shown here.

Ambient reflection, like ambient light, is nondirectional. Ambient reflection has a lesser impact on the apparent color of a rendered object, but it does affect the overall color, and is most noticeable when little or no diffuse light reflects off the material. A material's ambient reflection is affected by the ambient light set for a scene by calling the IDirect3DDevice7::SetRenderState method with the D3DRENDERSTATE_AMBIENT flag.

Diffuse and ambient reflection work together to determine the perceived color of an object, and are usually identical values. For example, to render a blue crystalline object, you would create a material that reflected only the blue component of diffuse and ambient light. When placed in a room with a white light, the crystal appears to be blue. However, in a room that has only red light, the same crystal would appear to be black, because its material doesn't reflect red light.

Emission

Materials can be used to make a rendered object appear to be self-luminous. The dcvEmissive member of the D3DMATERIAL7 structure is used to describe the color and transparency of the emitted light. Emission affects an object's color and can, for example, make a dark material brighter and take on part of the emitted color.

You can use a material's emissive property to add the illusion that an object is emitting light, without incurring the computational overhead of adding a light to the scene. In the case of the blue crystal, the emissive property could be handy if you wanted to make the crystal appear to light up, but not actually cast light on other objects in the scene. Remember, materials with emissive properties don't actually emit light that can be reflected by other objects in a scene. To achieve this effect, you would need to place an additional light within the scene.

Specular Reflection

Specular reflection creates highlights on objects, making them appear shiny. The D3DMATERIAL7 structure contains two members that describe the specular highlight color as well as the material's overall shininess. You establish the color of the specular highlights by setting the dcvSpecular member to the desired RGBA color—the most common colors are white or light gray. The values you set in the dvPower member control how sharp the specular effects are.

Specular highlights can create dramatic effects. Drawing again on the blue crystal analogy: a larger dvPower value will create sharper specular highlights, making the crystal appear to be quite shiny. Smaller values increase the area of the effect, creating a dull reflection that might make the crystal look frosty. To make an object truly matte, set the dvPower member to zero, and the color in dcvSpecular to black. Experiment with different levels of reflection to produce a realistic appearance for your needs. The following illustration shows two identical models, the one on the left uses a specular reflection power of 10; the model on the right has no specular reflection.

[Visual Basic]

Material properties detail a material's diffuse reflection, ambient reflection, light emission, and specular highlighting characteristics. Direct3D uses the D3DMATERIAL7 type to carry all material property information. Material properties affect the colors Direct3D uses to rasterize polygons that use the material. With the exception of the specular property, each of the properties is described as an RGBA color that represents how much of the red, green, and blue parts of a given type of light it reflects, and an alpha blending factor (the alpha component of the RGBA color). The material's specular property is described in two parts: color and power. For more information, see Color Values for Lights and Materials.

Diffuse and Ambient Reflection

The diffuse and ambient members of the D3DMATERIAL7 type describe how a material reflects the ambient and diffuse light in a scene. Because most scenes contain much more diffuse light than ambient light, diffuse reflection plays the largest part in determining color. Additionally, because diffuse light is directional, the angle of incidence for diffuse light affects the overall intensity of the reflection. Diffuse reflection is greatest when the light strikes a vertex parallel to the vertex normal. As the angle increases, the effect of diffuse reflection diminishes. The amount of light reflected is the cosine of the angle between the incoming light and the vertex normal, as shown here.

Ambient reflection, like ambient light, is nondirectional. Ambient reflection has a lesser impact on the apparent color of a rendered object, but it does affect the overall color, and is most noticeable when little or no diffuse light reflects off the material. A material's ambient reflection is affected by the ambient light set for a scene by calling the Direct3DDevice7.SetRenderState method with the D3DRENDERSTATE_AMBIENT flag.

Diffuse and ambient reflection work together to determine the perceived color of an object, and are usually identical values. For example, to render a blue crystalline object, you would create a material that reflected only the blue component of diffuse and ambient light. When placed in a room with a white light, the crystal appears to be blue. However, in a room that has only red light, the same crystal would appear to be black, because its material doesn't reflect red light.

Emission

Materials can be used to make a rendered object appear to be self-luminous. The emissive member of the D3DMATERIAL7 type is used to describe the color and transparency of the emitted light. Emission affects an object's color and can, for example, make a dark material brighter and take on part of the emitted color.

You can use a material's emissive property to add the illusion that an object is emitting light, without incurring the computational overhead of adding a light to the scene. In the case of the blue crystal, the emissive property could be handy if you wanted to make the crystal appear to light up, but not actually cast light on other objects in the scene. Remember, materials with emissive properties don't actually emit light that can be reflected by other objects in a scene. To achieve this effect, you would need to place an additional light within the scene.

Specular Reflection

Specular reflection creates highlights on objects, making them appear shiny. The D3DMATERIAL7 type contains two members that describe the specular highlight color as well as the material's overall shininess. You establish the color of the specular highlights by setting the specular member to the desired RGBA color—the most common colors are white or light gray. The values you set in the power member control how sharp the specular effects are.

Specular highlights can create dramatic effects. Drawing again on the blue crystal analogy: a larger power value will create sharper specular highlights, making the crystal appear to be quite shiny. Smaller values increase the area of the effect, creating a dull reflection that might make the crystal look frosty. To make an object truly matte, set the power member to zero, and the color in specular to black. Experiment with different levels of reflection to produce a realistic appearance for your needs. The following illustration shows two identical models, the one on the left uses a specular reflection power of 10; the model on the right has no specular reflection.


Using Materials

This section contains information about using materials in a Direct3D application. Information is divided into the following topics:

  • Setting Material Properties
  • Retrieving Material Properties


Setting Material Properties

Direct3D rendering devices can render with one set of material properties at a time.

[C++]

In a C++ application, you set the material properties that you want the system to use by preparing a D3DMATERIAL7 structure, then calling the IDirect3DDevice7::SetMaterial method.

To prepare the D3DMATERIAL7 structure for use, set the property information in the structure to create the desired effect during rendering. The following code fragment sets up the D3DMATERIAL7 structure for a purple material with sharp white specular highlights:

    D3DMATERIAL7 mat;

    // Set the RGBA for diffuse reflection.
    mat.dcvDiffuse.r = (D3DVALUE)0.5;
    mat.dcvDiffuse.g = (D3DVALUE)0.0;
    mat.dcvDiffuse.b = (D3DVALUE)0.5;
    mat.dcvDiffuse.a = (D3DVALUE)1.0;

    // Set the RGBA for ambient reflection.
    mat.dcvAmbient.r = (D3DVALUE)0.5;
    mat.dcvAmbient.g = (D3DVALUE)0.0;
    mat.dcvAmbient.b = (D3DVALUE)0.5;
    mat.dcvAmbient.a = (D3DVALUE)1.0;

    // Set the color and sharpness of specular highlights.
    mat.dcvSpecular.r = (D3DVALUE)1.0;
    mat.dcvSpecular.g = (D3DVALUE)1.0;
    mat.dcvSpecular.b = (D3DVALUE)1.0;
    mat.dcvSpecular.a = (D3DVALUE)1.0;
    mat.dvPower = (float)50.0;

After preparing the D3DMATERIAL7 structure, you apply them by calling the IDirect3DDevice7::SetMaterial method of the rendering device. This method accepts the address of a prepared D3DMATERIAL7 structure as its only parameter. You can call SetMaterial with new information as needed to update the material properties for the device. The following example shows how this might look in code:

    // This code fragment uses the material properties defined for
    // the mat variable earlier in this topic. The lpd3dDev is assumed
    // to be a valid pointer to an IDirect3DDevice7 interface.
    HRESULT hr;
    hr = lpd3dDev->SetMaterial(&mat);
    if(FAILED(hr))
    {
// Code to handle the error goes here.
    }
[Visual Basic]

From Visual Basic, set the material properties that you want the system to use by preparing a D3DMATERIAL7 type, then calling the Direct3DDevice7.SetMaterial method.

To prepare the D3DMATERIAL7 type for use, set the property information in the structure to create the desired effect during rendering. The following code fragment sets up the D3DMATERIAL7 type for a purple material with sharp white specular highlights:

    Dim mat As D3DMATERIAL7

    ' Set the RGBA for diffuse reflection.
    mat.diffuse.r = 0.5
    mat.diffuse.g = 0#
    mat.diffuse.b = 0.5
    mat.diffuse.a = 1#

    ' Set the RGBA for ambient reflection.
    mat.ambient.r = 0.5
    mat.ambient.g = 0#
    mat.ambient.b = 0.5
    mat.ambient.a = 1#

    ' Set the color and sharpness of specular highlights.
    mat.specular.r = 1#
    mat.specular.g = 1#
    mat.specular.b = 1#
    mat.specular.a = 1#
    mat.power = 50#

After preparing the D3DMATERIAL7 type, you apply the properties by calling the Direct3DDevice7.SetMaterial method of the rendering device. This method accepts the address of a prepared D3DMATERIAL7 type as its only parameter. You can call SetMaterial with new information as needed to update the material properties for the device. The following example shows how this might look in code:

    ' This code fragment uses the material properties defined for
    ' the mat variable earlier in this topic. The d3dDev is assumed
    ' to contain a valid reference to a Direct3DDevice7 object.
    On Local Error Resume Next

    Call d3dDev.SetMaterial(mat)
    If Err.Number <> DD_OK Then
' Code to handle the error goes here.
    End If


Retrieving Material Properties

[C++]

You retrieve the material properties that the rendering device is currently using by calling the IDirect3DDevice7::GetMaterial method for the device. Unlike the IDirect3DDevice7::SetMaterial method, GetMaterial doesn't require preparation. The GetMaterial method accepts the address of a D3DMATERIAL7 structure, and fills the provided structure with information describing the current material properties before returning.

    // For this example, the lpd3dDev variable is assumed to
    // be a valid pointer to an IDirect3DDevice7 interface.
    HRESULT hr;
    D3DMATERIAL7 mat;

    hr = lpd3dDev->GetMaterial(&mat);
    if(FAILED(hr))
    {
// Code to handle the error goes here.
    }
[Visual Basic]

You retrieve the material properties that the rendering device is currently using by calling the Direct3DDevice7.GetMaterial method for the device. Unlike the Direct3DDevice7.SetMaterial method, GetMaterial doesn't require preparation. The GetMaterial method accepts a variable of type D3DMATERIAL7, and fills it with information describing the current material properties before returning.

    ' For this example, the d3dDev variable is assumed to
    ' contain a valid reference to a Direct3DDevice7 object.
    On Local Error Resume Next
    Dim mat As D3DMATERIAL7

    Call d3dDev.GetMaterial(mat)
    If Err.Number <> DD_OK Then
' Code to handle the error goes here.
    End If


Mathematics of Direct3D Lighting

Direct3D models illumination by estimating how light behaves in nature. The Direct3D light model keeps track of light color, the direction and distance that light travels, the position of the viewer, and the characteristics of the current material to compute two color components for each vertex in a face. Direct3D uses these color components to compute the color it draws while rasterizing the pixels of a face.

Note All computations are made in model space by transforming the light source's position and direction, along with the camera position to model space using the inverse of the world matrix, then backtransformed. As a result, if the world or view matrices introduce non-uniform scaling, the resultant lighting could be inaccurate.

This section presents a technical look at the formulas that Direct3D uses to come up with diffuse and specular components. By understanding the approach of Direct3D, you will be better equipped to decide if the Direct3D light model suits your needs. The Direct3D light model was designed to be accurate, efficient, and easy to use. However, if the formulas used by Direct3D don't suit your needs, you can implement your own light model, bypassing the Direct3D lighting module altogether.

  • Light Color Types and Sources
  • Light Attenuation Over Distance
  • Reflectance Model
  • Spotlight Falloff Model
  • Fog Effects


Light Color Types and Sources

Light sources in Direct3D emit diffuse, ambient, and specular colors as distinct light components that factor into lighting computations independently of each other. (Note that this is a departure from the light model employed in versions of DirectX prior to DirectX 7.0, which used a single light color for all lighting calculations.) Similarly, the vertices that the system renders can use discrete diffuse, ambient, specular, and emissive colors, as defined by their vertex format.

[C++]

For a C++ application, these vertex colors are used by the system only when you set the D3DRENDERSTATE_COLORVERTEX render state to TRUE. Vertex color sources are selectable; that is, you can configure the system to select the source for the vertex-color portions of lighting formulas at run time. The D3DRENDERSTATE_AMBIENTMATERIALSOURCE, D3DRENDERSTATE_DIFFUSEMATERIALSOURCE, and D3DRENDERSTATE_SPECULARMATERIALSOURCE render states control the source from which the system draws the associated colors during lighting calculations. Each of these render states can be set to a member of the D3DMATERIALCOLORSOURCE enumerated type, which defines values that cause the system to use the current material, or a color from the vertex, as the color source.

[Visual Basic]

From Visual Basic, vertex colors are used by the system only when you set the D3DRENDERSTATE_COLORVERTEX render state to True. Vertex color sources are selectable; that is, you can configure the system to select the source for the vertex-color portions of lighting formulas at run time. The D3DRENDERSTATE_AMBIENTMATERIALSOURCE, D3DRENDERSTATE_DIFFUSEMATERIALSOURCE, and D3DRENDERSTATE_SPECULARMATERIALSOURCE render states control the source from which the system draws the associated colors during lighting calculations. Each of these render states can be set to a member of the CONST_D3DMATERIALCOLORSOURCE enumeration, which defines values that cause the system to use the current material, or a color from the vertex, as the color source.


Light Attenuation Over Distance

[C++]

Direct3D determines the distance between a light source and a vertex being lit by taking the magnitude of the vector that exists between the light's position and the vertex. This is represented by the following formula:

In the preceding formula, D is the distance being calculated, V is the position of the vertex being lit, and L is the light source's position. If D is greater than the light's range (dvRange), no further attenuation calculations are made and no light effects from the light are applied to the vertex. If the distance is within the light's range, Direct3D then applies the following formula to calculate light attenuation over distance for point lights and spotlights (directional lights don't attenuate):

In this attenuation formula, A is the calculated total attenuation and D is the distance from the light source to the vertex. The dvAttenuation0, dvAttenuation1, and dvAttenuation2 values are the light's constant, linear, and quadratic attenuation factors as specified by the members of a light object's D3DLIGHT7 structure. (Not surprisingly, the corresponding structure members are dvAttenuation0, dvAttenuation1, and dvAttenuation2.) The system normalizes D to be within the range [0.0,1.0], where 0.0 indicates no light at the vertex, and 1.0 indicates full light intensity at the vertex.

The constant, linear and quadratic attenuation factors act as coefficients in the formula—you can produce a wide variety of attenuation curves by making simple adjustments to them. You could set the constant attenuation factor to 1.0 to create a light that doesn't attenuate (but will still be limited by range), or you can experiment with different values to achieve various attenuation effects.

The attenuation formula used by Direct3D computes an attenuation value that typically ranges from 1.0 at the light source to 0.0 at the maximum range of the light. The attenuation value is multiplied into the red, green and blue components of the light's color to scale the light's intensity as a factor of the distance light travels to a vertex. After computing the light attenuation, Direct3D also considers spotlight effects (if applicable), the angle that the light reflects from a surface, as well as the reflectance of the current material to come up with the diffuse and specular components for that vertex. For more information, see Spotlight Falloff Model and Reflectance Model.

[Visual Basic]

Direct3D determines the distance between a light source and a vertex being lit by taking the magnitude of the vector that exists between the light's position and the vertex. This is represented by the following formula:

In the preceding formula, D is the distance being calculated, V is the position of the vertex being lit, and L is the light source's position. If D is greater than the light's range (range), no further attenuation calculations are made and no light effects from the light are applied to the vertex. If the distance is within the light's range, Direct3D then applies the following formula to calculate light attenuation over distance for point lights and spotlights (directional lights don't attenuate):

In this attenuation formula, A is the calculated total attenuation and D is the distance from the light source to the vertex. The attenuation0, attenuation1, and attenuation2 values are the light's constant, linear, and quadratic attenuation factors as specified by the members of a light object's D3DLIGHT7 type. (Not surprisingly, the corresponding structure members are attenuation0, attenuation1, and attenuation2.) The system normalizes D to be within the range [0.0,1.0], where 0.0 indicates no light at the vertex, and 1.0 indicates full light intensity at the vertex.

The constant, linear and quadratic attenuation factors act as coefficients in the formula—you can produce a wide variety of attenuation curves by making simple adjustments to them. You could set the constant attenuation factor to 1.0 to create a light that doesn't attenuate (but will still be limited by range), or you can experiment with different values to achieve various attenuation effects.

The attenuation formula used by Direct3D computes an attenuation value that typically ranges from 1.0 at the light source to 0.0 at the maximum range of the light. The attenuation value is multiplied into the red, green and blue components of the light's color to scale the light's intensity as a factor of the distance light travels to a vertex. After computing the light attenuation, Direct3D also considers spotlight effects (if applicable), the angle that the light reflects from a surface, as well as the reflectance of the current material to come up with the diffuse and specular components for that vertex. For more information, see Spotlight Falloff Model and Reflectance Model.


Reflectance Model

After adjusting the light intensity for any attenuation effects, Direct3D computes how much of the remaining light reflects from a vertex given the angle of the vertex normal and the direction of the incident light. (Direct3D skips to this step for directional lights, because they don't attenuate over distance.)

The system considers two reflection types, diffuse and specular, and uses a different formula to determine how much light is reflected for each. After figuring out the amounts of light reflected, Direct3D applies these new values to the diffuse and specular reflectance properties of the current material. The resulting color values are the diffuse and specular components that the rasterizer uses to produce Gouraud shading and specular highlighting.

This section provides information on the methods that the system uses for calculating reflectance. Information is divided according to the type of reflectance being calculated:

  • Diffuse Reflection Model
  • Specular Reflection Model


Diffuse Reflection Model

[C++]

Direct3D uses the following formula to compute diffuse reflection factors:

In this formula, Rd is the diffuse reflectance factor, D is the direction that the light travels to the vertex, and N is the vertex normal. Vector D is normalized, and vector N is normalized only if the D3DRENDERSTATE_NORMALIZENORMALS render state is enabled. The light's direction vector is reversed by multiplying it by -1 to create the proper association between the direction vector and the vertex normal. This formula produces values that range from -1.0 to 1.0, which are clamped to the range of 0.0 to 1.0 and used to scale the intensity of the light reflecting from the vertex.

After the diffuse reflection formula is applied, the scaled light is then applied to the diffuse reflectance formula to determine the diffuse component at that vertex. The formula that combines ambient and diffuse reflection to create the diffuse component for the vertex looks like this:

In the preceding formula, Dv is the diffuse component being calculated for the vertex, Ia is the ambient light level in the scene, and A is the light intensity for a light source that has been attenuated for distance and spotlight effects (attenuation from Light Attenuation Over Distance multiplied by Spotlight Falloff Model). The L variables represent the light's properties, and the V entries represent the vertex color, where the subscripts a, d, and e applied to each denote the type of color—ambient, diffuse, or emissive. As the formula notation states, the system computes IaVa + Ve once, adding A(RdVdLd + VaLa) for every active light.

If the D3DRENDERSTATE_COLORVERTEX render state is enabled, the system selects colors for V based on the values set for the D3DRENDERSTATE_AMBIENTMATERIALSOURCE and D3DRENDERSTATE_DIFFUSEMATERIALSOURCE render states. Set these render states set to a member of the D3DMATERIALCOLORSOURCE enumerated type to cause the system to use the current material, or a color from the vertex, as the color source.

For more information, see Specular Reflection Model.

[Visual Basic]

Direct3D uses the following formula to compute diffuse reflection factors:

In this formula, Rd is the diffuse reflectance factor, D is the direction that the light travels to the vertex, and N is the vertex normal. Vector D is normalized, and vector N is normalized only if the D3DRENDERSTATE_NORMALIZENORMALS render state is enabled. The light's direction vector is reversed by multiplying it by -1 to create the proper association between the direction vector and the vertex normal. This formula produces values that range from -1.0 to 1.0, which are clamped to the range of 0.0 to 1.0 and used to scale the intensity of the light reflecting from the vertex.

After the diffuse reflection formula is applied, the scaled light is then applied to the diffuse reflectance formula to determine the diffuse component at that vertex. The formula that combines ambient and diffuse reflection to create the diffuse component for the vertex looks like this:

In the preceding formula, Dv is the diffuse component being calculated for the vertex, Ia is the ambient light level in the scene, and A is the light intensity for a light source that has been attenuated for distance and spotlight effects (attenuation from Light Attenuation Over Distance multiplied by Spotlight Falloff Model). The L variables represent the light's properties, and the V entries represent the vertex color, where the subscripts a, d, and e applied to each denote the type of color—ambient, diffuse, or emissive. As the formula notation states, the system computes IaVa + Ve once, adding A(RdVdLd + VaLa) for every active light.

If the D3DRENDERSTATE_COLORVERTEX render state is enabled, the system selects colors for V based on the values set for the D3DRENDERSTATE_AMBIENTMATERIALSOURCE and D3DRENDERSTATE_DIFFUSEMATERIALSOURCE render states. Set these render states set to a member of the CONST_D3DMATERIALCOLORSOURCE enumeration to cause the system to use the current material, or a color from the vertex, as the color source.

For more information, see Specular Reflection Model.


Specular Reflection Model

[C++]

Modeling specular reflection requires that the system not only know the direction that light is traveling, but also the direction to the viewer's eye. The system uses a simplified version of the Phong specular-reflection model, which employs a "halfway vector" to approximate the intensity of specular reflection. This halfway vector exists midway between the vector to the light source and the vector to the eye. Direct3D provides applications with two ways to compute the halfway vector, controlled by the D3DRENDERSTATE_LOCALVIEWER render state. If D3DRENDERSTATE_LOCALVIEWER is set to TRUE, the system calculates the halfway vector using the position of the camera and the position of the vertex, along with the light's direction vector. The following formula illustrates:

In the preceding formula, norm() is an operator that normalizes an input vector, VC is the vector that exists from the position of the vertex to the position of the viewpoint (or eye), and Ld is the light's direction vector.

Determining the halfway vector in this manner is somewhat computationally intensive. An alternative would be to set D3DRENDERSTATE_LOCALVIEWER to FALSE, which instructs the system to act as though the viewpoint is infinitely distant on the z-axis. This setting is less computationally expensive, but much less accurate, so it is best used by applications that use orthogonal projection. When D3DRENDERSTATE_LOCALVIEWER is set to FALSE, Direct3D determines the halfway vector by the following formula:

This formula is similar to the first formula, but substitutes the vector I (0, 0, -1)—which points at a viewpoint infinitely distant on the z-axis—instead of computing the vector VC.

After determining the halfway vector, H, the system uses the following formula to compute specular reflection:

In the preceding formula, Rs is the specular reflectance, N in the vertex normal, H is the halfway vector, and p is the specular reflection power of the current material (as specified by the dvPower member of the material's D3DMATERIAL7 structure). Vector H is normalized, and vector N is normalized only if the D3DRENDERSTATE_NORMALIZENORMALS render state is enabled.

Like the diffuse reflectance formula, this formula produces values that range from -1.0 to 1.0, which are clamped to the range of 0.0 to 1.0 and used to scale the light reflecting from the vertex. Also similar to the diffuse reflection model, the remaining light is applied to a formula that derives the specular component at that vertex:

In the preceding formula, Sv is the specular color being computed, A is the light from a single light source that has been attenuated for distance and spotlight effects (see Light Attenuation Over Distance and Spotlight Falloff Model). The Rs variable is the previously calculated specular reflectance, Vs is the selected specular component for the vertex, and Ls is the specular light color output by the light.

If the D3DRENDERSTATE_COLORVERTEX render state is enabled, the system selects the color source for V based on the value of the D3DRENDERSTATE_SPECULARMATERIALSOURCE render state. This render state can be set to a member of the D3DMATERIALCOLORSOURCE enumerated type to cause the system to use the current material, or one of the color components for the vertex, as the color source.

For more information, see Diffuse Reflection Model.

[Visual Basic]

Modeling specular reflection requires that the system not only know the direction that light is traveling, but also the direction to the viewer's eye. The system uses a simplified version of the Phong specular-reflection model, which employs a "halfway vector" to approximate the intensity of specular reflection. This halfway vector exists midway between the vector to the light source and the vector to the eye. Direct3D provides applications with two ways to compute the halfway vector, controlled by the D3DRENDERSTATE_LOCALVIEWER render state. If D3DRENDERSTATE_LOCALVIEWER is set to True, the system calculates the halfway vector using the position of the camera and the position of the vertex, along with the light's direction vector. The following formula illustrates:

In the preceding formula, norm() is an operator that normalizes an input vector, VC is the vector that exists from the position of the vertex to the position of the viewpoint (or eye), and Ld is the light's direction vector.

Determining the halfway vector in this manner is somewhat computationally intensive. An alternative would be to set D3DRENDERSTATE_LOCALVIEWER to False, which instructs the system to act as though the viewpoint is infinitely distant on the z-axis. This setting is less computationally expensive, but much less accurate, so it is best used by applications that use orthogonal projection. When D3DRENDERSTATE_LOCALVIEWER is set to False, Direct3D determines the halfway vector by the following formula:

This formula is similar to the first formula, but substitutes the vector I (0, 0, -1)—which points at a viewpoint infinitely distant on the z-axis—instead of computing the vector VC.

After determining the halfway vector, H, the system uses the following formula to compute specular reflection:

In the preceding formula, Rs is the specular reflectance, N in the vertex normal, H is the halfway vector, and p is the specular reflection power of the current material (as specified by the power member of the material's D3DMATERIAL7 type). Vector H is normalized, and vector N is normalized only if the D3DRENDERSTATE_NORMALIZENORMALS render state is enabled.

Like the diffuse reflectance formula, this formula produces values that range from -1.0 to 1.0, which are clamped to the range of 0.0 to 1.0 and used to scale the light reflecting from the vertex. Also similar to the diffuse reflection model, the remaining light is applied to a formula that derives the specular component at that vertex:

In the preceding formula, Sv is the specular color being computed, A is the light from a single light source that has been attenuated for distance and spotlight effects (see Light Attenuation Over Distance and Spotlight Falloff Model). The Rs variable is the previously calculated specular reflectance, Vs is the selected specular component for the vertex, and Ls is the specular light color output by the light.

If the D3DRENDERSTATE_COLORVERTEX render state is enabled, the system selects the color source for V based on the value of the D3DRENDERSTATE_SPECULARMATERIALSOURCE render state. This render state can be set to a member of the CONST_D3DMATERIALCOLORSOURCE enumerated type to cause the system to use the current material, or one of the color components for the vertex, as the color source.

For more information, see Diffuse Reflection Model.


Spotlight Falloff Model

[C++]

Spotlights emit a cone of light that has two parts: a bright inner cone and an outer cone. Light is brightest within the inner cone and isn't present outside the outer cone, with light intensity attenuating between the two areas. This type of attenuation is commonly referred to as falloff.

How much the light a vertex receives is based on the vertex's location within the inner or outer cones. Direct3D computes the dot product of the spotlight's direction vector (L) and the vector from the vertex to the light (D). This value is equal to the cosine of the angle between the two vectors, and serves as a indicator of the vertex's position that can be compared to the light's cone angles to determine where the vertex might lie in the inner or outer cones. The following illustration provides a graphical representation of the association between these two vectors:

Next, the system compares this value to the cosine of the spotlight's inner and outer cone angles. In the light's D3DLIGHT7 structure, the dvTheta and dvPhi members represent the total cone angles for the inner and outer cones. Because the attenuation occurs as the vertex becomes more distant from the center of illumination, rather than across the total cone angle, Direct3D halves these cone angles before calculating their cosines.

If the dot product of vectors L and D is less than or equal to the cosine of the outer cone angle, the vertex lies beyond the outer cone, and receives no light. If the dot product of L and D is greater than the cosine of the inner cone angle, then the vertex is within the inner cone, and receives the maximum amount of light (still considering attenuation over distance). If the vertex is somewhere between the two regions, Direct3D calculates falloff for the vertex by using the following formula:

In the formula, If is light intensity (after falloff) for the vertex being lit, α is the angle between vectors L and D, φ is half of the outer cone angle, θ is half of the inner cone angle, and p is the spotlight's falloff property (dvFalloff in the D3DLIGHT7 structure). This formula generates a value between 0.0 and 1.0 that scales the light's intensity at the vertex to account for falloff. Attenuation as a factor of the vertex's distance from the light is also applied. The p value corresponds to the dvFalloff member of the D3DLIGHT7 structure and controls the shape of the falloff curve. The following illustration shows how different dvFalloff values can affect the falloff curve:

The effect of various dvFalloff values on the actual lighting is subtle, and a small performance penalty is incurred by shaping the falloff curve with dvFalloff values other than 1.0. For these reasons, most people will set this value to 1.0.

For more information, see Light Attenuation Over Distance.

[Visual Basic]

Spotlights emit a cone of light that has two parts: a bright inner cone and an outer cone. Light is brightest within the inner cone and isn't present outside the outer cone, with light intensity attenuating between the two areas. This type of attenuation is commonly referred to as falloff.

How much the light a vertex receives is based on the vertex's location within the inner or outer cones. Direct3D computes the dot product of the spotlight's direction vector (L) and the vector from the vertex to the light (D). This value is equal to the cosine of the angle between the two vectors, and serves as a indicator of the vertex's position that can be compared to the light's cone angles to determine where the vertex might lie in the inner or outer cones. The following illustration provides a graphical representation of the association between these two vectors:

Next, the system compares this value to the cosine of the spotlight's inner and outer cone angles. In the light's D3DLIGHT7 structure, the theta and phi members represent the total cone angles for the inner and outer cones. Because the attenuation occurs as the vertex becomes more distant from the center of illumination, rather than across the total cone angle, Direct3D halves these cone angles before calculating their cosines.

If the dot product of vectors L and D is less than or equal to the cosine of the outer cone angle, the vertex lies beyond the outer cone, and receives no light. If the dot product of L and D is greater than the cosine of the inner cone angle, then the vertex is within the inner cone, and receives the maximum amount of light (still considering attenuation over distance). If the vertex is somewhere between the two regions, Direct3D calculates falloff for the vertex by using the following formula:

In the formula, If is light intensity (after falloff) for the vertex being lit, α is the angle between vectors L and D, φ is half of the outer cone angle, θ is half of the inner cone angle, and p is the spotlight's falloff property (falloff in the D3DLIGHT7 type). This formula generates a value between 0.0 and 1.0 that scales the light's intensity at the vertex to account for falloff. Attenuation as a factor of the vertex's distance from the light is also applied. The p value corresponds to the falloff member of the D3DLIGHT7 type and controls the shape of the falloff curve. The following illustration shows how different falloff values can affect the falloff curve:

The effect of various falloff values on the actual lighting is subtle, and a small performance penalty is incurred by shaping the falloff curve with values other than 1.0. For these reasons, most people will set this value to 1.0.

For more information, see Light Attenuation Over Distance.


Fog Effects

The Direct3D transformation and lighting engine can create fog effects during lighting. This type of fog is usually referred to as "vertex fog" because fog information is placed into the alpha component of the vertex to be rasterized. For more information see Fog and Vertex Fog.


Vertex Formats

This section describes the concepts you need to understand to specify vertices in Direct3D, and provides information about the various formats your application can use to declare vertices. The following topics are discussed:

  • About Vertex Formats
  • Untransformed and Unlit Vertices
  • Untransformed and Lit Vertices
  • Transformed and Lit Vertices
  • Strided Vertex Format
[C++]

Note Prior to DirectX 6.0, applications were required to use one of three vertex types—D3DVERTEX, D3DLVERTEX, and D3DTLVERTEX—depending on which parts of the Direct3D geometry pipeline were being used. With support for more flexible vertex formats in DirectX 6.0 and later, you can declare vertices in many more ways than before, but you can still use the predefined structures to describe untransformed and unlit vertices, untransformed but lit vertices, and vertices that are both transformed and lit. For more information, read the topics for each type of vertex in this section thoroughly.

[C++,Visual Basic]


About Vertex Formats

Direct3D Immediate Mode applications can define model vertices in several different ways. Support for flexible vertex definitions (also known as "flexible vertex formats") makes it possible for your application to use only the vertex components it needs, eliminating those components that aren't used. By using only the needed vertex components, your application can conserve memory and minimize the processing bandwidth required to render models. You describe how your vertices are formatted by using a combination of flexible vertex format flags.

[C++]

The rendering methods of the IDirect3DDevice7 interface presents C++ applications with methods that accept a combination of these flags, and uses them to determine how to render primitives. Basically, these flags tell the system which vertex components—position, vertex blending weights, normal, colors, the number and format of texture coordinates—your application uses and, indirectly, which parts of the rendering pipeline you want Direct3D to apply to them. In addition, the presence or absence of a particular vertex format flag communicates to the system which vertex component fields are present in memory, and which you've omitted.

Note The behavior is slightly different if your application uses the IDirect3DDevice7::DrawPrimitiveStrided or IDirect3DDevice7::DrawIndexedPrimitiveStrided methods. For more information, see Strided Vertex Format.

One significant requirement that the system places on how you format your vertices is on the order in which the data appears. The following illustration depicts the required order for all possible vertex components in memory, and their associated data types.

Note In DirectX 7.0, texture coordinates can be declared in different formats, allowing textures to be addressed using as few as one coordinate, or as many as three texture coordinates (for 2-D projected texture coordinates). For more information, see Texture Coordinate Formats. Use the D3DFVF_TEXCOORDSIZEn set of macros to create bit patterns that identify the texture coordinate formats that your vertex format uses.

No real application will use every single component—the RHW (reciprocal homogenous W) and vertex normal fields are mutually exclusive–nor will most applications try to use all eight sets of texture coordinates, but the flexibility is there. There are several restrictions on which flags you can use with other flags. These are mostly common sense. For example, you can't use the D3DFVF_XYZ and D3DFVF_XYZRHW flags together, as this would indicate that your application is describing a vertex's position with both untransformed and transformed vertices. For more information, take a look at the description for each of the flags in Flexible Vertex Format Flags.

[Visual Basic]

The Direct3DDevice7 Visual Basic class includes methods that accept a combination of these flags, and uses them to determine how to render primitives. Basically, these flags tell the system which vertex components—position, vertex blending weights, normal, colors, the number and format of texture coordinates—your application uses and, indirectly, which parts of the rendering pipeline you want Direct3D to apply to them. In addition, the presence or absence of a particular vertex format flag communicates to the system which vertex component fields are present in memory, and which you've omitted.

One significant requirement that the system places on how you format your vertices is on the order in which the data appears. The following illustration depicts the required order for all possible vertex components in memory, and their associated data types.

Texture coordinates can be declared in different formats, allowing textures to be addressed using as few as one coordinate, or as many as three texture coordinates (for 2-D projected texture coordinates). Use the D3DFVF_TEXCOORDSIZEn set of helper functions from the Math.bas to create bit patterns that identify the texture coordinate formats that your vertex format uses. The Math.bas Visual Basic code module is included with this SDK.

No real application will use every single component—the RHW (reciprocal homogenous W) and vertex normal fields are mutually exclusive–nor will most applications try to use all eight sets of texture coordinates, but the flexibility is there. There are several restrictions on which flags you can use with other flags. These are mostly common sense. For example, you can't use the D3DFVF_XYZ and D3DFVF_XYZRHW flags together, as this would indicate that your application is describing a vertex's position with both untransformed and transformed vertices. For more information, take a look at the description for each of the flags in Flexible Vertex Format Flags.


Untransformed and Unlit Vertices

The presence of the D3DFVF_XYZ (or any of the D3DFVF_XYZBn flags) and D3DFVF_NORMAL flags in the vertex description that you pass to rendering methods identifies the untransformed and unlit vertex type. By using untransformed and unlit vertices, your application effectively requests that Direct3D perform all transformation and lighting operations using its internal algorithms. (If you want, you can disable the Direct3D lighting engine for the primitives being rendered by setting the D3DRENDERSTATE_LIGHTING render state to FALSE.)

Many applications use this vertex type, as it frees them from implementing their own transformation and lighting engines. However, because the system is making calculations for you, it requires that you provide a certain amount of information with each vertex:

  • You are required to specify vertices in untransformed model coordinates (a model coordinate vertex is positioned relative to a local origin for the model, not for the world). The system then applies world, view, and projection transformations to the model coordinates to position them within your scene, and determine their final locations on the screen.
  • Include a vertex normal for more realistic lighting effects. (Vertices lit by the system that don't include a vertex normal will use a dot product of 0 in all lighting calculations, meaning that they are assumed to receive no incident light.) The system uses the vertex normal, along with the current material, in its lighting calculations. For details, see Face and Vertex Normal Vectors, Lighting and Materials, and Mathematics of Direct3D Lighting.
[C++]

Other than these requirements, you have the flexibility to use, or disregard, the other vertex components. For example, if you want to include a diffuse or specular color with your untransformed vertices, you can. (This wasn't possible before DirectX 6.0). Including individual colors for each vertex makes it possible to achieve shading effects that are much more subtle and flexible than lighting calculations that use only the material color. Keep in mind that you must enable per-vertex color through the D3DRENDERSTATE_COLORVERTEX render state. Untransformed, unlit vertices can also include up to eight sets of texture coordinates.

Applications can still use the legacy D3DVERTEX structure for vertices. In fact, the d3dtypes.h header file defines a shortcut macro to identify this vertex format:

#define D3DFVF_VERTEX ( D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_TEX1 )

If the D3DVERTEX structure doesn't suit your application's needs, feel free to define your own. Remember which vertex components your application needs, and make sure they appear in the required order by declaring a properly ordered structure. The following code declares a valid vertex format structure that includes a position, a vertex normal, a diffuse color, and two sets of texture coordinates:

//
// The vertex format description for this vertex
// would be: (D3DFVF_XYZ | D3DFVF_NORMAL |
//    D3DFVF_DIFFUSE | D3DFVF_TEX2)
//
typedef struct _UNLITVERTEX {
    float x, y, z;// position

    float nx, ny, nz;     // normal

    DWORD dwDiffuseRGBA;  // diffuse color

    float tu1,    // texture coordinates
  tv1;

    float tu2,
  tv2;
} UNLITVERTEX, *LPUNLITVERTEX;

The vertex description for the preceding structure would be a combination of the D3DFVF_XYZ, D3DFVF_NORMAL, D3DFVF_DIFFUSE, and D3DFVF_TEX2 flexible vertex format flags. The rendering methods, such as IDirect3DDevice7::DrawPrimitive, accept the address of a vertex array as a void pointer, so remember to cast your vertex array pointer to the LPVOID data type when you call the rendering methods.

For more information, see About Vertex Formats.

[Visual Basic]

Other than these requirements, you have the flexibility to use, or disregard, the other vertex components. For example, if you want to include a diffuse or specular color with your untransformed vertices, you can. (This wasn't possible before DirectX 6.0). Including individual colors for each vertex makes it possible to achieve shading effects that are much more subtle and flexible than lighting calculations that use only the material color. Keep in mind that you must enable per-vertex color through the D3DRENDERSTATE_COLORVERTEX render state. Untransformed, unlit vertices can also include up to eight sets of texture coordinates. Visual Basic applications can use the D3DVERTEX type for vertices.

If the D3DVERTEX type doesn't suit your application's needs, feel free to define your own. Remember which vertex components your application needs, and make sure they appear in the required order by declaring a properly ordered structure. The following code declares a valid vertex format structure that includes a position, a vertex normal, a diffuse color, and two sets of texture coordinates:

'
' The vertex format description for this vertex
' would be: (D3DFVF_XYZ Or D3DFVF_NORMAL Or
'    D3DFVF_DIFFUSE Or D3DFVF_TEX2)
'
Type UNLITVERTEX
    x As Single ' Position
    y As Single
    z As Single

    nx As Single ' Normal
    ny As Single
    nz As Single

    DiffuseRGBA As Long  ' diffuse color

    tu1 As Single ' texture coordinates
    tv1 As Single

    tu2 As Single ' texture coordinates
    tv2 As Single
End Type

The vertex description for the preceding structure would be a combination of the D3DFVF_XYZ, D3DFVF_NORMAL, D3DFVF_DIFFUSE, and D3DFVF_TEX2 flexible vertex format flags. The rendering methods, such as Direct3DDevice7.DrawPrimitive, accept the first element of a vertex array as type Any, to accommodate all types of vertex formats.

For more information, see About Vertex Formats.


Untransformed and Lit Vertices

If you include the D3DFVF_XYZ flag, but not the D3DFVF_NORMAL flag, in the vertex format description you use with the Direct3D rendering methods, you are identifying your vertices as untransformed, but already lit. (For information about other dependencies and exclusions, see Flexible Vertex Format Flags.)

By using untransformed and lit vertices, your application requests that Direct3D not perform any lighting calculations on your vertices, but it should still transform them using the previously set world, view, and projection matrices. Because the system isn't doing lighting calculations, it doesn't need a vertex normal. The system uses the diffuse and specular components at each vertex for shading. These colors might be arbitrary, or they might be computed using your own lighting formulas. If you don't include a diffuse or specular component, the system uses the default colors. The default value for both the diffuse and specular colors is 0xFFFFFFFF.

Like the other vertex types, other than including a position and some amount of color information, you are free to include or disregard the texture coordinate sets in the unlit vertex format.

[C++]

C++ applications can still use the legacy D3DLVERTEX structure for vertices. The d3dtypes.h header file defines the following helper macro that you can use to describe the D3DLVERTEX structure's format:

#define D3DFVF_LVERTEX ( D3DFVF_XYZ | D3DFVF_RESERVED1 | D3DFVF_DIFFUSE | \
 D3DFVF_SPECULAR | D3DFVF_TEX1 )

Note that the helper macro includes the D3DFVF_RESERVED1 flag, indicating to the system that you're using the D3DLVERTEX structure, which includes the dwReserved member. This is required when using D3DLVERTEX because vertex formats don't usually include reserved fields; the D3DFVF_RESERVED1 flag informs the system that there is an unused DWORD between the vertex's position and diffuse color vertex components.

If the D3DLVERTEX structure doesn't include all the fields your application needs, you can define another structure. Make sure that your vertex components appear in the required order, declaring a new structure accordingly. The following code declares a valid untransformed and lit vertex, with diffuse and specular vertex colors, and three sets of texture coordinates:

//
// The vertex format description for this vertex
// would be: (D3DFVF_XYZ | D3DFVF_DIFFUSE |
//    D3DFVF_SPECULAR | D3DFVF_TEX3)
//
typedef struct _LITVERTEX {
    float x, y, z;// position

    DWORD dwDiffuseRGBA;  // diffuse color

    DWORD dwSpecularRGBA; // specular color

    float tu1,    // texture coordinates
  tv1;

    float tu2,
  tv2;

    float tu3,
  tv3;
} LITVERTEX, *LPLITVERTEX;

The vertex description for the preceding structure would be a combination of the D3DFVF_XYZ, D3DFVF_DIFFUSE, D3DFVF_SPECULAR, and D3DFVF_TEX3 flexible vertex format flags. The rendering methods, such as IDirect3DDevice7::DrawPrimitive, accept the address of a vertex array as a void pointer, so remember to cast your vertex array pointer to the LPVOID data type when you call the rendering methods.

For more information, see About Vertex Formats.

[Visual Basic]

Applications written in Visual Basic can define their own vertex formats, or use the D3DLVERTEX type for lit vertices. If the D3DLVERTEX type doesn't include all the fields your application needs, you can define another type. Make sure that your vertex components appear in the required order, declaring a new type accordingly. The following code declares a valid untransformed and lit vertex, with diffuse and specular vertex colors, and three sets of texture coordinates:

'
' The vertex format description for this vertex
' would be: (D3DFVF_XYZ Or D3DFVF_DIFFUSE Or
'    D3DFVF_SPECULAR Or D3DFVF_TEX3)
'
Type LITVERTEX
    x As Single ' position
    y As Single
    z As Single

    DiffuseRGBA As Long ' diffuse color

    SpecularRGBA As Long ' specular color

    tu1 As Single ' texture coordinates
    tv1 As Single

    tu2 As Single
    tv2 As Single

    tu3 As Single
    tv3 As Single
End Type

The vertex description for the preceding type would be a combination of the D3DFVF_XYZ, D3DFVF_DIFFUSE, D3DFVF_SPECULAR, and D3DFVF_TEX3 flexible vertex format flags. The rendering methods, such as Direct3DDevice7.DrawPrimitive, accept the first element of a vertex array as type Any, to accommodate all types of vertex formats.

For more information, see About Vertex Formats.


Transformed and Lit Vertices

If you include the D3DFVF_XYZRHW flag in your vertex format description, you are telling the system that your application is using transformed and lit vertices. This means that Direct3D doesn't transform your vertices with the world, view, or projection matrices, nor does it perform any lighting calculations; it assumes that your application has already taken care of these steps. (This fact makes transformed and lit vertices common when porting existing 3-D applications to Direct3D Immediate Mode.) In short, Direct3D does not modify transformed and lit vertices at all; it passes them directly to the driver to be rasterized.

The vertex format flags associated with untransformed vertices and lighting (D3DFVF_XYZ and D3DFVF_NORMAL) are not allowed if D3DFVF_XYZRHW is present. For more about flag dependencies and exclusions, see Flexible Vertex Format Flags.

The system requires that the vertex position you specify be already transformed. The x and y values must be in screen coordinates, and z must be the depth value of the pixel to be used in the z-buffer. Z values can range from 0.0 to 1.0, where 0.0 is the closest possible position to the viewer, and 1.0 is the farthest position still visible within the viewing area. Immediately following the position, transformed and lit vertices must include an RHW value (reciprocal of homogeneous W) value. RHW is the reciprocal of the W coordinate from the homogeneous point (x,y,z,w) at which the vertex exists in projection space. (This value often works out to be the distance from the eyepoint to the vertex, taken along the z-axis.)

Other than the position and RHW requirements, this vertex format is similar to an untransformed and lit vertex. To recap:

  • The system doesn't do any lighting calculations with this format, so it doesn't need a vertex normal.
  • You can specify a diffuse or specular color. If you don't, the system uses 0xFFFFFFFF for both these components.
  • You can use up to eight sets of texture coordinates, or none at all.
[C++]

Applications written in C++ can still use the legacy D3DTLVERTEX structure for transformed and lit vertices. The d3dtypes.h header file defines the following helper macro that you can use to describe the vertex format declared by the D3DTLVERTEX structure:

#define D3DFVF_TLVERTEX ( D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_SPECULAR | \
  D3DFVF_TEX1 )

It's possible that the D3DTLVERTEX structure doesn't include the fields you need. If this is the case, define another structure that does, but make sure that the vertex components are ordered properly. The following code declares a valid transformed and lit vertex, with diffuse and specular vertex colors, and one set of texture coordinates:

//
// The vertex format description for this vertex
// would be: (D3DFVF_XYZRHW | D3DFVF_DIFFUSE |
//    D3DFVF_SPECULAR | D3DFVF_TEX1)
//
typedef struct _TRANSLITVERTEX {
    float x, y;   // screen position

    float z;      // Z-buffer depth

    float rhw;    // reciprocal homogeneous W

    DWORD dwDiffuseRGBA;  // diffuse color

    DWORD dwSpecularRGBA; // specular color

    float tu1,    // texture coordinates
  tv1;
} TRANSLITVERTEX, *LPTRANSLITVERTEX;

The vertex description for the preceding structure would be a combination of the D3DFVF_XYZRHW, D3DFVF_DIFFUSE, D3DFVF_SPECULAR, and D3DFVF_TEX1 flexible vertex format flags. The rendering methods, such as IDirect3DDevice7::DrawPrimitive, accept the address of a vertex array as a void pointer, so remember to cast your vertex array pointer to the LPVOID data type when you call the rendering methods.

For more information, see About Vertex Formats.

[Visual Basic]

Visual Vasic applications can use the D3DTLVERTEX type for transformed and lit vertices. It's possible that the D3DTLVERTEX type doesn't include the fields you need. If this is the case, define another type that does, but make sure that the vertex components are ordered properly. The following code declares a valid transformed and lit vertex, with diffuse and specular vertex colors, and one set of texture coordinates:

'
' The vertex format description for this vertex
' would be: (D3DFVF_XYZRHW Or D3DFVF_DIFFUSE Or
'    D3DFVF_SPECULAR Or D3DFVF_TEX1)
'
Type TRANSLITVERTEX
    x As Single ' screen position
    y As Single

    z As Single ' Z-buffer depth

    rhw As Single ' reciprocal homogeneous W

    DiffuseRGBA As Long ' diffuse color

    dwSpecularRGBA As Long ' specular color

    tu1 As Single ' texture coordinates
    tv1 As Single
End Type

The vertex description for the preceding type would be a combination of the D3DFVF_XYZRHW, D3DFVF_DIFFUSE, D3DFVF_SPECULAR, and D3DFVF_TEX1 flexible vertex format flags. The rendering methods, such as Direct3DDevice7.DrawPrimitive, accept the first element of a vertex array as type Any, to accommodate all types of vertex formats.

For more information, see About Vertex Formats.


Strided Vertex Format

[Visual Basic]

Note Information in this topic pertains only to applications written in C++. DirectX for Visual Basic does not support strided vertices.

[C++]

The strided vertex format contains fields to represent untransformed vertices, lit or unlit, for the IDirect3DDevice7::DrawPrimitiveStrided, IDirect3DDevice7::DrawIndexedPrimitiveStrided, and IDirect3DVertexBuffer7::ProcessVerticesStrided methods. You cannot use the strided vertex format for transformed vertices. Unlike a "normal" vertex, which is a structure that physically contains all the necessary vertex components, a "strided" vertex is a structure that contains pointers to the vertex components rather than the components themselves.

This indirection is accomplished through the D3DDRAWPRIMITIVESTRIDEDDATA structure that is accepted by the DrawPrimitiveStrided, DrawIndexedPrimitiveStrided, and ProcessVerticesStrided methods. You describe strided vertices using the same combinations of flexible vertex format flags as a non-strided vertex. However, unlike non-strided vertices, the flags you use do not indicate the presence of a given field in memory (D3DDRAWPRIMITIVESTRIDEDDATA includes them all), they indicate which the structure members that your application uses. The restrictions for these flags are identical to non-strided vertices, for details, see Flexible Vertex Format Flags.

The D3DDRAWPRIMITIVESTRIDEDDATA structure contains 12 D3DDP_PTRSTRIDE structures, one structure each for the position, normal, diffuse color, specular color, and texture coordinate sets for the vertices. Each D3DDP_PTRSTRIDE structure contains a pointer to an array of data, and the stride of that array. These 12 structures provide the indirection that allows your application to arrange vertex components however it needs. For instance, you might use distinct arrays for every vertex component, as shown in the following illustration.

The lpvData member of the corresponding D3DDP_PTRSTRIDE structures contains the address of a buffer that contains an array of vertex components. Each element in each array represents a component for one vertex, which is made up of some number of floats (for position, normal, and texture coordinates) or an RGBA value (for diffuse and specular colors). There is one entry within each array for every vertex to be rendered. The dwStride member of D3DDP_PTRSTRIDE should be set to the memory stride, in bytes, from one entry in the array to the next. The following table describes the components and the corresponding strides for each.

Component | Stride
untransformed position | 3 to 6 floats (x,y,z, plus 0 to 3 blend weights)
vertex normal | 3 floats (nx,ny,nz)
diffuse color | 1 DWORD (RGBA)
specular color | 1 DWORD (RGBA)
texture coordinate set | 1, 2, 3, or 4, floats (1st, 2nd, 3rd, or 4th texture coordinates)

Note In DirectX 7.0, texture coordinates can be declared in different formats, allowing textures to be addressed using as few as one coordinate, or as many as three texture coordinates (for 2-D projected texture coordinates). For more information, see Texture Coordinate Formats. Use the D3DFVF_TEXCOORDSIZEn set of macros to create bit patterns that identify the texture coordinate formats that your vertex format uses.

Some developers might choose to include some or all vertex components in an interleaved array. The strided vertex format makes doing this very simple. If your application interleaves the vertex position and normal components, for example, you could visualize the memory layout and corresponding settings in D3DDP_PTRSTRIDE structures as follows.

In this case, the lpvData members of the D3DDP_PTRSTRIDE structures point to two locations within the same buffer, and the strides are set to the combined width of the interleaved components. Of course, you aren't limited to any particular interleaving scheme. So long as you set the data pointers and their strides correctly, any interleaving scheme will work.


Textures

Textures are a powerful tool in the quest for realism in computer-generated 3-D images. Direct3D supports an extensive texturing feature set, providing developers with easy access to advanced texturing techniques. This section discusses the purposes and uses of textures in Direct3D. The information is presented in the following topics:

  • Basic Texturing Concepts
  • Texture Coordinates
  • Texture Surface Objects
  • Texture Filtering
  • Texture Wrapping
  • Texture Blending
  • Texture Compression
  • Automatic Texture Management
  • Hardware Considerations for Texturing

If you are familiar with what textures are and how they are used, you may want to skip the Basic Texturing Concepts section. It is important to note, however, that Direct3D now uses texture interfaces to access many of its most powerful texturing features. Therefore, you may want to look over the section entitled Texture Surface Objects.


Basic Texturing Concepts

This section presents the most fundamental concepts required for an understanding of texturing in Direct3D. The information in this section is presented in the following topics:

  • What Is a Texture?
  • Texture Addressing Modes
  • Texture Interfaces and Texture Handles
  • Palettized Textures


What Is a Texture?

Early computer-generated 3-D images, although generally advanced for their time, tended to have a shiny plastic look. They lacked the types of markings that give 3-D objects realistic visual complexity such as scuffs, cracks, fingerprints, and smudges. In recent years, textures have gained popularity among developers as a tool for enhancing the realism of computer-generated 3-D images.

At its most basic, a texture is simply a bitmap of pixel colors. In this sense, the word texture has a specific definition when used in the context of computer graphics. In the normal semantics associated with the word texture, we refer both to the patterns of color on an object and its roughness or smoothness. Direct3D textures don't add "bumpiness" to an object. Rather, the textures, or patterns of colors, just give it the appearance of bumpiness.

Because Direct3D textures are simply bitmaps, any bitmap can be applied to a Direct3D primitive. For instance, applications can create and manipulate objects that appear to have a wood grain pattern in them. Grass, dirt, and rocks can be applied to a set of 3-D primitives that form a hill. The result is a very realistic-looking hillside. Texturing can also be used to create effects such as signs along a roadside, rock strata in a cliff, or the appearance of marble on a floor.

In addition, Direct3D supports more advanced texturing techniques such as texture blending (with or without transparency) and light mapping. Information on these techniques is presented in Texture Blending and Light Mapping With Textures.

If your application creates a HAL device, an MMX device, or an RGB device (see Direct3D Device Types), it can use 8-, 16-, 24-, or 32-bit textures. Legacy applications that use the monochromatic (or ramp) device must use 8-bit textures.


Texture Addressing Modes

This section describes the purpose and use of Direct3D texture addressing modes. It is organized into the following topics:

  • What Are Texture Addressing Modes?
  • About the Wrap Texture Address Mode
  • About the Mirror Texture Address Mode
  • About the Clamp Texture Address Mode
  • About the Border Color Texture Address Mode
  • Setting and Retrieving Texture Addressing Modes
  • Texture Addressing Modes and Texture Wrapping
  • Device Limitations for Texture Addressing


What Are Texture Addressing Modes?

Your Direct3D application can assign texture coordinates to any vertex of any primitive. For details, see Texture Coordinates. Typically, the u- and v-texture coordinates that you assign to a vertex will be in the range of 0.0 to 1.0 inclusive. However, by assigning texture coordinates outside that range, you can create certain special texturing effects.

You control what Direct3D does with texture coordinates that are outside the [0.0, 1.0] range by setting the texture addressing mode. For instance, you can have your application set the texture addressing mode such that a texture is tiled across a primitive. The following topics contain additional details:

  • About the Wrap Texture Address Mode
  • About the Mirror Texture Address Mode
  • About the Clamp Texture Address Mode
  • About the Border Color Texture Address Mode


About the Wrap Texture Address Mode

[C++]

The "wrap" texture address mode, identified by the D3DTADDRESS_WRAP member of the D3DTEXTUREADDRESS enumerated type, makes Direct3D repeat the texture on every integer junction. Suppose, for example, your program creates a square primitive and specifies texture coordinates of (0.0,0.0), (0.0,3.0), (3.0,3.0), and (3.0,0.0). Setting the texture addressing mode to D3DTADDRESS_WRAP will result in the texture being applied three times in both the u-and v-directions.

[Visual Basic]

The "wrap" texture address mode, identified by the D3DTADDRESS_WRAP member of the CONST_D3DTEXTUREADDRESS enumeration, makes Direct3D repeat the texture on every integer junction. Suppose, for example, your program creates a square primitive and specifies texture coordinates of (0.0,0.0), (0.0,3.0), (3.0,3.0), and (3.0,0.0). Setting the texture addressing mode to D3DTADDRESS_WRAP will result in the texture being applied three times in both the u- and v-directions.

This is illustrated in the following figure.

The effects of this texture address mode are similar to, but distinct from, those of the "mirror" mode. For more information, see About the Mirror Texture Address Mode.


About the Mirror Texture Address Mode

[C++]

The "mirror" texture address mode, identified by the D3DTADDRESS_MIRROR member of the D3DTEXTUREADDRESS enumerated type, causes Direct3D to mirror the texture at every integer boundary. Suppose, for example, your program creates a square primitive and specifies texture coordinates of (0.0,0.0), (0.0,3.0), (3.0,3.0), and (3.0,0.0). Setting the texture addressing mode to D3DTADDRESS_MIRROR will result in the texture being applied three times in both the u- and v-directions. Every other row and column that it is applied to will be a mirror image of the preceding row or column.

[Visual Basic]

The "mirror" texture address mode, identified by the D3DTADDRESS_MIRROR member of the CONST_D3DTEXTUREADDRESS enumeration, causes Direct3D to mirror the texture at every integer boundary. Suppose, for example, your program creates a square primitive and specifies texture coordinates of (0.0,0.0), (0.0,3.0), (3.0,3.0), and (3.0,0.0). Setting the texture addressing mode to D3DTADDRESS_MIRROR will result in the texture being applied three times in both the u- and v-directions. Every other row and column that it is applied to will be a mirror image of the preceding row or column.

This is illustrated in the following figure:

The effects of this texture address mode are similar to, but distinct from, those of the "wrap" mode. For more information, see About the Wrap Texture Address Mode.


About the Clamp Texture Address Mode

[C++]

The "clamp" texture address mode, identified by the D3DTADDRESS_CLAMP member of the D3DTEXTUREADDRESS enumerated type, causes Direct3D to clamp your texture coordinates to the [0.0, 1.0] range. That is, it will apply the texture once, then "smear" the color of edge pixels. For instance, suppose that your program creates a square primitive and assigns texture coordinates of (0.0,0.0), (0.0,3.0), (3.0,3.0), and (3.0,0.0) to the primitive's vertices. Setting the texture addressing mode to D3DTADDRESS_CLAMP will result in the texture being applied once. The pixel colors at the top of the columns and the end of the rows are extended to the top and right of the primitive respectively.

[Visual Basic]

The "clamp" texture address mode, identified by the D3DTADDRESS_CLAMP member of the CONST_D3DTEXTUREADDRESS enumeration, causes Direct3D to clamp your texture coordinates to the [0.0, 1.0] range. That is, it will apply the texture once, then "smear" the color of edge pixels. For instance, suppose that your program creates a square primitive and assigns texture coordinates of (0.0,0.0), (0.0,3.0), (3.0,3.0), and (3.0,0.0) to the primitive's vertices. Setting the texture addressing mode to D3DTADDRESS_CLAMP will result in the texture being applied once. The pixel colors at the top of the columns and the end of the rows are extended to the top and right of the primitive respectively.

This is illustrated in the following figure:


About the Border Color Texture Address Mode

[C++]

The "border color" texture address mode, identified by the D3DTADDRESS_BORDER member of the D3DTEXTUREADDRESS enumerated type, causes Direct3D to use an arbitrary color, known as the border color, for any texture coordinates outside the range of 0.0 through 1.0, inclusive.

[Visual Basic]

The "border color" texture address mode, identified by the D3DTADDRESS_BORDER member of the CONST_D3DTEXTUREADDRESS enumeration, causes Direct3D to use an arbitrary color, known as the border color, for any texture coordinates outside the range of 0.0 through 1.0, inclusive.

This is shown in the next illustration in which the application specified that the texture be applied to the primitive using a red border.

[C++]

Applications set the border color by calling IDirect3DDevice7::SetTextureStageState. Set the first parameter for the call to the desired texture stage identifier, the second parameter to the D3DTSS_BORDERCOLOR stage state value, and the third parameter to the new RGBA border color.

If your application stills uses the legacy IDirect3DDevice2 interface, you can set the border color by calling IDirect3DDevice2::SetRenderState method, specifying the D3DRENDERSTATE_BORDERCOLOR render state value and the new RGBA border color as parameters. (The D3DRENDERSTATE_BORDERCOLOR render state is obsolete and is not recognized by the IDirect3DDevice7 interface.)

[Visual Basic]

Visual Basic applications set the border color by calling Direct3DDevice7.SetTextureStageState. Set the first parameter for the call to the desired texture stage identifier, the second parameter to the D3DTSS_BORDERCOLOR stage state value, and the third parameter to the new RGBA border color.


Setting and Retrieving Texture Addressing Modes

[C++]

You can set texture addressing modes for individual texture stages by calling the IDirect3DDevice7::SetTextureStageState method. Specify the desired texture stage identifier in the first parameter. Set the second parameter to D3DTSS_ADDRESS to change both the u- and v-texture addressing modes simultaneously, or use the D3DTSS_ADDRESSU or D3DTSS_ADDRESSV values to update the u- or v-addressing modes individually. The third parameter you pass to SetTextureStageState determines which mode is being set; this can be any one of the members of the D3DTEXTUREADDRESS enumerated type. To retrieve the current texture address mode for a given texture stage, call IDirect3DDevice7::GetTextureStageState, using the D3DTSS_ADDRESS, D3DTSS_ADDRESSU, or D3DTSS_ADDRESSV members of the D3DTEXTURESTAGESTATETYPE enumeration to identify the address mode about which you want information.

If your application uses the legacy IDirect3DDevice2 interface, you set texture addressing modes by calling the IDirect3DDevice2::SetRenderState method, using the D3DRENDERSTATE_TEXTUREADDRESS render state to simultaneously set u- and v-texture addressing. You can set u- and v-addressing individually with the D3DRENDERSTATE_TEXTUREADDRESSU or D3DRENDERSTATE_TEXTUREADDRESSV render states. Like their newer SetTextureStageState counterparts, these render states also use the values from D3DTEXTUREADDRESS enumerated type.

Note The IDirect3DDevice7::SetRenderState method (as opposed to the IDirect3DDevice2 version) still recognizes the D3DRENDERSTATE_TEXTUREADDRESS, D3DRENDERSTATE_TEXTUREADDRESSU, D3DRENDERSTATE_TEXTUREADDRESSV render states, even though they have been superseded. Instead of failing these legacy render states, the IDirect3DDevice7 implementation maps their effects to the first texture stage (stage 0). Applications should not mix the legacy render states with their corresponding texture stage states, as unpredictable results can occur.

[Visual Basic]

From Visual Basic, you set texture addressing modes for individual texture stages by calling the Direct3DDevice7.SetTextureStageState method. Specify the desired texture stage identifier in the first parameter. Set the second parameter to D3DTSS_ADDRESS to change both the u- and v-texture addressing modes simultaneously, or use the D3DTSS_ADDRESSU or D3DTSS_ADDRESSV values to update the u- or v-addressing modes individually. The third parameter you pass to SetTextureStageState determines which mode is being set; this can be any one of the members of the CONST_D3DTEXTUREADDRESS enumeration.

To retrieve the current texture address mode for a given texture stage, call Direct3DDevice7.GetTextureStageState, using the D3DTSS_ADDRESS, D3DTSS_ADDRESSU, or D3DTSS_ADDRESSV members of the CONST_D3DTEXTURESTAGESTATETYPE enumeration to the address mode about which you want information.


Texture Addressing Modes and Texture Wrapping

Direct3D enables applications to perform texture wrapping. It is important to note that setting the texture addressing mode to D3DTADDRESS_WRAP is not the same as performing texture wrapping. Setting the texture addressing mode to D3DTADDRESS_WRAP results in multiple copies of the source texture being applied to the current primitive, and enabling texture wrapping changes how the system rasterizes textured polygons. For details, see Texture Wrapping.

Enabling texture wrapping effectively makes texture coordinates outside the [0.0, 1.0] range invalid, and the behavior for rasterizing such "delinquent" texture coordinates is undefined in this case. When texture wrapping is enabled, texture addressing modes are not used. Take care that your application does not specify texture coordinates lower than 0.0 or higher than 1.0 when texture wrapping is enabled.


Device Limitations for Texture Addressing

[C++]

Although the system generally allows texture coordinates outside the range of 0.0 and 1.0, inclusive, hardware limitations often affect how far outside that range texture coordinates can be. A rendering device communicates this limit in the dwMaxTextureRepeat member of the D3DDEVICEDESC7 structure when you retrieve device capabilities. The value in this member describes the full range of texture coordinates allowed by the device. For instance, if this value is 128, then the input texture coordinates must be kept in the range -128.0 to +128.0. Passing vertices with texture coordinates outside of this range is invalid. The same restriction applies to the texture coordinates generated as a result of automatic texture coordinate generation and texture coordinate transformations.

The interpretation of dwMaxTextureRepeat is also affected by the D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE capability bit. When this bit is set, the value in the dwMaxTextureRepeat member of D3DDEVICEDESC7 is used precisely as described. However, when D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE is not set, texture repeating limitations depend on the size of the texture indexed by the texture coordinates. In this case, dwMaxTextureRepeat must be scaled by the current texture size (at the largest level of detail) to compute the valid texture coordinate range. For example, given a texture dimension of 32 and dwMaxTextureRepeat value of 512, the actual valid texture coordinate range is 512/32 = 16, so the texture coordinates for this device must be within the range of -16.0 to +16.0.

[Visual Basic]

Although the system generally allows texture coordinates outside the range of 0.0 and 1.0, inclusive, hardware limitations often affect how far outside that range texture coordinates can be. A rendering device communicates this limit in the lMaxTextureRepeat member of the D3DDEVICEDESC7 type when you retrieve device capabilities. The value in this member describes the full range of texture coordinates allowed by the device. For instance, if this value is 128, then the input texture coordinates must be kept in the range -128.0 to +128.0. Passing vertices with texture coordinates outside of this range is invalid. The same restriction applies to the texture coordinates generated as a result of automatic texture coordinate generation and texture coordinate transformations.

The interpretation of lMaxTextureRepeat is also affected by the D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE capability bit. When this bit is set, the value in the lMaxTextureRepeat member of D3DDEVICEDESC7 is used precisely as described. However, when D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE is not set, texture repeating limitations depend on the size of the texture indexed by the texture coordinates. In this case, lMaxTextureRepeat must be scaled by the current texture size (at the largest level of detail) to compute the valid texture coordinate range. For example, given a texture dimension of 32 and lMaxTextureRepeat value of 512, the actual valid texture coordinate range is 512/32 = 16, so the texture coordinates for this device must be within the range of -16.0 to +16.0.


Texture Interfaces and Texture Handles

[Visual Basic]

Note Information in this topic pertains only to applications written in C++. DirectX for Visual Basic does not use texture handles.

[C++]

Texture handles are obsolete. They were used in applications that utilized the IDirect3D and IDirect3D2 interfaces.

With the IDirect3D7 interface (and the legacy IDirect3D3 interface), you create and use textures through interface pointers to the texture surfaces. You obtain a texture surface interface pointer when you create the texture surface by calling the IDirectDraw7::CreateSurface method. Direct3D supports the blending of up to eight textures onto a primitive at once. For details, see Texture Surface Objects.


Palettized Textures

[C++]

Direct3D devices can support texturing from texture surfaces that use attached palettes. These types of textures are sometimes called "palettized textures." A palettized texture is a DirectDrawSurface object, created with the DDSCAPS_TEXTURE capability, that uses one of the DDPF_PALETTEINDEXEDn pixel formats (where n is 1, 2, 4, or 8). These capabilities are included in the DDSURFACEDESC2 structure that you use to create a texture (and the DDPIXELFORMAT structure that the description contains). Like all palettized surfaces, instead of a color, each pixel is an index into a table of values held within an attached DirectDrawPalette object. For more information about creating and using palettized surfaces, see Surfaces and Palettes in the DirectDraw documentation. As you should always do when checking texture-related device capabilities, be sure to verify the supported texture pixel formats by calling the IDirect3DDevice7::EnumTextureFormats method.

To prepare a palettized texture

  1. Check DirectDraw and Direct3D capabilities as described in this section.
  2. Create a surface of the desired dimensions that includes the DDSCAPS_TEXTURE capability and uses one of the DDPF_PALETTEINDEXEDn pixel formats.
  3. Create and initialize a DirectDrawPalette object. For more information, see Palettes in the DirectDraw documentation. (To use an alpha-only palettized texture, include the DDPCAPS_ALPHA capability when you create the palette. See the reference for IDirectDraw7::CreatePalette for more information.)
  4. Attach the palette to the surface by calling the IDirectDrawSurface7::SetPalette method for the texture surface.

Note If you create a palettized texture surface, but neglect to attach a palette, your application will cause an access violation within Direct3D Immediate Mode during rendering.

The palettes you use with palettized textures need not be limited to color data. In some cases, devices support texture palettes that also contain alpha information. If so, DirectDraw will expose the DDPCAPS_ALPHA palette capability flag when you call the IDirectDraw7::GetCaps method—the flag is found in the dwPalCaps member of the associated DDCAPS structure. If the rendering device can perform texturing from alpha-capable palettized textures, it will expose the D3DPTEXTURECAPS_ALPHAPALETTE capability when you call IDirect3DDevice7::GetCaps. (The D3DPTEXTURECAPS_ALPHAPALETTE flag can be found in the two D3DPRIMCAPS structures contained by the D3DDEVICEDESC7 structure you pass with the call.)

[Visual Basic]

Direct3D devices can support texturing from texture surfaces that use attached palettes. These types of textures are sometimes called "palettized textures." A palettized texture is a DirectDrawSurface object, created with the DDSCAPS_TEXTURE capability, that uses one of the DDPF_PALETTEINDEXEDn pixel formats (where n is 1, 2, 4, or 8). These capabilities are included in the DDSURFACEDESC2 type that you use to create a texture (and the DDPIXELFORMAT type that the description contains). Like all palettized surfaces, instead of a color, each pixel is an index into a table of values held within an attached DirectDrawPalette object. For more information about creating and using palettized surfaces, see Surfaces and Palettes in the DirectDraw documentation. As you should always do when checking texture-related device capabilities, be sure to verify the supported texture pixel formats by using Direct3DEnumPixelFormats class retrieved by the Direct3DDevice7.GetTextureFormatsEnum method.

To prepare a palettized texture

  1. Check DirectDraw and Direct3D capabilities as described in this section.
  2. Create a surface of the desired dimensions that includes the DDSCAPS_TEXTURE capability and uses one of the DDPF_PALETTEINDEXEDn pixel formats.
  3. Create and initialize a DirectDrawPalette object. For more information, see Palettes in the DirectDraw documentation. (To use an alpha-only palettized texture, include the DDPCAPS_ALPHA capability when you create the palette. See the reference for DirectDraw7.CreatePalette for more information.)
  4. Attach the palette to the surface by calling the DirectDrawSurface7.SetPalette method for the texture surface.

Note If you create a palettized texture surface, but neglect to attach a palette, your application will cause an access violation within Direct3D Immediate Mode during rendering.

The palettes you use with palettized textures need not be limited to color data. In some cases, devices support texture palettes that also contain alpha information. If so, DirectDraw will expose the DDPCAPS_ALPHA palette capability flag when you call the DirectDraw7.GetCaps method—the flag is found in the lPalCaps member of the associated DDCAPS type. If the rendering device can perform texturing from alpha-capable palettized textures, it will expose the D3DPTEXTURECAPS_ALPHAPALETTE capability when you call Direct3DDevice7.GetCaps. (The D3DPTEXTURECAPS_ALPHAPALETTE flag can be found in the two D3DPRIMCAPS types contained by the D3DDEVICEDESC7 type you pass with the call.)


Texture Coordinates

The following topics introduce the concept of texture coordinates, their formats, and the Direct3D services used to manipulate them.

  • Understanding Texture Coordinates
  • Directly Mapping Texels to Pixels
  • Texture Coordinate Formats
  • Texture Coordinate Processing


Understanding Texture Coordinates

Most textures, like bitmaps, are a two dimensional array of color values. (Cubic-environment map textures are an exception. For details, see Cubic Environment Mapping.) The individual color values are called texture elements, or texels. Each texel has a unique address in the texture. The address can be thought of as a column and row number, which are labeled u and v respectively.

Texture coordinates are in texture space. That is, they are relative to the location (0,0) in the texture. When a texture is applied to a primitive in 3-D space, its texel addresses must be mapped into object coordinates. They must then be translated into screen coordinates, or pixel locations.

Direct3D maps texels in texture space directly to pixels in screen space, skipping the intermediate step for greater efficiency. This mapping process is actually an inverse mapping. That is, for each pixel in screen space, the corresponding texel position in texture space is calculated. The texture color at or around that point is sampled. The sampling process is called texture filtering. For more information, see Texture Filtering.

Each texel in a texture can be specified by its texel coordinate. However, in order to map texels onto primitives, Direct3D requires a uniform address range for all texels in all textures. Therefore, it uses a generic addressing scheme in which all texel addresses are in the range of 0.0 to 1.0 inclusive. Direct3D programs specify texture coordinates in terms of u,v values, much like 2-D Cartesian coordinates are specified in terms of x,y coordinates. (Technically, the system can actually process texture coordinates outside the range of 0.0 and 1.0, and does so by using the parameters you set for texture addressing. For more information, see Texture Addressing Modes.)

A result of this is that identical texture addresses can map to different texel coordinates in different textures. In the following illustration, the texture address being used is (0.5,1.0). However, because the textures are different sizes, the texture address maps to different texels. Texture 1, on the left, is 5x5. The texture address (0.5,1.0) maps to texel (2,4). Texture 2, on the right, is 7x7. The texture address (0.5,1.0) maps to texel (3,6).

A simplified version of the texel mapping process is shown in the following diagram. (Admittedly, this example is extremely simple. For more detailed information, see Directly Mapping Texels to Pixels.)

For this example, we are idealizing a pixel, shown at the left of the illustration, into a square of color. The addresses of the four corners of the pixel are mapped onto the 3-D primitive in object space. The shape of the pixel is often distorted because of the shape of the primitive in 3-D space and because of the viewing angle. The corners of the surface area on the primitive that correspond the corners of the pixel are then mapped into texture space. The mapping process distorts the pixel's shape again, which is common. The final color value of the pixel is computed from the texels in the region to which the pixel maps. You determine the method that Direct3D uses to arrive at the pixel color when you set the texture filtering method. For more information, see Texture Filtering.

Your application can assign texture coordinates directly to vertices. For details, see the reference for the D3DVERTEX C++ structure (or the D3DVERTEX Visual Basic type). This capability gives you control over which portion of a texture is mapped onto a primitive. For instance, suppose you create a rectangular primitive that is exactly the same size as the texture in the following illustration. In this example, you want your application to map the whole texture onto the whole wall. The texture coordinates your application would assign to the vertices of the primitive are (0.0,0.0), (1.0,0.0), (1.0,1.0), and (0.0,1.0).

Let's say you decide to decrease the height of the wall by one-half. You can either distort the texture to fit onto the smaller wall, or you can assign texture coordinates that will cause Direct3D to use the bottom half of the texture.

If you decide to distort or scale the texture to fit the smaller wall, the texture filtering method that you use will influence the quality of the image. For more information, see Texture Filtering.

If, instead, you decide to assign texture coordinates to make Direct3D use the bottom half of the texture for the smaller wall, the texture coordinates your application would assign to the vertices of the primitive in this example are (0.0,0.0), (1.0,0.0), (1.0,0.5), and (0.0,0.5). Direct3D will apply the bottom half of the texture to the wall.

It is possible for texture coordinates of a vertex to be greater than 1.0. When you assign texture coordinates to a vertex that are not in the range of 0.0 to 1.0 inclusive, you should also set the texture addressing mode. For further information, see Texture Addressing Modes.


Directly Mapping Texels to Pixels

Applications often need to apply textures to geometry in a scene such that texels map directly to on-screen pixels. For example, take an application that needs to display text within a texture on an object within a scene. In order to clearly display textual information in a texture, the application needs some way to ensure that the textured geometry receives texels undisrupted by texture filtering. Failing this, the resulting image is often blurred, or in the case of point-sampled texture filtering, can cause rough edges.

Because the Direct3D pixel and texture sampling rules are carefully defined to unify pixel and texture sampling while supporting image and texture filtering, getting the texels in a texture to map directly to on-screen pixels can be a significant and often frustrating challenge. Overcoming this challenge requires a clear understanding of how Direct3D maps the floating-point texture coordinates for a vertex to the integer pixel coordinates used by the rasterizer.

Direct3D performs the following computations to map floating point texture coordinates into texel addresses is.

In the preceding formulas, Tx and Ty are the horizontal and vertical output texel coordinates, and u, v are the horizontal and vertical texture coordinates supplied for the vertex. The Mx and My elements represent the number of horizontal or vertical texels at the current mipmap level. (The remainder of this discussion targets horizontal mapping of texels to pixels; keep in mind that mapping in the vertical is identical to the horizontal case.)

Placing the texture coordinate limits 0.0 and 1.0 into these formulas maps a texture coordinate of 0.0 halfway between the first and last texels of a repeated texture map. The coordinate 1.0 is mapped halfway between the last texel of the current iteration of the texture map and the next iteration. For a repeated texture that's four texels wide, at mipmap level 0, the following illustration shows where the system maps the coordinates 0.0 and 1.0.

Given an understanding of this mapping, you can apply a simple bias to your screen-space geometry coordinates to force the system to map each texel to a corresponding pixel. For example, to draw a four-sided polygon (or "quad') that maps each texel from the preceding texture to one—and only one—pixel on the screen, you must force geometry coordinates to overlap the pixels, effectively placing the center of each texel at the center of each pixel. The result is the 1-to-1 mapping often sought-after by applications.

To map the texture (with a 4 texel width) to the pixel coordinates 0 through 3, you would draw a four-sided polygon (from two triangles) that have screen-space coordinates of –0.5 to 3.5, and texture coordinates of 0.0 to 1.0, respectively. For example, take the pixel at screen coordinate 0.0. Because 0.0 is one-half pixel away from the first vertex (at -0.5), and the total width is 4.0, the iterated texture coordinate is 0.125 (remember the formulas). Scaling this by the texture size, which is 4, gives 0.5. Subtracting the 0.5 bias produces a texture address of 0.0, which fully maps to the first texel in the map.

To summarize, texture coordinates overlap the texture map evenly on both sides. Given a texture of size 4, the mapping is as follows:

The system normalizes pixel coordinates in the same way it does texels, so if the vertices overlap the pixels into which you need to render, and the vertices use texture coordinates of 0.0 and 1.0, the two line up. If both are of similar size and properly aligned, they will match up exactly, texel to pixel, as shown in the following figure.


Texture Coordinate Formats

Texture coordinates in Direct3D can include 1, 2, 3, or 4 floating point elements to address textures with varying levels of dimension. A 1-D texture (a texture surface with dimensions of 1-by-n texels) would be addressed by one texture coordinate. The most common case, 2-D textures, are addressed with two texture coordinates commonly called u and v. Direct3D supports a single type of 3-D texture, called a cubic-environment map. Cubic environment maps aren't truly 3-D, but they are addressed with a 3-element vector. For details, see Cubic Environment Mapping.

[C++]

As described in About Vertex Formats, applications encode texture coordinates within the vertex format. The vertex format can include multiple sets of texture coordinates. Use the D3DFVF_TEX0 through D3DFVF_TEX8 flexible vertex format flags to describe a vertex format that includes no texture coordinates, or as many as eight sets.

Each texture coordinate set can have between 1 and 4 elements. The D3DFVF_TEXTUREFORMAT1 through D3DFVF_TEXTUREFORMAT4 flags describe the number of elements are in a given texture coordinate in a given set, but these flags aren't used by themselves. Rather, the D3DFVF_TEXCOORDSIZEn set of macros use these flags to create bit patterns that describe the number of elements used by a particular set of texture coordinates in the vertex format. These macros accept a single parameter that identifies the index of the coordinate set whose number of elements is being defined. The following example illustrates how these macros are used.

// This vertex format contains two sets of texture coordinates. The first
// set (index 0) has 2 elements, and the second set has 1 element.
//
// The description for this vertex format would be:
//     dwFVF = D3DFVF_XYZ  | D3DFVF_NORMAL |
//             D3DFVF_DIFFUSE | D3DFVF_TEX2|
//             D3DFVF_TEXCOORDSIZE2(0) | D3DFVF_TEXCOORDSIZE1(1);
//
typedef struct CVF {
    D3DVECTOR position;
    D3DVECTOR normal;
    D3DCOLOR  diffuse;
    float     u, v;   // 1st set, 2-D
    float     t;      // 2nd set, 1-D
} CustomVertexFormat;
[Visual Basic]

As described in About Vertex Formats, applications encode texture coordinates within the vertex format. The vertex format can include multiple sets of texture coordinates. Use the D3DFVF_TEX0 through D3DFVF_TEX8 flexible vertex format flags to describe a vertex format that includes no texture coordinates, or as many as eight sets.

Each texture coordinate set can have between 1 and 4 elements. Use the D3DFVF_TEXCOORDSIZEn set of helper functions functions in the Math.bas source file that ships with this SDK to generate bit patterns that describe the number of elements used by a particular set of texture coordinates in the vertex format. These macros accept a single parameter that identifies the index of the coordinate set whose number of elements is being defined. The following example illustrates how these macros are used.

Private Sub Form_Load()
' This vertex format contains two sets of texture coordinates. The first
' set (index 0) has 2 elements, and the second set has 1 element.
'
' The description for this vertex format would be:
'     lFVF = D3DFVF_XYZ Or D3DFVF_NORMAL Or _
'            D3DFVF_DIFFUSE Or D3DFVF_TEX2 Or _
'            D3DFVF_TEXCOORDSIZE2(0) Or D3DFVF_TEXCOORDSIZE1(1)
'
Type CustomVertexFormat
    position As D3DVECTOR
    normal As D3DVECTOR
    diffuse  As D3DVECTOR
    ' 1st set, 2-D
    u As Single
    v As Single
    ' 2nd set, 1-D
    t As Single
End Type

Note With the exception of cubic-environment maps, rasterizers cannot address textures by using any more than two elements. Applications can supply up to three elements for a texture coordinate, but only if the texture is a cube map, or the D3DTTFF_PROJECTED texture transform flag is used. The D3DTTFF_PROJECTED flag causes the rasterizer to divide the first two elements by the third (or nth) element. For more information, see Texture Coordinate Transformations.


Texture Coordinate Processing

This section describes Direct3D support for processing texture coordinates. Information is organized into the following topics:

  • Texture Coordinate Processing Path
  • Automatically-Generated Texture Coordinates
  • Texture Coordinate Transformations
  • Using Texture Coordinate Processing


Texture Coordinate Processing Path

The following figure shows the path taken by the texture coordinates from their source, through processing, and to the rasterizer.

[C++]

There are two sources from which the system can draw texture coordinates. For a given texture stage, you can use texture coordinates included in the vertex format (D3DFVF_TEX1 through D3DFVF_TEX8), or you can use texture coordinates automatically generated by Direct3D. For details about the latter case, see Automatically-Generated Texture Coordinates. If the D3DTSS_TEXTURETRANSFORMFLAGS texture stage state for the current texture stage is set to D3DTTFF_DISABLE (the default setting), input coordinates are not transformed. If D3DTSS_TEXTURETRANSFORMFLAGS is set to any other value, the transformation matrix for that stage is applied to the input coordinates.

The D3DTEXTURETRANSFORMFLAGS enumerated type defines valid values for the D3DTSS_TEXTURETRANSFORMFLAGS texture-stage state. With the exception of the D3DTTFF_DISABLE flag, which bypasses texture coordinate transformation, the values defined in this enumeration configure the number of output coordinates that the system passes to the rasterizer. The D3DTTFF_COUNT1 through D3DTTFF_COUNT4 flags instruct the system to pass 1, 2, 3, or 4 elements from the output coordinates to the rasterizer. (Currently 1-D texture coordinates aren't supported.)

The D3DTTFF_PROJECTED flag is special: it tells the system that the texture coordinates are for a projected texture. Combine the D3DTTFF_PROJECTED flag with one of the other members of D3DTEXTURETRANSFORMFLAGS to instruct the rasterizer to divide all the elements by the last element before rasterization takes place. For instance, when explicitly using three-element texture coordinates (or when transformation results in a three-element texture coordinate), you could combine the D3DTTFF_COUNT3 and D3DTTFF_PROJECTED flags to cause the rasterizer to divide the first two elements by the last, producing 2-D texture coordinates required to address a 2-D texture.

[Visual Basic]

There are two sources from which the system can draw texture coordinates. For a given texture stage, you can use texture coordinates included in the vertex format (D3DFVF_TEX1 through D3DFVF_TEX8), or you can use texture coordinates automatically generated by Direct3D. For details about the latter case, see Automatically-Generated Texture Coordinates. If the D3DTSS_TEXTURETRANSFORMFLAGS texture stage state for the current texture stage is set to D3DTTFF_DISABLE (the default setting), input coordinates are not transformed. If D3DTSS_TEXTURETRANSFORMFLAGS is set to any other value, the transformation matrix for that stage is applied to the input coordinates.

The CONST_D3DTEXTURETRANSFORMFLAGS enumeration defines valid values for the D3DTSS_TEXTURETRANSFORMFLAGS texture-stage state. With the exception of the D3DTTFF_DISABLE flag, which bypasses texture coordinate transformation, the values defined in this enumeration configure the number of output coordinates that the system passes to the rasterizer. The D3DTTFF_COUNT1 through D3DTTFF_COUNT4 flags instruct the system to pass 1, 2, 3, or 4 elements from the output coordinates to the rasterizer.

The D3DTTFF_PROJECTED flag is special: it tells the system that the texture coordinates are for a projected texture. Combine the D3DTTFF_PROJECTED flag with one of the other members of CONST_D3DTEXTURETRANSFORMFLAGS to instruct the rasterizer to divide all the elements by the last element before rasterization takes place. For instance, when explicitly using three-element texture coordinates (or when transformation results in a three-element texture coordinate), you could combine the D3DTTFF_COUNT3 and D3DTTFF_PROJECTED flags to cause the rasterizer to divide the first two elements by the last, producing 2-D texture coordinates required to address a 2-D texture.

Note With the exception of cubic-environment maps, rasterizers cannot address textures by using texture coordinates with more than two elements. If you specify more elements than can be used to address the current texture for that stage, the extraneous elements will be ignored. This also applies when using 2-D texture coordinates for a 1-D texture.


Automatically-Generated Texture Coordinates

Direct3D can automatically generate the texture coordinates for a vertex. This section describes the services offered by the system and includes details on how the services are used. The following topics are discussed:

  • About Automatically-Generated Texture Coordinates
  • Configuring Automatically-Generated Texture Coordinates


About Automatically-Generated Texture Coordinates

The system can use the transformed camera-space position or normal from a vertex as texture coordinates, or it can compute the 3 element vectors used to address a cubic environment map. Like texture coordinates that you explicitly specify in a vertex, automatically-generated texture coordinates can be used as input for texture coordinate transformations.

Automatically-generated texture coordinates can significantly reduce the bandwidth required for geometry data by eliminating the need for explicit texture coordinates in the vertex format. In many cases, the texture coordinates that the system generates can be used in concert with transformations to produce special effects. Of course, this feature is special-purpose, and there will be many occasions in which you will want to use explicit texture coordinates.


Configuring Automatically-Generated Texture Coordinates

[C++]

In C++, the D3DTSS_TEXCOORDINDEX texture-stage state (from the D3DTEXTURESTAGESTATETYPE enumerated type) controls how the system generates texture coordinates.

[Visual Basic]

In Visual Basic, the D3DTSS_TEXCOORDINDEX texture-stage state (from the CONST_D3DTEXTURESTAGESTATETYPE enumeration) controls how the system generates texture coordinates.

Normally, this state instructs the system to use a particular set of texture coordinates encoded in the vertex format. When you include the D3DTSS_TCI_CAMERASPACENORMAL, D3DTSS_TCI_CAMERASPACEPOSITION, or D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR flags in the value you assign to this state, the system's behavior is quite different. If any of these flags are present, the texture stage ignores the texture coordinates within the vertex format in favor of coordinates that the system generates. The meanings for each flag are as follows:

D3DTSS_TCI_CAMERASPACENORMAL
Use the vertex normal, transformed to camera space, as input texture coordinates.
D3DTSS_TCI_CAMERASPACEPOSITION
Use the vertex position, transformed to camera space, as input texture coordinates.
D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR
Use the reflection vector, transformed to camera space, as input texture coordinates. The reflection vector is computed from the input vertex position and normal vector.

The preceding flags are mutually exclusive, so they cannot be combined. If you include one of these flags, you can still specify an index value, which the system uses to determine the texture wrapping mode.

[C++]

The following code fragment shows how these flags are used in C++.

// For this example, the lpd3dDevice variable is a valid
// pointer to an IDirect3DDevice7 interface.

// Use the vertex position (camera-space) as the input
// texture coordinates for this texture stage, and to use the
// wrap mode set in the D3DRENDERSTATE_WRAP1 render state
lpd3dDevice->SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX,
                                   D3DTSS_TCI_CAMERASPACEPOSITION | 1 );
[Visual Basic]

The following code fragment shows how these flags are used in Visual Basic.

' For this example, the d3dDevice variable is a valid
' reference to a Direct3DDevice7 object.

' Use the vertex position (camera-space) as the input
' texture coordinates for this texture stage, and the
' wrap mode set in the D3DRENDERSTATE_WRAP1 render state
Call d3dDevice.SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, _
                                    D3DTSS_TCI_CAMERASPACEPOSITION Or 1)

Note Automatically-generated texture coordinates are most useful as input values for a texture coordinate transformation, or to eliminate the need for your application to compute 3-element vectors for cubic-environment maps.

See Also

Texture Coordinate Transformations, Cubic Environment Mapping


Texture Coordinate Transformations

This following topics provide information about working with the texture coordinate transformation features offered by Direct3D Immediate Mode.

  • About Texture Coordinate Transformations
  • Setting and Retrieving Texture Coordinate Transformations
  • Enabling Texture Coordinate Transformations


About Texture Coordinate Transformations

Direct3D devices can transform the texture coordinates for vertices by applying a 4×4 matrix. The system applies transformations to texture coordinates in the same manner as geometry, and any transformations that can be communicated in a 4×4 matrix—scales, rotations, translations, projections, shears, or any concatenation of these—can be applied.

Devices that support hardware-accelerated transformation and lighting operations (TnLHAL Device) also accelerate the transformation of texture coordinates. When hardware acceleration of transformations isn't available, platform-specific optimizations in the Direct3D geometry pipeline apply to texture coordinate transformations.

Texture coordinate transformations are useful for producing special effects while avoiding the need to directly modify the texture coordinates of your geometry. You could use simple translation or rotation matrices to animate textures on an object, or you might transform texture coordinates that are automatically generated by Direct3D to simplify and perhaps accelerate advanced effects such as projected textures and dynamic light-mapping. Additionally, you might use texture coordinate transforms to "reuse" a single set of texture coordinates for multiple purposes (in multiple texture stages).

For more information, see Using Texture Coordinate Processing.


Setting and Retrieving Texture Coordinate Transformations

[C++]

Like the matrices that your application uses for geometry, you set and retrieve texture coordinate transformations by calling the IDirect3DDevice7::SetTransform and IDirect3DDevice7::GetTransform methods. These methods accept the D3DTRANSFORMSTATE_TEXTURE0 through D3DTRANSFORMSTATE_TEXTURE7 members of the D3DTRANSFORMSTATETYPE enumerated type to identify the transformation matrices for texture stages 0 through 7, respectively.

The following code sets a matrix to be applied to the texture coordinates for texture stage 0.

// For this example, the lpd3dDevice variable contains a
// valid pointer to an IDirect3DDevice7 interface.

D3DMATRIX matTrans  = D3DUtil_SetIdentityMatrix(); // declared in d3dutil.h

// Set-up the matrix for the desired transformation.
lpd3dDevice->SetTransform(D3DTRANSFORMSTATE_TEXTURE0, &matTrans);
[Visual Basic]

Like the matrices that your application uses for geometry, you set and retrieve texture coordinate transformations by calling the Direct3DDevice7.SetTransform and Direct3DDevice7.GetTransform methods. These methods accept the D3DTRANSFORMSTATE_TEXTURE0 through D3DTRANSFORMSTATE_TEXTURE7 members of the CONST_D3DTRANSFORMSTATETYPE enumeration to identify the transformation matrices for texture stages 0 through 7, respectively.

The following code sets a matrix to be applied to the texture coordinates for texture stage 0.

' For this example, the d3dDevice variable contains a
' valid reference to a Direct3DDevice7 object, and
' dx contains a valid reference to a DirectX7 object.
Dim matTrans As D3DMATRIX
Call dx.IdentityMatrix(matTrans)

' Set-up the matrix for the desired transformation.
Call d3dDevice.SetTransform(D3DTRANSFORMSTATE_TEXTURE0, matTrans)


Enabling Texture Coordinate Transformations

[C++]

The D3DTSS_TEXTURETRANSFORMFLAGS texture stage state controls the application of texture coordinate transformations. Values for this texture stage state are defined by the D3DTEXTURETRANSFORMFLAGS enumerated type.

Texture coordinate transformations are disabled when D3DTSS_TEXTURETRANSFORMFLAGS is set to D3DTTFF_DISABLE (the default value). Assuming that texture coordinate transformations were enabled for stage 0, the following code disables them:

// For this example, the lpd3dDevice variable contains a
// valid pointer to an IDirect3DDevice7 interface.

lpd3dDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE);

The other values defined in D3DTEXTURETRANSFORMFLAGS are used to enable texture coordinate transformations, and to control how many of the resulting texture coordinate elements are to be passed to the rasterizer. For example, take the following code:

// For this example, the lpd3dDevice variable contains a
// valid pointer to an IDirect3DDevice7 interface.

lpd3dDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2);

The D3DTTFF_COUNT2 value instructs the system to apply the transformation matrix set for texture stage 0, then pass the first two elements of the modified texture coordinates to the rasterizer.

The D3DTTFF_PROJECTED texture transformation flag indicates coordinates for a projected texture. When this flag is specified, the rasterizer divides the elements passed-in by the last element. Take the following code, for example:

// For this example, the lpd3dDevice variable contains a
// valid pointer to an IDirect3DDevice7 interface.

lpd3dDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS,
                                   D3DTTFF_COUNT3 | D3DTTFF_PROJECTED );

The preceding code informs the system to pass three texture coordinate elements to the rasterizer, and the rasterizer is to divide first two elements by the third, producing the 2-D texture coordinates needed to address the texture.

[Visual Basic]

The D3DTSS_TEXTURETRANSFORMFLAGS texture stage state controls the application of texture coordinate transformations. Values for this texture stage state are defined by the CONST_D3DTEXTURETRANSFORMFLAGS enumeration.

Texture coordinate transformations are disabled when D3DTSS_TEXTURETRANSFORMFLAGS is set to D3DTTFF_DISABLE (the default value). Assuming that texture coordinate transformations were enabled for stage 0, the following code disables them:

' For this example, the d3dDevice variable contains a
' valid reference to a Direct3DDevice7 object

Call d3dDevice.SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, _
                                    D3DTTFF_DISABLE)

The other values defined in CONST_D3DTEXTURETRANSFORMFLAGS are used to enable texture coordinate transformations, and to control how many of the resulting texture coordinate elements are to be passed to the rasterizer. For example, take the following code:

' For this example, the d3dDevice variable contains a
' valid reference to a Direct3DDevice7 object.

Call d3dDevice.SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, _
                                    D3DTTFF_COUNT2)

The D3DTTFF_COUNT2 value instructs the system to apply the transformation matrix set for texture stage 0, then pass the first two elements of the modified texture coordinates to the rasterizer.

The D3DTTFF_PROJECTED texture transformation flag indicates coordinates for a projected texture. When this flag is specified, the rasterizer divides the elements passed-in by the last element. Take the following code, for example:

' For this example, the d3dDevice variable contains a
' valid pointer to an IDirect3DDevice7 interface.

Call d3dDevice.SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, _
                                    D3DTTFF_COUNT3 | D3DTTFF_PROJECTED)

The preceding code informs the system to pass three texture coordinate elements to the rasterizer, and the rasterizer is to divide first two elements by the third, producing the 2-D texture coordinates needed to address the texture.


Using Texture Coordinate Processing

[C++]

The following are some ways you might use texture coordinate processing to achieve special texturing effects, expressed with psuedo-code.

Animating textures (by translation or rotation) on a model:

  • Define 2-D texture coordinates in your vertex format:
    // Use a single texture, with 2-D texture coordinates. This
// bit-pattern should be expanded to include position, normal,
// and color information as needed.
DWORD dwFVFTex = D3FVF_TEX1 | D3DFVF_TEXCOORDSIZE2(0);
  • Configure the rasterizer to use 2-D texture coordinates:
    SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2)
  • Define and set an appropriate texture coordinate transformation matrix:
    // M is a D3DMATRIX being set to translate texture
// coordinates in the U and V directions.
//      1   0  0  0
//      0   1  0  0
//      du dv  1  0 (du and dv change each frame)
//      0   0  0  1

D3DMATRIX M = D3DUtil_SetIdentityMatrix(); // declared in d3dutil.h
M._31 = du;
M._32 = dv;

Creating texture coordinates as a linear function of a model's camera-space position:

  • Use the D3DTSS_TCI_CAMERASPACEPOSITION flag to instruct the system to pass the vertex position, in camera space, as input to a texture transformation:
    // The input vertices have NO texture coordinates (saving bandwidth!!!)
// 3 texture coordinates are generated by using vertex position in
// camera space (x, y, z)
SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEPOSITION)
  • Instruct the rasterizer to expect 2-D texture coordinates:
    // Two output coordinates will be used.
SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2)
  • Define and set a matrix that applies a linear function:
    // Generate texture coordinates as linear functions
// such that:
//      u = Ux*x + Uy*x + Uz*x + Uw
//      v = Vx*x + Vy*x + Vz*x + Vw
// The matrix M for this case is:
//      Ux  Vx  0  0
//      Uy  Vy  0  0
//      Uz  Vz  0  0
//      Uw  Vw  0  0

SetTransform(D3DTRANSFORMSTATE_TEXTURE0, &M)

Performing environment mapping with a cubic environment map:

  • Use the D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR flag to instruct the system to automatically generate texture coordinates (as reflection vectors) for cubic mapping.
    SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR)
  • Instruct the rasterizer to expect texture coordinates with 3 elements:
    SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT3)

Performing projective texturing:

  • Use the D3DTSS_TCI_CAMERASPACEPOSITION flag to instruct the system to pass the vertex position as input to a texture transformation matrix:
    SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEPOSITION)
  • Create and apply the texture projection matrix. (This is beyond the scope of this documentation, and is the topic of several industry articles).
  • Instruct the rasterizer to expect 3-element projected texture coordinates.
    // Two output coordinates will be used.
SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTF_PROJECTED | D3DTTFF_COUNT3)
[Visual Basic]

The following are some ways you might use texture coordinate processing to achieve special texturing effects, expressed with psuedo-code.

Animating textures (by translation or rotation) on a model:

  • Define 2-D texture coordinates in your vertex format:
    ' Use a single texture, with 2-D texture coordinates. This
' bit-pattern should be expanded to include position, normal,
' and color information as needed.
lFVFTex = (D3FVF_TEX1 Or D3DFVF_TEXCOORDSIZE2(0))
  • Configure the rasterizer to use 2-D texture coordinates:
    SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2)
  • Define and set an appropriate texture coordinate transformation matrix:
    ' M is a D3DMATRIX being set to translate texture
' coordinates in the U and V directions.
'      1   0  0  0
'      0   1  0  0
'      du dv  0  0 (du and dv change each frame)
'      0   0  0  0
dx.IdentityMatrix(M)
M.rc31 = du
M.ec32 = dv

Creating texture coordinates as a linear function of a model's camera-space position:

  • Use the D3DTSS_TCI_CAMERASPACEPOSITION flag to instruct the system to pass the vertex position, in camera space, as input to a texture transformation:
    ' The input vertices have NO texture coordinates (saving bandwidth!!!)
' 3 texture coordinates are generated by using vertex position in
' camera space (x, y, z)
SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEPOSITION)
  • Instruct the rasterizer to expect 2-D texture coordinates:
    ' Two output coordinates will be used.
SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2)
  • Define and set a matrix that applies a linear function:
    ' Generate texture coordinates as linear functions
' such that:
'      u = Ux*x + Uy*x + Uz*x + Uw
'      v = Vx*x + Vy*x + Vz*x + Vw
' The matrix M for this case is:
'      Ux  Vx  0  0
'      Uy  Vy  0  0
'      Uz  Vz  0  0
'      Uw  Vw  0  0

SetTransform(D3DTRANSFORMSTATE_TEXTURE0, M)

Performing environment mapping with a cubic environment map:

  • Use the D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR flag to instruct the system to automatically generate texture coordinates (as reflection vectors) for cubic mapping.
    SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR)
  • Instruct the rasterizer to expect texture coordinates with 3 elements:
    SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT3)

Performing projective texturing:

  • Use the D3DTSS_TCI_CAMERASPACEPOSITION flag to instruct the system to pass the vertex position as input to a texture transformation matrix:
    SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEPOSITION)
  • Create and apply the texture projection matrix. (This is beyond the scope of this documentation, and is the topic of several industry articles).
  • Instruct the rasterizer to expect 3-element projected texture coordinates.
    ' Two output coordinates will be used.
SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTF_PROJECTED | D3DTTFF_COUNT3)


Texture Surface Objects

This section presents information on creating and rendering with texture interface pointers in the following topics:

  • Obtaining a Texture Surface Object
  • Rendering with Texture Surfaces


Obtaining a Texture Surface Object

[C++]

Textures are simply DirectDraw surface objects, and therefore they expose the IDirectDrawSurface7 interface. The first step in obtaining a pointer to a texture surface interface is to create a DirectDraw surface with the DDSCAPS_TEXTURE capability set. See Creating Surfaces and DDSCAPS2.

Once the surface is created, your application has a pointer to the texture surface's IDirectDrawSurface7 interface. You can use the methods of the surface interface to manipulate the data it contains the same as you would with any other surface. The IDirectDrawSurface7 of a texture serves as its identifier; all of the texture-related methods in the IDirect3DDevice7 interface accept pointers to this interface.

Note Use the IDirect3DDevice7::Load method to load images into your textures. Loading textures into video memory by calling this method is preferred over blit operations.

[Visual Basic]

Textures are simply DirectDraw surface objects, represented by the DirectDrawSurface7 class. The first step in obtaining a texture is to create a DirectDraw surface with the DDSCAPS_TEXTURE capability set. See Creating Surfaces and DDSCAPS2.

Once the surface is created, your application has a reference to the surface class object. You can use the methods of DirectDrawSurface7 to manipulate the data it contains the same as you would with any other surface. Textures are identified by the reference to the DirectDrawSurface7 class that your application holds. All of the texture-related methods in the Direct3DDevice7 class accept this class reference as a parameter.

Note Use the Direct3DDevice7.Load method to load images into your textures. Loading textures into video memory by calling this method is preferred over blit operations.


Rendering with Texture Surfaces

Direct3D supports multiple texture blending through the concept of texture stages. Each texture stage contains a texture and operations that can be performed on the texture. The textures in the texture stages form the set of current textures. For more information, see Multiple Texture Blending. The state of each texture is encapsulated in its texture stage.

[C++]

In a C++ application, the state of each texture must be set with the IDirect3DDevice7::SetTextureStageState method. Pass the stage number (0-7) as the value of the first parameter. Set the value of the second parameter to a member of the member of the D3DTEXTURESTAGESTATETYPE enumerated type. The final parameter is the state value for the particular texture state.

Using texture interface pointers, your application can render a blend of up to eight textures. Set the current textures by invoking the IDirect3DDevice7::SetTexture method. Direct3D will blend all current textures onto the primitives that it renders.

Note The SetTexture method increments the reference count of the texture surface being assigned. When the texture is no longer needed, you should set the texture at the appropriate stage to NULL. If you fail to do this, the surface will not be released, resulting in a memory leak.

Your application can set the texture wrapping state for the current textures by calling the IDirect3DDevice7::SetRenderState method. Pass a value from D3DRENDERSTATE_WRAP0 through D3DRENDERSTATE_WRAP7 as the value of the first parameter, and use a combination of the D3DWRAPCOORD_0, D3DWRAPCOORD_1, D3DWRAPCOORD_2, and D3DWRAPCOORD_3 flags to enable wrapping in the u or v directions.

Your application can also set the texture perspective and texture filtering states. See Texture Perspective State, Texture Filtering, and Texture Filtering State.

[Visual Basic]

From Visual Basic, the state of each texture must be set with the Direct3DDevice7.SetTextureStageState method. Pass the stage number (0-7) as the value of the first parameter. Set the value of the second parameter to a member of the member of the CONST_D3DTEXTURESTAGESTATETYPE enumeration. The final parameter is the state value for the particular texture state.

Applications can render a blend of up to eight textures. Set the current textures by invoking the Direct3DDevice7.SetTexture method. Direct3D will blend all current textures onto the primitives that it renders.

Note When the texture is no longer needed, you should set the texture at the appropriate stage to Nothing. If you fail to do this, the memory for the surface may be lost when your application closes.

Your application can set the texture wrapping state for the current textures by calling the Direct3DDevice7.SetRenderState method. Pass a value from D3DRENDERSTATE_WRAP0 through D3DRENDERSTATE_WRAP7 as the value of the first parameterand use a combination of the D3DWRAPCOORD_0, D3DWRAPCOORD_1, D3DWRAPCOORD_2, and D3DWRAPCOORD_3 flags (from the CONST_D3D enumeration) to enable wrapping in the u or v directions.

Your application can also set the texture perspective and texture filtering states. See Texture Perspective State, Texture Filtering, and Texture Filtering State.


Texture Filtering

When Direct3D renders a primitive, it maps the 3-D primitive onto a 2-D screen. If the primitive has a texture, Direct3D must use that texture to produce a color for each pixel in the primitive's 2-D rendered image. For every pixel in the primitive's on-screen image, it must obtain a color value from the texture. This process is called texture filtering.

When a texture filter operation is performed, the texture being used is typically also being magnified or minified. In other words, it is being mapped onto a primitive image that is larger or smaller than itself. Magnification of a texture can result in many pixels being mapped to one texel. The result can be a chunky appearance. Minification of a texture often means that a single pixel is mapped to many texels. The resulting image can be blurry or aliased. To resolve these problems, some blending of the texel colors must be performed to arrive at a color for the pixel.

Direct3D simplifies the complex process of texture filtering. It provides developers with three types of texture filtering—linear filtering, anisotropic filtering, and mipmap filtering. If you select no texture filtering, Direct3D utilizes a technique called nearest point sampling.

Each type of texture filtering has advantages and disadvantages. For instance, linear texture filtering can produce jagged edges or a chunky appearance in the final image. However, it is a computationally low-overhead method of texture filtering. On the other hand, filtering with mipmaps usually produces the best results, especially when combined with anisotropic filtering. However it requires the most memory of the techniques that Direct3D supports.

[C++]

Applications that use texture interface pointers should set the current texture filtering method by calling the IDirect3DDevice7::SetTextureStageState method. Set the value of the first parameter to the integer index number (0-7) of the texture for which you are selecting a texture filtering method. Pass either D3DTSS_MAGFILTER, D3DTSS_MINFILTER, or D3DTSS_MIPFILTER as the value of the second parameter. Set the third parameter to a member of the D3DTEXTUREMAGFILTER, D3DTEXTUREMINFILTER, or D3DTEXTUREMIPFILTER enumerated types respectively.

[Visual Basic]

Visual Basic applications should set the current texture filtering method by calling the Direct3DDevice7.SetTextureStageState method. Set the value of the first parameter to the integer index number (0-7) of the texture for which you are selecting a texture filtering method. Pass either D3DTSS_MAGFILTER, D3DTSS_MINFILTER, or D3DTSS_MIPFILTER as the value of the second parameter. Set the third parameter to a member of the CONST_D3DTEXTUREMAGFILTER, CONST_D3DTEXTUREMINFILTER, or CONST_D3DTEXTUREMIPFILTER enumerated types respectively.

This section presents the texture filtering methods that Direct3D supports. It is organized into the following topics:

  • Nearest Point Sampling
  • Linear Texture Filtering
  • Anisotropic Texture Filtering
  • Texture Filtering With Mipmaps
[C++]

Note Although the texture-filtering render states present in the D3DRENDERSTATETYPE enumerated type are superseded by texture stage states, the IDirect3DDevice7::SetRenderState (as opposed to the IDirect3DDevice2 version) does not fail if you attempt to use them. Rather, the system maps the effects of these render states to the first stage in the multi-texture cascade, stage 0. Applications should not mix the legacy render states with their corresponding texture stage states, as unpredictable results can occur.


Nearest Point Sampling

Applications are not required to use texture filtering. Direct3D can be set so that it computes the texel address, which often does not evaluate to integers, and simply copies the color of the texel with the closest integer address. This process is called nearest point sampling. This can be a fast and efficient way to process textures if the size of the texture is similar to the size of the primitive's image on the screen. If not, the texture will need to be magnified or minified. The result can be a chunky, aliased, or blurred image.

[C++]

Your C++ application can select nearest point sampling by calling the IDirect3DDevice7::SetTextureStageState method. Set the value of the first parameter to the integer index number (0-7) of the texture for which you are selecting a texture filtering method, and set the second parameter to D3DTSS_MAGFILTER, D3DTSS_MINFILTER, or D3DTSS_MIPFILTER. Pass a member of D3DTEXTUREMAGFILTER, D3DTEXTUREMINFILTER, or D3DTEXTUREMIPFILTER enumerated types as the value in the next parameter to set the magnification, minification, or mipmapping filter.

For more information, see Texture Filtering State.

[Visual Basic]

Your Visual Basic application can select nearest point sampling by calling the Direct3DDevice7.SetTextureStageState method. Set the value of the first parameter to the integer index number (0-7) of the texture for which you are selecting a texture filtering method, and set the second parameter to D3DTSS_MAGFILTER, D3DTSS_MINFILTER, or D3DTSS_MIPFILTER. Pass a member of the CONST_D3DTEXTUREMAGFILTER, CONST_D3DTEXTUREMINFILTER, or CONST_D3DTEXTUREMIPFILTER enumerations in the next parameter to set the magnification, minification, or mipmapping filter.

For more information, see Texture Filtering State.

You should use nearest point sampling carefully, as it can sometimes cause graphic artifacts when the texture is sampled at the boundary between two texels. This boundary is the position along the texture (u or v) at which the sampled texel transitions from one texel to the next. When point sampling is used, the system chooses one sample texel or the other, and the result can change abruptly from one texel to the next texel as the boundary is crossed. This effect can appear as undesired graphic artifacts in the displayed texture. (When linear filtering is used, the resulting texel is computed from both adjacent texels and smoothly blends between them as the texture index moves through the boundary.)

This effect can be seen when mapping a very small texture onto a very large polygon: an operation often called "magnification." For example, when using a texture that looks like a checkerboard, nearest point sampling results in a larger checkerboard that shows distinct edges. By contrast, linear texture filtering results in an image where the checkerboard colors vary smoothly across the polygon.

In most cases, applications can receive the best results by avoiding nearest point sample wherever possible. The majority of hardware today is optimized for linear filtering, so your application should not suffer degraded performance. If the effect you desire absolutely requires the use of the nearest point sampling—such as when using textures to display readable text characters—then your application should be extremely careful to avoid sampling at the texel boundaries, which might result in undesired effects. The following screen capture shows what these artifacts can look like:

Notice that the two squares in the top-right of the group appear different that their neighbors. To avoid graphic artifacts like these, you should start by understanding Direct3D texture sampling rules for nearest-point filtering. Direct3D maps a floating-point texture coordinate ranging from [0.0, 1.0] (0.0 to 1.0, inclusive) to an integer texel space value ranging from [–0.5, n – 0.5], where n is the number of texels in a given dimension on the texture. The resulting texture index is rounded to the nearest integer. This mapping can introduce sampling inaccuracies at texel boundaries.

For a simple example, imagine an application that renders polygons with the D3DTADDRESS_WRAP texture addressing mode. Using the mapping employed by Direct3D, the u texture index maps as follows for a texture with a width of 4 texels:

Notice that the texture coordinates—0.0 and 1.0—for this illustration are exactly at the boundary between texels. Using the method by which Direct3D maps values, the texture coordinates range from [–0.5, 4 – 0.5], where 4 is the width of the texture. For this case, the sampled texel will be the 0th texel for a texture index of 1.0. However, if the texture coordinate was only slightly less than 1.0, the sampled texel would be the nth texel instead of the 0th texel.

The implication of this is that magnifying a small texture using texture coordinates of exactly 0.0 and 1.0 with nearest-point filtering on a screen-space aligned triangle will result in pixels for which the texture map is sampled at the boundary between texels. Any inaccuracies in the computation of texture coordinates, however small, will result in artifacts along the areas in the rendered image which correspond to the texel edges of the texture map.

Performing this mapping of floating point texture coordinates to integer texels with perfect accuracy is difficult, computationally expensive, and generally not necessary. Most hardware implementations use an iterative approach for computing texture coordinates at each pixel location within a triangle. Iterative approaches tend to hide these inaccuracies somewhat because the errors are accumulated evenly during iteration.

The Direct3D reference rasterizer uses a direct-evaluation approach for computing texture indices at each pixel location. Direct evaluation differs from the iterative approach in that any inaccuracy in the operation exhibits a more random error distribution. The result of this is that the sampling errors occurring at the boundaries can be more noticeable since the reference rasterizer does not perform this operation with perfect accuracy (which is, again, difficult and very expensive with floating point texture coordinates).

The best approach is to use nearest-point filtering only when necessary. When you must use it, it is recommended that you offset texture coordinates slightly from the boundary positions to avoid artifacts.


Linear Texture Filtering

Direct3D uses a form of linear texture filtering called bilinear filtering. Like nearest point sampling, bilinear texture filtering first computes a texel address, which is usually not an integer address. Just as in nearest point sampling, if then finds the texel whose integer address is closest the computed address. In addition, the Direct3D rendering module will compute a weighted average of the texels that are immediately above, below, to the left of, and to the right of the nearest sample point.

[C++]

Select bilinear texture filtering by invoking the IDirect3DDevice7::SetTextureStageState method. Set the value of the first parameter to the integer index number (0-7) of the texture for which you are selecting a texture filtering method. Pass D3DTEXTUREMAGFILTER as the value of the second parameter if you are setting the magnification filter. Pass D3DTEXTUREMINFILTER as the value of the second parameter if you are setting the minification filter. Pass D3DTEXTUREMIPFILTER as the value of the second parameter if you are setting the mipmapping filter. Set the third parameter to D3DTFG_LINEAR if you are setting the magnification filter, D3DTFN_LINEAR if you are setting the minification filter, or D3DTFP_LINEAR if you are setting the mipmap filter. For more information, see Texture Filtering State.

[Visual Basic]

Select bilinear texture filtering by invoking the Direct3DDevice7.SetTextureStageState method. Set the value of the first parameter to the integer index number (0-7) of the texture for which you are selecting a texture filtering method. Pass a member of the CONST_D3DTEXTUREMAGFILTER, CONST_D3DTEXTUREMINFILTER, or CONST_D3DTEXTUREMIPFILTER enumerations in the second parameter to set the magnification, minification, or mipmapping filter. Set the third parameter to D3DTFG_LINEAR if you are setting the magnification filter, D3DTFN_LINEAR if you are setting the minification filter, or D3DTFP_LINEAR if you are setting the mipmap filter. For more information, see Texture Filtering State.


Anisotropic Texture Filtering

Anisotropy is the distortion visible in the texels of a 3-D object whose surface is oriented at an angle with respect to the plane of the screen. When a pixel from an anisotropic primitive is mapped into texels, its shape is distorted. Direct3D measures the anisotropy of a pixel as the elongation (length divided by width) of a screen pixel that is inverse-mapped into texture space.

[C++]

Anisotropic texture filtering can be used in conjunction with linear texture filtering or mipmap texture filtering to improve rendering results. Your application enables anisotropic texture filtering by calling the IDirect3DDevice7::SetTextureStageState method. Set the value of the first parameter to the integer index number (0-7) of the texture for which you are selecting a texture filtering method. Pass D3DTEXTUREMAGFILTER as the value of the second parameter if you are setting the magnification filter. Pass D3DTEXTUREMINFILTER as the value of the second parameter if you are setting the minification filter. Set the third parameter to D3DTFG_ANISOTROPIC if you are setting the magnification filter, or D3DTFN_ANISOTROPIC if you are setting the minification filter. For more information, see Texture Filtering State.

Your program must also set the degree of anisotropy to a value greater than one. Do this by calling the IDirect3DDevice7::SetTextureStageState method. Set the value of the first parameter to the integer index number (0-7) of the texture for which you are setting the degree of isotropy. Pass D3DTSS_MAXANISOTROPY as the value of the second parameter. The final parameter should be the degree of isotropy.

Disable isotropic filtering by setting the degree of isotropy to one (any value larger than one enables it). Check the D3DPRASTERCAPS_ANISOTROPY flag in the D3DPRIMCAPS structure to determine the possible range of values for the degree of anisotropy.

[Visual Basic]

Anisotropic texture filtering can be used in conjunction with linear texture filtering or mipmap texture filtering to improve rendering results. Your application enables anisotropic texture filtering by calling the Direct3DDevice7.SetTextureStageState method. Set the value of the first parameter to the integer index number (0-7) of the texture for which you are selecting a texture filtering method. Pass a member of the CONST_D3DTEXTUREMAGFILTER, CONST_D3DTEXTUREMINFILTER, or CONST_D3DTEXTUREMIPFILTER enumerations in the second parameter to set the magnification, minification, or mipmapping filter. Set the third parameter to D3DTFG_ANISOTROPIC if you are setting the magnification filter, or D3DTFN_ANISOTROPIC if you are setting the minification filter. For more information, see Texture Filtering State.

You must also set the degree of anisotropy to a value greater than one. Do this by calling the Direct3DDevice7.SetTextureStageState method. Set the value of the first parameter to the integer index number (0-7) of the texture for which you are setting the degree of isotropy. Pass D3DTSS_MAXANISOTROPY as the value of the second parameter. The final parameter should be the degree of isotropy.

Disable isotropic filtering by setting the degree of isotropy to one (any value larger than one enables it). Check the D3DPRASTERCAPS_ANISOTROPY flag in the D3DPRIMCAPS type to determine the possible range of values for the degree of anisotropy.


Texture Filtering With Mipmaps

Mipmap textures are used in 3-D scenes to decrease the time required for rendering a scene. They also improve the scene's realism. However, they often require large amounts of memory.

This section presents the fundamentals of using mipmap textures in 3-D scenes in the following topics:

  • What Is a Mipmap?
  • Creating a Set of Mipmaps
  • Selecting and Displaying a Mipmap


What Is a Mipmap?

A mipmap is a sequence of textures, each of which is a progressively lower resolution representation of the same image. The height and width of each image, or level, in the mipmap is a power of two smaller than the previous level. Mipmaps do not have to be square.

A high-resolution mipmap image is used for objects that are close to the viewer. Lower-resolution images are used as the object moves farther away. Mipmapping improves the quality of rendered textures at the expense of using more memory.

Direct3D represents mipmaps as a chain of attached surfaces. The highest resolution texture is at the head of the chain and has, as an attachment, the next level of the mipmap. That level has, in turn, an attachment that is the next level in the mipmap, and so on down to the lowest resolution level of the mipmap.

The following set of illustrations shows an example. The set of bitmap textures represents a sign on the side of a container in a 3-D, first-person game. When created as a mipmap, the highest-resolution texture is first in the set. Each succeeding texture in the mipmap set is a power of 2 smaller in height and width. In this case, the maximum-resolution mipmap is 256 pixels by 256 pixels. The next, texture is 128x128. The last texture in the chain is 64x64.

This sign would have a maximum distance from which it is visible. If the player begins far away from the sign, the game would display the smallest texture in the mipmap chain, which in this case the 64x64 texture.

As the player moves the point of view closer to the sign, progressively higher-resolution textures in the mipmap chain are used.

The highest-resolution texture is used when the user's point of view is at the minimum allowable distance from the sign.

This is a computationally lower-overhead way of simulating perspective effects for textures. Rather than render a single texture to many resolutions, it is faster to use multiple textures at varying resolutions.

Direct3D is able to assess which texture in a mipmap set is the closest resolution to the desired output and map pixels into its texel space. If the resolution of the final image is between the resolutions of the textures in the mipmap set, Direct3D can examine texels in both of the mipmaps and blend their color values together.

If you want your application to use mipmaps, it must build a set of mipmaps. For details, see Creating a Set of Mipmaps. Applications apply mipmaps by selecting the mipmap set as the first texture in the set of current textures. For more information, see Multiple Texture Blending.

Next, your program must set the filtering method that Direct3D uses to sample texels. The fastest method of mipmap filtering is to have Direct3D select the nearest texel. Use the D3DTFP_POINT enumerated value to select this. Direct3D can produce better filtering results if your application uses the D3DTFP_LINEAR enumerated value. This will select the nearest mipmap, then compute a weighted average of the texels surrounding the location in the texture to which the current pixel maps.


Creating a Set of Mipmaps

[C++]

To create a mipmap chain, specify the DDSCAPS_MIPMAP and DDSCAPS_COMPLEX flags in the DDSURFACEDESC2 structure passed to the IDirectDraw7::CreateSurface method. Because all mipmaps are also textures, the DDSCAPS_TEXTURE flag must also be specified.

The following example demonstrates how your application can use the IDirectDraw7::CreateSurface method to build a chain of five mipmap levels of sizes 256×256, 128×128, 64×64, 32×32, and 16×16:

// This code fragment assumes that the variable lpDD is a
// valid pointer to a DirectDraw interface.

DDSURFACEDESC2       ddsd;
LPDIRECTDRAWSURFACE7 lpDDMipMap;
ZeroMemory(&ddsd, sizeof(ddsd));
ddsd.dwSize = sizeof(ddsd);
ddsd.dwFlags = DDSD_CAPS | DDSD_MIPMAPCOUNT;
ddsd.dwMipMapCount = 5;
ddsd.ddsCaps.dwCaps = DDSCAPS_TEXTURE |
    DDSCAPS_MIPMAP | DDSCAPS_COMPLEX;
ddsd.dwWidth = 256UL;
ddsd.dwHeight = 256UL;

ddres = lpDD->CreateSurface(&ddsd, &lpDDMipMap);
if (FAILED(ddres))
.
.
.

You can omit the number of mipmap levels, in which case the IDirectDraw7::CreateSurface method will create a chain of surfaces, each a power of two smaller than the previous one, down to the smallest possible size. It is also possible to omit the width and height, in which case IDirectDraw7::CreateSurface will create the number of levels you specify, with a minimum level size of 1×1.

Note Each surface in a mipmap chain has dimensions that are one-half that of the previous surface in the chain. If the top-level mipmap has dimensions of 256×128, the dimensions of the second-level mipmap are 128×64, the third-level is 64×32, and so on down to 2×1. If you explicitly specify dimensions in the dwWidth and dwHeight members, you should be aware of some restrictions. Namely, you cannot request a number of mipmap levels in dwMipMapCount that would cause either the width or height of any mipmap in the chain to be smaller than 1. Take the very simple case of a 4×2 top-level mipmap surface: the maximum value allowed for dwMipMapCount here is 2: the top-level dimensions are 4×2, and the dimensions for the second level 2×1. A value larger than 2 in dwMipMapCount would result in a fractional value in the height of the second-level mipmap, and is therefore disallowed.

[Visual Basic]

To create a mipmap chain, specify the DDSCAPS_MIPMAP and DDSCAPS_COMPLEX flags in the DDSURFACEDESC2 type passed to the DirectDraw7.CreateSurface method. Because all mipmaps are also textures, the DDSCAPS_TEXTURE flag must also be specified.

The following example demonstrates how your application can use the DirectDraw7.CreateSurface method to build a chain of five mipmap levels of sizes 256×256, 128×128, 64×64, 32×32, and 16×16:

' This code fragment assumes that the variable DD contains
' a valid reference to a DirectDraw7 object.
On Local Error Resume Next
Dim ddsd As DDSURFACEDESC2
Dim DDMipMap As DirectDrawSurface7

ddsd.lFlags = DDSD_CAPS Or DDSD_MIPMAPCOUNT
ddsd.lMipMapCount = 5
ddsd.ddsCaps.lCaps = DDSCAPS_TEXTURE Or DDSCAPS_MIPMAP Or DDSCAPS_COMPLEX
ddsd.lWidth = 256
ddsd.lHeight = 256

Set DDMipMap = DD.CreateSurface(ddsd)
If Err.Number <> DD_OK Then
    ' Code to handle error goes here
End If

You can omit the number of mipmap levels, in which case the DirectDraw7.CreateSurface method will create a chain of surfaces, each a power of two smaller than the previous one, down to the smallest possible size. It is also possible to omit the width and height, in which case DirectDraw7.CreateSurface will create the number of levels you specify, with a minimum level size of 1×1.

Note Each surface in a mipmap chain has dimensions that are one-half that of the previous surface in the chain. If the top-level mipmap has dimensions of 256×128, the dimensions of the second-level mipmap are 128×64, the third-level is 64×32, and so on down to 2×1. If you explicitly specify dimensions in the lWidth and lHeight members, you should be aware of some restrictions. Namely, you cannot request a number of mipmap levels in lMipMapCount that would cause either the width or height of any mipmap in the chain to be smaller than 1. Take the very simple case of a 4×2 top-level mipmap surface: the maximum value allowed for lMipMapCount here is 2: the top-level dimensions are 4×2, and the dimensions for the second level 2×1. A value larger than 2 in lMipMapCount would result in a fractional value in the height of the second-level mipmap, and is therefore disallowed.


Selecting and Displaying a Mipmap

[C++]

Call the IDirect3DDevice7::SetTexture method to set the mipmap texture set as the first texture in the list of current textures. For more information, see Multiple Texture Blending.

After your application selects the mipmap texture set, it must assign values from the D3DTEXTUREMIPFILTER enumerated type to the D3DTSS_MIPFILTER texture stage state. Direct3D will then automatically perform mipmap texture filtering.

Your application can also manually traverse a chain of mipmap surfaces by using the IDirectDrawSurface7::GetAttachedSurface method and specifying the DDSCAPS_MIPMAP and DDSCAPS_TEXTURE flags in the DDSCAPS2 structure. The following example traverses a mipmap chain from highest to lowest resolutions:

LPDIRECTDRAWSURFACE7 lpDDLevel, lpDDNextLevel;
DDSCAPS2 ddsCaps;
HRESULT ddres;

lpDDLevel = lpDDMipMap;
lpDDLevel->AddRef();
ddsCaps.dwCaps = DDSCAPS_TEXTURE | DDSCAPS_MIPMAP;
ddres = DD_OK;
while (ddres == DD_OK)
{
    // Process this level.
    .
    .
    .
    ddres = lpDDLevel->GetAttachedSurface(
&ddsCaps, &lpDDNextLevel);
    lpDDLevel->Release();
    lpDDLevel = lpDDNextLevel;
}
if ((ddres != DD_OK) && (ddres != DDERR_NOTFOUND))
{
    // Code to handle the error goes here
}
.
.
.

Applications need to manually traverse a mipmap chain to load bitmap data into each surface in the chain. This is typically the only reason to traverse the chain.

Direct3D explicitly stores the number of levels in a mipmap chain. When an application obtains the surface description of a mipmap (by calling the IDirectDrawSurface7::Lock or IDirectDrawSurface7::GetSurfaceDesc method), the dwMipMapCount member of the DDSURFACEDESC2 structure contains the number of levels in the mipmap, including the top level. For levels other than the top level in the mipmap, the dwMipMapCount member specifies the number of levels from that mipmap to the smallest mipmap in the chain.

[Visual Basic]

Call the Direct3DDevice7.SetTexture method to set the mipmap texture set as the first texture in the list of current textures. For more information, see Multiple Texture Blending.

After your application selects the mipmap texture set, it must assign values from the CONST_D3DTEXTUREMIPFILTER enumerated type to the D3DTSS_MIPFILTER texture stage state. Direct3D will then automatically perform mipmap texture filtering.

Your application can also manually traverse a chain of mipmap surfaces by using the DirectDrawSurface7.GetAttachedSurface method and specifying the DDSCAPS_MIPMAP and DDSCAPS_TEXTURE flags in the DDSCAPS2 type. The following example traverses a mipmap chain from highest to lowest resolutions:

On Local Error Resume Next

Dim DDLevel As DirectDrawSurface7, _
    DDNextLevel As DirectDrawSurface7

Dim ddsCaps As DDSCAPS2

DDLevel = DDMipMap
ddsCaps.lCaps = DDSCAPS_TEXTURE Or DDSCAPS_MIPMAP
While Err.Number = DD_OK
    ' Process this level.
    ' .
    ' .
    ' .
    Set DDNextLevel = DDLevel.GetAttachedSurface(ddsCaps)
    DDLevel = DDNextLevel
Wend
If ((Err.Number <> DD_OK) And (Err.Number <> DDERR_NOTFOUND)) Then
    ' Code to handle the error goes here
End If
.
.
.

Applications need to manually traverse a mipmap chain to load bitmap data into each surface in the chain. This is typically the only reason to traverse the chain.

Direct3D explicitly stores the number of levels in a mipmap chain. When an application obtains the surface description of a mipmap (by calling the DirectDrawSurface7.Lock or DirectDrawSurface7.GetSurfaceDesc method), the lMipMapCount member of the DDSURFACEDESC2 type contains the number of levels in the mipmap, including the top level. For levels other than the top level in the mipmap, the lMipMapCount member specifies the number of levels from that mipmap to the smallest mipmap in the chain.


Texture Wrapping

This section presents information on wrapping textures around 3-D primitives. The discussion is divided into the following topics:

  • What Is Texture Wrapping?
  • Using Texture Wrapping

Note Texture wrapping should not be confused with the similarly named texture addressing modes. For more information, see Texture Addressing Modes and Texture Wrapping and Texture Addressing Modes.


What Is Texture Wrapping?

Texture wrapping, in short, changes the basic way in which Direct3D rasterizes textured polygons using the texture coordinates specified for each vertex. (Don't confuse texture wrapping with the "wrap" texture addressing mode. For more information, see Texture Addressing Modes and Texture Wrapping.) While rasterizing a polygon, the system interpolates between the texture coordinates at each of the polygon's vertices to determine the texels that should be used for every pixel of the polygon. Normally, the system treats the texture as a 2-D plane, interpolating new texels by taking the shortest route from point A within a texture to point B. If point A represents the u, v position (0.8, 0.1), and point B is at (0.1,0.1), the line of interpolation would look like:

Note that the shortest distance between A and B in the preceding illustration runs roughly through the middle of the texture. Enabling u- or v-texture coordinate wrapping changes how Direct3D perceives the shortest route between texture coordinates in the u- and v-directions. By definition, texture wrapping causes the rasterizer to take the shortest route between texture coordinate sets, assuming that 0.0 and 1.0 are coincident. The last bit is the tricky part: you can imagine that enabling texture wrapping in one direction causes the system to treat a texture as though it were "wrapped" around a cylinder. For example, take the following illustration:

The preceding diagram shows how wrapping in the u- direction affects the way the system interpolates texture coordinates. Using the same points we used in the example for "normal", or non-wrapped, textures, you can see that the shortest route between points A and B is no longer across the middle of the texture; it's now across the border where 0.0 and 1.0 exist together. Wrapping in the v-direction is similar, only it "wraps" the texture around a cylinder that is lying on its side. Wrapping in both the u- and v-directions is a little more complex. In this situation, you might envision the texture as a torus, or doughnut.

The most common practical application for texture wrapping is to perform environment mapping. Usually, an object textured with an environment map appears very reflective, showing a mirrored image of the object's surroundings in the scene. For the sake of this discussion, picture a room with four walls, each one painted with a letter R, G, B, Y and the corresponding colors: red, green, blue, and yellow. The environment map for such a simple room might look like:

Imagine that the room's ceiling is held up by a perfectly reflective, four sided, pillar. Mapping the environment map texture to the pillar is pretty simple—making it look as though it's reflecting the letters and colors as they appear on the walls isn't as easy. The following diagram shows a wire frame of the pillar with the applicable texture coordinates listed near the top vertices (the "seam" where wrapping will cross the edges of the texture is shown with a dotted line):

With wrapping enabled in the u- direction, the textured pillar shows the colors and symbols from the environment map appropriately and, at the "seam" in the front of the texture, the rasterizer properly chooses the shortest route between the texture coordinates, assuming that u- coordinates 0.0 and 1.0 share the same location. The textured pillar would look something like the following:

If texture wrapping wasn't enabled, the rasterizer would not interpolate in the direction needed to generate a believable, reflected, image. Rather, the area at the front of the pillar would contain a horizontally compressed version of the texels between u- coordinates 0.175 and 0.875, as they pass through the center of the texture. The effect would be ruined.


Using Texture Wrapping

[C++]

In a C++ application, the process of enabling texture wrapping differs across versions the Direct3D device interfaces. If your application uses the IDirect3DDevice7 interface, you enable texture wrapping for texture coordinate sets used by vertices, not for the texture stages themselves. In this case, call the IDirect3DDevice7::SetRenderState method to enable texture wrapping, passing one of the D3DRENDERSTATE_WRAP0 through D3DRENDERSTATE_WRAP7 enumerated values as the first parameter to identify which texture coordinate set will receive wrapping. Specify the D3DWRAPCOORD_0 thorugh D3DWRAPCOORD_3 flags in the second parameter to enable texture wrapping in the corresponding direction, or combine them to enable wrapping in multiple directions. If you omit a flag, texture wrapping in the corresponding direction is disabled. To disable texture wrapping for a particular set of texture coordinates, set the value for the corresponding render state to 0.

If your application uses the legacy IDirect3DDevice2 interface, you still enable texture wrapping by calling the SetRenderState method; however, these interface versions do not support D3DRENDERSTATE_WRAP0 through D3DRENDERSTATE_WRAP7. Instead, use the D3DRENDERSTATE_WRAPU or D3DRENDERSTATE_WRAPV value in the first parameter. Specify TRUE as in the second parameter to enable wrapping, or FALSE to disable it.

Note The IDirect3DDevice7 interface does recognize the legacy D3DRENDERSTATE_WRAPU and D3DRENDERSTATE_WRAPV render states, even though they were superseded by D3DRENDERSTATE_WRAP0 through D3DRENDERSTATE_WRAP7. These older render states, when passed to the IDirect3DDevice7 version of SetRenderState, affect u- and v-texture wrapping for the first set of texture coordinates.

[Visual Basic]

In Visual Basic, you enable texture wrapping for texture coordinate sets used by vertices. Call the Direct3DDevice7.SetRenderState method to enable texture wrapping, passing one of the D3DRENDERSTATE_WRAP0 through D3DRENDERSTATE_WRAP7 enumerated values as the first parameter to identify which texture coordinate set will receive wrapping. Use the D3DWRAPCOORD_0 through D3DWRAPCOORD_3 flags (from the CONST_D3D enumeration) in the second parameter to enable texture wrapping in the corresponding direction, or use combinations to enable wrapping in multiple directions. If you omit a flag, texture wrapping in the corresponding direction is disabled. To disable texture wrapping for a particular set of texture coordinates, set the value for the corresponding render state to 0.


Texture Blending

Direct3D can produce transparency effects by blending a texture with a primitive's color. It can also blend multiple textures onto a primitive. This section presents information on how texture blending is done. It is divided into the following topics:

  • Alpha Texture Blending
  • Multipass Texture Blending
  • Multiple Texture Blending
  • Light Mapping With Textures
[C++]

If you want your C++ application to use texture blending, the program should first check to see if the user's hardware supports it. The relevant information is found in the dwTextureCaps member of the D3DPRIMCAPS structure. For details on how to query the user's hardware for texture blending capabilities, see IDirect3DDevice7::GetCaps and D3DDEVICEDESC7.

[Visual Basic]

If you want your Visual Basic application to use texture blending, it should first check to see if the user's hardware supports it. The relevant information is found in the lTextureCaps member of the D3DPRIMCAPS type. For details on how to query the user's hardware for texture blending capabilities, see Direct3DDevice7.GetCaps and D3DDEVICEDESC7.


Alpha Texture Blending

When Direct3D renders a primitive, it generates a color for the primitive based on the primitive's material (or the colors of its vertices) and lighting information. For details, see Lighting and Materials. If an application enables texture blending, Direct3D must then blend the texel colors of one or more textures with the primitive's current colors. Direct3D uses the following formula to determine the final color for each pixel in the primitive's image.

In the preceding formula, FinalColor is the pixel color that is output to the target rendering surface. TexelColor stands for the color of the texel that corresponds to the current pixel. For details on how Direct3D maps pixels to texels, see Texture Filtering. SourceBlendFactor is a calculated value that Direct3D uses to determine the percentage of the texel color to apply to the final color. PixelColor is the color of the current pixel in the primitive's image. DestBlendFactor represents the percentage of the current pixel's color that will be used in the final color. The values of SourceBlendFactor and DestBlendFactor range from 0.0 or 1.0 inclusive.

As you can see from the preceding formula, a texture is not rendered as transparent at all if the SourceBlendFactor is 1.0 and the DestBlendFactor is 0.0. It is completely transparent if the SourceBlendFactor is 0.0 and the DestBlendFactor is 1.0. If an application sets these factors to any other values, the resulting texture will be blended with some degree of transparency.

Every texel in a texture has a red, a green, and a blue color value. By default, Direct3D uses the alpha values of texels as the SourceBlendFactor. Therefore, applications can control the transparency of textures by setting the alpha values in their textures.

[C++]

An application developed with C++ controls the blending factors with the D3DRENDERSTATE_SRCBLEND and D3DRENDERSTATE_DESTBLEND render states. Invoke the IDirect3DDevice7::SetRenderState method and pass either D3DRENDERSTATE_SRCBLEND or D3DRENDERSTATE_DESTBLEND as the value of the first parameter. The second parameter must be a member of the D3DBLEND enumerated type.

[Visual Basic]

A Visual Basic application can control the blending factors by using the D3DRENDERSTATE_SRCBLEND and D3DRENDERSTATE_DESTBLEND render states. Invoke the Direct3DDevice7.SetRenderState method and pass either render state value in the first parameter. The second parameter must be a member of the CONST_D3DBLEND enumeration.


Multipass Texture Blending

Direct3D applications can achieve numerous special effects by applying various textures onto a primitive over the course of multiple rendering passes. The common term for this is multipass texture blending. A typical use for multipass texture blending is to emulate the effects of complex lighting and shading models by applying multiple colors from several different textures. One such application is called light mapping. For more information, see Light Mapping With Textures.

Note Some devices are capable of applying multiple textures onto primitives in a single pass. For details, see Multiple Texture Blending.

If your user's hardware does not support multiple texture blending, your application can use multipass texture blending to achieve the same visual effects. However, it will not be able to sustain the frame rates that are possible when using multiple texture blending.

[C++]

To perform multipass texture blending in a C++ application

  1. Set a texture in texture stage 0 by calling the IDirect3DDevice7::SetTexture method.
  2. Select the desired color and alpha blending arguments and operations with the IDirect3DDevice7::SetTextureStageState method. (The default settings are well-suited for multi-pass texture blending.)
  3. Render the appropriate objects in the scene.
  4. Set the next texture in texture stage 0.
  5. Set the D3DRENDERSTATE_SRCBLEND and D3DRENDERSTATE_DESTBLEND render states to adjust the source and destination blending factors as needed. The system will blend the new textures with the existing pixels in the render-target surface according to these parameters.
  6. Repeat Steps 3, 4, and 5 with as many textures as needed.
[Visual Basic]

To perform multipass texture blending in a Visual Basic application

  1. Set a texture in texture stage 0 by calling the Direct3DDevice7.SetTexture method.
  2. Select the desired color and alpha blending arguments and operations with the Direct3DDevice7.SetTextureStageState method. (The default settings are well-suited for multi-pass texture blending.)
  3. Render the appropriate objects in the scene.
  4. Set the next texture in texture stage 0.
  5. Set the D3DRENDERSTATE_SRCBLEND and D3DRENDERSTATE_DESTBLEND render states to adjust the source and destination blending factors as needed. The system will blend the new textures with the existing pixels in the render-target surface according to these parameters.
  6. Repeat Steps 3, 4, and 5 with as many textures as needed.


Multiple Texture Blending

Direct3D can blend as many as eight textures onto primitives in a single pass. The use of multiple texture blending can profoundly increase the frame rate of Direct3D applications. Applications employ multiple texture blending to apply textures, shadows, specular lighting, diffuse lighting, and other special effects in a single pass.

To blend multiple textures, applications assign textures into the set of current textures, and then create blending stages. The topics in the following list present information on how these steps are accomplished:

  • Texture Stages and the Texture Blending Cascade
  • Texture Blending Operations and Arguments
  • Assigning the Current Textures
  • Creating Blending Stages


Texture Stages and the Texture Blending Cascade

Direct3D supports single-pass multiple texture blending through the use of "texture stages." A texture stage takes two arguments and performs a blending operation on them, passing the result on for further processing or for rasterization. You could visualize a texture stage as shown in the following figure.

As the preceding illustration shows, texture stages blend two arguments by using a specified operator. Common operations include simple modulation or addition of the color or alpha components of the arguments, but more than two dozen operations are currently supported. The arguments for a stage can be an associated texture, the iterated color or alpha (iterated during Gouraud shading), arbitrary color and alpha, or the result from the previous texture stage. For more information, see Texture Blending Operations and Arguments.

Note Direct3D distinguishes color blending from alpha blending. Applications set blending operations and arguments for color and alpha individually, and the results of those settings are independent of one another.

The combination of arguments and operations used by multiple blending stages define a simple flow-based blending language. The results from one stage flow down to another stage, and then from that stage to the next, and so on. The idea that results flow from stage to stage to eventually be rasterized on a polygon is often called the "texture blending cascade." The following illustration shows how individual texture stages make up the texture blending cascade.

Each stage in a device has a zero-based index. Direct3D currently allows up to eight blending stages, although you should always check device capabilities to determine how many stages the current hardware supports. The first blending stage is at index 0, the second is at 1, and so on up to index 7. The system blends stages in increasing order of index.

Use only the number of stages you need; the unused blending stages are disabled by default. So, if your application only uses the first two stages, it need only set operations and arguments for stage 0 and 1, leaving the remaining stages alone. The system blends the two stages, and ignores the disabled stages.

Optimization Note If your application varies the number of stages it uses for different situations—such as four stages for some objects, and only two for others—you don't need to explicitly disable all previously used stages. If you disable the color operation for the first unused stage, all stages with a higher index will not be applied. You can disable texture mapping altogether by setting the color operation for the first texture stage (stage 0).


Texture Blending Operations and Arguments

Applications associate a blending stage with each texture in the set of current textures. As mentioned in Texture Stages and the Texture Blending Cascade, Direct3D evaluates each blending stage in order, beginning with the first texture in the set and ending with the eighth.

[C++]

Direct3D applies the information from each texture in the set of current textures to the blending stage that is associated with it. Applications control what information from a given texture stage is used by calling IDirect3DDevice7::SetTextureStageState. You can set separate operations for the color and alpha channels independently, and each operation uses two arguments. Specify color channel operations by using the D3DTSS_COLOROP stage state, and D3DTSS_ALPHAOP for alpha operations–both use values from the D3DTEXTUREOP enumerated type.

Texture blending arguments use the D3DTSS_COLORARG1, D3DTSS_COLORARG2, D3DTSS_ALPHARG1, and D3DTSS_ALPHARG2 members of the D3DTEXTURESTAGESTATETYPE enumerated type. The corresponding argument values are identified using texture argument flags.

Note You can disable a texture stage—and any subsequent texture blending stages in the cascade—by setting the color operation for that stage to D3DTOP_DISABLE. Disabling the color operation effectively disables the alpha operation as well. Alpha operations cannot be disabled when color operations are enabled. Setting the alpha operation to D3DTOP_DISABLE when color blending is enabled causes undefined behavior.

[Visual Basic]

Direct3D applies the information from each texture in the set of current textures to the blending stage that is associated with it. Applications control what information from a given texture stage is used by calling Direct3DDevice7.SetTextureStageState. You can set separate operations for the color and alpha channels independently, and each operation uses two arguments. Specify color channel operations by using the D3DTSS_COLOROP stage state, and D3DTSS_ALPHAOP for alpha operations–both use values from the CONST_D3DTEXTUREOP enumeration.

Texture blending arguments use the D3DTSS_COLORARG1, D3DTSS_COLORARG2, D3DTSS_ALPHARG1, and D3DTSS_ALPHARG2 members of the CONST_D3DTEXTURESTAGESTATETYPE enumeration. The corresponding argument values are identified using texture argument flags.

Note You can disable a texture stage—and any subsequent texture blending stages in the cascade—by setting the color operation for that stage to D3DTOP_DISABLE. Disabling the color operation effectively disables the alpha operation as well. Alpha operations cannot be disabled when color operations are enabled. Setting the alpha operation to D3DTOP_DISABLE when color blending is enabled causes undefined behavior.


Assigning the Current Textures

Direct3D maintains a list of up to eight current textures. It blends these textures onto all of the primitive it renders. Only textures created as texture interface pointers can be used in the set of current textures.

[C++]

Applications call the IDirect3DDevice7::SetTexture method to assign textures into the set of current textures. The first parameter must be from the a number in the range of 0-7 inclusive. Pass the texture interface pointer as the second parameter.

The following C++ code fragment demonstrates how a texture can be assigned into the set of current textures:

// This code fragment assumes that the variable lpd3dDev is a valid
// pointer to an IDirect3DDevice7 interface and lpd3dTexture is a valid
// pointer to an IDirectDrawSurface7 interface.

// Set the third texture.
lpd3dDev->SetTexture(2, lpd3dTexture);
[Visual Basic]

Applications written in Visual Basic call Direct3DDevice7.SetTexture to assign textures into the set of current textures. The first parameter must be from the a number in the range of 0-7 inclusive. Pass the texture interface pointer as the second parameter.

This Visual Basic code fragment demonstrates how a texture can be assigned into the set of current textures:

' This code fragment assumes that the variable d3dDev is a valid
' reference to a Direct3DDevice7 object and d3dTexture is a valid
' reference to a DirectDrawSurface7 object.

' Set the third texture.
Call d3dDev.SetTexture(2, d3dTexture)

Note Software devices do not support assigning a texture to more than one texture stage at a time.


Creating Blending Stages

[C++]

A blending stage is a set of texture operations, together with their arguments, that define how textures are blended. When making a blending stage, C++ applications invoke the IDirect3DDevice7::SetTextureStageState method. The first call specifies the operation that will be performed. Two additional invocations define the arguments to which the operation will be applied. The following code fragment illustrates the creation of a blending stage:

// This example assumes that lpD3DDev is a valid pointer to an
// IDirect3DDevice7 interface.

// Set the operation for the 1st texture.
lpD3DDev->SetTextureStageState(0,D3DTSS_COLOROP,D3DTOP_ADD);

// Set arg1 for the texture operation.
lpD3DDev->SetTextureStageState(0, // First texture
       D3DTSS_COLORARG1,  // Set color arg 1
       D3DTA_TEXTURE);    // Color arg 1 value

// Set arg2 for the texture operation.
lpD3DDev->SetTextureStageState(0, // First texture
       D3DTSS_COLORARG2,  // Set color arg 2
       D3DTA_DIFFUSE);    // Color arg 2 value

Texel data in textures contain color and alpha values. Programs can define separate operations for both color and alpha values in a single blending stage. Each operation (color and alpha) has its own arguments. For details, see D3DTEXTURESTAGESTATETYPE.

Although not part of the Direct3D API, the following macros can also be inserted into your program to abbreviate the code required for creating texture blending stage.

#define SetTextureColorStage( dev, i, arg1, op, arg2 )       \
   dev->SetTextureStageState( i, D3DTSS_COLOROP, op);\
   dev->SetTextureStageState( i, D3DTSS_COLORARG1, arg1 );   \
   dev->SetTextureStageState( i, D3DTSS_COLORARG2, arg2 );

#define SetTextureAlphaStage( dev, i, arg1, op, arg2 )       \
   dev->SetTextureStageState( i, D3DTSS_ALPHAOP, op);\
   dev->SetTextureStageState( i, D3DTSS_ALPHARG1, arg1 );    \
   dev->SetTextureStageState( i  D3DTSS_ALPHARG2, arg2 );
[Visual Basic]

A blending stage is a set of texture operations, together with their arguments, that define how textures are blended. When making a blending stage, Visual Basic applications invoke the Direct3DDevice7.SetTextureStageState method. The first call specifies the operation that will be performed. Two additional invocations define the arguments to which the operation will be applied. The following code fragment illustrates the creation of a blending stage:

' This example assumes that d3dDev is a valid reference to a
' Direct3DDevice7 object.

' Set the color operation for the 1st texture.
Call d3dDev.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_ADD)

' Set arg1 to the texture color.
Call d3dDev.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE)

' Set arg2 to the iterated diffuse color.
Call d3dDev.SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE)

Texel data in textures contain color and alpha values. Programs can define separate operations for both color and alpha values in a single blending stage. Each operation (color and alpha) has its own arguments. For details, see CONST_D3DTEXTURESTAGESTATETYPE.


Light Mapping With Textures

For an application to realistically render a 3-D scene, it must take into account the effect that light sources have on the appearance of the scene. Although techniques such as flat and Gouraud shading are valuable tools in this respect, they can be insufficient for your needs. Direct3D supports multipass and multiple texture blending. These capabilities enable your application to render scenes whose appearance is much more realistic than scenes rendered with shading techniques alone. By applying one or more light maps, your application can map areas of light and shadow onto its primitives.

A light map is a texture or group of textures that contain information about lighting in a 3-D scene. You can store the lighting information in the alpha values of the light map, in the color values, or in both.

If you implement light mapping using multipass texture blending, your program should render the light map onto its primitives on the first pass. It should use a second pass to render the base texture. The exception to this is specular light mapping. In that case, render the base texture first, then add the light map.

Multiple texture blending enables your application to render both the light map and the base texture in one pass. If your user's hardware provides for multiple texture blending, your application should take advantage of it when performing light mapping. It will significantly improve your application's performance.

Using light maps, a Direct3D application can achieve a variety of lighting effects when it renders primitives. It can map not only monochrome and colored lights in a scene, it can add details such as specular highlights and diffuse lighting.

Information on using Direct3D texture blending to perform light mapping is presented in the following topics:

  • Monochrome Light Maps
  • Color Light Maps
  • Specular Light Maps
  • Diffuse Light Maps


Monochrome Light Maps

Some older 3-D accelerator boards do not support texture blending using the alpha value of the destination pixel (see Alpha Texture Blending). These adapters also generally do not support multiple texture blending. If your application is running on an adapter such as this, it can use multipass texture blending to perform monochrome light mapping.

To perform monochrome light mapping, an application stores the lighting information in the alpha data of its light map textures. The program uses the texture filtering capabilities of Direct3D to perform a mapping from each pixel in the primitive's image to a corresponding texel in the light map. It sets the source blending factor to the alpha value of the corresponding texel.

[C++]

The following C++ code fragment illustrates how an application can use a texture as a monochrome light map:

// This example assumes that lpD3DDev is a valid pointer to an
// IDirect3DDevice7 interface and that lptexLightMap is a valid
// pointer to a texture that contains monochrome light map data.

// Set the light map texture as the current texture.
lpD3DDev->SetTexture(0,lptexLightMap);

// Set the color operation.
lpD3DDev->SetTextureStageState(0,D3DTSS_COLOROP,
       D3DTOP_SELECTARG1);

// Set argument 1 to the color operation.
lpD3DDev->SetTextureStageState(0,D3DTSS_COLORARG1,
       D3DTA_TEXTURE | D3DTA_ALPHAREPLICATE);
[Visual Basic]

The following Visual Basic code fragment illustrates how an application can use a texture as a monochrome light map:

' This example assumes that d3dDev is a valid reference to a
' Direct3DDevice7 object and that texLightMap is a valid reference
' to a DirectDrawSurface7 texture that contains monochrome light map data.

' Set the light map texture as the current texture.
Call d3dDev.SetTexture(0, texLightMap)

' Set the color operation.
Call d3dDev.SetTextureStageState(0, D3DTSS_COLOROP, _
 D3DTOP_SELECTARG1)

' Set argument 1 to the color operation.
Call d3dDev.SetTextureStageState(0, D3DTSS_COLORARG1, _
 D3DTA_TEXTURE Or D3DTA_ALPHAREPLICATE)

Since display adapters that do not support destination alpha blending usually do not support multiple texture blending, this example sets the light map as the first texture, which is available on all 3-D accelerator cards. The sample code sets the color operation for the texture's blending stage to blend the texture data with the primitive's existing color. It then selects the first texture and the primitive's existing color as the input data.


Color Light Maps

Your application will usually render 3-D scenes more realistically if it uses colored light maps. A colored light map uses the RGB data in the light map for its lighting information.

[C++]

The following C++ code fragment demonstrates light mapping with RGB color data:

// This example assumes that lpD3DDev is a valid pointer to an
// IDirect3DDevice7 interface and that lptexLightMap is a valid
// pointer to a texture that contains RGB light map data.

// Set the light map texture as the 1st texture.
lpD3DDev->SetTexture(0, lptexLightMap);

lpD3DDev->SetTextureStageState(0,D3DTSS_COLOROP,
       D3DTOP_MODULATE);

lpD3DDev->SetTextureStageState(0,D3DTSS_COLORARG1,
       D3DTA_TEXTURE);

lpD3DDev->SetTextureStageState(0,D3DTSS_COLORARG2,
       D3DTA_DIFFUSE);

This sample sets the light map as the first texture. It then sets the state of the first blending stage to modulate the incoming texture data. It uses the first texture and the current color of the primitive as the arguments to the modulate operation.

[Visual Basic]

The following Visual Basic code demonstrates light mapping with RGB color data:

' This example assumes that D3DDev is a valid reference to a
' Direct3DDevice7 object and that texLightMap is a valid reference
' to a DirectDrawSurface7 texture surface that contains RGB light map data.

' Set the light map texture as the 1st texture.
Call d3dDev.SetTexture(0, texLightMap)

Call d3dDev.SetTextureStageState(0, D3DTSS_COLOROP, _
 D3DTOP_MODULATE)

Call d3dDev.SetTextureStageState(0, D3DTSS_COLORARG1, _
 D3DTA_TEXTURE)

Call d3dDev.SetTextureStageState(0, D3DTSS_COLORARG2, _
 D3DTA_DIFFUSE)

This sample sets the light map as the first texture. It then sets the state of the first blending stage to modulate the incoming texture data. It uses the first texture and the current color of the primitive as the arguments to the modulate operation.


Specular Light Maps

When illuminated by a light source, "shiny" objects (those that use highly reflective materials) will receive specular highlights. In some cases, the specular highlights produced by the lighting module will not be accurate. To produce a more appealing highlight, many Direct3D applications apply specular light maps to primitives.

To perform specular light mapping, first modulate the specular light map with the primitive's existing texture. Then add the monochrome or RGB light map.

[C++]

The following code fragment illustrates this process in C++:

// This example assumes that lpD3DDev is a valid pointer to an
// IDirect3DDevice7 interface.
// lptexBaseTexture is a valid pointer to a texture.
// lptexSpecLightMap is a valid pointer to a texture that contains RGB
// specular light map data.
// lptexLightMap is a valid pointer to a texture that contains RGB
// light map data.

// Set the base texture.
lpD3DDev->SetTexture(0,lptexBaseTexture );

// Set the base texture operation and args
lpD3DDev->SetTextureStageState(0,D3DTSS_COLOROP,
       D3DTOP_MODULATE );
lpD3DDev->SetTextureStageState(0,D3DTSS_COLORARG1, D3DTA_TEXTURE );
lpD3DDev->SetTextureStageState(0,D3DTSS_COLORARG2, D3DTA_DIFFUSE );

// Set the specular light map.
lpD3DDev->SetTexture(1,lptexSpecLightMap );

// Set the specular light map operation and args
lpD3DDev->SetTextureStageState(1,D3DTSS_COLOROP,
       D3DTOP_ADD );
lpD3DDev->SetTextureStageState(1,D3DTSS_COLORARG1, D3DTA_TEXTURE );
lpD3DDev->SetTextureStageState(1,D3DTSS_COLORARG2, D3DTA_CURRENT );

// Set the RGB light map.
lpD3DDev->SetTexture(2,lptexLightMap);

// Set the RGB light map operation and args
lpD3DDev->SetTextureStageState(2,D3DTSS_COLOROP, D3DTOP_MODULATE);
lpD3DDev->SetTextureStageState(2,D3DTSS_COLORARG1, D3DTA_TEXTURE );
lpD3DDev->SetTextureStageState(2,D3DTSS_COLORARG2, D3DTA_CURRENT );
[Visual Basic]

The following Visual Basic code fragment illustrates this process:

' This example assumes that d3dDev is a valid reference to an
' Direct3DDevice7 object.
' texBaseTexture is a valid reference to a texture.
' texSpecLightMap is a valid reference to a texture that contains RGB
' specular light map data.
' texLightMap is a valid reference to a texture that contains RGB
' light map data.

' Set the base texture.
Call d3dDev.SetTexture(0, texBaseTexture)

' Set the base texture operation and args
Call d3dDev.SetTextureStageState(0, D3DTSS_COLOROP, _
 D3DTOP_MODULATE)
Call d3dDev.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE)
Call d3dDev.SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE)

' Set the specular light map.
Call d3dDev.SetTexture(1, texSpecLightMap)

' Set the specular light map operation and args
Call d3dDev.SetTextureStageState(1, D3DTSS_COLOROP, _
 D3DTOP_ADD)
Call d3dDev.SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_TEXTURE)
Call d3dDev.SetTextureStageState(1, D3DTSS_COLORARG2, D3DTA_CURRENT)

' Set the RGB light map.
Call d3dDev.SetTexture(2, texLightMap)

' Set the RGB light map operation and args
Call d3dDev.SetTextureStageState(2, D3DTSS_COLOROP, D3DTOP_MODULATE)
Call d3dDev.SetTextureStageState(2, D3DTSS_COLORARG1, D3DTA_TEXTURE)
Call d3dDev.SetTextureStageState(2, D3DTSS_COLORARG2, D3DTA_CURRENT)


Diffuse Light Maps

When illuminated by a light source, matte surfaces display diffuse light reflection. The brightness of diffuse light depends on the distance from the light source and the angle between the surface normal and the light source direction vector. The diffuse lighting effects simulated by lighting calculations produce only general effects.

[C++]

Your application can simulate more complex diffuse lighting with texture light maps. Do this by adding the diffuse light map to the base texture, as shown in the following C++ code fragment:

// This example assumes that lpD3DDev is a valid pointer to an
// IDirect3DDevice7 interface.
// lptexBaseTexture is a valid pointer to a texture.
// lptexDiffuseLightMap is a valid pointer to a texture that contains
// RGB diffuse light map data.

// Set the base texture.
lpD3DDev->SetTexture(0,lptexBaseTexture );

// Set the base texture operation and args
lpD3DDev->SetTextureStageState(0,D3DTSS_COLOROP,
       D3DTOP_MODULATE );
lpD3DDev->SetTextureStageState(0,D3DTSS_COLORARG1, D3DTA_TEXTURE );
lpD3DDev->SetTextureStageState(0,D3DTSS_COLORARG2, D3DTA_DIFFUSE );

// Set the diffuse light map.
lpD3DDev->SetTexture(1,lptexDiffuseLightMap );

// Set the blend stage.
lpD3DDev->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_MODULATE );
lpD3DDev->SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_TEXTURE );
lpD3DDev->SetTextureStageState(1, D3DTSS_COLORARG2, D3DTA_CURRENT );
[Visual Basic]

Your application can simulate more complex diffuse lighting with texture light maps. Do this by adding the diffuse light map to the base texture, as shown in the following code Visual Basic fragment:

' This example assumes that d3dDev is a valid reference to
' a Direct3DDevice7 object.
' texBaseTexture is a valid reference to a texture.
' texDiffuseLightMap is a valid reference to a texture that contains
' RGB diffuse light map data.

' Set the base texture.
Call d3dDev.SetTexture(0, texBaseTexture)

' Set the base texture operation and args
Call d3dDev.SetTextureStageState(0, D3DTSS_COLOROP, _
 D3DTOP_MODULATE)
Call d3dDev.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE)
Call d3dDev.SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE)

' Set the diffuse light map.
Call d3dDev.SetTexture(1, texDiffuseLightMap)

' Set the blend stage.
Call d3dDev.SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_MODULATE)
Call d3dDev.SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_TEXTURE)
Call d3dDev.SetTextureStageState(1, D3DTSS_COLORARG2, D3DTA_CURRENT)


Texture Compression

DirectDraw provides services to compress surfaces that will be used for texturing 3-D models. For information on creating and manipulating the data in a compressed texture surface, see Compressed Texture Surfaces in the DirectDraw documentation.

[C++]

Once your application creates a rendering device, it can determine if the device supports texturing from compressed texture surfaces by calling the IDirect3DDevice7::EnumTextureFormats method. The method calls the D3DEnumPixelFormatsCallback callback function that you provide for each pixel format that the device supports for texture maps. If any of the enumerated pixel formats use the DXT1, DXT2, DXT3, DXT4, or DXT5 four character codes (FOURCCs), the device can texture directly from a compressed texture surface that uses that format. If so, you can use compressed texture surfaces directly with Direct3D by calling the IDirect3DDevice7::SetTexture method. If the device doesn't support texturing from compressed texture surfaces, you can still store texture data in a compressed format surface, but you must convert any compressed textures to a supported format before they can be used for texturing. The DirectDraw blit methods, IDirectDrawSurface7::Blt and IDirectDrawSurface7::BltFast, automatically perform conversion of compressed formats to standard RGBA formats. To minimize loss of information, try to pick a destination pixel format that closely matches the compressed format. For instance, ARGB:1555 would be a good destination format for DXT1, but ARGB:4444 would be a better choice for DXT3 since DXT3 contains four bits of alpha information.

[Visual Basic]

Once your application creates a rendering device, it can determine if the device supports texturing from compressed texture surfaces by calling the Direct3DDevice7.GetTextureFormatsEnum method. The method returns a reference to a Direct3DEnumPixelFormats class object, which exposes methods to retrieve information about the supported texture surface pixel formats. The Direct3DEnumPixelFormats.GetItem method fills a DDPIXELFORMAT type to describe a supported texture format. If any of the enumerated pixel formats use the DXT1, DXT2, DXT3, DXT4, or DXT5 four character codes (FOURCCs), the device can texture directly from a compressed texture surface that uses that format. If so, you can use compressed texture surfaces directly with Direct3D by calling the Direct3DDevice7.SetTexture method. If the device doesn't support texturing from compressed texture surfaces, you can still store texture data in a compressed format surface, but you must convert any compressed textures to a supported format before they can be used for texturing. The DirectDraw blit methods, DirectDrawSurface7.Blt and DirectDrawSurface7.BltFast, automatically perform conversion of compressed formats to standard RGBA formats. To minimize loss of information, try to pick a destination pixel format that closely matches the compressed format. For instance, ARGB:1555 would be a good destination format for DXT1, but ARGB:4444 would be a better choice for DXT3 since DXT3 contains four bits of alpha information.


Automatic Texture Management

Texture management, in short, is the process of determining which textures are needed for rendering at a given time, and ensuring that those textures are loaded into video memory. Like any algorithm, texture management schemes vary in complexity, but any approach to texture management involves the following key tasks:

  • Tracking the amount of available texture memory.
  • Calculating which textures are currently needed for rendering, and which aren't.
  • Determining which of the existing texture surfaces can be reloaded with another texture image, and which surfaces should be destroyed and replaced with new texture surfaces.

Historically, Direct3D applications were responsible for managing textures on their own. Direct3D Immediate Mode for DirectX 6.0 introduced system-supported texture management, where Direct3D efficiently and intelligently performs texture management, ensuring that textures are loaded for optimal performance. (Texture surfaces that Direct3D manages are casually referred to as "managed textures.")

The texture manager uses a least-recently-used (LRU) algorithm to determine which textures should be evicted, which tracks textures with a time-stamp that identifies when the texture was last used. Texture priorities are used as "tie breakers" when two textures are targeted for removal from memory. If two textures have the same priority value, the least recently used texture will be removed in favor of the other texture. However, if two textures have the same time-stamp, the texture that has a lower priority will be evicted first.

[C++]

You request automatic texture management for textures surfaces when you create them. To get a managed texture in a C++ application, simply create a texture surface that also includes the DDSCAPS2_TEXTUREMANAGE or DDSCAPS2_D3DTEXTUREMANAGE flags in the dwCaps2 member of the associated DDSCAPS2 structure. Note that you are not allowed to specify where you want the texture created–you can't use the DDSCAPS_SYSTEMMEMORY or DDSCAPS_VIDEOMEMORY flags when creating a managed texture. After creating the managed texture, you can call the IDirect3DDevice7::SetTexture method to set it to a stage in the rendering device's texture cascade.

You can assign a priority to managed textures by calling the IDirectDrawSurface7::SetPriority method for the texture surface.

[Visual Basic]

You request automatic texture management for textures surfaces when you create them. To get a managed texture from Visual Basic, create a texture surface that also includes the DDSCAPS2_TEXTUREMANAGE or DDSCAPS2_D3DTEXTUREMANAGE flags in the lCaps2 member of the associated DDSCAPS2 type. Note that you are not allowed to specify where you want the texture created–you can't use the DDSCAPS_SYSTEMMEMORY or DDSCAPS_VIDEOMEMORY flags when creating a managed texture. After creating the managed texture, you can call the Direct3DDevice7.SetTexture method to set it to a stage in the rendering device's texture cascade.

You can assign a priority to managed textures by calling the DirectDrawSurface7.SetPriority method for the texture surface.

Direct3D automatically downloads textures into video memory as needed. (The system might cache managed textures in local or non-local video memory, depending on the availability of non-local video memory or other factors. Where your managed textures are cached is not communicated to your application, nor is this knowledge required to take advantage of automatic texture management.) If your application uses more textures than can fit in video memory, Direct3D will evict older textures from video memory to make room for the new textures. If you use an evicted texture again, the system uses the original system memory texture surface to reload the texture in the video memory cache. Reloading the texture is a minor, but obviously necessary, performance hit to the application.

You can dynamically modify the original system memory copy of the texture by blitting or locking the texture surface. When the system detects a "dirty" surface—after a blit is completed, or when the surface is unlocked—the texture manager automatically updates the video memory copy of the texture. The performance hit incurred is similar to reloading an evicted texture.

[C++]

When entering a new level in a game, your application may need to flush all managed textures from video memory. You can explicitly request that all managed textures be evicted by calling the IDirect3D7::EvictManagedTextures method. When you call this method, Direct3D destroys any cached local and non-local video memory textures, but leaves the original system memory copies untouched.

[Visual Basic]

When entering a new level in a game, your application may need to flush all managed textures from video memory. You can explicitly request that all managed textures be evicted by calling the Direct3D7.EvictManagedTextures method. When you call this method, Direct3D destroys any cached local and non-local video memory textures, but leaves the original system memory copies untouched.


Hardware Considerations for Texturing

Current hardware does not necessarily implement all of the functionality that the Direct3D interface enables. Your program must test user's hardware and adjust its rendering strategies accordingly.

Many 3-D accelerator cards do not support diffuse iterated values as arguments to blending units. However, your program can introduce iterated color data when it performs texture blending.

Some 3-D hardware may not have a blending stage associated with the first texture. On these adapters, your application will need to perform blending in the second and third texture stages in the set of current textures.

[C++]

Due to limitations in much of today's hardware, few display adapters can perform trilinear mipmap interpolation through the multiple texture blending interface offered by IDirect3DDevice7. Specifically, there is little support for setting the D3DTSS_MIPFILTER texture stage state to D3DTFP_LINEAR. Your application can use multipass texture blending to achieve the same effects, or degrade to the D3DTFP_POINT mipmap filter mode, which is widely supported.

[Visual Basic]

Due to limitations in much of today's hardware, few display adapters can perform trilinear mipmap interpolation through the multiple texture blending interface offered by the Direct3DDevice7 Visual Basic class. Specifically, there is little support for setting the D3DTSS_MIPFILTER texture stage state to D3DTFP_LINEAR. Your application can use multipass texture blending to achieve the same effects, or degrade to the D3DTFP_POINT mipmap filter mode, which is widely supported.


Depth Buffers

This section presents information on using depth buffers for hidden line and hidden surface removal. It is organized into the following topics:

  • What Are Depth Buffers?
  • Using Depth Buffers
[C++]

The Direct3D Immediate Mode C++ tutorials provide additional information about using depth buffers. See Tutorial 2: Adding a Depth Buffer (C++) for details.

[Visual Basic]

The Direct3D Immediate Mode Visual Basic tutorials provide additional information about using depth buffers. See Tutorial 2: Adding a Depth Buffer (Visual Basic) for details.


What Are Depth Buffers?

A depth buffer, often called a z-buffer or a w-buffer, is a DirectDraw surface that stores depth information to be used by Direct3D. When Direct3D renders a 3-D scene to a target surface, it can use the memory in an attached depth buffer surface as a workspace to determine how the pixels of rasterized polygons occlude one another. Direct3D uses an off-screen DirectDraw surface as the target to which final color values are written. The depth buffer surface that is attached to the render-target surface is used to store depth information which tells Direct3D how "deep" each visible pixel is in the scene.

When a 3-D scene is rasterized with depth buffering enabled, each point on the rendering surface is tested. The values in the depth buffer can be a point's z-coordinate or its homogeneous w-coordinate—from the point's (x,y,z,w) location in projection space. A depth buffer that uses z values is often called a "z-buffer," and one that uses w values called a "w-buffer." Each type of depth buffer has its advantages and disadvantages, which are discussed later.

At the beginning of the test, the depth value in the depth buffer is set to the largest possible value for the scene. The color value on the rendering surface is set to either the background color value, or the color value of the background texture at that point. Each polygon in the scene is tested to see if it intersects with the current coordinate (x,y) on the rendering surface. If it does, the depth value (which will be the z coordinate in a z-buffer, and the w coordinate in a w-buffer) at the current point is tested to see if it is smaller than the depth value already stored in the depth buffer. If the depth of the polygon value is smaller, it is stored in the depth buffer and the color value from the polygon is written to the current point on the rendering surface. If the depth value of the polygon at that point is larger, the next polygon in the list is tested. This process is shown in the following illustration.

[C++]

Note Although most applications don't use this feature, you can change the comparison Direct3D uses to determine which values will be placed in the depth buffer and subsequently the render-target surface. To do so, change the value for the D3DRENDERSTATE_ZFUNC render state.

[Visual Basic]

Note Although most applications don't use this feature, you can change the comparison Direct3D uses to determine which values will be placed in the depth buffer and subsequently the render-target surface. To do so, change the value for the D3DRENDERSTATE_ZFUNC render state.

Nearly all 3-D accelerators on the market support z-buffering, making z-buffers the most common type of depth buffer today. However ubiquitous, z-buffers do have their drawbacks. Due to the mathematics involved, the generated z values in a z-buffer tend not to be distributed evenly across the z-buffer range (typically 0.0 to 1.0, inclusive). Specifically, the ratio between the far and near clipping planes strongly affects how unevenly z values are distributed. Using a far-plane distance to near-plane distance ratio of 100, 90% of the depth buffer range is spent on the first 10% of the scene depth range. Typical applications for entertainment or visual simulations with exterior scenes often require far plane/near plane ratios of anywhere between 1000 to 10000. At a ratio of 1000, 98% of the range is spent on the 1st 2% of the depth range, and the distribution gets worse with higher ratios. This can cause hidden surface artifacts in distant objects, especially when using 16-bit depth buffers (the most commonly supported bit-depth).

A w-based depth buffer, on the other hand, is often more evenly distributed between the near and far clip planes than z-buffer. The key benefit is that the ratio of distances for the far and near clipping planes is no longer an issue. This allows applications to support large maximum ranges, while still getting relatively accurate depth buffering close to the eye point. A w-based depth buffer isn't perfect, and can sometimes exhibit hidden surface artifacts for near objects. Another drawback to the w-buffered approach is related to hardware support: w-buffering isn't supported as widely in hardware as z-buffering.

[C++]

The DirectDraw HEL can create depth buffers for use by Direct3D or other 3-D–rendering software. The HEL supports 16-bit depth buffers. The DirectDraw device driver for a 3-D accelerator can permit the creation of depth buffers in display memory by exposing the DDSCAPS_ZBUFFER flag. You can query for the supported depth buffer bit-depths by calling the IDirect3D7::EnumZBufferFormats method.

Whenever a z-buffer surface is created, your application should maintain a pointer to the z-buffer until it shuts the Direct3D system down. Your program should release the z-buffer surface just before it releases the rendering surface.

[Visual Basic]

The DirectDraw HEL can create depth buffers for use by Direct3D or other 3-D–rendering software. The HEL supports 16-bit depth buffers. The DirectDraw device driver for a 3-D accelerator can permit the creation of depth buffers in display memory by exposing the DDSCAPS_ZBUFFER flag. You can query for the supported depth buffer bit-depths by using the Direct3D7.GetEnumZBufferFormats method. The GetEnumZBufferFormats method returns a reference to a Direct3DEnumPixelFormats class object that contains the supported pixel formats for depth buffers.

Z-buffering requires overhead during rendering. Various techniques can be used to optimized rendering when using z-buffers. For details, see Z-Buffer Performance.

Note The actual interpretation of a depth value is specific to the 3-D renderer.


Using Depth Buffers

The following topics discuss common usage scenarios for depth buffers:

  • Querying for Depth Buffer Support
  • Creating a Depth Buffer
  • Enabling Depth Buffering
  • Clearing Depth Buffers
  • Changing Depth Buffer Write Access
  • Changing Depth Buffer Comparison Functions
  • Using Z-Bias

See Also

What Are Depth Buffers?, Tutorial 2: Adding a Depth Buffer (C++), Tutorial 2: Adding a Depth Buffer (Visual Basic)


Querying for Depth Buffer Support

As with any feature, don't assume that the driver your application uses supports depth buffering; you should always check the driver's capabilities. Although most drivers support z-based depth buffering, not all will be able to provide support to w-based depth buffering. (For general information about depth buffering, see What Are Depth Buffers?) Drivers don't fail if you attempt to enable an unsupported scheme, falling back on another depth buffering method instead, or sometimes disabling depth buffering altogether, which can result in scenes rendered with extreme depth-sorting artifacts.

You can check for general support for depth buffers by querying the DirectDraw for the display device your application uses before you create a Direct3D device. If the DirectDraw object reports that it supports depth buffering, any hardware devices you create from this DirectDraw object will support z-buffering (but you don't yet know if the driver supports w-buffering).

[C++]

To query for general depth buffering support from C++

  1. Call the IDirectDraw7::GetCaps method of the DirectDraw object for the display device your application uses, passing initialized DDCAPS structures as parameters. After the call, the DDCAPS structures contain information about hardware and emulation capabilities of DirectDraw.
  2. Examine the ddsCaps member of the structure you passed as the first parameter. If this member–a DDSCAPS2 structure–includes the DDSCAPS_ZBUFFER flag, the driver supports depth buffering through z-buffers.
[Visual Basic]

To query for general depth buffering support in Visual Basic

  1. Call the DirectDraw7.GetCaps method of the DirectDraw object for the display device your application uses, passing variables of type DDCAPS as parameters. After the call, the DDCAPS variables contain information about hardware and emulation capabilities of DirectDraw.
  2. Examine the ddsCaps member of the variable you passed as the first parameter. If this member–a DDSCAPS2 type–includes the DDSCAPS_ZBUFFER flag, the driver supports depth buffering through z-buffers.

Once you know that the driver supports z-buffers, you can verify w-buffer support. Although z-buffers are supported for all software rasterizers, w-buffers are only supported by the reference rasterizer, which is hardly suited for use by real-world applications. No matter what type of device your application uses, you should verify support for w-buffers before you attempt to enable w-based depth buffering.

[C++]

To determine support for w-buffers in a C++ application

  1. After creating your device (HAL or emulated), call the IDirect3DDevice7::GetCaps method, passing an initialized D3DDEVICEDESC7 structure.
  2. After the call, the dpcTriCaps and dpcLineCaps members (D3DPRIMCAPS structures) contain information about the driver's support for rendering primitives.
  3. If the dwRasterCaps member of these structures contains the D3DPRASTERCAPS_WBUFFER flag, then the driver supports w-based depth buffering for that primitive type.
[Visual Basic]

To determine support for w-buffers in Visual Basic

  1. After creating your device (HAL or emulated), call the Direct3DDevice7.GetCaps method, passing a variable of type D3DDEVICEDESC7 type as a parameter.
  2. After the call, the dpcTriCaps and dpcLineCaps members (D3DPRIMCAPS types) each contain information about the driver's support for rendering primitives.
  3. If the lRasterCaps members of dpcTriCaps and dpcLineCaps contain the D3DPRASTERCAPS_WBUFFER flag, the driver supports w-based depth buffering for that primitive type.


Creating a Depth Buffer

You usually create a depth buffer during your application's startup sequence, before creating a Direct3D device object for rendering. Use the following steps to create and attach a depth buffer surface to the render-target surface:

[C++]

To create a depth buffer in a C++ application

  1. Call the IDirect3D7::EnumZBufferFormats method to determine the depth-buffer pixel formats that the device supports.
  2. Prepare a DDSURFACEDESC2 structure that describes a DirectDraw surface that matches the render-target surface's dimensions, includes the DDSCAPS_ZBUFFER capability flag, and uses a supported depth-buffer pixel format (retrieved in Step 1).
  3. Create the surface in video memory or system memory, depending on what type of rendering device your application will use. (See note.)
  4. Attach the depth buffer surface to the rendering surface using the IDirectDrawSurface7::AddAttachedSurface method.

After creating the depth buffer surface and attaching it to the render-target surface, call the IDirect3D7::CreateDevice method to create a rendering device that uses the render-target surface and its depth buffer.

Create the depth buffer in video memory—with the DDSCAPS_VIDEOMEMORY surface capability—when your application uses a hardware driver (HAL device), and in system memory—the DDSCAPS_SYSTEMMEMORY surface capability—when using software emulation drivers (the MMX or RGB devices). Failing to create a depth buffer in the appropriate type of memory will cause the CreateDevice method to fail.

Note Some popular hardware devices require that the render target and depth buffer surfaces use the same bit depth. On such hardware, if your application uses a 16-bit render-target surface, the attached depth buffer must also be 16-bits. For a 32-bit render-target surface, the depth buffer must be 32-bits, of which 8-bits can be used for stencil buffering (if needed).

If the hardware upon which your application is running has this requirement, and your application fails to meet it, any attempts to create a rendering device that uses the non-compliant surfaces will fail. You can use the DirectDraw method, IDirectDraw7::GetDeviceIdentifier to track hardware that imposes this limitation.

[Visual Basic]

To create a depth buffer in a Visual Basic application

  1. Call the Direct3D7.GetEnumZBufferFormats method to retrieve a reference to a Direct3DEnumPixelFormats object that can enumerate the supported depth-buffer formats. Query the enumeration object for the depth-buffer pixel formats that the device supports.
  2. Prepare a DDSURFACEDESC2 type that describes a DirectDraw surface that matches the render-target surface's dimensions, includes the DDSCAPS_ZBUFFER capability flag, and uses a supported depth-buffer pixel format (retrieved in Step 2).
  3. Create the surface in video memory or system memory, depending on what type of rendering device your application will use. (See note.)
  4. Attach the depth buffer surface to the rendering surface using the DirectDrawSurface7.AddAttachedSurface method.

After creating the depth buffer surface and attaching it to the render-target surface, call Direct3D7.CreateDevice to create a rendering device that uses the render-target surface and its depth buffer.

Create the depth buffer in video memory—with the DDSCAPS_VIDEOMEMORY surface capability—when your application uses a hardware driver (HAL device), and in system memory—the DDSCAPS_SYSTEMMEMORY surface capability—when using software emulation drivers (the MMX or RGB devices). Failing to create a depth buffer in the appropriate type of memory will cause the CreateDevice method to fail.

Note Some popular hardware devices require that the render target and depth buffer surfaces use the same bit depth. On such hardware, if your application uses a 16-bit render-target surface, the attached depth buffer must also be 16-bits. For a 32-bit render-target surface, the depth buffer must be 32-bits, of which 8-bits can be used for stencil buffering (if needed).

If the hardware upon which your application is running has this requirement, and your application fails to meet it, any attempts to create a rendering device that uses the non-compliant surfaces will fail. You can use the DirectDraw method, DirectDraw7.GetDeviceIdentifier and the associated object (DirectDrawIdentifier) to track hardware that imposes this limitation.


Enabling Depth Buffering

[C++]

After you create a depth buffer (as described in Creating a Depth Buffer), enabling depth buffering is as simple as calling the IDirect3DDevice7::SetRenderState method. Set the D3DRENDERSTATE_ZENABLE render state to enable depth-buffering. Use the D3DZB_TRUE value (or TRUE) to enable z-buffering, D3DZB_USEW to enable w-buffering, or D3DZB_FALSE (or FALSE) to disable depth buffering.

Note To use w-buffering, your application must set a compliant projection matrix even if it doesn't use the Direct3D transformation pipeline. For information about providing an appropriate projection matrix, see A W-Friendly Projection Matrix. (The projection matrix discussed in What Is the Projection Transformation? is compliant.)

[Visual Basic]

After you create a depth buffer (as described in Creating a Depth Buffer), enabling depth buffering is as simple as calling the Direct3DDevice7.SetRenderState method. Set the D3DRENDERSTATE_ZENABLE render state to enable depth-buffering. Use the D3DZB_TRUE member of the CONST_D3DZBUFFERTYPE enumeration to enable z-buffering, D3DZB_USEW to enable w-buffering, or D3DZB_FALSE to disable depth buffering altogether.

Note To use w-buffering, your application must set a compliant projection matrix even if it doesn't use the Direct3D transformation pipeline. For information about providing an appropriate projection matrix, see A W-Friendly Projection Matrix. (The projection matrix discussed in What Is the Projection Transformation? is compliant.)


Clearing Depth Buffers

[C++]

Many C++ applications clear the depth buffer prior to rendering each new frame. You can explicitly clear the depth buffer through Direct3D by using the IDirect3DDevice7::Clear method. The Clear method allows you to specify an arbitrary depth value in the dvZ parameter.

You can also use DirectDraw to clear a depth buffer. Call the depth buffer surface's IDirectDrawSurface7::Blt method to clear it. The DDBLT_DEPTHFILL flag indicates that the blit is being used to a clear depth buffer. When this flag is specified, the DDBLTFX structure passed to the IDirectDrawSurface7::Blt method should be initialized and have its dwFillDepth member set to the required depth.

If the DirectDraw device driver for a 3-D accelerator is designed to provide support for depth buffer clearing in hardware, it will report the DDCAPS_BLTDEPTHFILL flag and should handle DDBLT_DEPTHFILL blits. The destination surface of a depth-fill blit must be a depth buffer surface.

[Visual Basic]

Many Visual Basic applications clear the depth buffer prior to rendering each new frame. You can explicitly clear the depth buffer through Direct3D by using the Direct3DDevice7.Clear method. The Clear method allows you to specify an arbitrary depth value in the z parameter.

You can also use DirectDraw to clear a depth buffer. Call the depth buffer surface's DirectDrawSurface7.Blt method to clear it. The DDBLT_DEPTHFILL flag indicates that the blit is being used to a clear depth buffer. When this flag is specified, the DDBLTFX type passed to the DirectDrawSurface7.Blt method have its lFill member set to the required depth.

If the DirectDraw device driver for a 3-D accelerator is designed to provide support for depth buffer clearing in hardware, it will report the DDCAPS_BLTDEPTHFILL flag and should handle DDBLT_DEPTHFILL blits. The destination surface of a depth-fill blit must be a depth buffer surface.


Changing Depth Buffer Write Access

By default, the Direct3D system is allowed to write to the depth buffer. Most applications will leave writing to the depth buffer enabled, but there are some special effects that can be achieved by not allowing the Direct3D system to write to the depth buffer.

[C++]

You can disable depth buffer writes in C++ by calling the IDirect3DDevice7::SetRenderState method with the dwRenderStateType parameter set to D3DRENDERSTATE_ZWRITEENABLE and the dwRenderState parameter set to 0.

[Visual Basic]

You can disable depth buffer writes in a Visual Basic application by calling the Direct3DDevice7.SetRenderState method with the state parameter set to D3DRENDERSTATE_ZWRITEENABLE and the renderstate parameter set to 0.


Changing Depth Buffer Comparison Functions

[C++]

By default, when depth-testing is performed on a rendering surface, the Direct3D system updates the render-target surface if the corresponding depth value (z or w) for each point is less than the value already in the depth buffer. In a C++ application, you change how the system performs comparisons on depth values by calling the IDirect3DDevice7::SetRenderState method with the dwRenderStateType parameter set to D3DRENDERSTATE_ZFUNC. The dwRenderState parameter should be set to one of the values in the D3DCMPFUNC enumerated type.

[Visual Basic]

By default, when depth testing is performed on a rendering surface, the Direct3D system updates the render-target surface if the corresponding depth value (z or w) for each point is less than the value already in the depth buffer. In Visual Basic, you can change how the system performs comparisons on depth values by calling the Direct3DDevice7.SetRenderState method with the state parameter set to D3DRENDERSTATE_ZFUNC. The renderstate parameter should be set to one of the values in the CONST_D3DCMPFUNC enumeration.


Using Z-Bias

Polygons that are coplanar in your 3-D space can be made to appear as if they are not coplanar by adding a z-bias to each one. This is a technique commonly used to ensure that shadows in a scene are displayed properly. For instance, a shadow on a wall will likely have the same depth value as the wall does. If you render the wall first, then the shadow, the shadow might not be visible, or depth artifacts may be visible. You could reverse the order in which you render the coplanar objects in hopes of reversing the effect, but depth artifacts are still likely.

[C++]

A C++ application can help ensure that coplanar polygons are rendered properly by adding a bias to the z-values that the system uses when rendering the sets of coplanar polygons. To add a z-bias to a set of polygons, call the IDirect3DDevice7::SetRenderState method just before rendering them, setting the dwRenderStateType parameter to D3DRENDERSTATE_ZBIAS, and the dwRenderState parameter to a value between 0-16 inclusive. A higher z-bias value will increase the likelihood that the polygons you render will be visible when displayed with other coplanar polygons.

[Visual Basic]

A Visual Basic application can help ensure that coplanar polygons are rendered properly by adding a bias to the z-values that the system uses when rendering the sets of coplanar polygons. To add a z-bias to a set of polygons, call the Direct3DDevice7.SetRenderState method just before rendering them, setting the first parameter to D3DRENDERSTATE_ZBIAS, and the second parameter to a value between 0-16 inclusive. A higher z-bias value will increase the likelihood that the polygons you render will be visible when displayed with other coplanar polygons.


Stencil Buffers

This section presents a discussion of the purpose and use stencil buffers. It is divided into the following topics:

  • What Is a Stencil Buffer?
  • How the Stencil Buffer Works
  • Customizing the Stencil Buffer


What Is a Stencil Buffer?

The stencil buffer enables or disables drawing to the rendering target surface on a pixel-by-pixel basis. At its most fundamental level, it enables applications to mask off sections of the rendered image so that it is not displayed. Applications often use stencil buffers for special effects such as dissolves, decaling, and outlining. For details, see Stencil Buffer Techniques.

[C++]

Stencil buffer information is embedded in the z-buffer data. Your application can test the user's hardware to see if it supports stencil buffers by invoking the IDirect3D7::EnumZBufferFormats method. The method passes depth-buffer formats, in the form of DDPIXELFORMAT structures, to your application. The relevant information is in the dwZBufferBitDepth, dwStencilBitDepth, dwZBitMask, and dwStencilBitMask members.

[Visual Basic]

Stencil buffer information is embedded in the z-buffer data. Your application can test the user's hardware to see if it supports stencil buffers by calling the Direct3D7.GetEnumZBufferFormats method, then using the returned Direct3DEnumPixelFormats object to retrieve information about each supported depth-buffer pixel format. The Direct3DenumPixelFormats.GetItem method retrieves depth-buffer formats, in the form of a DDPIXELFORMAT type each, to your application. The relevant information is in the lZBufferBitDepth, lStencilBitDepth, lZBitMask, and lStencilBitMask members.


How the Stencil Buffer Works

[C++]

Direct3D performs a test on the contents of the stencil buffer on a pixel-by-pixel basis. For each pixel in the target surface, it performs a test using the corresponding value in the stencil buffer, a stencil reference value, and a stencil mask value. If the test passes, Direct3D performs an action. The test is performed using the following steps:

  1. Bitwise AND the stencil reference value with the stencil mask.
  2. Bitwise AND the stencil buffer value for the current pixel with the stencil mask.
  3. Compare the result of step 1 to the result of step 2 using the comparison function.

Written in pseudocode, these steps would look like this:

(StencilRef & StencilMask) CompFunc (StencilBufferValue & StencilMask)

Where StencilBufferValue is the contents of the stencil buffer for the current pixel. This pseudocode uses the & symbol to represent the bitwise AND operation. StencilMask represents the value of the stencil mask, and StencilRef represents the stencil reference value. CompFunc is the comparison function.

The current pixel is written to the target surface if the stencil test passes, and ignored otherwise. The default comparison behavior is to write the pixel no matter how each of the bitwise operations turn-out (D3DCMP_ALWAYS). You can change this behavior by changing the value of the D3DRENDERSTATE_STENCILFUNC render state, passing one of the members of the D3DCMPFUNC enumerated type to identify the desired comparison function.

[Visual Basic]

Direct3D performs a test on the contents of the stencil buffer on a pixel-by-pixel basis. For each pixel in the target surface, it performs a test using the corresponding value in the stencil buffer, a stencil reference value, and a stencil mask value. If the test passes, Direct3D performs an action. The test is performed using the following steps:

  1. Bitwise And the stencil reference value with the stencil mask.
  2. Bitwise And the stencil buffer value for the current pixel with the stencil mask.
  3. Compare the result of step 1 to the result of step 2 using the comparison function.

Written in pseudocode, these steps would look like this:

(StencilRef And StencilMask) CompFunc (StencilBufferValue And StencilMask)

Where StencilBufferValue is the contents of the stencil buffer for the current pixel. StencilMask represents the value of the stencil mask, and StencilRef represents the stencil reference value. CompFunc is the comparison function.

The current pixel is written to the target surface if the stencil test passes, and ignored otherwise. The default comparison behavior is to write the pixel no matter how each of the bitwise operations turn-out (D3DCMP_ALWAYS). You can change this behavior by changing the value of the D3DRENDERSTATE_STENCILFUNC render state, passing one of the members of the CONST_D3DCMPFUNC enumeration to identify the desired comparison function.


Customizing the Stencil Buffer

Your application can customize the operation of the stencil buffer. It can set the comparison function, the stencil mask, and the stencil reference value. It can also control the action that Direct3D takes when the stencil test passes or fails. For more information, see Stencil Buffer State.


Vertex Buffers

This section introduces the concepts necessary to understand and use vertex buffers in a Direct3D application. Information is divided into the following sections:

  • What Are Vertex Buffers?
  • Vertex Buffer Descriptions
  • Device Types and Vertex Processing Requirements
  • Using Vertex Buffers


What Are Vertex Buffers?

[C++]

Vertex buffers, represented by the IDirect3DVertexBuffer7 interface, are simply memory buffers that contain vertex data. Vertex buffers can contain any vertex type—transformed or untransformed, lit or unlit—that can be rendered through the use of the vertex buffer rendering methods in the IDirect3DDevice7 interface. You can process the vertices in a vertex buffer to perform operations such as transformation, lighting, or generating clipping flags. (Transformation is always performed.)

[Visual Basic]

Vertex buffers, represented by the Direct3DVertexBuffer7 class, are simply memory buffers that contain vertex data. Vertex buffers can contain any vertex type—transformed or untransformed, lit or unlit—that can be rendered through the use of the vertex buffer rendering methods in the Direct3DDevice7 class. You can process the vertices in a vertex buffer to perform operations such as transformation, lighting, or generating clipping flags. (Transformation is always performed.)

The flexibility of vertex buffers make them ideal staging points for reusing transformed geometry. You could create a single vertex buffer, transform, light, and clip the vertices in it, and render the model in the scene as many times as you need without re-transforming it, even with interleaved render state changes. This can be very useful when rendering models that use multiple textures: the geometry is only transformed once, and then portions of it can be rendered as needed, interleaved with the required texture changes. Render state changes made after vertices are processed take effect the next time the vertices are processed. For more information, see Processing Vertices.

You can optimize geometry in vertex buffers to get maximum performance for vertex operations and rendering. See Optimizing a Vertex Buffer for details.

[C++]

Note Internally, vertex buffers use DirectDrawSurface objects for their memory management services. As a result, the semantics for accessing vertex buffer memory are similar to those of DirectDrawSurface objects. In fact, the IDirect3DVertexBuffer7::Lock method accepts the same flags as the IDirectDrawSurface7::Lock method. For more information, see Accessing the Contents of a Vertex Buffer.

[Visual Basic]

Note Internally, vertex buffers use DirectDrawSurface objects for their memory management services. As a result, the semantics for accessing vertex buffer memory are similar to those of DirectDrawSurface objects. In fact, the Direct3DVertexBuffer7.Lock method accepts the same flags as the DirectDrawSurface7.Lock method. For more information, see Accessing the Contents of a Vertex Buffer.


Vertex Buffer Descriptions

[C++]

A vertex buffer is described in terms of its capabilities: if it can only exist in system memory, if it is only to be used for write operations, the type and number of vertices it can contain, and whether or not it has been optimized since it was created. All these traits are held within a D3DVERTEXBUFFERDESC structure.

[Visual Basic]

A vertex buffer is described in terms of its capabilities: if it can only exist in system memory, if it is only to be used for write operations, the type and number of vertices it can contain, and whether or not it has been optimized since it was created. All these traits are held within a D3DVERTEXBUFFERDESC type.

Vertex buffer descriptions tell the system how to create a vertex buffer or tell your application how an existing buffer was created (and if it has been optimized since being created). You must specify a complete description to create a new vertex buffer, and you provide an empty description structure for the system to fill with the capabilities of a previously created vertex buffer. For more information about these tasks, see Creating a Vertex Buffer and Retrieving Vertex Buffer Descriptions.

[C++]

The dwSize member, common to most DirectX structures, is used for identify structure versions and must be set to the structure size before the structure can be used with any methods. The dwCaps structure member contains general capability flags. The D3DVBCAPS_SYSTEMMEMORY flag indicates that the system should create (or already has created) the vertex buffer in system memory. Create an explicit system memory vertex buffer if your application uses a software rendering device; otherwise, it is best to let the system determine the best location by omitting the flag. For more information about explicit system memory vertex buffers, see Device Types and Vertex Processing Requirements.

The presence of the D3DVBCAPS_WRITEONLY flag in dwCaps hints to the system that the vertex buffer memory is used only for write operations. This frees the driver to place the vertex data in the best possible memory location it can to enable fast processing and rendering. Reading from a vertex buffer that uses this flag can result in very slow memory access times. If the D3DVBCAPS_WRITEONLY flag isn't used, the driver is less likely to put the data in a location inefficient for read operations, sacrificing some processing and rendering speed. If no flags are specified, it is assumed that applications will perform read and write operations on the data within the vertex buffer.

Note The D3DVBCAPS_OPTIMIZED flag is not used during vertex buffer creation. The system sets this capability when it optimizes a vertex buffer.

The final two D3DVERTEXBUFFERDESC structure members describe other capabilities. The dwFVF member contains a combination of flexible vertex format flags that identify the type of vertices that the buffer can contain. Vertex buffer capacity is measured by the total number of vertices it can contain, given in the dwNumVertices member.

[Visual Basic]

The lCaps member contains general capability flags. The D3DVBCAPS_SYSTEMMEMORY flag indicates that the system should create (or already has created) the vertex buffer in system memory. Create an explicit system memory vertex buffer if your application uses a software rendering device; otherwise, it is best to let the system determine the best location by omitting the flag. For more information about explicit system memory vertex buffers, see Device Types and Vertex Processing Requirements.

The presence of the D3DVBCAPS_WRITEONLY flag in lCaps hints to the system that the vertex buffer memory is used only for write operations. This frees the driver to place the vertex data in the best possible memory location it can to enable fast processing and rendering. Reading from a vertex buffer that uses this flag can result in very slow memory access times. If the D3DVBCAPS_WRITEONLY flag isn't used, the driver is less likely to put the data in a location inefficient for read operations, sacrificing some processing and rendering speed. If no flags are specified, it is assumed that applications will perform read and write operations on the data within the vertex buffer.

Note The D3DVBCAPS_OPTIMIZED flag is not used during vertex buffer creation. The system sets this capability when it optimizes a vertex buffer.

The final two D3DVERTEXBUFFERDESC members describe other capabilities. The lFVF member contains a combination of flexible vertex format flags that identify the type of vertices that the buffer can contain. Vertex buffer capacity is measured by the total number of vertices it can contain, given in the lNumVertices member.


Device Types and Vertex Processing Requirements

The performance of vertex processing operations, including transformation and lighting, depends heavily on where the vertex buffer exists in memory and what type of rendering device is being used. Applications control the memory allocation for vertex buffers when they are created. When the D3DVBCAPS_SYSTEMMEMORY capability flag is set in the vertex buffer description, the vertex buffer is created in system memory. When the capability is not used, the device driver determines where the memory for vertex buffer is best allocated, often referred to as "driver-optimal" memory. Driver-optimal memory can be local video memory, nonlocal video memory, or system memory.

[C++]

Direct3D applies vertex processing operations when you call the IDirect3DDevice7::DrawPrimitiveVB, IDirect3DDevice7::DrawIndexedPrimitiveVB, or IDirect3DVertexBuffer7::ProcessVertices methods. These operations include transformation and lighting. The performance of these calls depends on the location of the buffer in memory, and whether that location is best for the given type of device (hardware or software).

[Visual Basic]

Direct3D applies vertex processing operations when you call the Direct3DDevice7.DrawPrimitiveVB, Direct3DDevice7.DrawIndexedPrimitiveVB, or Direct3DVertexBuffer7.ProcessVertices methods. These operations include transformation and lighting. The performance of these calls depends on the location of the buffer in memory, and whether that location is best for the given type of device (hardware or software).

The reasoning you should apply to determine the memory location—system or driver optimal—for vertex buffers is the same as textures. In the case of textures, hardware rasterization works best when textures are allocated in driver-optimal memory, while software rasterization works best with system-memory textures. Likewise, vertex processing (including transformation and lighting) in hardware works best when the vertex buffers are allocated in driver-optimal memory, while software vertex processing works best with vertex buffers allocated in system memory.

Note Vertex processing done by the ProcessVertices method is always done in software, so the source vertex buffer for must always be in system memory. The destination vertex buffer for can be allocated in driver-optimal memory unless it is to be directly locked and read by the application, or if clipping is requested in the call to ProcessVertices (which requires reading from the vertex buffer when a vertex-buffer rendering method is called).

If your application performs its own vertex processing (and passes transformed, lit, and clipped vertices to the vertex-buffer rendering methods), then vertices can be directly written by the application into a vertex-buffer allocated in driver-optimal memory. This technique prevents a redundant copy operation later. Note that this technique will not work well if your application reads data back from a vertex-buffer, because read operations done by the host from driver-optimal memory can be very slow. So, if your application needs to read during processing or if writes data to the buffer erratically, then a system-memory vertex buffer is a better choice.

When using the Direct3D vertex processing features (by passing untransformed vertices to vertex-buffer rendering methods), processing can occur in either hardware or software, depending on the device type. If the device is a TnLHAL Device (IID_IDirect3DTnLHALDevice), vertex processing is done in hardware and the vertex buffer should be created in driver-optimal memory for best performance. If the device is a HAL Device (IID_IDirect3DHALDevice), vertex processing is done in software and the vertex buffer should be created in system memory. When rendering with the RGB Device (IID_IDirect3DRGBDevice), all vertex buffers should be allocated in system memory.

[C++]

The following C++ style pseudo-code summarizes the logic you should apply when creating and processing vertex buffers:

if (software rasterization)
    use system-memory vertex buffers (D3DVBCAPS_SYSTEMMEMORY)
else if (application vertex processing)
    if (application does not read and does not use erratic writes)
        use driver-optimal vertex buffers
    else
        use system-memory vertex buffers (D3DVBCAPS_SYSTEMMEMORY)
else // Direct3D vertex processing
    if (TnLHAL device)
        use driver-optimal vertex buffers
    else if (HAL device)
        use system-memory vertex (D3DVBCAPS_SYSTEMMEMORY)
[Visual Basic]

The following Visual Basic style pseudo-code summarizes the logic you should apply when creating and processing vertex buffers:

If (software rasterization) Then
    use system-memory vertex buffers (D3DVBCAPS_SYSTEMMEMORY)
Else If (application vertex processing) Then
    If (application does not read and does not use erratic writes) Then
        use driver-optimal vertex buffers
    Else
        use system-memory vertex buffers (D3DVBCAPS_SYSTEMMEMORY)
Else // Direct3D vertex processing
    If (TnLHAL device) Then
        use driver-optimal vertex buffers
    Else If (HAL device)
        use system-memory vertex (D3DVBCAPS_SYSTEMMEMORY)
End If


Using Vertex Buffers

The following topics discuss common tasks that applications will perform when working with vertex buffers:

  • Creating a Vertex Buffer
  • Accessing the Contents of a Vertex Buffer
  • Processing Vertices
  • Optimizing a Vertex Buffer
  • Rendering From a Vertex Buffer
  • Retrieving Vertex Buffer Descriptions


Creating a Vertex Buffer

[C++]

The following figure illustrates the steps necessary to create a single vertex buffer from C++.

Note As discussed in Accessing Direct3D, the DirectDraw component comprises two COM objects. The newest object—called DirectDraw7 and created by calling the DirectDrawCreateEx function—is the only object that exposes the IDirect3D7 interface, and is the only object capable of spawning a vertex buffer that exposes the IDirect3DVertexBuffer7 interface. The Direct3DDevice object created in this manner doesn't expose legacy Direct3D interfaces. Applications that require previous iterations of the Direct3D must use the DirectDrawCreate method to create a DirectDraw object and then create the desired legacy objects.

You create a vertex buffer object by calling the IDirect3D7::CreateVertexBuffer method, which accepts four parameters. The first parameter is the address of a D3DVERTEXBUFFERDESC structure that describes the desired vertex format, buffer size, and general capabilities. These capabilities are detailed in Vertex Buffer Descriptions. Normally, the system automatically determines the best memory location (system or display memory) for the vertex buffer. However, software devices can only be used with explicit system-memory vertex buffers. For more information, see Device Types and Vertex Processing Requirements.

The second parameter that CreateVertexBuffer accepts is the address of a variable that will be filled with a pointer to the new IDirect3DVertexBuffer7 interface of the vertex buffer object if the call succeeds. The third parameter determines if the vertex buffer will be capable of containing clipping information—in the form of clip flags—for vertices that exist outside the viewing area. Set this to 0 to create a "clipping-capable" vertex buffer, or include the D3DDP_DONOTCLIP flag to create a vertex buffer that cannot contain clip flags. The D3DDP_DONOTCLIP flag is only applied if you also indicate that the vertex buffer will contain transformed vertices (the D3DFVF_XYZRHW flag is included in the dwFVF member of the description structure). The CreateVertexBuffer method ignores the D3DDP_DONOTCLIP flag if you indicate that the buffer will contain untransformed vertices (the D3DFVF_XYZ flag). Clipping flags occupy additional memory, making a clipping-capable vertex buffer slightly larger than a vertex buffer incapable of containing clipping flags. Because these resources are allocated when the vertex buffer is created, you must request a clipping-capable vertex buffer ahead of time.

Note Creating a vertex buffer that can contain clip flags does not necessarily mean that you must request that clip flags be generated during vertex processing or applied during rendering. Each vertex buffer rendering method accepts the D3DDP_DONOTCLIP flag to bypass clipping during rendering, and the IDirect3DVertexBuffer7::ProcessVertices method accepts the D3DVOP_CLIP flag, which can be omitted to prevent the system from generating clip flags while it processes vertices.

There is no way to produce clip flags for a vertex buffer that was created without support for them. Attempts to use the IDirect3DVertexBuffer7::ProcessVertices method to do this will fail in debug builds, returning D3DERR_INVALIDVERTEXFORMAT. Rendering methods will ignore clipping requests when rendering from a transformed vertex buffer that does not contain clip flags.

The last parameter that CreateVertexBuffer accepts is provided for future compatibility with COM aggregation features. Currently, aggregation isn't supported, so this parameter must be set to NULL.

The following C++ example shows what creating a vertex buffer might look like in code:

    /*
     * For the purposes of this example, the g_lpD3D variable is the
     * address of an IDirect3D7 interface exposed by a Direct3D
     * object, g_vbVertexBuffer is a variable of type LPD3DVERTEXBUFFER7,
     * and the fIsAHardwareDevice variable is a BOOL variable that is
     * assumed to be set during application initialization.
     */

    D3DVERTEXBUFFERDESC vbdesc;
    ZeroMemory(&vbdesc, sizeof(D3DVERTEXBUFFERDESC));
    vbdesc.dwSize= sizeof(D3DVERTEXBUFFERDESC);
    vbdesc.dwCaps        = 0L;
    vbdesc.dwFVF         = D3DFVF_VERTEX;
    vbdesc.dwNumVertices = NUM_FLAG_VERTICES;

    // If this isn't a hardware device, make sure the
    // vertex buffer uses system memory.
    if( !fIsAHardwareDevice )
        vbdesc.dwCaps |= D3DVBCAPS_SYSTEMMEMORY;

    // Create a clipping-capable vertex buffer.
    if(FAILED(g_lpD3D->CreateVertexBuffer(&vbdesc,
                                          &g_pvbVertexBuffer, 0L,
                                          NULL)))
        return E_FAIL;
[Visual Basic]

The following figure illustrates the steps necessary to create a single vertex buffer from Visual Basic.

You create a vertex buffer object from Visual Basic by calling the Direct3D7.CreateVertexBuffer method, which accepts four parameters. The first parameter is the address of a D3DVERTEXBUFFERDESC type that describes the desired vertex format, buffer size, and general capabilities. These capabilities are detailed in Vertex Buffer Descriptions. Normally, the system automatically determines the best memory location (system or display memory) for the vertex buffer. However, software devices can only be used with explicit system-memory vertex buffers. For more information, see Device Types and Vertex Processing Requirements.

The second parameter determines if the vertex buffer will be capable of containing clipping information—in the form of clip flags—for vertices that exist outside the viewing area. Set this to 0 to create a "clipping-capable" vertex buffer, or include the D3DDP_DONOTCLIP flag to create a vertex buffer that cannot contain clip flags. The D3DDP_DONOTCLIP flag is only applied if you also indicate that the vertex buffer will contain transformed vertices (the D3DFVF_XYZRHW flag is included in the lFVF member of the description). The CreateVertexBuffer method ignores the D3DDP_DONOTCLIP flag if you indicate that the buffer will contain untransformed vertices (the D3DFVF_XYZ flag). Clipping flags occupy additional memory, making a clipping-capable vertex buffer slightly larger than a vertex buffer incapable of containing clipping flags. Because these resources are allocated when the vertex buffer is created, you must request a clipping-capable vertex buffer ahead of time.

The CreateVertexBuffer method returns a reference to a new Direct3DVertexBuffer7 object if the call succeeds.

Note Creating a vertex buffer that can contain clip flags does not necessarily mean that you must request that clip flags be generated during vertex processing or applied during rendering. Each vertex buffer rendering method accepts the D3DDP_DONOTCLIP flag to bypass clipping during rendering, and the Direct3DVertexBuffer7.ProcessVertices method accepts the D3DVOP_CLIP flag, which can be omitted to prevent the system from generating clip flags while it processes vertices.

There is no way to produce clip flags for a vertex buffer that was created without support for them. Attempts to use the Direct3DVertexBuffer7.ProcessVertices method to do this will fail in debug builds, raising the D3DERR_INVALIDVERTEXFORMAT error. Rendering methods will ignore clipping requests when rendering from a transformed vertex buffer that does not contain clip flags.

The following Visual Basic example shows what creating a vertex buffer might look like in code:

    '
    ' For the purposes of this example, the g_D3D variable is a reference
    ' to a Direct3D7 object and g_VertexBuffer is a reference to a
    ' Direct3DVertexBuffer7 object.
    '
    On Local Error Resume Next

    Dim VBDesc As D3DVERTEXBUFFERDESC
    VBDesc.lFVF = D3DFVF_VERTEX
    VBDesc.lNumVertices = NUM_FLAG_VERTICES

    ' Create a clipping-capable vertex buffer.
    Set g_VertexBuffer = g_D3D.CreateVertexBuffer(VBDesc, D3DDP_DEFAULT)

    If Err.Number <> DD_OK Then
        ' Code to handle error goes here.
    End If


Accessing the Contents of a Vertex Buffer

[C++]

Vertex buffer objects enable applications to directly access the memory allocated for vertex data. You can retrieve a pointer to vertex buffer memory by calling the IDirect3DVertexBuffer7::Lock method, then access the memory as needed to fill the buffer with new vertex data, or to read any data it already contains.

The IDirect3DVertexBuffer7::Lock method accepts three parameters. The first, dwFlags, tells the system how the memory should be locked, and can be used to hint how the application will be accessing the data within the buffer. (You can hint for read-only or write-only access, which allows the driver to lock the memory to provide the best performance given the requested access type. These hints are not required, but can improve performance for memory access in some situations.) Because vertex buffers use DirectDrawSurface objects to contain vertex data, the flags that IDirect3DVertexBuffer7::Lock accepts are identical to those accepted by the IDirectDrawSurface7::Lock method, with identical results.

The second parameter accepted by the Lock method, lplpData, is the address of an LPVOID variable that will contain a valid pointer to the vertex buffer memory if the call succeeds. The last parameter, lpdwSize, is the address of a variable that will contain the size, measured in bytes, of the buffer at lplpData after the call returns. You can set lpdwSize to NULL if your application doesn't need information about the buffer size.

Performance Notes Use the DDLOCK_READONLY flag if your application will only be reading from the vertex buffer memory. Including this flag enables Direct3D to optimize its internal procedures to improve efficiency, given that access to the memory will be read-only. Although it is possible to write to memory locked with the DDLOCK_READONLY flag, doing so can produce unexpected results. In addition, attempting to read from a vertex buffer that was created with the D3DVBCAPS_WRITEONLY flag can be extremely slow, even if you lock the buffer for read-only access.

In C++, you directly access the memory allocated for the vertex buffer. As such, you must take care that your application properly accesses the allocated memory, or risk rendering that memory invalid. Use the stride of the vertex format your application uses to move from one vertex in the allocated buffer to another. The vertex buffer memory itself is a simple array of vertices, specified in flexible vertex format. If your application is uses the legacy vertex structures, D3DVERTEX, D3DLVERTEX, and D3DTLVERTEX, the stride is simply the size of the structure, in bytes. If you are using a vertex format different from the legacy formats, use the stride of whatever vertex format structure you define. You can calculate the stride of each vertex at run time by examining the flexible vertex format flags contained within the vertex buffer description. The following table shows the size for each vertex component.

Vertex Format Flag | Size
D3DFVF_DIFFUSE | sizeof(DWORD)
D3DFVF_NORMAL | sizeof(float) × 3
D3DFVF_SPECULAR | sizeof(DWORD)
D3DFVF_TEXn | sizeof(float) × 2 × n
D3DFVF_XYZ | sizeof(float) × 3
D3DFVF_XYZRHW | sizeof(float) × 4

The number of texture coordinates present in the vertex format is described by the D3DFVF_TEXn flags (where n is a value from 0 to 8). Because each set of texture coordinates in the vertex format occupies the space of two float variables, multiply the number of texture coordinate sets by the size of one set of texture coordinates to calculate the memory required for that number of texture coordinates.

Use the total vertex stride to increment and decrement the memory pointer as needed to access particular vertices.

[Visual Basic]

Vertex buffers enable Visual Basic applications to easily update the vertex data they contain. You prepare to access the contents of the vertex buffer by calling the Direct3DVertexBuffer7.Lock method. The Lock method offers the flags parameter to tell the system how the memory should be locked. The flags parameter hints to the system how the application will be accessing the data within the buffer. (You can request read-only or write-only access, which allows the driver to lock the memory to provide the best performance given the requested access type. These hints are not required, but can improve performance for memory access in some situations.) Because vertex buffers use DirectDrawSurface objects to contain vertex data, the flags that Direct3DVertexBuffer7.Lock accepts are identical to those accepted by the DirectDrawSurface7.Lock method, with identical results.

Performance Notes Use the DDLOCK_READONLY flag if your application will only be reading from the vertex buffer memory. Including this flag enables Direct3D to optimize its internal procedures to improve efficiency, given that access to the memory will be read-only. Although it is possible to write to memory locked with the DDLOCK_READONLY flag, doing so can produce unexpected results. In addition, attempting to read from a vertex buffer that was created with the D3DVBCAPS_WRITEONLY flag can be extremely slow, even if you lock the buffer for read-only access.

Once the vertex buffer is locked, you can call the Direct3DVertexBuffer7.GetVertices method to fill an array with the current contents of the vertex buffer. Set the first parameter to the zero-based index of the first vertex in the buffer to need and set the second parameter to the total number of vertices to retrieve. The last parameter should be the first element in an array that uses the same vertex format as the vertex buffer, which will contain the requested data after the call.

The vertex buffer memory itself is a simple array of vertices, specified in flexible vertex format. The number of texture coordinates present in the vertex format is described by the D3DFVF_TEXn flags (where n is a value from 0 to 8). Because each set of texture coordinates in the vertex format occupies the space of two Single variables, multiply the number of texture coordinate sets by the size of one set of texture coordinates to calculate the memory required for that number of texture coordinates.

To change the contents of the vertex buffer after it is locked, modify the contents of the array, then call the Direct3DVertexBuffer7.SetVertices method to copy the vertices into the buffer. You must also unlock the vertex buffer by way of the Direct3DVertexBuffer7.Unlock method before performing any vertex buffer processing or rendering operations.


Processing Vertices

[C++]

Processing the vertices in a vertex buffer applies the current transformation matrices for the device, and can optionally apply vertex operations such as lighting, generating clip flags, and updating extents. The IDirect3DVertexBuffer7 interface exposes the IDirect3DVertexBuffer7::ProcessVertices method to process vertices. You process vertices from a source vertex buffer into a destination vertex buffer by calling the ProcessVertices method of the destination vertex buffer, not the source buffer. The method accepts seven parameters that describe the operations to be performed, the location of the source vertex buffer's IDirect3DVertexBuffer7 interface, the rendering device that will perform the vertex operations, and the location and quantity of vertices that the method targets. After the call, the destination buffer contains the processed vertex data, and the source buffer is unchanged.

When preparing to process vertices, set the first parameter, dwVertexOp, to indicate the vertex operations you want to perform. You must include the D3DVOP_TRANSFORM flag, or the method will fail, but the remaining operations are optional. You can include any combination of optional flags to light the vertices, generate clip flags, and update extents during vertex processing.

The second and third parameters, dwDestIndex and dwCount, reflect the index within the destination buffer at which the vertices will be placed and the total number of vertices that should be processed and placed in the destination buffer. The fourth parameter, lpSrcBuffer, should be set to the address of the IDirect3DVertexBuffer7 of the vertex buffer object that contains the source vertices. The dwSrcIndex specifies the index at which the method should start processing vertices. (The total number of source vertices to be processed is implied by the dwCount parameter.) Set the lpD3DDevice parameter to the address of the IDirect3DDevice7 interface for the rendering device that processes the vertices.

The final parameter, dwFlags, determines special processing options for the method. You can set this parameter to 0 for default vertex processing, or to D3DPV_DONOTCOPYDATA to optimize processing in some situations. When you set dwFlags to 0, vertex components of the destination vertex buffer's vertex format that are not affected by the vertex operation are still copied from the source vertex buffer (when present in the source buffer) or set to 0. However, by using D3DPV_DONOTCOPYDATA, any vertex components of the destination buffer's vertex format not computed as part of the call to ProcessVertices are left untouched. Picture yourself calling the ProcessVertices method intending to transform vertices without lighting them (with the D3DVOP_TRANSFORM vertex operation by itself). If the destination vertex buffer uses the D3DFVF_TLVERTEX vertex format, specifying D3DPV_DONOTCOPYDATA flag will cause the system to ignore the diffuse, specular, and the texture coordinate components of the destination buffer. The result is lighter processing and data transfer overhead—you only wanted the system to transform the vertices. Without using D3DPV_DONOTCOPYDATA, the system would copy the extraneous lighting and texture coordinate components to the vertices in the destination buffer, even though your application doesn't need them. The D3DPV_DONOTCOPYDATA flag is useful to reduce the amount of work required by the system for vertex processing. An application that uses ProcessVertices can copy static vertex components to the destination vertex buffer directly, eliminating the need for the system to copy from the source buffer to the destination buffer.

[Visual Basic]

Processing the vertices in a vertex buffer applies the current transformation matrices for the device, and can optionally apply vertex operations such as lighting, generating clip flags, and updating extents. The Direct3DVertexBuffer7 class offers the Direct3DVertexBuffer7.ProcessVertices method to process vertices. You process vertices from a source vertex buffer into a destination vertex buffer by calling the ProcessVertices method of the destination vertex buffer, not the source buffer. The method accepts seven parameters that describe the operations to be performed, a reference to the source Direct3DVertexBuffer7 object, the rendering device that will perform the vertex operations, and the location and quantity of vertices that the method targets. After the call, the destination buffer contains the processed vertex data, and the source buffer is unchanged.

When preparing to process vertices, set the first parameter, vertexOp, to indicate the vertex operations you want to perform. You must include the D3DVOP_TRANSFORM flag, or the method will fail, but the remaining operations are optional. You can include any combination of optional flags to light the vertices, generate clip flags, and update extents during vertex processing.

The second and third parameters, destIndex and count, reflect the index within the destination buffer at which the vertices will be placed and the total number of vertices that should be processed and placed in the destination buffer. The fourth parameter, srcBuffer, should be the Direct3DVertexBuffer7 object that contains the source vertices. The srcIndex specifies the index at which the method should start processing vertices. (The total number of source vertices to be processed is implied by the count parameter.) Set the dev parameter to the Direct3DDevice7 object that will process the vertices.

The final parameter, flags, determines special processing options for the method. You can set this parameter to 0 for default vertex processing, or to D3DPV_DONOTCOPYDATA to optimize processing in some situations. When you set flags to 0, vertex components of the destination vertex buffer's vertex format that are not affected by the vertex operation are still copied from the source vertex buffer (when present in the source buffer) or set to 0. However, by using D3DPV_DONOTCOPYDATA, any vertex components of the destination buffer's vertex format not computed as part of the call to ProcessVertices are left untouched. Picture yourself calling the ProcessVertices method intending to transform vertices without lighting them (with the D3DVOP_TRANSFORM vertex operation by itself). If the destination vertex buffer uses the D3DFVF_TLVERTEX vertex format, specifying D3DPV_DONOTCOPYDATA flag will cause the system to ignore the diffuse, specular, and the texture coordinate components of the destination buffer. The result is lighter processing and data transfer overhead—you only wanted the system to transform the vertices. Without using D3DPV_DONOTCOPYDATA, the system would copy the extraneous lighting and texture coordinate components to the vertices in the destination buffer, even though your application doesn't need them. The D3DPV_DONOTCOPYDATA flag is useful to reduce the amount of work required by the system for vertex processing. An application that uses ProcessVertices can copy static vertex components to the destination vertex buffer directly, eliminating the need for the system to copy from the source buffer to the destination buffer.

Take care to create vertex buffers that use compatible vertex formats. At the least, the source buffer should contain untransformed vertices (using the D3DFVF_XYZ flag in the vertex format of the buffer description), and the destination buffer should contain transformed vertices (using the D3DFVF_XYZRHW flag). Any lighting or clipping services require that the source and destination vertex formats contain the appropriate fields. For instance, don't request lighting on vertices when the vertex format doesn't include a vertex normal. Likewise, you can't request that the system produce clip flags for a destination vertex buffer that was created without clipping capabilities. Attempts to perform operations on incompatible buffers will fail in debug builds.

You cannot process vertices when the source or destination vertex buffers are locked.


Optimizing a Vertex Buffer

Optimizing a vertex buffer causes the system to modify the contents of the buffer for better performance when processing or rendering vertices. Exactly how vertices are optimized is platform-specific and subject to change. Consequently, you cannot lock or otherwise access the contents of an optimized vertex buffer.

[C++]

Performance of both hardware and software devices can benefit from using optimized vertex buffers. The optimization of vertex buffers differs depending on whether the vertex buffer is to be used for hardware or software vertex processing. Vertex buffers created with the D3DVBCAPS_SYSTEMMEMORY flag will, when optimized, be optimized for use with software vertex processing only, and can only be used with the IDirect3DVertexBuffer7::ProcessVertices method or the vertex-buffer rendering methods on a HAL Device (as opposed to a TnLHAL Device). Vertex buffers created without the D3DVBCAPS_SYSTEMMEMORY flag (for driver-optimal memory) will be optimized for hardware vertex processing, and thus can only be used for rendering methods on a TnLHAL Device. Optimized vertex buffers cannot be used as the destination buffer for the IDirect3DVertexBuffer7::ProcessVertices or IDirect3DVertexBuffer7::ProcessVerticesStrided methods.

Call the IDirect3DVertexBuffer7::Optimize method to optimize a vertex buffer. Optimizing a vertex buffer improves performance of vertex operations and rendering. The IDirect3DVertexBuffer7::Optimize method accepts two parameters, only one of which is used. Set the lpD3DDevice parameter to the address of the device for which the vertices will be optimized, and set the last parameter to 0. Locked vertex buffers cannot be optimized until they are unlocked.

You can improve performance by keeping vertices in optimized format. However, optimized vertex buffers should be used only for static geometry, because once a vertex buffer is optimized, you can't lock it to change the optimized contents. After you optimize a vertex buffer, it can only be used with the IDirect3DVertexBuffer7::ProcessVertices method and the vertex buffer rendering methods.

[Visual Basic]

Performance of both hardware and software devices can benefit from using optimized vertex buffers. The optimization of vertex buffers differs depending on whether the vertex buffer is to be used for hardware or software vertex processing. Vertex buffers created with the D3DVBCAPS_SYSTEMMEMORY flag will, when optimized, be optimized for use with software vertex processing only, and can only be used with the Direct3DVertexBuffer7.ProcessVertices method or the vertex-buffer rendering methods on a HAL Device (as opposed to a TnLHAL Device). Vertex buffers created without the D3DVBCAPS_SYSTEMMEMORY flag (for driver-optimal memory) will be optimized for hardware vertex processing, and thus can only be used for rendering methods on a TnLHAL Device. Optimized vertex buffers cannot be used as the destination buffer for the Direct3DVertexBuffer7.ProcessVertices method.

Call the Direct3DVertexBuffer7.Optimize method to optimize a vertex buffer. Optimizing a vertex buffer improves performance of vertex operations and rendering. The Direct3DVertexBuffer7.Optimize method accepts one parameter. Set it to the Direct3DDevice7 object for which the vertices will be optimized. Locked vertex buffers cannot be optimized until they are unlocked.

You can improve performance by keeping vertices in optimized format. However, optimized vertex buffers should be used only for static geometry, because once a vertex buffer is optimized, you can't lock it to change the optimized contents. After you optimize a vertex buffer, it can only be used with the Direct3DVertexBuffer7.ProcessVertices method and the vertex buffer rendering methods.


Rendering From a Vertex Buffer

As introduced in Rendering, rendering devices offer methods to render primitives from a vertex buffer. These methods work very much like most other rendering methods, but employ slightly different parameters to accommodate vertex buffer objects.

The following topics introduce common rendering situations, and discuss specific issues related to calling the vertex buffer rendering methods:

  • About Vertex Buffer Rendering
  • Calling Vertex Buffer Rendering Methods


About Vertex Buffer Rendering

There are two common situations in which your application will render vertices from a vertex buffer. At the most basic level, the two situations break down according to the type of vertex that is in the vertex buffer at "render time," but indirectly, the procedure your application uses also determines when vertex and rendering operations occur. The following diagram illustrates the process of rendering from an untransformed vertex buffer.

[C++]

As shown in the preceding illustration, the IDirect3DDevice7::DrawPrimitiveVB and IDirect3DDevice7::DrawIndexedPrimitiveVB methods are capable of rendering from a non-transformed vertex buffer. In this case, the system performs vertex and rendering operations each time you call a rendering method. Using this approach isn't likely to provide improved performance over traditional DrawPrimitive rendering methods, but it might be more convenient in some situations. You can optimize performance by reusing transformed vertex data when you can, as shown in the following illustration.

[Visual Basic]

As shown in the preceding illustration, the Direct3DDevice7.DrawPrimitiveVB and Direct3DDevice7.DrawIndexedPrimitiveVB Visual Basic methods are capable of rendering from a non-transformed vertex buffer. In this case, the system performs vertex and rendering operations each time you call a rendering method. Using this approach isn't likely to provide improved performance over traditional DrawPrimitive rendering methods, but it might be more convenient in some situations. You can optimize performance by reusing transformed vertex data when you can, as shown in the following illustration.

[C++]

In this case, your application creates two vertex buffers: one for untransformed geometry, and another for transformed geometry. The second buffer receives transformed vertex data when the IDirect3DVertexBuffer7::ProcessVertices is called. The ProcessVertices method reads the vertices in the source buffer, performs the requested vertex operations on them, and places the results in the destination buffer. You can call the same rendering methods for transformed vertices that you would to render untransformed vertices. However, unlike untransformed vertices, Direct3D automatically detects that the data in the vertex buffer is transformed, sending it be rasterized right away. The performance overhead is kept to a minimum by eliminating unnecessary transformations.

Note The IDirect3DVertexBuffer7 interface provides a new method, IDirect3DVertexBuffer7::ProcessVerticesStrided, to process strided vertices into a destination vertex buffer.

[Visual Basic]

In this case, your application creates two vertex buffers: one for untransformed geometry, and another for transformed geometry. The second buffer receives transformed vertex data when the Direct3DVertexBuffer7.ProcessVertices is called. The ProcessVertices method reads the vertices in the source buffer, performs the requested vertex operations on them, and places the results in the destination buffer. You can call the same rendering methods for transformed vertices that you would to render untransformed vertices. However, unlike untransformed vertices, Direct3D automatically detects that the data in the vertex buffer is transformed, sending it be rasterized right away. The performance overhead is kept to a minimum by eliminating unnecessary transformations.

You can optimize vertex buffer contents to increase performance even more. For more information, see Optimizing a Vertex Buffer.


Calling Vertex Buffer Rendering Methods

[C++]

The IDirect3DDevice7::DrawPrimitiveVB method corresponds to the IDirect3DDevice7::DrawPrimitive method. Like its relative, the DrawPrimitiveVB method assumes that vertices appear in sequential order within the vertex buffer.

The DrawPrimitiveVB method accepts five parameters. Set the d3dptPrimitiveType parameter to indicate the type of primitive being rendered by using one the members of the D3DPRIMITIVETYPE enumerated type. Specify the address of the vertex buffer that contains the vertices in the second parameter, lpd3dVertexBuffer, then set values in the dwStartVertex and dwNumVertices parameters to reflect the first vertex and the total number of vertices that will be rendered. You don't need to render all the vertices that the vertex buffer contains, but you must use the appropriate number of vertices for that primitive type (as documented in the reference information for D3DPRIMITIVETYPE). The last parameter, dwFlags, determines the rendering behavior. These flags are identical to those used with other rendering methods. You can set flags to enable lighting and clipping, or to update the clip extents during rendering.

The IDirect3DDevice7::DrawIndexedPrimitiveVB method renders primitives by indexing the vertices within a vertex buffer. The first two parameters are identical to those of the DrawPrimitiveVB method. The third and fourth parameters should be the index of the first vertex in the buffer and the total number of vertices to be rendered. The fifth parameter, lpwIndices, should be set to the address of an ordered array of WORD indices that the method will use to access the vertices to be rendered, and the sixth parameter, dwIndexCount, should be set to the number of index values that the array contains. The dwFlags parameter is identical to its counterpart in the DrawPrimitiveVB method.

[Visual Basic]

The Direct3DDevice7.DrawPrimitiveVB method corresponds to the Direct3DDevice7.DrawPrimitive method. Like its relative, the DrawPrimitiveVB method assumes that vertices appear in sequential order within the vertex buffer.

The DrawPrimitiveVB method accepts five parameters. Set the d3dpt parameter to indicate the type of primitive being rendered by using one the members of the CONST_D3DPRIMITIVETYPE enumeration. Specify the Direct3DVertexBuffer7 object that contains the vertices in the second parameter, vertexBuffer, then set values in the startVertex and numVertices parameters to reflect the first vertex and the total number of vertices that will be rendered. You don't need to render all the vertices that the vertex buffer contains, but you must use the appropriate number of vertices for that primitive type (as documented in the reference information for D3DPRIMITIVETYPE). The last parameter, flags, determines the rendering behavior. These flags are identical to those used with other rendering methods. You can set flags to enable lighting and clipping, or to update the clip extents during rendering.

The Direct3DDevice7.DrawIndexedPrimitiveVB method renders primitives by indexing the vertices within a vertex buffer. The first two parameters are identical to those of the DrawPrimitiveVB method. The third and fourth parameters should be the index of the first vertex in the buffer and the total number of vertices to be rendered. The fifth parameter, indexArray, should be set to the first element in an ordered array of Integer indices that the method will use to access the vertices to be rendered, and the sixth parameter, indexCount, should be to the number of index values that the array contains. The flags parameter is identical to its counterpart in the DrawPrimitiveVB method.

You cannot request that vertex buffer rendering methods perform lighting if the format of the vertices within the buffer does not contain a vertex normal. Nor can you request that the rendering methods clip vertices when rendering from a transformed vertex buffer created with the D3DDP_DONOTCLIP flag. (This is allowed for untransformed vertex buffers, as the system will create a clipping-capable version at render time.) Attempts to request unavailable services will not cause the method to fail in debug builds, but the services will not be applied.

A software device, as opposed to a hardware-accelerated device, can only render from vertex buffers that were created with the D3DVBCAPS_SYSTEMMEMORY flag. For more information, see Device Types and Vertex Processing Requirements.


Retrieving Vertex Buffer Descriptions

[C++]

Applications often need to retrieve information about existing vertex buffers at run time. Direct3D makes this possible through the IDirect3DVertexBuffer7::GetVertexBufferDesc method. Call this method using the IDirect3DVertexBuffer7 interface of any vertex buffer to retrieve its current description.

The GetVertexBufferDesc method accepts only one parameter: the address of a properly initialized D3DVERTEXBUFFERDESC structure. To initialize the structure, set the dwSize member to the structure size, in bytes, and set the remaining members to 0. After the method returns, the structure will contain information about the vertex buffer capabilities, the vertex format in the buffer, and the total number of vertices that it can contain.

Note Optimizing a vertex buffer sets the D3DVBCAPS_OPTIMIZED capability flag in the dwCaps member of the D3DVERTEXBUFFERDESC structure. If this flag is set, the vertex buffer cannot be locked. The contents of an optimized vertex buffer are not made available to anything but rendering methods and vertex buffer processing methods (IDirect3DVertexBuffer7::ProcessVertices and IDirect3DVertexBuffer7::ProcessVerticesStrided).

For general information, see Vertex Buffer Descriptions.

[Visual Basic]

Applications often need to retrieve information about existing vertex buffers at run time. Direct3D makes this possible for Visual Basic applications through the Direct3DVertexBuffer7.GetVertexBufferDesc method.

The GetVertexBufferDesc method accepts only one parameter: a properly variable of type D3DVERTEXBUFFERDESC. After the method returns, the structure will contain information about the vertex buffer capabilities, the vertex format in the buffer, and the total number of vertices that it can contain.

Note Optimizing a vertex buffer sets the D3DVBCAPS_OPTIMIZED capability flag in the lCaps member of the D3DVERTEXBUFFERDESC type retrieved by GetVertexBufferDesc. If this flag is set, the vertex buffer cannot be locked. The contents of an optimized vertex buffer are not made available to anything but rendering methods and the Direct3DVertexBuffer7.ProcessVertices method.

For general information, see Vertex Buffer Descriptions.


Common Techniques and Special Effects

Direct3D provides a powerful set of tools that can be used to increase the realistic appearance of a 3-D scene. This section presents information on some common special effects that can be produced with Direct3D. The range of possible effects is by no means limited to those presented here. The discussion in this section is organized into the following topics:

  • Fog
  • Geometry Blending
  • User-defined Clip Planes
  • Environment Mapping
  • Bump Mapping
  • Billboarding
  • Clouds, Smoke, and Vapor Trails
  • Fire, Flares, Explosions, and More
  • Motion Blur
  • Stencil Buffer Techniques
  • Colored Lights
  • Antialiasing


Fog

The following topics introduce fog and present information about using various fog features in Direct3D applications:

  • Introduction to Fog
  • Fog Formulas
  • Fog Parameters
  • Fog Blending
  • Fog Color
  • Pixel Fog
  • Vertex Fog


Introduction to Fog

Adding fog to a 3-D scene can enhance realism, provide ambiance or set a mood, and obscure artifacts sometimes caused when distant geometry comes into view. Direct3D Immediate Mode supports two fog models, pixel fog and vertex fog, each with its own features and programming interface.

Essentially, fog is implemented by blending the color of objects in a scene with a chosen fog color based on the depth of an object in a scene, or its distance from the viewpoint. As objects grow more distant, their original color blends more and more into the chosen fog color, creating the illusion that the object is being increasingly obscured by tiny particles floating in the scene—fog. The following screen capture shows a scene rendered without fog, and a similar scene rendered with fog enabled.

In the preceding figure, the scene on the left has a clear horizon, beyond which no scenery is visible, even though it would be visible in the real world. The scene on the right obscures the horizon by using a fog color identical to the background color, making polygons appear to fade into the distance. By combining discrete fog effects with creative scene design you can add mood and soften the color of objects in a scene.

Direct3D provides applications with two ways to add fog to a scene, pixel fog and vertex fog, named according to how the fog effects are applied. For details, see Pixel Fog and Vertex Fog. In short, pixel fog (also called "table fog") is implemented in the device driver, and vertex fog is implemented in the Direct3D lighting engine.

Note Regardless of which type of fog—pixel or vertex—you use, your application must provide a compliant projection matrix to ensure that fog effects will be properly applied. This restriction applies even to applications that do not use the Direct3D transformation and lighting engine. For additional details about how you can provide an appropriate matrix, see A W-Friendly Projection Matrix.


Fog Formulas

[C++]

C++ applications can control how fog affects the color of objects in a scene by changing how Direct3D computes fog effects over distance. The D3DFOGMODE enumerated type contains members that identify the three fog formulas. All formulas calculate a fog factor as a function of distance, given parameters that your application sets. How distance itself is computed varies on the projection matrix or if range-based fog is enabled. For more information, see Eye-Relative vs. Z-based Depth and Range-Based Fog.

[Visual Basic]

Applications written in Visual Basic can control how fog affects the color of objects in a scene by changing how Direct3D computes fog effects over distance. The CONST_D3DFOGMODE enumeration contains members that identify the three fog formulas. All formulas calculate a fog factor as a function of distance, given parameters that your application sets. How distance itself is computed varies on the projection matrix or if range-based fog is enabled. For more information, see Eye-Relative vs. Z-based Depth and Range-Based Fog.

D3DFOG_LINEAR

In the linear formula, start is the distance at which fog effects begin, end is the distance at which fog effects no longer increase, and d represents depth (or distance from the viewpoint) within a scene. Values for d increase as objects become more distant. The linear formula is supported for both pixel fog and vertex fog, but the exponential formulas are currently only supported when using pixel fog:

D3DFOG_EXP

D3DFOG_EXP2

In the preceding two exponential formulas, e is the base of natural logarithms (approximately 2.71828), density is an arbitrary fog density that can range from 0.0 to 1.0, and d is depth (or distance from the viewpoint) within a scene.

Note The system stores the fog factor in the alpha component of the specular color for a vertex. If your application performs its own transformation and lighting, you can insert fog factor values manually, to be applied by the system during rendering.

The following illustration graphs these formulas, using common values as in the formula parameters.

When Direct3D calculates fog effects, it uses the fog factor from one of the preceding equations in a blending formula, shown here:

This formula effectively scales the color of the current polygon Ci by the fog factor f, and adds the product to the fog color Cf scaled by the bitwise inverse of the fog factor. The resulting color value is a blend of the fog color and the original color, as a factor of distance. The formula applies to all devices supported in DirectX 7.0. For the legacy ramp device, the fog factor scales the diffuse and specular color components, clamped to the range of 0.0 and 1.0, inclusive. The fog factor typically starts at 1.0 for the near plane and decreases to 0.0 at the far plane.


Fog Parameters

[C++]

Fog parameters are controlled through device render states. Both pixel and vertex fog types support all of the fog formulas introduced in Fog Formulas. The D3DFOGMODE enumerated type defines constants that you can use to identify the fog formula you want Direct3D to use. The D3DRENDERSTATE_FOGTABLEMODE render state controls the fog mode that Direct3D will use for pixel fog, and the D3DRENDERSTATE_FOGVERTEXMODE render state controls the mode for vertex fog.

When using the linear fog formula, you set the starting and ending distances through the D3DRENDERSTATE_FOGSTART and D3DRENDERSTATE_FOGEND render states. How the system inteprets these values depends on the type of fog your application uses—pixel or vertex fog—and, when using pixel fog, if z-based or w-based depth is being used. (For information z- and w-based pixel fog, see Eye Relative vs. Z-based Depth.) The following table summarizes:

Fog Type | Fog Start/End Units
Pixel (Z) | Device space [0.0,1.0]
Pixel (W) | Camera space
Vertex | Camera space

The D3DRENDERSTATE_FOGDENSITY render state controls the fog density applied when an exponential fog formula is enabled. Fog density is a essentially weighting factor, ranging from 0.0 to 1.0 (inclusive), that scales the distance value in the exponent.

The color that the system uses for fog blending is controlled through the D3DRENDERSTATE_FOGCOLOR device render state. For more information, see Fog Color and Fog Blending.

[Visual Basic]

Fog parameters are controlled through device render states. Both pixel and vertex fog types support all of the fog formulas introduced in Fog Formulas. The CONST_D3DFOGMODE enumeration defines constants that you can use to identify the fog formula you want Direct3D to use. The D3DRENDERSTATE_FOGTABLEMODE render state controls the fog mode that Direct3D will use for pixel fog, and the D3DRENDERSTATE_FOGVERTEXMODE render state controls the mode for vertex fog.

When using the linear fog formula, you set the starting and ending distances through the D3DRENDERSTATE_FOGSTART and D3DRENDERSTATE_FOGEND render states. How the system inteprets these values depends on the type of fog your application uses—pixel or vertex fog—and, when using pixel fog, if z-based or w-based depth is being used. (For information z- and w-based pixel fog, see Eye Relative vs. Z-based Depth.) The following table summarizes:

Fog Type | Fog Start/End Units
Pixel (Z) | Device space [0.0,1.0]
Pixel (W) | Camera space
Vertex | Camera space

The D3DRENDERSTATE_FOGDENSITY render state controls the fog density applied when an exponential fog formula is enabled. Fog density is a essentially weighting factor, ranging from 0.0 to 1.0 (inclusive), that scales the distance value in the exponent.

The color that the system uses for fog blending is controlled through the D3DRENDERSTATE_FOGCOLOR device render state. Use the DirectX7.CreateColorRGB method to generate valid color values for this render state. For more information, see Fog Color and Fog Blending.


Fog Blending

[C++]

Fog blending refers to the application of the fog factor to the fog and object colors to produce the final color that appears in a scene, as discussed in Fog Formulas. The D3DRENDERSTATE_FOGENABLE render state controls fog blending. Set this render state to TRUE to enable fog blending (the default is FALSE), as in the following example code:

//
// For this example, g_lpDevice is a valid pointer
// to an IDirect3DDevice7 interface.
HRESULT hr;
hr = g_lpDevice->SetRenderState(
                     D3DRENDERSTATE_FOGENABLE,
                     TRUE);
if FAILED(hr)
    return hr;

You must enable fog blending for both pixel fog and vertex fog. For information about using these types of fog, see Pixel Fog and Vertex Fog.

[Visual Basic]

Fog blending refers to the application of the fog factor to the fog and object colors to produce the final color that appears in a scene, as discussed in Fog Formulas. The D3DRENDERSTATE_FOGENABLE render state controls fog blending. Set this render state to True to enable fog blending (the default is False), as in the following example code:

'
' For this example, g_d3dDevice contains a valid
' reference to an Direct3DDevice7 object.
'
On Local Error Resume Next

Call g_d3dDevice.SetRenderState( _
                     D3DRENDERSTATE_FOGENABLE, _
                     True)

If Err.Number <> DD_OK Then
    ' Code to handle error goes here.
End If

You must enable fog blending for both pixel fog and vertex fog. For information about using these types of fog, see Pixel Fog and Vertex Fog.


Fog Color

[C++]

Fog color for both pixel and vertex fog is set through the D3DRENDERSTATE_FOGCOLOR render state. The render state values can be any RGB color, specified as an RGBA color (the alpha component is ignored).

The following C++ example sets the fog color to white:

/* For this example, the g_lpD3DDevice variable is
 * a valid pointer to an IDirect3DDevice7 interface.
 */
HRESULT hr;

hr = g_lpd3dDevice->SetRenderState(
                    D3DRENDERSTATE_FOGCOLOR,
                    0x00FFFFFF); // Highest 8 bits aren't used.

if(FAILED(hr))
    return hr;
[Visual Basic]

Fog color for both pixel and vertex fog is set through the D3DRENDERSTATE_FOGCOLOR render state. The render state values can be any RGB color, as returned by the DirectX7.CreateColorRGB method.

The following Visual Basic example sets the fog color to white:

'
' For this example, the g_d3dDevice variable is
' a valid reference to a Direct3DDevice7 object,
' and g_dx is a valid reference to a DirectX7 object.
'
On Local Error Resume Next

Call g_d3dDevice.SetRenderState( _
                    D3DRENDERSTATE_FOGCOLOR, _
                    g_dx.CreateColorRGB(1#, 1#, 1#))

If Err.Number <> DD_OK Then
    ' Code to handle error goes here.
End If


Pixel Fog

This section introduces the concept of pixel fog and provides information about using it in Direct3D applications. Information is divided into the following topics:

  • About Pixel Fog
  • Eye-Relative vs. Z-based Depth
  • Using Pixel Fog


About Pixel Fog

Pixel fog gets its name from the fact that it is calculated on a per-pixel basis in the device driver. (This is unlike vertex fog, in which Direct3D computes fog effects when it performs transformation and lighting.) Pixel fog is sometimes called "table fog" because some drivers use a precalculated look-up table to determine the fog factor (using the depth of each pixel) to be applied in blending computations.

[C++]

Pixel fog can be applied using any of the fog formulas identified by members of the D3DFOGMODE enumerated type. Pixel-fog formula implementations are driver-specific, and if a driver doesn't support a complex fog formula, it should degrade to a less complex formula.

[Visual Basic]

Pixel fog can be applied using any of the fog formulas identified by members of the CONST_D3DFOGMODE enumeration. Pixel-fog formula implementations are driver-specific, and if a driver doesn't support a complex fog formula, it should degrade to a less complex formula.

Note As discussed in Range-Based Fog, pixel fog does not support range-based fog calculations.


Eye-Relative vs. Z-based Depth

[C++]

To alleviate fog-related graphic artifacts caused by uneven distribution of z-values within a depth buffer, most hardware devices use eye-relative depth instead of z-based depth values for pixel fog. Eye-relative depth is essentially the w element from a homogenous coordinate set. (Direct3D takes the reciprocal of the RHW element from a device space coordinate set to reproduce true w.) If a device supports eye-relative fog, it sets the D3DPRASTERCAPS_WFOG flag in the dwRasterCaps member of the D3DPRIMCAPS when you call IDirect3DDevice7::GetCaps method. (The D3DDEVICEDESC7 structure you pass to GetCaps contains multiple D3DPRIMCAPS structures that describe capabilities for various types of primitives.)

Note With the exception of the reference rasterizer, software devices always use z to calculate pixel fog effects.

When eye-relative fog is supported, the system will automatically use eye-relative depth in favor of z-based depth if the provided projection matrix produces z-values in world space that are equivalent to w-values in device space. (You set the projection matrix by calling the IDirect3DDevice7::SetTransform method, using the D3DTRANSFORMSTATE_PROJECTION value and passing a D3DMATRIX structure that represents the desired matrix.) If the projection matrix isn't compliant with this requirement, fog effects will not be applied properly. For details about producing a compliant matrix, see A W-Friendly Projection Matrix. (The perspective projection matrix provided in What Is the Projection Transformation? produces a compliant projection matrix.)

Usage Notes Direct3D uses the currently set projection matrix in its w-based depth calculations. As a result, applications must set a compliant projection matrix to receive the desired w-based features, even if they do not use the Direct3D transformation pipeline.

Direct3D checks the fourth column of the projection matrix, and if the coefficients are [0,0,0,1] (for an affine projection) the system will use z-based depth values for fog. In this case, you must also specify the start and end distances for linear fog effects in device space, which ranges from 0.0 at the nearest point to the user, and 1.0 at the farthest point.

[Visual Basic]

To alleviate fog-related graphic artifacts caused by uneven distribution of z-values within a depth buffer, most hardware devices use eye-relative depth instead of z-based depth values for pixel fog. Eye-relative depth is essentially the w element from a homogenous coordinate set. (Direct3D takes the reciprocal of the RHW element from a device space coordinate set to reproduce true w.) If a device supports eye-relative fog, it sets the D3DPRASTERCAPS_WFOG flag in the lRasterCaps member of the D3DPRIMCAPS type when you call Direct3DDevice7.GetCaps method. (The D3DDEVICEDESC7 type you pass to GetCaps contains multiple D3DPRIMCAPS type that describe capabilities for various types of primitives.)

Note With the exception of the reference rasterizer, software devices always use z to calculate pixel fog effects.

When eye-relative fog is supported, the system will automatically use eye-relative depth in favor of z-based depth if the provided projection matrix produces z-values in world space that are equivalent to w-values in device space. (You set the projection matrix by calling the Direct3DDevice7.SetTransform method, using the D3DTRANSFORMSTATE_PROJECTION value from CONST_D3DTRANSFORMSTATETYPE and passing a D3DMATRIX type that represents the desired matrix.) If the projection matrix isn't compliant with this requirement, fog effects will not be applied properly. For details about producing a compliant matrix, see A W-Friendly Projection Matrix. (The perspective projection matrix provided in What Is the Projection Transformation? produces a compliant projection matrix.)

Usage Notes Direct3D uses the currently set projection matrix in its w-based depth calculations. As a result, applications must set a compliant projection matrix to receive the desired w-based features, even if they do not use the Direct3D transformation pipeline.

Direct3D checks the fourth column of the projection matrix, and if the coefficients are [0,0,0,1] (for an affine projection) the system will use z-based depth values for fog. In this case, you must also specify the start and end distances for linear fog effects in device space, which ranges from 0.0 at the nearest point to the user, and 1.0 at the farthest point.


Using Pixel Fog

Use the following steps to enable pixel fog in your application:

[C++]

To enable pixel fog in a C++ application

  1. Enable fog blending by setting the D3DRENDERSTATE_FOGENABLE render state to TRUE.
  2. Set the desired fog color in the D3DRENDERSTATE_FOGCOLOR render state.
  3. Choose the fog formula you want to use by setting the D3DRENDERSTATE_FOGTABLEMODE render state to the corresponding member of the D3DFOGMODE enumerated type.
  4. Set the fog parameters as desired for the selected fog mode in the associated render states. This includes the start and end distances for linear fog, and fog density for exponential fog mode.

The following example shows what these steps might look like in code:

// For brevity, error values in this example are not checked
// after each call. A real-world application should check
// these values appropriately.
//
// For the purposes of this example, g_lpDevice is a valid
// pointer to an IDirect3DDevice7 interface.
void SetupPixelFog(DWORD dwColor, DWORD dwMode)
{
    float fStart = 0.5f,    // for linear mode
          fEnd   = 0.8f,
          fDensity = 0.66;  // for exponential modes

    // Enable fog blending.
    g_lpDevice->SetRenderState(D3DRENDERSTATE_FOGENABLE, TRUE);

    // Set the fog color.
    g_lpDevice->SetRenderState(D3DRENDERSTATE_FOGCOLOR, dwColor);

    // Set fog parameters.
    if(D3DFOG_LINEAR == dwMode)
    {
        g_lpDevice->SetRenderState(D3DRENDERSTATE_FOGTABLEMODE, dwMode);
        g_lpDevice->SetRenderState(D3DRENDERSTATE_FOGSTART, *(DWORD *)(&fStart));
        g_lpDevice->SetRenderState(D3DRENDERSTATE_FOGEND,   *(DWORD *)(&fEnd));
    }
    else
    {
        g_lpDevice->SetRenderState(D3DRENDERSTATE_FOGTABLEMODE, dwMode);
        g_lpDevice->SetRenderState(D3DRENDERSTATE_FOGDENSITY, *(DWORD *)(&fDensity));
    }

}

Note Some fog parameters are required as floating-point values, even though the IDirect3DDevice7::SetRenderState method only accepts DWORD values in the second parameter. The preceding example provides the floating-point values to SetRenderState without data translation by casting the addresses of the floating-point variables as DWORD pointers, then dereferencing them.

[Visual Basic]

To enable pixel fog in a Visual Basic application

  1. Enable fog blending by setting the D3DRENDERSTATE_FOGENABLE render state to True.
  2. Set the desired fog color in the D3DRENDERSTATE_FOGCOLOR render state.
  3. Choose the fog formula you want to use by setting the D3DRENDERSTATE_FOGTABLEMODE render state to the corresponding member of the CONST_D3DFOGMODE enumeration.
  4. Set the fog parameters as desired for the selected fog mode in the associated render states. This includes the start and end distances for linear fog, and fog density for exponential fog mode.

The following example shows what these steps might look like in code:

' For brevity, error values in this example are not checked
' after each call. A real-world application should check
' these values appropriately.
'
' For the purposes of this example, g_d3dDevice is a valid
' pointer to a Direct3DDevice7 object.
Sub SetupPixelFog(lColor As Long, Mode As CONST_D3DFOGMODE)
    Dim StartFog As Single, _
        EndFog As Single, _
        Density As Single

    ' For linear mode.
    StartFog = 0.5: EndFog = 0.8

    ' For exponential mode.
    Density = 0.66

    ' Enable fog blending.
    Call g_d3dDevice.SetRenderState(D3DRENDERSTATE_FOGENABLE, True)

    ' Set the fog color.
    Call g_d3dDevice.SetRenderState(D3DRENDERSTATE_FOGCOLOR, lColor)

    ' Set fog parameters.
    If Mode = D3DFOG_LINEAR Then
        Call g_d3dDevice.SetRenderState(D3DRENDERSTATE_FOGTABLEMODE, Mode)
        Call g_d3dDevice.SetRenderStateSingle(D3DRENDERSTATE_FOGSTART, StartFog)
        Call g_d3dDevice.SetRenderStateSingle(D3DRENDERSTATE_FOGEND, EndFog)
    Else
        Call g_d3dDevice.SetRenderState(D3DRENDERSTATE_FOGTABLEMODE, Mode)
        Call g_d3dDevice.SetRenderStateSingle(D3DRENDERSTATE_FOGDENSITY, Density)
    End If
End Sub


Vertex Fog

This section introduces vertex fog and provides details about using it in Direct3D applications. Information is divided into the following topics:

  • About Vertex Fog
  • Range-Based Fog
  • Using Vertex Fog


About Vertex Fog

When the system performs vertex fogging, it applies fog calculations at each vertex in a polygon, then interpolates the results across the face of the polygon during rasterization. Vertex fog effects are computed by the Direct3D lighting and transformation engine. For more information, see Fog Parameters.

If your application doesn't use Direct3D for transformation and lighting, it must perform fog calculations on its own. In this case, your application can place the fog factor it computes in the alpha component of the specular color for each vertex. You are free to use whatever formulas you desire—range-based, volumetric, or otherwise. Direct3D uses the supplied fog factor to interpolate across the face of each polygon. Applications that do not use Direct3D transformation and lighting need not set vertex fog parameters, but must still enable fog and set the fog color through the associated render states. For more information, see Fog Parameters.

Note Applications that perform their own transformation and lighting must also perform their own vertex fog calculations. As a result, such an application need only enable fog blending and set the fog color through the associated render states, as described in Fog Blending and Fog Color.


Range-Based Fog

Note Direct3D used range-based fog calculations only when using vertex fog with the Direct3D transformation and lighting engine. This is because pixel fog is implemented in the device driver, and no hardware currently exists to support per-pixel range-based fog. If your application performs its own transformation and lighting it must perform its own fog calculations, range-based or otherwise.

Sometimes, using fog can introduce graphic artifacts that cause objects to be blended with the fog color in non-intuitive ways. For example, imagine a scene in which there are two visible objects, one distant enough to be affected by fog, and the other near enough to be unaffected. If the viewing area rotates in place, the apparent fog effects can change, even if the objects are stationary. The following illustration shows a top-down view of such a situation.

Range-based fog is another, more accurate, way to determine the fog effects. In range-based fog, Direct3D uses the actual distance from the viewpoint to a vertex for its fog calculations, increasing the effects of fog as the distance between the two points increases, rather than the depth of the vertex within in the scene, thereby avoiding rotational artifacts.

[C++]

If the current device supports range-based fog, it will set the D3DPRASTERCAPS_FOGRANGE capability flag in the dwRasterCaps member of the D3DPRIMCAPS structure when you call the IDirect3DDevice7::GetCaps method. To enable range-based fog, set the D3DRENDERSTATE_RANGEFOGENABLE render state to TRUE.

[Visual Basic]

If the current device supports range-based fog, it will set the D3DPRASTERCAPS_FOGRANGE capability flag in the lRasterCaps member of the D3DPRIMCAPS type when you call the Direct3DDevice7.GetCaps method. To enable range-based fog, set the D3DRENDERSTATE_RANGEFOGENABLE render state to True.

Range-based fog is computed by Direct3D during transformation and lighting. As discussed in About Vertex Fog, applications that don't use the Direct3D transformation and lighting engine must also perform their own vertex fog calculations. In this case, provide the range-based fog factor in the alpha component of the specular component for each vertex.


Using Vertex Fog

Use the following steps to enable vertex fog in your application:

[C++]

To enable vertex fog in a C++ application

  1. Enable fog blending by setting D3DRENDERSTATE_FOGENABLE to TRUE.
  2. Set the fog color in the D3DRENDERSTATE_FOGCOLOR render state.
  3. Choose the desired fog formula by setting the D3DRENDERSTATE_FOGVERTEXMODE render state to a member of the D3DFOGMODE enumerated type.
  4. Set the fog parameters as desired for the selected fog formula in the render states.

The following example, written in C++, shows what these steps might look like in code:

// For brevity, error values in this example are not checked
// after each call. A real-world application should check
// these values appropriately.
//
// For the purposes of this example, g_lpDevice is a valid
// pointer to an IDirect3DDevice7 interface.
void SetupVertexFog(DWORD dwColor, DWORD dwMode, BOOL fUseRange, FLOAT fDensity)
{
    float fStart = 0.5f,    // linear fog distances
          fEnd   = 0.8f;

    // Enable fog blending.
    g_lpDevice->SetRenderState(D3DRENDERSTATE_FOGENABLE, TRUE);

    // Set the fog color.
    g_lpDevice->SetRenderState(D3DRENDERSTATE_FOGCOLOR, dwColor);

    // Set fog parameters.
    if(D3DFOG_LINEAR == dwMode)
    {
        g_lpDevice->SetRenderState(D3DRENDERSTATE_FOGVERTEXMODE, dwMode);
        g_lpDevice->SetRenderState(D3DRENDERSTATE_FOGSTART, *(DWORD *)(&fStart));
        g_lpDevice->SetRenderState(D3DRENDERSTATE_FOGEND,   *(DWORD *)(&fEnd));
    }
    else
    {
        g_lpDevice->SetRenderState(D3DRENDERSTATE_FOGVERTEXMODE, dwMode);
        g_lpDevice->SetRenderState(D3DRENDERSTATE_FOGDENSITY, *(DWORD *)(&fDensity));
    }

    // Enable range-based fog if desired (only supported for vertex fog).
    // For this example, it is assumed that fUseRange is set to a nonzero value
    // only if the driver exposes the D3DPRASTERCAPS_FOGRANGE capability.
    //
    // Note: this is slightly more performance intensive
    //       than non-range-based fog.
    if(fUseRange)
        g_lpDevice->SetRenderState(
                       D3DRENDERSTATE_RANGEFOGENABLE,
                       TRUE);
}

Note Some fog parameters are required as floating-point values, even though the IDirect3DDevice7::SetRenderState method only accepts DWORD values in the second parameter. The preceding example successfully provides the floating-point values to these methods without data translation by casting the addresses of the floating-point variables as DWORD pointers, then dereferencing them.

[Visual Basic]

To enable vertex fog from a Visual Basic application

  1. Enable fog blending by setting D3DRENDERSTATE_FOGENABLE to True.
  2. Set the fog color in the D3DRENDERSTATE_FOGCOLOR render state.
  3. Choose the desired fog formula by setting the D3DRENDERSTATE_FOGVERTEXMODE render state to a member of the CONST_D3DFOGMODE enumeration.
  4. Set the fog parameters as desired for the selected fog formula in the render states.

The following Visual Basic example code shows what these steps might look like in code:

' For brevity, error values in this example are not checked
' after each call. A real-world application should check
' these values appropriately.
'
' For the purposes of this example, g_d3dDevice is a valid
' reference to a Direct3DDevice7 object.
Sub SetupVertexFog(lColor As Long, Mode As CONST_D3DFOGMODE, _
                   bUseRange As Boolean, Optional Density As Single)

    Dim StartFog As Single, _
        EndFog As Single

    ' Set linear fog distances
    StartFog = 0.5: EndFog = 0.8

    ' Enable fog blending.
    Call g_d3dDevice.SetRenderState(D3DRENDERSTATE_FOGENABLE, True)

    ' Set the fog color.
    Call g_d3dDevice.SetRenderState(D3DRENDERSTATE_FOGCOLOR, lColor)

    ' Set fog parameters.
    If Mode = D3DFOG_LINEAR Then
        Call g_d3dDevice.SetRenderState(D3DRENDERSTATE_FOGVERTEXMODE, Mode)
        Call g_d3dDevice.SetRenderStateSingle(D3DRENDERSTATE_FOGSTART, StartFog)
        Call g_d3dDevice.SetRenderStateSingle(D3DRENDERSTATE_FOGEND, EndFog)
    Else
        Call g_d3dDevice.SetRenderState(D3DRENDERSTATE_FOGVERTEXMODE, Mode)
        Call g_d3dDevice.SetRenderStateSingle(D3DRENDERSTATE_FOGDENSITY, Density)
    End If

    ' Enable range-based fog if desired (only supported for vertex fog).
    ' For this example, it is assumed that bUseRange is set to True only
    ' if the driver exposes the D3DPRASTERCAPS_FOGRANGE capability.
    '
    ' Note: this is slightly more performance intensive
    '       than non-range-based fog.
    If bUseRange = True Then
        Call g_d3dDevice.SetRenderState( _
                       D3DRENDERSTATE_RANGEFOGENABLE, True)
    End If
End Sub


Geometry Blending

This section contains information about a new feature in DirectX 7.0: geometry blending. The following topics are discussed:

  • About Geometry Blending
  • Blending Transform and Render States
  • Blending Weights
  • Using Geometry Blending


About Geometry Blending

Direct3D Immediate Mode for DirectX 7.0 enables applications to increase the realism of their scenes by rendering segmented polygonal objects—especially characters—that have smoothly-blended joints. (These effects are often referred to as "skinning.") The system achieves this effect by applying additional "world" transformation matrices to a single set of vertices to create multiple results, then performing a linear blend between the resultant vertices to create a single set of geometry for rendering. The following image, based on the banana rendered by the Bend Sample, illustrates.

The preceding image shows how you might imagine the geometry-blending process. In a single rendering call, the system takes the vertices for the banana, transforms them twice—once without modification, and once with a simple rotation—and blends the results to create a "bent" banana. The system blends the vertex position, as well as the vertex normal (when lighting is enabled). Applications are not limited to two blending paths; Direct3D can blend geometry between as many as four different world matrices (including the standard world matrix, D3DTRANSFORMSTATE_WORLD).

[C++]

Note When lighting is enabled, vertex normals are transformed by a corresponding inverse world-view matrix, weighted in the same way as the vertex position computations. The system normalizes the resulting normal vector if the D3DRENDERSTATE_NORMALIZENORMALS render state is set to TRUE.

Without geometry blending, dynamic articulated models are often rendered in segments. For instance, take a 3-D model of the human arm. In the simplest view, an arm has two parts: the upper arm which connects to the body, and the lower arm, which connects to the hand. The two are connected at the elbow, and the lower arm rotates at that point. An application that renders an arm might retain vertex data for the upper and lower arm, each with a separate world transformation matrix. The following code illustrates:

typedef struct _Arm {
    D3DVERTEX upper_arm_verts[200];
    D3DMATRIX matWorld_Upper;

    D3DVERTEX lower_arm_verts[200];
    D3DMATRIX matWorld_Lower;
} ARM, *LPARM;

ARM MyArm; // This will need to be initialized.

To render the arm, two rendering calls would be made, as shown in the following code:

// Render the upper arm.
d3dDevice->SetTransform( D3DTRANSFORMSTATE_WORLD, &MyArm.matWorld_Upper );
d3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, D3DFVF_VERTEX,
                          MyArm.upper_arm_verts, 200, 0 );

// Render the lower arm, updating its world matrix to articulate the arm
// by pi/4 radians (45 degrees) at the elbow.
MyArm.matWorld_Lower = RotateMyArm(MyArm.matWorld, pi/4);
d3dDevice->SetTransform( D3DTRANSFORMSTATE_WORLD, &MyArm.matWorld_Lower );
d3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, D3DFVF_VERTEX,
                          MyArm.lower_arm_verts, 200, 0 );
[Visual Basic]

Note When lighting is enabled, vertex normals are transformed by a corresponding inverse world-view matrix, weighted in the same way as the vertex position computations. The system normalizes the resulting normal vector if the D3DRENDERSTATE_NORMALIZENORMALS render state is set to True.

Without geometry blending, dynamic articulated models are often rendered in segments. For instance, take a 3-D model of the human arm. In the simplest view, an arm has two parts: the upper arm which connects to the body, and the lower arm, which connects to the hand. The two are connected at the elbow, and the lower arm rotates at that point. An application that renders an arm might retain vertex data for the upper and lower arm, each with a separate world transformation matrix. The following pseudo-code illustrates:

Type Arm
    upper_arm_verts(200) As D3DVERTEX
    matWorld_Upper As D3DMATRIX

    lower_arm_verts(200) As D3DVERTEX
    matWorld_Lower As D3DMATRIX
End Type

Dim MyArm As Arm ' This will need to be initialized.

To render the arm, two rendering calls would be made, as shown in the following code:

' Render the upper arm.
Call d3DDevice.SetTransform(D3DTRANSFORMSTATE_WORLD, MyArm.matWorld_Upper)
Call d3DDevice.DrawPrimitive(D3DPT_TRIANGLELIST, D3DFVF_VERTEX, _
                             MyArm.upper_arm_verts, 200, 0)

' Render the lower arm, updating its world matrix to articulate the arm
' by pi/4 radians (45 degrees) at the elbow.
MyArm.matWorld_Lower = RotateMyArm(MyArm.matWorld, pi / 4)
Call d3DDevice.SetTransform(D3DTRANSFORMSTATE_WORLD, MyArm.matWorld_Lower)
Call d3DDevice.DrawPrimitive(D3DPT_TRIANGLELIST, D3DFVF_VERTEX, _
                             MyArm.lower_arm_verts, 200, 0)

The following image is the banana from a version of the Bend Sample, modified to use this technique.

The differences between the blended geometry and the non-blended geometry are obvious. This example is admittedly somewhat extreme. In a real-world application, the "joints" of segmented models are designed such that seams aren't as obvious. However, ugly seams are visible at times, which presents constant challenges for model designers.

Geometry blending in Direct3D presents an alternative to the classic segmented-modeling scenario. Geometry blending isn't free; the improved visual quality of segmented objects comes at the cost of the blending computations during rendering. To minimize the impact of these additional operations, the Direct3D geometry pipeline is optimized to blend geometry with the least possible overhead. Applications that intelligently use the geometry blending services offered by Direct3D can improve the realism of their characters while avoiding serious performance repercussions.


Blending Transform and Render States

[C++]

The IDirect3DDevice7::SetTransform and IDirect3DDevice7::SetTransform methods recognize the D3DTRANSFORMSTATE_WORLD, D3DTRANSFORMSTATE_WORLD1, D3DTRANSFORMSTATE_WORLD2, and D3DTRANSFORMSTATE_WORLD3 members of the D3DTRANSFORMSTATETYPE enumerated type to identify the matrices between which geometry will be blended. (The D3DTRANSFORMSTATE_WORLD member might be thought of as "D3DTRANSFORMSTATE_WORLD0".)

The D3DRENDERSTATETYPE enumerated type includes the D3DRENDERSTATE_VERTEXBLEND render state to enable and control geometry blending. Valid values for this renderstate are defined by the D3DVERTEXBLENDFLAGS enumerated type, which includes the D3DVBLEND_DISABLE, D3DVBLEND_1WEIGHT, D3DVBLEND_2WEIGHT, D3DVBLEND_3WEIGHT members. If geometry blending is enabled, the vertex format must include the appropriate number of blending weights.

[Visual Basic]

The Direct3DDevice7.SetTransform and Direct3DDevice7.SetTransform methods recognize the D3DTRANSFORMSTATE_WORLD, D3DTRANSFORMSTATE_WORLD1, D3DTRANSFORMSTATE_WORLD2, and D3DTRANSFORMSTATE_WORLD3 members of the CONST_D3DTRANSFORMSTATETYPE enumeration to identify the matrices between which geometry will be blended. (The D3DTRANSFORMSTATE_WORLD member might be thought of as "D3DTRANSFORMSTATE_WORLD0".)

The CONST_D3DRENDERSTATETYPE enumeration includes the D3DRENDERSTATE_VERTEXBLEND render state to enable and control geometry blending. Valid values for this renderstate are defined by the CONST_D3DVERTEXBLENDFLAGS enumerated type, which includes the D3DVBLEND_DISABLE, D3DVBLEND_1WEIGHT, D3DVBLEND_2WEIGHT, D3DVBLEND_3WEIGHT members. If geometry blending is enabled, the vertex format must include the appropriate number of blending weights.

See Also

Setting Blending Matrices, Enabling Geometry Blending, Blending Weights


Blending Weights

A blending weight (sometimes called a "beta weight") controls the extent to which a given world matrix affects a vertex. Blending weights are floating-point values that range from 0.0 to 1.0, encoded in the vertex format, where a value of 0.0 means the vertex is not blended with that matrix, and 1.0 means that the vertex is affected in full by the matrix.

[C++]

Geometry blending weights are encoded in the vertex format, appearing immediately after the position for each vertex, as described in About Vertex Formats. You communicate the number of blending weights in the vertex format by including one of the D3DFVF_XYZB1 through D3DFVF_XYZB5 flexible vertex format flags in the vertex description that you provide to the Direct3D rendering methods.

[Visual Basic]

Geometry blending weights are encoded in the vertex format, appearing immediately after the position for each vertex, as described in About Vertex Formats. You communicate the number of blending weights in the vertex format by including one of the D3DFVF_XYZB1 through D3DFVF_XYZB5 flexible vertex format flags in the vertex description that you provide to the Direct3D rendering methods.

The system performs a linear blend between the weighted results of the blend matrices. The following is the complete blending formula:

In the preceding formula, vBlend is the output vertex, the v-elements are the vertices produced by the applied world matrix (D3DTRANSFORMSTATE_WORLDn). The W elements are the corresponding weight values within the vertex format. A vertex blended between n matrices can have n–1 blending weight values, one for each blending matrix, except the last. The system automatically generates the weight for the last world matrix such that the sum of all weights is 1.0, expressed in sigma notation here. This formula can be simplified for each of the cases currently supported by Direct3D:

The preceding are the simplified forms of the complete blending formula for the two, three, and four blend matrix cases (the only cases currently supported).

Note Although Direct3D includes flexible vertex format descriptors to define vertices that contain up to five blending weights, only three can be used in this release of DirectX.


Using Geometry Blending

The following topics are discussed:

  • Defining Vertices for Blending
  • Setting Blending Matrices
  • Enabling Geometry Blending


Defining Vertices for Blending

[C++]

The following user-defined structure could be used for vertices that will be blended between two matrices:

//
// The flexible vertex format descriptor for this vertex would be:
//
//     dwFVF = D3DFVF_XYZB1 | D3DFVF_NORMAL | D3DFVF_TEX1;
//
struct D3DBLENDVERTEX {
    D3DVECTOR v;
    FLOAT     blend;
    D3DVECTOR n;
    FLOAT     tu, tv;
};

As described in Blending Weights, the blend weight must appear after the position and RHW data in the flexible vertex format, and before the vertex normal.

Notice that the preceding vertex format contains only one blending weight value. This is because there will be two world matrices, defined in the D3DTRANSFORMSTATE_WORLD and D3DTRANSFORMSTATE_WORLD1 transform states. The system blends each vertex between these two matrices using the single weight value. For three matrices, only two weights are required, and so on.

[Visual Basic]

The following user-defined type could be used for vertices that will be blended between two matrices:

'
' The flexible vertex format descriptor for this vertex would be:
'
'     lFVF = (D3DFVF_XYZB1 Or D3DFVF_NORMAL Or D3DFVF_TEX1)
'
Type D3DBLENDVERTEX
    v As D3DVECTOR
    blend As Single
    n As D3DVECTOR
    tu As Single
    tv As Single
End Type

As described in Blending Weights, the blend weight must appear after the position and RHW data in the flexible vertex format, and before the vertex normal.

Notice that the preceding vertex format contains only one blending weight value. This is because there will be two world matrices, defined in the D3DTRANSFORMSTATE_WORLD and D3DTRANSFORMSTATE_WORLD1 transform states. The system blends each vertex between these two matrices using the single weight value. For three matrices, only two weights are required, and so on.

Note Defining skin weights is easy. Using a linear function of the distance between joints is good start, but a smoother sigmoid function will look better. Choosing a skin weight distribution function can result in sharp creases at joints if desired (by using a large variation in skin weight over a short distance).

See Also

About Vertex Formats, Flexible Vertex Format Flags


Setting Blending Matrices

[C++]

You set the transformation matrices between which the system blends by calling the IDirect3DDevice7::SetTransform method. Set the first parameter to one of the "D3DTRANSFORMSTATE_WORLD" members from the D3DTRANSFORMSTATETYPE enumerated type, and set the second parameter to the address of the matrix to be set.

The following C++ code fragment sets two world matrices, between which geometry will be blended to create the illusion of a jointed arm:

// For this example, the pd3dDevice variable is assumed to be a
// valid pointer to an IDirect3DDevice7 interface for an initialized
// 3-D scene.
float     fBendAngle = 3.1415926f / 4.0f; // 45 degrees
D3DMATRIX matUpperArm, matLowerArm;

// The upper arm is immobile, use the identity matrix.
D3DUtil_SetIdentityMatrix( matUpperArm );
pd3dDevice->SetTransform( D3DTRANSFORMSTATE_WORLD,  &matUpperArm );

// The lower arm rotates about the x-axis, attached to the upper arm.
D3DUtil_SetRotateXMatrix( matLowerArm, -fBendAngle );
pd3dDevice->SetTransform( D3DTRANSFORMSTATE_WORLD1, &matLowerArm );

Setting a blending matrix merely causes the system to cache the matrix for later use, it doesn't instruct the system to begin blending vertices. For more information, see Enabling Geometry Blending.

[Visual Basic]

You set the transformation matrices between which the system blends by calling the Direct3DDevice7.SetTransform method. Set the first parameter to one of the "D3DTRANSFORMSTATE_WORLD" members from the CONST_D3DTRANSFORMSTATETYPE enumeration, and set the second parameter to the address of the matrix to be set.

The following Visual Basic code fragment sets two world matrices, between which geometry will be blended to create the illusion of a jointed arm:

' For this example, the d3dDevice variable is assumed to be a
' valid reference to a Direct3DDevice7 object for an initialized
' 3-D scene. The dx variable is a valid reference to a DirectX7 object.
Dim nBendAngle As Single
Dim matUpperArm As D3DMATRIX, _
    matLowerArm As D3DMATRIX

nBendAngle = 3.1415926 / 4#  ' 45 degrees

' The upper arm is immobile, use the identity matrix.
Call dx.IdentityMatrix(matUpperArm)
Call d3dDevice.SetTransform(D3DTRANSFORMSTATE_WORLD, matUpperArm)

' The lower arm rotates about the x-axis, attached to the upper arm.
Call dx.RotateXMatrix(matLowerArm, -nBendAngle)
Call d3dDevice.SetTransform(D3DTRANSFORMSTATE_WORLD1, matLowerArm)

Setting a blending matrix merely causes the system to cache the matrix for later use, it doesn't instruct the system to begin blending vertices. For more information, see Enabling Geometry Blending.


Enabling Geometry Blending

[C++]

Geometry blending is disabled by default. To enable geometry blending, simply call the IDirect3DDevice7::SetRenderState method to set the D3DRENDERSTATE_VERTEXBLEND render state to a value from the D3DVERTEXBLENDFLAGS enumerated type. The following code fragment shows what this call might look like when setting the render state for a blend between two world matrices.

pd3dDevice->SetRenderState( D3DRENDERSTATE_VERTEXBLEND, D3DVBLEND_1WEIGHT );

When D3DRENDERSTATE_VERTEXBLEND is set to any value other than D3DVBLEND_DISABLE, the system assumes that the appropriate number of blending weights will be included in the vertex format. It is your responsibility to provide a compliant vertex format, and to provide a proper description of that format to the Direct3D rendering methods. For more information, see Defining Vertices for Blending.

When enabled, the system performs geometry blending for all objects rendered by the DrawPrimitive rendering methods.

[Visual Basic]

Geometry blending is disabled by default. To enable geometry blending, simply call the Direct3DDevice7.SetRenderState method to set the D3DRENDERSTATE_VERTEXBLEND render state to a value from the CONST_D3DVERTEXBLENDFLAGS enumeration. The following code fragment shows what this call might look like when setting the render state for a blend between two world matrices.

Call d3dDevice.SetRenderState(D3DRENDERSTATE_VERTEXBLEND, D3DVBLEND_1WEIGHT)

When D3DRENDERSTATE_VERTEXBLEND is set to any value other than D3DVBLEND_DISABLE, the system assumes that the appropriate number of blending weights will be included in the vertex format. It is your responsibility to provide a compliant vertex format, and to provide a proper description of that format to the Direct3D rendering methods. For more information, see Defining Vertices for Blending.

When enabled, the system performs geometry blending for all objects rendered by the DrawPrimitive rendering methods.


User-defined Clip Planes

Direct3D enables applications to clip geometry according to arbitrarily defined-clip planes. This following topics introduce user-defined clip planes, and provide information about how you can use them in your application.

  • What Are User-defined Clip Planes?
  • Using User-defined Clip Planes


What Are User-defined Clip Planes?

User-defined clip planes enable applications to clip geometry in a scene by applying arbitrary clip planes. These clipping planes are described by the general plane equation, which the system assumes to be in world-space.

The following image is taken from a version of the Spheremap sample, slightly modified to emphasize the effects of clipping. (The sample was modified to render in wire-frame, with back-face culling disabled.) In this image, no clip planes are applied.

When user-defined clipping planes are applied, you can easily clip the geometry in a scene. A point with world-coordinates coordinates (x, y, z) are clipped from the half space of the plane if the following inequality is satisfied.

In the preceding formula, A, B, C, and D are coefficients supplied by an application to the system to define a plane. Points that exist on or behind the clipping plane are clipped from the scene. The following image shows two teapots, clipped by two different planes.

The teapot on the left has been clipped by a plane that has the coefficients [A = -1.0, B = 0.0, C = 0.0, D = 0.0], which causes the system to clip all vertices with at x >=0. The teapot on the right was clipped by a plane defined by the coefficients [A = 1.0, B = 0.0, C = 1.0, D = 0.0], which clips all vertices at z >= 0.0.

You can clip geometry by clipping with multiple planes. When you use multiple clip planes, the rendered area is the union of the half-spaces defined by each plane. The following image shows the teapot clipped by two planes.

The teapot in the preceding image was clipped by two planes: one with the coefficients [A = 1.0, B = 0.0, C = 0.0, D = 0.0], and another plane defined by the [A = 0.0, B = -1.0, C = 0.0, D = 0.0] coefficients.

[C++]

Direct3D supports clipping with up to 32 (D3DMAXUSERCLIPPLANES) clipping planes, although device support can vary. To be sure, always check device capabilities for the current device (the wMaxUserClipPlanes member of the D3DDEVICEDESC7 structure).

[Visual Basic]

Direct3D supports clipping with up to 32 clipping planes, although device support can vary. To be sure, always check device capabilities for the current device (the nMaxUserClipPlanes member of the D3DDEVICEDESC7 type).

User-defined clip planes can be used for much more than the simple geometry clipping shown here, although this can be useful in many cases. You might combine user-defined clip planes and stencil buffers to perform advanced tasks like capping, or interference testing.


Using User-defined Clip Planes

User-defined clip planes are simple to define, manipulate, and enable. The following topics provide information about these common tasks.

  • Setting and Retrieving Clip Planes
  • Enabling and Disabling Clip Planes


Setting and Retrieving Clip Planes

[C++]

You set and retrieve user-defined clip planes by calling the IDirect3DDevice7::SetClipPlane and IDirect3DDevice7::GetClipPlane methods. The coefficients that describe the plane are in a four-element array of type D3DVALUE.

The SetClipPlane method accepts two parameters. The first parameter is the zero-based index of the clip plane being set, and the second parameter is the address of a buffer that contains the coefficients for the general plane equation.

Note The coefficients passed to SetClipPlane take the form of the general plane equation. If the values in the array you pass with the method were labeled A, B, C, and D (in the order they appear in memory), they would fit into the general plane equation so that Ax + By + Cz + D = 0. A point with world-space coordinates (x, y, z) is visible in the half space of the plane if Ax + By + Cz + D >= 0. Points that exist on or behind the clipping plane are clipped from the scene.

The following code shows how this method is called in C++.

// For this example, the pd3dDevice variable is a valid
// pointer to an IDirect3DDevice7 interface.

    // Set-up a clipping plane such that vertices with
    // x<=0 will be clipped.
    D3DVALUE clip[4];
    ZeroMemory( (LPVOID)clip, sizeof(clip) );

    clip[0] = 1.0f;
    pd3dDevice->SetClipPlane( 0, clip );

Setting coefficients for a clip plane does not enable clipping with that plane. For more information, see Enabling and Disabling Clip Planes.

You can define up to 32 (D3DMAXUSERCLIPPLANES) clip planes. Therefore, the highest index you can pass to the SetClipPlane method is 31. If you pass an invalid value, the method will fail, returning DDERR_INVALIDPARAMS.

The IDirect3DDevice7::GetClipPlane method is semantically similar to its counterpart. The following C++ code retrieves the coefficients currently set for the clip plane at index 2.

// For this example, the pd3dDevice variable is a valid
// pointer to an IDirect3DDevice7 interface.

    D3DVALUE clip[4];
    pd3dDevice->GetClipPlane( 2, clip );
[Visual Basic]

You set and retrieve user-defined clip planes by calling the Direct3DDevice7.SetClipPlane and Direct3DDevice7.GetClipPlane methods. The coefficients that describe the plane are in a four-element array of type D3DVALUE.

The first parameter to SetClipPlane is the zero-based index of the clip plane being set, and the remaining parameters contain the coefficients for the general plane equation.

Note The coefficients passed to SetClipPlane take the form of the general plane equation. If the values in the array you pass with the method were labeled A, B, C, and D (in the order they appear in memory), they would fit into the general plane equation so that Ax + By + Cz + D = 0. A point with world-space coordinates (x, y, z) is visible in the half space of the plane if Ax + By + Cz + D >= 0. Points that exist on or behind the clipping plane are clipped from the scene.

The following code shows how this method is called in Visual Basic.

' For this example, the d3dDevice variable is a valid
' reference to an Direct3DDevice object.

    ' Set-up a clipping plane such that vertices with
    ' x<=0 will be clipped.
    Dim A As Single, B As Single, _
        C As Single, D As Single

    A = 1#

    Call d3dDevice.SetClipPlane(0, A, B, C, D)

Setting coefficients for a clip plane does not enable clipping with that plane. For more information, see Enabling and Disabling Clip Planes.

You can define up to 32 (D3DMAXUSERCLIPPLANES) clip planes. Therefore, the highest index you can pass to the SetClipPlane method is 31. If you pass an invalid value, the method will fail, returning DDERR_INVALIDPARAMS.

The Direct3DDevice7.GetClipPlane method is semantically similar to its counterpart. The following Visual Basic code retrieves the coefficients currently set for the clip plane at index 2.

' For this example, the d3dDevice variable is a valid
' reference to an Direct3DDevice object.

    Dim A As Single, B As Single, _
        C As Single, D As Single

    Call d3dDevice.GetClipPlane(2, A, B, C, D)


Enabling and Disabling Clip Planes

[C++]

It's important to remember that clip planes are not automatically enabled when you call the IDirect3DDevice7::SetClipPlane method. Use the D3DRENDERSTATE_CLIPPLANEENABLE render state to enable or disable the clip planes currently set for the device. This render state accepts a DWORD value, where each bit starting with the least significant bit corresponds to a clip plane. If a bit is set, the clip plane is enabled; if the bit is cleared, the corresponding plane is disabled. In the value, bit 0 enables and disables clip plane at index zero, bit 1 controls clip plane one, and so on to bit 31. (Direct3D can clip with up to 32 planes at once, but device support can vary.) These semantics allow applications to enable or disable every clip plane in a single call.

The d3dtypes.h header file defines the D3DCLIPPLANEn macros to create patterns that you can combine and pass as values for the D3DRENDERSTATE_CLIPPLANEENABLE render state. The following C++ code uses this macro.

// For this example, the pd3dDevice variable is a valid
// pointer to an IDirect3DDevice7 interface.

    // Enable clip plane 0 and 1, while implicitly disabling
    // all other user-defined clip planes.
    pd3dDevice->SetRenderState( D3DRENDERSTATE_CLIPPLANEENABLE,
                                D3DCLIPPLANE0 | D3DCLIPPLANE1);
[Visual Basic]

It's important to remember that clip planes are not automatically enabled when you call the Direct3DDevice7.SetClipPlane method. Use the D3DRENDERSTATE_CLIPPLANEENABLE render state to enable or disable the clip planes currently set for the device. This render state values from the CONST_D3DCLIPPLANEFLAGS enumeration. Combine values from this enumeration to enable the corresponding clip plane, or omit them to disable the corresponding clip plane. (Use the D3DCPF_DISABLEALL value to disable all clip planes.) These semantics allow applications to enable or disable every clip plane in a single call.

The following Visual Basic code shows how this method is used.

' For this example, the d3dDevice variable is a valid
' reference to a Direct3DDevice7 object.

    ' Enable clip plane 0 and 1, while implicitly disabling
    ' all other user-defined clip planes.
    Call d3dDevice.SetRenderState(D3DRENDERSTATE_CLIPPLANEENABLE, _
                                  (D3DCPF_ENABLEPLANE0 Or D3DCPF_ENABLEPLANE1))


Environment Mapping

This section provides information about performing two common types of environment mapping with Direct3D Immediate Mode. There are many types of environment mapping in use throughout the graphics industry, but the following topics target the two most common forms: cubic environment mapping, and spherical environment mapping.

  • What Is Environment Mapping?
  • Cubic Environment Mapping
  • Spherical Environment Mapping


What Is Environment Mapping?

Environment mapping is a technique that simulates highly reflective surfaces without using ray-tracing. In practice, environment mapping applies a special texture map that contains an image of the scene surrounding an object to the object itself. The result approximates the appearance of a reflective surface, close enough to fool the eye, without incurring any of the expensive computations involved in ray-tracing.

The following image is taken from the Spheremap sample (C++) which, as its name implies, uses a type of environment mapping called "spherical environment mapping." For details, see Spherical Environment Mapping.

The teapot in the preceding image appears to reflect its surroundings, actually a texture being applied to the object. Because environment mapping uses a texture (combined with specially computed texture coordinates), it can be performed in real-time.


Cubic Environment Mapping

Cubic environment mapping textures an object with an image of the space or lighting effects surrounding the object, represented in the form of six internal faces of a cube. Information in this section is divided into the following topics:

  • What Are Cubic Environment Maps?
  • Creating Cubic Environment Map Surfaces
  • Accessing Cubic Environment Map Faces
  • Mipmapped Cubic Environment Maps
  • Rendering to Cubic Environment Maps
  • Texture Coordinates for Cubic Environment Maps


What Are Cubic Environment Maps?

A cubic environment maps—sometimes casually referred to as "cube maps"—are textures that contain image data representing the scene surrounding an object, as if the object were in the center of a cube. Each face of the cubic environment map covers a ninety degree field of view in the horizontal and vertical, and there are six faces per cube map. The orientation of the faces is given in the following illustration.

Each face of the cube is oriented perpendicular to the x/y, y/z, or x/z plane, in world space. The following figure shows how each plane corresponds to a face.

Cubic-environment maps are implemented as a series of attached texture surfaces, created in a single call, which can be accessed like any other set of attached surfaces. Applications can use static images for cubic-environment mapping, or they can render into the faces of the cube map to perform dynamic environment mapping. (This technique requires that the cube-map surfaces be valid render-target surfaces, created with the DDSCAPS_3DDEVICE capability.)

The faces of a cube map don't need to contain extremely detailed renderings of the surrounding scene. In most cases, environment maps are applied to curved surfaces. Given the amount of curvature used by most applications, the resulting reflective distortion makes extreme detail in the environment map wasteful in terms of memory and rendering overhead.


Creating Cubic-Environment Map Surfaces

You create a cubic environment map by calling the IDirectDraw7::CreateSurface method in C++ or DirectDraw7.CreateSurface in Visual Basic. Cube maps are complex surfaces; that is, they are a set of attached surfaces, created by DirectDraw in a single call. Surfaces that were created individually cannot be attached to each other to create a cubic-environment map. Cubic-environment map textures must be square, with dimensions that are a powers-of-two.

[C++]

The following code shows how your C++ application might create a simple cubic-environment map.

// For this example, the pDD variable is a valid pointer
// to an IDirectDraw7 interface.
DDSURFACEDESC2 ddsd;

ZeroMemory((LPVOID)&ddsd, sizeof(DDSURFACEDESC2));

ddsd.dwSize         = sizeof(DDSURFACEDESC2);
ddsd.dwFlags        = DDSD_CAPS | DDSD_WIDTH |
                      DDSD_HEIGHT | DDSD_PIXELFORMAT;
ddsd.ddsCaps.dwCaps = DDSCAPS_TEXTURE;

// Set the pixel format to a valid texture format here.

// Dimensions are an arbitrary, but must be a power-of-two.
ddsd.dwWidth  = 64;
ddsd.dwHeight = 64;

// Set caps for a system memory cube-map texture that is a valid
// render-target surface.
ddsd.ddsCaps.dwCaps  = DDSCAPS_COMPLEX | DDSCAPS_3DDEVICE |
                       DDSCAPS_TEXTURE;
ddsd.ddsCaps.dwCaps2 = DDSCAPS2_CUBEMAP|DDSCAPS2_CUBEMAP_ALLFACES;

LPDIRECTDRAWSURFACE7 pddsCubeMap;

// Create the cube map.
if( FAILED( pDD->CreateSurface( &ddsd, pddsCubeMap, NULL ) ) )
{
    // code to handle error goes here.
}

Note If you intend to render into the faces of a cube map, the surface description you provide when you create the surface must contain the DDSCAPS_3DDEVICE capability.

Cube maps can be managed textures. If you include either the DDSCAPS2_TEXTUREMANAGE or DDSCAPS2_TEXTUREMANAGE capability flag in the surface capabilities when you create the surface, the resulting texture will be managed. For more information, see Automatic Texture Management.

[Visual Basic]

The following Visual Basic code shows how your application might create a simple cubic-environment map.

' For this example, the dd variable is a valid reference
' to a DirectDraw7 object.
On Local Error Resume Next

Dim ddsd As DDSURFACEDESC2

ddsd.lFlags = DDSD_CAPS Or DDSD_WIDTH Or _
              DDSD_HEIGHT Or DDSD_PIXELFORMAT

ddsd.ddsCaps.dwCaps = DDSCAPS_TEXTURE

' Set the pixel format to a valid texture format here.

' Dimensions are an arbitrary, but must be a power-of-two.
ddsd.dwWidth = 64: ddsd.dwHeight = 64

' Set caps for a system memory cube-map texture that is a valid
' render-target surface.
ddsd.ddsCaps.dwCaps = DDSCAPS_COMPLEX Or DDSCAPS_3DDEVICE Or _
                      DDSCAPS_TEXTURE
ddsd.ddsCaps.dwCaps2 = DDSCAPS2_CUBEMAP Or DDSCAPS2_CUBEMAP_ALLFACES

Dim ddsCubeMap As DirectDrawSurface7

' Create the cube map.
Set ddsCubeMap = dd.CreateSurface(ddsd)

If Err.Number <> DD_OK Then
    ' code to handle error goes here.
End If

Note If you intend to render into the faces of a cube map, the surface description you provide when you create the surface must contain the DDSCAPS_3DDEVICE capability.

Cube maps can be managed textures. If you include either the DDSCAPS2_TEXTUREMANAGE or DDSCAPS2_TEXTUREMANAGE capability flag in the surface capabilities when you create the surface, the resulting texture will be managed. For more information, see Automatic Texture Management.


Accessing Cubic Environment Map Faces

[C++]

Like any other complex surface, you navigate between faces of a cubic environment map by using the IDirectDrawSurface7::GetAttachedSurface method. The GetAttachedSurface method accepts a pointer to a DDSCAPS2 structure that describes the attached surface the method should retrieve. Set the dwCaps2 member to any of the flag values beginning with "DDSCAPS2_CUBEMAP_", combined with the DDSCAPS2_CUBEMAP flag, to retrieve the corresponding face.

The following code retrieves the cube-map surface used for the positive-y face (face 2).

// For this example, the pddsMainFace variable contains a valid
// pointer to the face returned by CreateSurface when the cube map
// was originally created.
LPDIRECTDRAWSURFACE7 pddsFace2;

DDSCAPS2 ddsCaps;
ddsCaps.dwCaps2 = DDSCAPS2_CUBEMAP_POSITIVEY | DDSCAPS2_CUBEMAP;

HRESULT hr;
hr = pddsMainFace->GetAttachedSurface( &ddsCaps,
                                       &pddsFace2);

if( FAILED(hr) )
{
    // code to handle error goes here.
}
[Visual Basic]

Like any other complex surface, you navigate between faces of a cubic environment map by using the DirectDrawSurface7.GetAttachedSurface method. The GetAttachedSurface method accepts a DDSCAPS2 type that describes the attached surface the method should retrieve. Set the lCaps2 member to any of the flag values from the CONST_DDSURFACECAPS2FLAGS enumeration that begin with "DDSCAPS2_CUBEMAP_", combined with the DDSCAPS2_CUBEMAP flag, to retrieve the corresponding face.

The following code retrieves the cube-map surface used for the positive-y face (face 2).

' For this example, the ddsMainFace variable contains a valid
' reference to the face returned by CreateSurface when the cube map
' was originally created.
Dim ddsFace2 As DirectDrawSurface7
Dim ddsCaps As DDSCAPS2

ddsCaps.lCaps2 = DDSCAPS2_CUBEMAP_POSITIVEY Or DDSCAPS2_CUBEMAP

Set ddsFace2 = ddsMainFace.GetAttachedSurface(ddsCaps)

If Err.Number <> DD_OK Then
    ' code to handle error goes here.
End If


Mipmapped Cubic Environment Maps

Cube maps can be mipmapped. If you include the DDSCAPS_MIPMAP capability, the system creates each face with attached mipmap surfaces. You might envision the topography of these surfaces as follows:

[C++]

Applications that create mipmapped cubic-environment maps can access each face by calling the IDirectDrawSurface7::GetAttachedSurface method, passing a one of the flags that begins with "DDSCAPS2_CUBEMAP_" flag to access the corresponding face (as discussed in Accessing Cubic Environment Map Faces). Then, the subordinate mipmap levels can be retrieved by calling the IDirectDrawSurface7::GetAttachedSurface for that face, passing the DDSCAPS_MIPMAP flag.

[Visual Basic]

Applications that create mipmapped cubic-environment maps can access each face by calling the DirectDrawSurface7.GetAttachedSurface method, passing a one of the flags from the CONST_DDSURFACECAPS2FLAGS enumeration that begins with "DDSCAPS2_CUBEMAP_" to access the corresponding face (as discussed in Accessing Cubic Environment Map Faces). Then, the subordinate mipmap levels can be retrieved by calling the DirectDrawSurface7.GetAttachedSurface for that face, passing the DDSCAPS_MIPMAP flag.


Rendering to Cubic Environment Maps

If you create a cubic environment map with the DDSCAPS_3DDEVICE capability, you can render to the individual faces of the cube map just like you would any other render-target surface. The most important thing to do before rendering to a face is set the transformation matrices such that the camera is positioned properly and points in the proper direction for that face: forward (+z), backward (-z), left (-x), right (+x), up (+y), or down (-y).

[C++]

The following C++ code prepares and sets a view matrix according to the face being rendered.

//
// The ppddsFaces variable is the address of an array of IDirectDrawSurface7
// interface pointers, one for each face.
//
void RenderFaces(LPDIRECTDRAWSURFACE7* ppddsFaces)
{
    // Loop through the six faces of the cube map.
    for( DWORD i=0; i<6; i++ )
    {
        DDSCAPS2 ddsc;
        ZeroMemory( (LPVOID)&ddsc, sizeof(DDSCAPS2) );

        // Get the surface caps (so we can find out which face this is).
        ppddsFaces[i]->GetCaps( &ddsc );

        // Standard view that will be overridden below
        D3DVECTOR vEnvEyePt = D3DVECTOR( 0.0f, 0.0f, 0.0f );
        D3DVECTOR vLookatPt, vUpVec;

        switch( ddsc.dwCaps2 & DDSCAPS2_CUBEMAP_ALLFACES )
        {
            case DDSCAPS2_CUBEMAP_POSITIVEX:
                vLookatPt = D3DVECTOR( 1.0f, 0.0f, 0.0f );
                vUpVec    = D3DVECTOR( 0.0f, 1.0f, 0.0f );
                break;
            case DDSCAPS2_CUBEMAP_NEGATIVEX:
                vLookatPt = D3DVECTOR(-1.0f, 0.0f, 0.0f );
                vUpVec    = D3DVECTOR( 0.0f, 1.0f, 0.0f );
                break;
            case DDSCAPS2_CUBEMAP_POSITIVEY:
                vLookatPt = D3DVECTOR( 0.0f, 1.0f, 0.0f );
                vUpVec    = D3DVECTOR( 0.0f, 0.0f,-1.0f );
                break;
            case DDSCAPS2_CUBEMAP_NEGATIVEY:
                vLookatPt = D3DVECTOR( 0.0f,-1.0f, 0.0f );
                vUpVec    = D3DVECTOR( 0.0f, 0.0f, 1.0f );
                break;
            case DDSCAPS2_CUBEMAP_POSITIVEZ:
                vLookatPt = D3DVECTOR( 0.0f, 0.0f, 1.0f );
                vUpVec    = D3DVECTOR( 0.0f, 1.0f, 0.0f );
                break;
            case DDSCAPS2_CUBEMAP_NEGATIVEZ:
                vLookatPt = D3DVECTOR( 0.0f, 0.0f,-1.0f );
                vUpVec    = D3DVECTOR( 0.0f, 1.0f, 0.0f );
                break;
        }

        D3DMATRIX matView;
        D3DUtil_SetViewMatrix( matView, vEnvEyePt, vLookatPt, vUpVec );
        g_pd3dDevice->SetTransform( D3DTRANSFORMSTATE_VIEW, &matView );

Remember, each face of a cubic-environment map represents a 90-degree field of view. Unless your application requires a different field of view angle (for special effects, perhaps), take care to set the projection matrix accordingly.

This code creates and sets a projection matrix for the most common case.

        // Use 90-degree field of view in the projection.
        D3DMATRIX matProj;
        D3DUtil_SetProjectionMatrix( matProj, g_PI/2, 1.0f, 0.5f, 1000.0f );
        g_pd3dDevice->SetTransform( D3DTRANSFORMSTATE_PROJECTION, &matProj );

Once the camera is in position, and the projection matrix set, you can render the scene. Each object in the scene should be positioned as you would normally position them. The following code, provided for completeness, outlines this task.

        //
        // Render the scene.
        //

        // Swap the depth-buffer to a face, then sets it as the render target.
        // This function is described in more detail later.
        ChangeRenderTarget( ppddsFaces[i] );

        // Clear the zbuffer.
        g_pd3dDevice->Clear( 0, NULL, D3DCLEAR_ZBUFFER, 0x000000ff, 1.0f, 0L );

        // Enable antialiasing, it makes the environment maps look better.
        g_pd3dDevice->SetRenderState( D3DRENDERSTATE_ANTIALIAS,
                                      D3DANTIALIAS_TRANSLUCENTSORTINDEPENDENT );

        // Begin the scene.
        if( SUCCEEDED( g_pd3dDevice->BeginScene() ) )
        {
            // Position the geometry of the scene, as normal, by setting the
            // world matrix for each object to be rendered.

            g_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST,
                                         D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_TEX1 | D3DFVF_TEXCOORDSIZE3(0),
                                         lpVertices, VERTEX_COUNT, 0);

            // End the scene.
            g_pd3dDevice->EndScene();
        }
    }
}

Note Most applications should enable antialiasing when rendering to the faces of a cubic environment map. Because each face is relatively small, enabling antialiasing when rendering to them can noticeably improve the appearance of the resulting environment map.

Notice the call to the ChangeRenderTarget function. When rendering to the cube map faces, you must of course assign the face as the current render-target surface. Applications that use depth buffers can explicitly create a depth-buffer for the render-target, or reassign an existing depth-buffer to the render-target surface. The following code uses the latter method.

HRESULT ChangeRenderTarget( LPDIRECTDRAWSURFACE7 pddsNewTarget)
{
    LPDIRECTDRAWSURFACE7 pddsOldRenderTarget = NULL;
    g_pd3dDevice->GetRenderTarget( &pddsOldRenderTarget );

    if( pddsOldRenderTarget )
    {
        LPDIRECTDRAWSURFACE7 pddsZBuffer = NULL;
        DDSCAPS2 ddscaps = { DDSCAPS_ZBUFFER, 0, 0, 0 };
        pddsOldRenderTarget->GetAttachedSurface( &ddscaps, &pddsZBuffer );

        if( pddsZBuffer )
        {
            pddsOldRenderTarget->DeleteAttachedSurface( 0, pddsZBuffer );
            pddsNewRenderTarget->AddAttachedSurface( pddsZBuffer );
            pddsZBuffer->Release();
        }
        pddsOldRenderTarget->Release();
    }

    g_pd3dDevice->SetRenderTarget( pddsNewRenderTarget, 0 );
    return S_OK;
}
[Visual Basic]

The following Visual Basic code prepares and sets a view matrix according to the face being rendered.

'
' The ddsFaces variable is the address of an array of DirectDrawSurface7
' objects, one for each face.
'
Sub RenderFaces(ddsFaces() As DirectDrawSurface7)
    Dim i As Integer

    ' Loop through the six faces of the cube map.
    For i = 0 To UBound(ddsFaces)
        Dim ddsc As DDSCAPS2
        Dim vEnvEyePt As D3DVECTOR, _
            vLookatPt As D3DVECTOR, _
            vUpVec As D3DVECTOR

        ' Get the surface caps (so we can find out which face this is).
        Call ddsFaces(i).GetCaps(ddsc)

        Select Case (ddsc.dwCaps2 And DDSCAPS2_CUBEMAP_ALLFACES)
            Case DDSCAPS2_CUBEMAP_POSITIVEX:
                vLookatPt.x = 1#: vUpVec.y = 1#

            Case DDSCAPS2_CUBEMAP_NEGATIVEX:
                vLookatPt.x = -1#: vUpVec = 1#

            Case DDSCAPS2_CUBEMAP_POSITIVEY:
                vLookatPt.y = 1#: vUpVec.z = -1#

            Case DDSCAPS2_CUBEMAP_NEGATIVEY:
                vLookatPt.y = -1#: vUpVec.z = 1#

            Case DDSCAPS2_CUBEMAP_POSITIVEZ:
                vLookatPt.z = 1#: vUpVec.y = 1#

            Case DDSCAPS2_CUBEMAP_NEGATIVEZ:
                vLookatPt.z = -1#: vUpVec.y = 1#

        End Select

        Dim matView As D3DMATRIX
        Call g_dx.ViewMatrix(matView, vEnvEyePt, vLookatPt, vUpVec)
        Call g_pd3dDevice.SetTransform(D3DTRANSFORMSTATE_VIEW, matView)

Remember, each face of a cubic-environment map represents a 90-degree field of view. Unless your application requires a different field of view angle (for special effects, perhaps), take care to set the projection matrix accordingly.

This code creates and sets a projection matrix for the most common case.

        ' Use 90-degree field of view in the projection.
        Dim matProj As D3DMATRIX
        Call g_dx.ProjectionMatrix(matProj, 0.5, 1000#, 3.1415926535 / 2)
        Call g_d3dDevice.SetTransform(D3DTRANSFORMSTATE_PROJECTION, matProj)

Once the camera is in position, and the projection matrix set, you can render the scene. Each object in the scene should be positioned as you would normally position them. The following code, provided for completeness, outlines this task.

        '
        ' Render the scene.
        '

        ' Swap the depth-buffer to a face, then sets it as the render target.
        ' This function is described in more detail later.
        Call ChangeRenderTarget(ddsFaces(i))

        Dim rec(1) As RECT
        rec.Top = 0: rec.Left = 0

        ' This assumes surface dimensions of 64 by 64
        rec.Bottom = 64: rec.Right = 64

        ' Clear the zbuffer.
        Call g_d3dDevice.Clear(0, rec(), D3DCLEAR_ZBUFFER, _
                               g_dx.CreateColorRGBA(0, 0, 256, 0), 1#, 0)

        ' Enable antialiasing, it makes the environment maps look better.
        Call g_d3dDevice.SetRenderState(D3DRENDERSTATE_ANTIALIAS, _
                                        D3DANTIALIAS_TRANSLUCENTSORTINDEPENDENT)

        ' Begin the scene.
        Call g_d3dDevice.BeginScene
        If Err.Number = DD_OK Then
            ' Position the geometry of the scene, as normal, by setting the
            ' world matrix for each object to be rendered.

            Call g_pd3dDevice.DrawPrimitive(D3DPT_TRIANGLELIST, D3DFVF_XYZ Or D3DFVF_NORMAL Or _
                                            D3DFVF_TEX1 Or D3DFVF_TEXCOORDSIZE3(0), _
                                            g_Vertices(0), VERTEX_COUNT, 0)

            ' End the scene.
            Call g_d3dDevice.EndScene
        End If
    Next i
End Sub

Note Most applications should enable antialiasing when rendering to the faces of a cubic environment map. Because each face is relatively small, enabling antialiasing when rendering to them can noticeably improve the appearance of the resulting environment map.

Notice the call to the ChangeRenderTarget subroutine. When rendering to the cube map faces, you must of course assign the face as the current render-target surface. Applications that use depth buffers can explicitly create a depth-buffer for the render-target, or reassign an existing depth-buffer to the render-target surface. The following code uses the latter method.

Sub ChangeRenderTarget(ddsNewTarget As DirectDrawSurface7)
    Dim ddsOldRenderTarget As DirectDrawSurface7

    Set ddsOldRenderTarget = g_pd3dDevice.GetRenderTarget

    If (ddsOldRenderTarget Is Not Nothing) Then
        Dim ddsZBuffer As DirectDrawSurface7
        Dim ddscaps As DDSCAPS2

        ddscaps.lCaps = DDSCAPS_ZBUFFER
        Set ddsZBuffer = ddsOldRenderTarget.GetAttachedSurface

        If (ddsZBuffer Is Not Nothing) Then
            Call ddsOldRenderTarget.DeleteAttachedSurface(ddsZBuffer)
            Call ddsNewRenderTarget.AddAttachedSurface(ddsZBuffer)
        End If
    End If

    Call g_pd3dDevice.SetRenderTarget(pddsNewRenderTarget)
End Sub


Texture Coordinates for Cubic Environment Maps

[C++]

Texture coordinates that index a cubic-environment map aren't the simple u, v style coordinates used when standard textures are applied. In fact, cubic environment maps don't really use texture coordinates at all. In the place of a set of texture coordinates, cubic environment maps require a 3-D vector. You must take care to specify a proper vertex format. In addition to telling the system how many sets of texture coordinates your application uses, you must provide information about how many elements are in each set. Direct3D offers the D3DFVF_TEXCOORDSIZEn set of macros for this purpose. These macros accept a single parameter, identifying the index of the texture coordinate set for which the size is being described. In the case of a 3-D vector, you would include the bit pattern created by the D3DFVF_TEXCOORDSIZE3 macro. The following code shows how this macro is used.

// Create a flexible vertex format descriptor for a vertex that
// contains a position, normal, and one set of 3-D texture
// coordinates.
DWORD dwFVF = D3DFVF_XYZ | D3DFVF_NORMAL |
              D3DFVF_TEX1 | D3DFVF_TEXCOORDSIZE3(0);

In some cases, such as diffuse light mapping, you will use the camera-space vertex normal for the vector. In other cases, like specular environment mapping, you would use a reflection vector. (Because transformed vertex normals are widely understood, the information here concentrates on computing a reflection vector.)

Computing a reflection vector on your own requires understanding of the position of each vertex, and a vector from the viewpoint to that vertex. Direct3D can automatically compute the reflection vectors for your geometry. Using this feature saves memory (you don't need to include texture coordinates for the environment map); it reduces bandwidth; and in the case of a TnLHAL Device, it can be significantly faster than the computations your application could make on its own. To take advantage of this feature, in the texture stage that contains the cubic-environment map, simply set the D3DTSS_TEXCOORDINDEX texture stage state to a combination of the D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR flag and the index of a texture coordinate set. (In some situations, like diffuse light mapping, you might use the D3DTSS_TCI_CAMERASPACENORMAL flag, which causes the system to use the transformed, camera-space, vertex normal as the addressing vector for the texture.) The index is only used by the system to determine the wrapping mode for the texture.

The following code shows how this value is used.

// The pd3dDevice variable is a valid pointer to an
// IDirect3DDevice7 interface.

// Automatically generate texture coordinates for stage 2. T
// This assumes that stage 2 is assigned a cube map.
// (Use the wrap mode from the texture coord set at index 1.)
pd3dDevice->SetTextureStageState( 2, D3DTSS_TEXCOORDINDEX,
                                  D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR | 1);

When you enable automatic texture coordinate generation, the system uses one of two formulas to compute the reflection vector for each vertex. When the D3DRENDERSTATE_LOCALVIEWER render state is set to TRUE, the formula used is the following:

In the preceding formula, R is the reflection vector being computed, E is the normalized position-to-eye vector, and N is the camera-space vertex normal.

When the D3DRENDERSTATE_LOCALVIEWER render state is set to FALSE, the system uses the following formula.

The R and N elements in this formula are identical to the previous formula. The Nz element is the world-space z of the vertex normal, and I is the vector (0,0,1) of an infinitely distant viewpoint. The system uses the reflection vector from either formula to select and address the appropriate face of the cube map.

Note In most cases, applications should enable automatic normalization of vertex normals. To do this, set D3DRENDERSTATE_NORMALIZENORMALS to TRUE. If you do not enable this render state, the appearance of the environment map will be drastically different than you might expect.

[Visual Basic]

Texture coordinates that index a cubic-environment map aren't the simple u, v style coordinates used when standard textures are applied. In fact, cubic environment maps don't really use texture coordinates at all. In the place of a set of texture coordinates, cubic environment maps require a 3-D vector. You must take care to specify a proper vertex format. In addition to telling the system how many sets of texture coordinates your application uses, you must provide information about how many elements are in each set. Direct3D offers the D3DFVF_TEXCOORDSIZEn set of helper functions in the Math.bas source file for this purpose. (The Math.bas file ships with this SDK.) These accept a single parameter, identifying the index of the texture coordinate set for which the size is being described. In the case of a 3-D vector, you would include the bit pattern created by the D3DFVF_TEXCOORDSIZE3 helper-function. The following code shows how this function is used.

' Create a flexible vertex format descriptor for a vertex that
' contains a position, normal, and one set of 3-D texture
' coordinates.
Dim lFVF As Long
lFVF = D3DFVF_XYZ Or D3DFVF_NORMAL Or
       D3DFVF_TEX1 Or D3DFVF_TEXCOORDSIZE3(0)

In some cases, such as diffuse light mapping, you will use the camera-space vertex normal for the vector. In other cases, like specular environment mapping, you would use a reflection vector. (Because transformed vertex normals are widely understood, the information here concentrates on computing a reflection vector.)

Computing a reflection vector on your own requires understanding of the position of each vertex, and a vector from the viewpoint to that vertex. Direct3D can automatically compute the reflection vectors for your geometry. Using this feature saves memory (you don't need to include texture coordinates for the environment map); it reduces bandwidth; and in the case of a TnLHAL Device, it can be significantly faster than the computations your application could make on its own. To take advantage of this feature, in the texture stage that contains the cubic-environment map, simply set the D3DTSS_TEXCOORDINDEX texture stage state to a combination of the D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR flag and the index of a texture coordinate set. (In some situations, like diffuse light mapping, you might use the D3DTSS_TCI_CAMERASPACENORMAL flag, which causes the system to use the transformed, camera-space, vertex normal as the addressing vector for the texture.) The index is only used by the system to determine the wrapping mode for the texture.

The following code shows how this value is used.

' The pd3dDevice variable is a valid reference to a
' Direct3DDevice7 object.

' Automatically generate texture coordinates for stage 2. T
' This assumes that stage 2 is assigned a cube map.
' (Use the wrap mode from the texture coord set at index 1.)
Call d3dDevice.SetTextureStageState(2, D3DTSS_TEXCOORDINDEX,
                                    D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR Or 1)

When you enable automatic texture coordinate generation, the system uses one of two formulas to compute the reflection vector for each vertex. When the D3DRENDERSTATE_LOCALVIEWER render state is set to True, the formula used is the following:

In the preceding formula, R is the reflection vector being computed, E is the normalized position-to-eye vector, and N is the camera-space vertex normal.

When the D3DRENDERSTATE_LOCALVIEWER render state is set to False, the system uses the following formula.

The R and N elements in this formula are identical to the previous formula. The Nz element is the world-space z of the vertex normal, and I is the vector (0,0,1) of an infinitely distant viewpoint. The system uses the reflection vector from either formula to select and address the appropriate face of the cube map.

Note In most cases, applications should enable automatic normalization of vertex normals. To do this, set D3DRENDERSTATE_NORMALIZENORMALS to True. If you do not enable this render state, the appearance of the environment map will be drastically different than you might expect.


Spherical Environment Mapping

Spherical environment mapping—often called "sphere mapping"—textures an object with an image or lighting effects of the space surrounding the object, where that space is encoded into a specially formatted texture map. The following topics introduce the concept of sphere mapping, and provide information about how you can use it in your Direct3D applications.

  • What Are Spherical Environment Maps?
  • Texture Coordinates for Spherical Environment Maps
  • Applying Spherical Environment Maps


What Are Spherical Environment Maps?

Spherical environment maps, or "sphere maps," are special textures that contain an image of the scene surrounding an object, or the lighting effects around the object. Unlike cubic environment maps, sphere maps don't directly represent an object's surroundings. The teapot image in the What Is Environment Mapping? topic shows the reflection effects you can achieve with sphere mapping.

A sphere map is a 2-D representation of the full 360 degree view of the scene surrounding of an object, as if taken through a fish-eye lens. The following is the sphere map in use by the Spheremap sample (C++).


Texture Coordinates for Spherical Environment Maps

The texture coordinates you specify for each vertex receiving an environment mapping should address the texture as a function of the reflective distortion created by the curvature of the surface. Applications must compute these texture coordinates for each vertex to achieve the desired effect. One very simple and effective way to generate texture coordinates uses the vertex normal as input. Although several methods exist, the following formula is common among applications that perform environment mapping with sphere maps.

In the preceding formulas, u and v are the texture coordinates being computed, and Nx and Ny are the x and y components of the camera-space vertex normal. The preceding formula is simple, but effective. If the normal has a positive x component, the normal points to the right, and the u coordinate is adjusted to address the texture appropriately. Likewise for the v coordinate: positive y indicates that the normal points up. The opposite is of course true for negatve values in each component.

If the normal points directly at the camera, the resulting coordinates should receive no distortion. The +0.5 bias to both coordinates places the point of zero-distortion at the center of the sphere map, and a vertex normal of (0, 0, z) addresses this point. Note that this formula doesn't take account for the z component of the normal, but applications that use the formula might optimize their computations by skipping vertices with a normal that has a positive z element. This works because, in camera space, if the normal points away from the camera (positive z), the vertex will be culled when the object is rendered.


Applying Spherical Environment Maps

[C++]

You apply an environment map to objects in the same manner you would any other texture, by setting the texture into the appropriate texture stage with the IDirect3DDevice7::SetTexture method. Set the first parameter to the index for the desired texture stage, and set the second parameter to the address of the IDirectDrawSurface7 interface returned when you created the texture for the environment map. You can set the color and alpha blending operations and arguments as needed to achieve the desired texture blending effects.

[Visual Basic]

You apply an environment map to objects in the same manner you would any other texture, by setting the texture into the appropriate texture stage with the Direct3DDevice7.SetTexture method. Set the first parameter to the index for the desired texture stage, and set the second parameter to the DirectDrawSurface7 object returned when you created the texture for the environment map. You can set the color and alpha blending operations and arguments as needed to achieve the desired texture blending effects.


Bump Mapping

This section provides information about performing bump mapping with Direct3D. The following topics introduce the bump mapping, identify and define its key concepts, and provide details about how you can use bump-mapping in your applications.

  • What Is Bump Mapping?
  • Bump Map Pixel Formats
  • Bump Mapping Formulas
  • Using Bump Mapping


What Is Bump Mapping?

Bump mapping is a special form of specular or diffuse environment mapping that simulates the reflections of finely tessellated objects without requiring extremely high polygon counts. The following image, based on the BumpEarth sample, demonstrates bump mapping effects.

The globe on the left is a sphere textured with an image of the Earth's surface, with a specular environment map applied. The globe on the right is exactly the same, but also applies a bump map. The polygon count for the second globe is unchanged from that of the first globe.

Bump mapping in Direct3D can be accurately described as "per-pixel texture coordinate perturbation of specular or diffuse environment maps," because you provide information about the contour of the bump map in terms of delta-values, which the system applies to the u and v texture coordinates of an environment map in the next texture stage. The delta values are encoded in the pixel format of the bump map surface. For more information, see Bump Map Pixel Formats.

The BumpEarth sample uses a height-map to store contour data. When the sample starts, it processes the pixels in the height map to compute the appropriate u and v delta values (based on the relative height of each pixel to the four neighboring pixels).

Note Direct3D does not natively support height-maps, they are merely a convenient format in which to store and visualize contour data. The preceding image is based on the height map used by the BumpEarth sample to produce the bump map it supplies to Direct3D, and is included here for descriptive purposes. Your application can store contour information in any format, or even generate a procedural bump map, as the BumpWaves sample does.

This is the height map image that the BumpEarth sample uses to compute the delta values encoded in the pixel format of the bump map texture.

Bump mapping relies completely on multiple texture blending services, and requires that the device support at least two blending stages—one for the bump map, and another for an environment map. A minimum of three texture blending stages are required to apply a base texture map (the most common case). The following figure shows the relationships between the base texture, the bump map, and the environment map in the texture blending cascade.

You must prepare the texture stages appropriately to enable bump mapping. This task is the topic of Configuring Bump Mapping Parameters.


Bump Map Pixel Formats

A bump map is a DirectDraw surface object that uses a specialized pixel format. Rather than storing red, green, and blue color components, each pixel in a bump map stores the delta values for u and v (Du and Dv) and sometimes a luminance component, L. These values are applied by the system as described in the Bump Mapping Formulas topic.

[C++]

Like any other surface, you specify a bump map pixel format by using a DDPIXELFORMAT structure. The DDPF_BUMPDUDV flag in the dwFlags member of the structure identifies a pixel format for a bump map texture. When the flag is present, the dwBumpBitCount, dwBumpDuBitMask, dwBumpDvBitMask, and dwBumpLuminanceBitMask members can be used to describe the bit depth for the bump map, and the mask values for each pixel component.

The Du and Dv components of a pixel are signed values that range from –1.0 to +1.0. The luminance component, when used, is an unsigned integer value that ranges from 0 to 255.

Note You should enumerate supported bump map pixel formats by calling the IDirect3DDevice7::EnumTextureFormats method. For more information, see Detecting Support for Bump Mapping.

[Visual Basic]

Like any other surface, you specify a bump map pixel format by using a DDPIXELFORMAT type. The DDPF_BUMPDUDV flag in the lFlags member of the type identifies a pixel format for a bump map texture. When the flag is present, the lBumpBitCount, lBumpDuBitMask, lBumpDvBitMask, and lBumpLuminanceBitMask members can be used to describe the bit depth for the bump map, and the mask values for each pixel component.

The Du and Dv components of a pixel are signed values that range from –1.0 to +1.0. The luminance component, when used, is an unsigned integer value that ranges from 0 to 255.

Note You should enumerate supported bump map pixel formats to ensure that the pixel format you intend to use is valid. Call the Direct3DDevice7.GetTextureFormatsEnum method to retrieve a reference to a Direct3DEnumPixelFormats enumerator class for texture formats. Use the enumerator to retrieve information about the supported texture formats, including bump map formats. For more information, see Detecting Support for Bump Mapping.


Bump Mapping Formulas

[C++]

Direct3D applies the following formulas to the Du and Dv components in each bump map pixel.

In the preceding formulas, the Du and Dv variables are taken directly from a bump map pixel, and transformed by a 2×2 matrix to produce the output delta values Du' and Dv'. The system uses the output values to modify the texture coordinates that address the environment map in the next texture stage. The coefficients of the transformation matrix are set though the D3DTSS_BUMPENVMAT00, D3DTSS_BUMPENVMAT10, D3DTSS_BUMPENVMAT01, and D3DTSS_BUMPENVMAT11 texture stage states.

In addition to the u and v delta values, the system can compute a luminance value it uses to modulate the color of the environment map in the next blending stage.

In the preceding formula, L' is the output luminance being computed. The L variable is the luminance value taken from a bump map pixel, which is multiplied by the scaling factor, S, and offset by the value in the variable O. The D3DTSS_BUMPENVLSCALE and D3DTSS_BUMPENVLOFFSET texture stage states control the values for the S and O variables in the formula. This formula is only applied when the texture blending operation for the stage that contains the bump map is set to D3DTOP_BUMPENVMAPLUMINANCE. When using D3DTOP_BUMPENVMAP, the system uses a value of 1.0 for L'.

After computing the output delta values Du' and Dv', the system adds them to the texture coordinates in the next texture stage, and modulates the chosen color by the luminance to produce the color applied to the polygon.

[Visual Basic]

Direct3D applies the following formulas to the Du and Dv components in each bump map pixel.

In the preceding formulas, the Du and Dv variables are taken directly from a bump map pixel, and transformed by a 2×2 matrix to produce the output delta values Du' and Dv'. The system uses the output values to modify the texture coordinates that address the environment map in the next texture stage. The coefficients of the transformation matrix are set though the D3DTSS_BUMPENVMAT00, D3DTSS_BUMPENVMAT10, D3DTSS_BUMPENVMAT01, and D3DTSS_BUMPENVMAT11 texture stage states.

In addition to the u and v delta values, the system can compute a luminance value it uses to modulate the color of the environment map in the next blending stage.

In the preceding formula, L' is the output luminance being computed (L' is clamped to the range of 0.0 to 1.0, inclusive). The L variable is the luminance value taken from a bump map pixel, which is multiplied by the scaling factor, S, and offset by the value in the variable O. The D3DTSS_BUMPENVLSCALE and D3DTSS_BUMPENVLOFFSET texture stage states control the values for the S and O variables in the formula. This formula is only applied when the texture blending operation for the stage that contains the bump map is set to D3DTOP_BUMPENVMAPLUMINANCE. When using D3DTOP_BUMPENVMAP, the system uses a value of 1.0 for L'.

After computing the output delta values Du' and Dv', the system adds them to the texture coordinates in the next texture stage, and modulates the chosen color by the luminance to produce the color applied to the polygon.


Using Bump Mapping

The following topics in this section provide details about the most common tasks your application will need to perform when using Direct3D bump mapping.

  • Detecting Support For Bump Mapping
  • Creating a Bump Map Texture
  • Configuring Bump Mapping Parameters


Detecting Support For Bump Mapping

[C++]

A Direct3D device can perform bump mapping if it supports either of the D3DTOP_BUMPENVMAP or D3DTOP_BUMPENVMAPLUMINANCE texture blending operations. Additionally, applications should check the device capabilities to make sure it supports an appropriate number of blending stages (usually at least 3) and exposes at least one bump mapping pixel format.

The following code checks device capabilities to detect support for bump mapping in the current device, using the given criteria.

BOOL SupportsBumpMapping()
{
    DDPIXELFORMAT ddpfBumpMap;
    D3DDEVICEDESC7 d3dDevDesc;
    ZeroMemory( &d3dDevDesc, sizeof(d3dDevDesc) );

    // Get the device capabilities.
    g_pd3dDevice->GetCaps( &d3dDevDesc );

    // Does this device support the two bump mapping blend operations?
    DWORD dwBumpOps = d3dDevDesc.dwTextureOpCaps &
                      (D3DTEXOPCAPS_BUMPENVMAP | D3DTEXOPCAPS_BUMPENVMAPLUMINANCE);
    if ( 0 == dwBumpOps)
        return FALSE;

    // Does this device support up to three blending stages?
    if( d3dDevDesc.wMaxTextureBlendStages < 3)
        return FALSE;

    //
    // Check for valid bump map pixel formats.
    //

    // The g_bFoundBumpFormat global variable will be set to TRUE
    // by the callback function if a valid format is found.
    g_bFoundBumpFormat = FALSE;

    g_pd3dDevice->EnumTextureFormats(TextureCallback, (LPVOID) &ddpfBumpMap);
    if( FALSE == g_bFoundBumpFormat )
        return FALSE;

    // The pixel format now in ddpfBumpMap can be used to create
    // a surface format that's guaranteed to be valid.
    return TRUE;
}

The following is the code for the callback function passes to the IDirect3DDevice7::EnumTextureFormats method.

HRESULT CALLBACK TextureCallback( DDPIXELFORMAT* pddpf, VOID* pddpfOut)
{
    // Take the first enumerated DuDv format.
    if( DDPF_BUMPDUDV == pddpf->dwFlags ){
        // Copy the format into the variable at pddpfOut
        // for use when creating the surface later.
        memcpy( pddpfOut, (LPVOID)pddpf, sizeof(DDPIXELFORMAT) );

        // Set the global flag to signal success.
        g_bFoundBumpFormat = TRUE;
        return D3DENUMRET_CANCEL;
    }

    return D3DENUMRET_OK;
}
[Visual Basic]

A Direct3D device can perform bump mapping if it supports either of the D3DTOP_BUMPENVMAP or D3DTOP_BUMPENVMAPLUMINANCE texture blending operations. Additionally, applications should check the device capabilities to make sure it supports an appropriate number of blending stages (usually at least 3) and exposes at least one bump mapping pixel format.

The following code checks device capabilities to detect support for bump mapping in the current device, using the given criteria.

Function SupportsBumpMapping() As Boolean
    Dim ddpfBumpMap As DDPIXELFORMAT
    Dim d3dDevDesc As D3DDEVICEDESC7

    SupportsBumpMapping = True

    ' Get the device capabilities.
    Call g_d3dDevice.GetCaps(d3dDevDesc)

    ' Does this device support the two bump mapping blend operations?
    Dim lBumpOps As Long
    lBumpOps = (d3dDevDesc.lTextureOpCaps And _
                (D3DTEXOPCAPS_BUMPENVMAP Or D3DTEXOPCAPS_BUMPENVMAPLUMINANCE))

    If lBumpOps = 0 Then SupportsBumpMapping = False

    ' Does this device support up to three blending stages?
    If d3dDevDesc.nMaxTextureBlendStages < 3 Then SupportsBumpMapping = False

    '
    ' Check for valid bump map pixel formats.
    '
    Dim BumpEnum As Direct3DEnumPixelFormats
    Set BumpEnum = g_d3dDevice.GetTextureFormatsEnum

    Dim iLoop As Integer
    For iLoop = 0 To BumpEnum.GetCount
        Call BumpEnum.GetItem(iLoop, ddpfBumpMap)

        ' Stop enumerating when a format is found.
        If ddpfBumpMap.lFlags And DDPF_BUMPDUDV Then Exit For
    Next iLoop

    If Not (ddpfBumpMap.lFlags And DDPF_BUMPDUDV) Then
        SupportsBumpMapping = False
    End If
End Function


Creating a Bump Map Texture

You create a bump map texture like any other texture. Once your application has verified support for bump mapping and retrieved a valid pixel format (as discussed in Detecting Support For Bump Mapping), you can create a bump map texture surface. For information on creating surfaces, see Obtaining a Texture Surface Object and Creating Surfaces.

After the surface is created, you can load each pixel with the appropriate delta values, and luminance (if the surface format includes luminance). The values for each pixel component are described in Bump Map Pixel Formats.


Configuring Bump Mapping Parameters

When your application has created a bump map and set the contents of each pixel, you can prepare for rendering by configuring bump mapping parameters. Bump mapping parameters include setting the required textures and their blending operations, as well as the transformation and luminance controls for the bump map itself.

[C++]

To configure bump mapping parameters in C++:

  1. Set the base texture map (if used), bump map, and environment map textures into texture blending stages.
  2. Set the color and alpha blending operations for each texture stage.
  3. Set the bump map transformation matrix.
  4. Set the luminance scale and offset values (as needed).

The following code sets three textures—the base texture map, the bump map, and a specular environment map—to the appropriate texture blending stages.

    // Set the three textures.
    g_pd3dDevice->SetTexture( 0, lpd3dBaseTexture);
    g_pd3dDevice->SetTexture( 1, lpd3dBumpMap);
    g_pd3dDevice->SetTexture( 2, lpd3dEnvMap);

After setting the textures to their blending stages, the following code prepares the blending operations and arguments for each stage.

    //
    // Set the color operations and arguments to prepare for bump mapping.
    //

    // Stage 0: the base texture
    g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE );
    g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
    g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
    g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1 );
    g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );
    g_pd3dDevice->SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX, 1 );

    // Stage 1: the bump map
    g_pd3dDevice->SetTextureStageState( 1, D3DTSS_TEXCOORDINDEX, 1 );
    // Use luminance for this example.
    g_pd3dDevice->SetTextureStageState( 1, D3DTSS_COLOROP, D3DTOP_BUMPENVMAPLUMINANCE);
    g_pd3dDevice->SetTextureStageState( 1, D3DTSS_COLORARG1, D3DTA_TEXTURE );
    g_pd3dDevice->SetTextureStageState( 1, D3DTSS_COLORARG2, D3DTA_CURRENT );

    // Stage 2: a specular environment map
    g_pd3dDevice->SetTextureStageState( 2, D3DTSS_TEXCOORDINDEX, 0 );
    g_pd3dDevice->SetTextureStageState( 2, D3DTSS_COLOROP, D3DTOP_ADD );
    g_pd3dDevice->SetTextureStageState( 2, D3DTSS_COLORARG1, D3DTA_TEXTURE );
    g_pd3dDevice->SetTextureStageState( 2, D3DTSS_COLORARG2, D3DTA_CURRENT );

Once the blending operations and arguments are set, the following code sets the 2×2 bump mapping matrix to the identity matrix, by setting the D3DTSS_BUMPENVMAT00 and D3DTSS_BUMPENVMAT11 texture stage states to 1.0. Setting the matrix to the identity causes the system to use the delta-values in the bump map unmodified, but this is not a requirement.

    // Set the bump mapping matrix.
    //
    // NOTE:
    //    These calls rely on the following inline shortcut function:
    //       inline DWORD F2DW( FLOAT f ) { return *((DWORD*)&f); }
    g_pd3dDevice->SetTextureStageState( 1, D3DTSS_BUMPENVMAT00, F2DW(1.0f) );
    g_pd3dDevice->SetTextureStageState( 1, D3DTSS_BUMPENVMAT01, F2DW(0.0f) );
    g_pd3dDevice->SetTextureStageState( 1, D3DTSS_BUMPENVMAT10, F2DW(0.0f) );
    g_pd3dDevice->SetTextureStageState( 1, D3DTSS_BUMPENVMAT11, F2DW(1.0f) );

If you set the bump mapping operation to include luminance (D3DTOP_BUMPENVMAPLUMINANCE), you must set the luminance controls. The luminance controls configure how the system computes luminance before modulating the color from the texture in the next stage. (For details, see Bump Mapping Formulas.)

    // Set luminance controls. This is only needed when using a bump map
    // that contains luminance, and when the D3DTOP_BUMPENVMAPLUMINANCE
    // texture blending operation is being used.
    //
    // NOTE:
    //    These calls rely on the following inline shortcut function:
    //       inline DWORD F2DW( FLOAT f ) { return *((DWORD*)&f); }
    g_pd3dDevice->SetTextureStageState( 1, D3DTSS_BUMPENVLSCALE, F2DW(0.5f) );
    g_pd3dDevice->SetTextureStageState( 1, D3DTSS_BUMPENVLOFFSET, F2DW(0.0f) );

After your application configures bump mapping parameters, it can render as it normally would, and the rendered polygons will receive bump mapping effects.

[Visual Basic]

To configure bump mapping parameters in Visual Basic:

  1. Set the base texture map (if used), bump map, and environment map textures into texture blending stages.
  2. Set the color and alpha blending operations for each texture stage.
  3. Set the bump map transformation matrix.
  4. Set the luminance scale and offset values (as needed).

The following code sets three textures—the base texture map, the bump map, and a specular environment map—to the appropriate texture blending stages.

    ' Set the three textures.
    Call g_d3dDevice.SetTexture(0, d3dBaseTexture)
    Call g_d3dDevice.SetTexture(1, d3dBumpMap)
    Call g_d3dDevice.SetTexture(2, d3dEnvMap)

After setting the textures to their blending stages, the following code prepares the blending operations and arguments for each stage.

  ' Create the bump map texture.

    '
    ' Set the color operations and arguments to prepare for bump mapping.
    '

    ' Stage 0: the base texture
    Call g_d3dDevice.SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE)
    Call g_d3dDevice.SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE)
    Call g_d3dDevice.SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE)
    Call g_d3dDevice.SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1)
    Call g_d3dDevice.SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE)
    Call g_d3dDevice.SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, 1)

    ' Stage 1: the bump map
    Call g_d3dDevice.SetTextureStageState(1, D3DTSS_TEXCOORDINDEX, 1)
    ' Use luminance for this example.
    Call g_d3dDevice.SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_BUMPENVMAPLUMINANCE)
    Call g_d3dDevice.SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_TEXTURE)
    Call g_d3dDevice.SetTextureStageState(1, D3DTSS_COLORARG2, D3DTA_CURRENT)

    ' Stage 2: a specular environment map
    Call g_d3dDevice.SetTextureStageState(2, D3DTSS_TEXCOORDINDEX, 0)
    Call g_d3dDevice.SetTextureStageState(2, D3DTSS_COLOROP, D3DTOP_ADD)
    Call g_d3dDevice.SetTextureStageState(2, D3DTSS_COLORARG1, D3DTA_TEXTURE)
    Call g_d3dDevice.SetTextureStageState(2, D3DTSS_COLORARG2, D3DTA_CURRENT)

Once the blending operations and arguments are set, the following code sets the 2×2 bump mapping matrix to the identity matrix, by setting the D3DTSS_BUMPENVMAT00 and D3DTSS_BUMPENVMAT11 texture stage states to 1.0. Setting the matrix to the identity causes the system to use the delta-values in the bump map unmodified, but this is not a requirement.

    ' Set the bump mapping matrix.
    Call g_d3dDevice.SetTextureStageStateSingle(1, D3DTSS_BUMPENVMAT00, 1#)
    Call g_d3dDevice.SetTextureStageStateSingle(1, D3DTSS_BUMPENVMAT01, 0#)
    Call g_d3dDevice.SetTextureStageStateSingle(1, D3DTSS_BUMPENVMAT10, 0#)
    Call g_d3dDevice.SetTextureStageStateSingle(1, D3DTSS_BUMPENVMAT11, 1#)

If you set the bump mapping operation to include luminance (D3DTOP_BUMPENVMAPLUMINANCE), you must set the luminance controls. The luminance controls configure how the system computes luminance before modulating the color from the texture in the next stage. (For details, see Bump Mapping Formulas.)

    ' Set luminance controls. This is only needed when using a bump map
    ' that contains luminance, and when the D3DTOP_BUMPENVMAPLUMINANCE
    ' texture blending operation is being used.
    Call g_d3dDevice.SetTextureStageStateSingle(1, D3DTSS_BUMPENVLSCALE, 0.5)
    Call g_d3dDevice.SetTextureStageStateSingle(1, D3DTSS_BUMPENVLOFFSET, 0#)

After your application configures bump mapping parameters, it can render as it normally would, and the rendered polygons will receive bump mapping effects.

Note: The preceding example shows parameters set for specular environment mapping. When performing diffuse light mapping, applications would set the texture blending operation for the last stage to D3DTOP_MODULATE. For more information, see Diffuse Light Maps.


Billboarding

When creating 3-D scenes, applications can sometimes gain performance advantages by rendering 2-D objects in a way that makes them appear to be 3-D objects. This is the basic idea behind the technique of billboarding.

A billboard in the normal sense of the word is a sign along a roadway. Direct3D applications can easily create and render this type of billboard by defining a rectangular solid and applying a texture to it. Billboarding in the more specialized sense of 3-D graphics is an extension of this. The goal is to make 2-D objects appear to be 3-D. The technique is to apply a texture containing the object's image to a rectangular primitive. The primitive is rotated so that it always faces the viewer. It doesn't matter if the object's image is not rectangular. Portions of the billboard can be made transparent, so the parts of the billboard image that you don't want seen are not visible.

Many games employ billboarding for their animated sprites. For instance, when the player is moving through a 3-D maze, he or she may see weapons or rewards that can be picked up. These are typically 2-D images textured onto a rectangular primitive. Billboarding is often used in games to render images of trees and bushes.

When an image is applied to a billboard, the rectangular primitive must first be rotated so that the resulting image faces the viewer. Your application must then translate it into position. The program can then apply a texture to the primitive.

Billboarding works best for symmetrical objects, especially objects that are symmetrical around the vertical axis. It also requires that the altitude of the viewpoint doesn't increase too much. If the user is allowed to view the billboarded from above, it will become readily apparent that the object is 2-D rather than 3-D.


Clouds, Smoke, and Vapor Trails

Clouds, smoke, and vapor trails can all be created by an extension of the billboarding technique (see Billboarding). By rotating the billboard around two axes instead of one, your application can enable the viewer to look at a billboard from any angle. Typically, your application will rotate the billboard around the horizontal and vertical axes.

To make a simple cloud, your application can rotate a rectangular primitive around one or two axes so that it faces the viewer. A cloud-like texture can then be applied to the primitive with transparency. For details on applying transparent textures to primitives, see Texture Blending. The cloud can be animated by applying a series of textures over time.

Applications can create more complex clouds by forming them from a group of primitives. Each part of the cloud is a rectangular primitive. The primitives can be moved independently over time to give the appearance of a dynamic mist. This concept is illustrated in the following figure.

The appearance of smoke is displayed in a manner similar to clouds. It typically requires multiple billboards, like complex clouds. Smoke usually billows and rises over time, so the billboards that make up the smoke plume need to be moved accordingly. More billboards may need to be added as the plume rises and disperses.

A vapor trail is just a smoke plume that doesn't rise. However, like a smoke plume, it does disperse over time. The following figure illustrates the technique of using billboards to simulate a vapor trail.


Fire, Flares, Explosions, and More

Applications can use Direct3D to simulate natural phenomena involving energy releases. For instance, a program can generate the appearance of fire by applying flame-like textures to a set of billboards. This is especially effective if the program uses a sequence of fire textures to animate the flames on each billboard in the fire. Varying the speed of the animation playback from billboard to billboard increases the appearance of real flames. The semblance of intermingled 3-D flames can be achieved by layering the billboards, and the textures on the billboards.

Flares and flashes can be simulated by applying successively brighter light maps to all primitives in a scene. Although this is a computationally high-overhead technique, it allows your program to simulate a localized flare or flash. That is, the portion of the scene where the flare or flash originates can be brightened first.

Another technique is to position a billboard in front of the scene so that the entire render target area is covered. The program applies successively whiter textures to the billboard and decreases the transparency over time. The entire scene will fade to white as time passes. This is a low overhead method of creating a flare. However, using this technique, it can be difficult to generate the appearance of a bright flash from a single point light source.

Explosions can be displayed in a 3-D scene procedures like those used for fire, flashes, and flares. For instance, your program might use a billboard to display a shock wave and rising plume of smoke when the explosion occurs. At the same time, your application can use a set of billboards to simulate flames. In addition, it can position a single billboard in front of the scene to add a flare of light to the entire scene.

Energy beams can be simulated using billboards. Your application can also display them using primitives that are defined as line lists or line strips. For details, see Line Lists and Line Strips.

Your application can create force fields using billboards or primitives defined as triangle lists. To create a force field from triangle lists, define a set of disjoint triangles in a triangle list equally spaced over the region covered by the force field. The gaps between the triangles will allow the viewer to see the scene behind the triangles, as you might expect when looking at a force field. Apply a texture to the triangle list that gives the triangles the appearance of glowing with energy. For further information, see Triangle Lists and Current Texture.


Motion Blur

The perceived speed of an object in a 3-D scene can be enhanced by blurring the object, and by leaving a blurred trail of object images behind the object. Direct3D applications can accomplish this by rendering the object multiple times per frame.

[Visual Basic]

Recall that Direct3D applications typically render scenes into an off-screen buffer. The contents of the buffer are displayed on the screen when the application calls the DirectDrawSurface7.Flip method. Your Direct3D program can render the object multiple times into a scene before it displays the frame on the screen.

Programmatically, your application makes multiple calls to a DrawPrimitive method, repeatedly passing the same 3-D object. Before each call, the position of the object is updated slightly, producing a series of blurred object images on the target rendering surface. If the object has one or more textures, your application can enhance the motion blur effect by rendering the first image of the object with all of its textures nearly transparent. Each time the object is rendered, the transparency of the object's texture is decreased. When your program renders the object in its final position, it should render the object's textures without transparency. The exception is if you're adding motion blur to another effect that requires texture transparency. In any case, the initial image of the object in the frame should be the most transparent. The final image should be the least transparent.

[C++]

After your application renders the series of object images onto the target rendering surface and renders the rest of the scene, it should call the IDirectDrawSurface7::Flip method to display the frame on the screen.

[Visual Basic]

After your application renders the series of object images onto the target rendering surface and renders the rest of the scene, it should call the DirectDrawSurface7.Flip method to display the frame on the screen.

If your program is simulating the effect of the user moving through a scene at high speed, it can add motion blur to the entire scene. In this case, your application would render the entire scene multiple times per frame. Each time the scene is rendered, your program must move the viewpoint slightly. If your scene is highly complex, your user may see a visible performance degradation as acceleration is increased because of the increasing number of scene renderings per frame.


Stencil Buffer Techniques

Applications use the stencil buffer to mask pixels in an image. The mask controls whether or not the pixel is drawn. For more information on the stencil buffer, see Stencil Buffers.

Direct3D applications can achieve a wide range of special effects with the stencil buffer. Some of the more common effects are listed here. This list is by no means exhaustive.

  • Dissolves, Fades, and Swipes
  • Decaling
  • Compositing
  • Outlines and Silhouettes


Dissolves, Fades, and Swipes

Applications are increasingly employing special effects that are commonly used in movies and video, such as dissolves, swipes, and fades.

In a dissolve, one image is gradually replaced by another in a smooth sequence of frames. Although Direct3D provides methods of using multiple texture blending to achieve the same effect, applications that use the stencil buffer for dissolves can utilize the texture blending capabilities for other effects while they do a dissolve.

When your application performs a dissolve, it must render two different images. It uses the stencil buffer to control which pixels from each image are drawn to the rendering target surface. You can define a series of stencil masks and copy them into the stencil buffer on successive frames. Alternately, you can define a base stencil mask for the first frame and alter it incrementally.

At the beginning of the dissolve, your application sets the stencil function and stencil mask such that most of the pixels from the starting image pass the test. Most of the pixels of the ending image should fail the stencil test. On successive frames, the stencil mask is updated so that fewer and fewer of the pixels in the starting image pass the test. As the frames progress, fewer and fewer of the pixels in the ending image fail the test. In this manner, your application can perform a dissolve using any arbitrary dissolve pattern.

Fading in or fading out is just a special case of dissolving. When fading in, the stencil buffer is used to dissolve from a black (or white) image to a rendering of a 3-D scene. Fading out is the opposite, your application starts with a rendering of a 3-D scene and dissolves to black (or white). The fade can be done using any arbitrary pattern you want to employ.

Direct3D applications use a similar technique for swipes. When an application performs, for instance, a left-to-right swipe. The ending image appears to gradually slide on top of the starting image from left to right. Just as in doing a dissolve, you must define a series of stencil masks that are loaded into the stencil buffer on successive frames, or successively modify the starting stencil mask. The stencil masks are used to disable the writing of pixels from the starting image and enable the writing of pixels from the ending image.

A swipe is somewhat more complex than a dissolve in that your application must read pixels from the ending image in the reverse order of the swipe. That is, if the swipe is moving left to right, your application must read pixels from the ending image from right to left.


Decaling

Direct3D applications use the technique of decaling to control which pixels from a particular primitive image are drawn to the rendering target surface. Programs apply decals to the images of primitives to enable coplanar polygons to be rendered correctly.

For instance, when applying tire marks and yellow lines to a roadway, the markings should appear directly on top of the road. However, the z values of the markings and the road are the same. Therefore, the depth buffer might not produce a clean separation between the two. Some pixels in the back primitive may be rendered on top of the front primitive and vice versa. The resulting image appears to shimmer from frame to frame. This effect is called "Z Fighting" or "flimmering".

To solve this problem, use a stencil to mask out the section of the back primitive where the decal will appear. Turn off z-buffering and render the image of the front primitive into the masked-off area of the render-target surface.

Although multiple texture blending can be used to solve this problem, doing so limits the number of other special effects that your application can produce. Using the stencil buffer to apply decals frees up texture blending stages for other effects.


Compositing

Your application can use the stencil buffer to composite 2-D or 3-D images onto a 3-D scene. A mask in the stencil buffer is used to occlude an area of the rendering target surface. Stored 2-D information, such as text or bitmaps, can then be written to the occluded area. Alternately, your application can render additional 3-D primitives to the stencil-masked region of the rendering target surface. It can even render an entire scene.

Games often composite multiple 3-D scenes together. For instance, driving games typically display a rear-view mirror. The mirror contains the view of the 3-D scene behind the driver. It is essentially a second 3-D scene composited together with the driver's forward view.


Outlines and Silhouettes

The stencil buffer can be used for more abstract effects, such as outlining and silhouetting.

If your program applies a stencil mask to the image of a primitive that is the same shape, but slightly smaller than the primitive, the resulting image will only contain the primitive's outline. It can then fill the stencil-masked area of the image with a solid color, giving the primitive an embossed look.

If the stencil mask is the same size and shape as the primitive you are rendering, the resulting image will contain a "hole" where the primitive should be. Your program can then fill the "hole" with black to produce a silhouette of the primitive.


Colored Lights

[C++]

The color-related members of the D3DLIGHT7 structure (dcvDiffuse, dcvSpecular, dcvAmbient) are D3DCOLORVALUE structures. The colors defined by these structures are RGBA values that generally range from zero to one, with zero being black. Although you will usually want the light color to fall within this range, you can use values outside the range for special effects. For example, you could create a strong light that washes out a scene by setting the color to large values. You could also set the color to negative values to create a dark light, which actually removes light from a scene. Dark lights are useful for forcing dramatic shadows in scenes and other special effects.

[Visual Basic]

The color-related members of the D3DLIGHT7 type (diffuse, specular, ambient) are D3DCOLORVALUE types. The colors defined by these are RGBA values that generally range from zero to one, with zero being black. Although you will usually want the light color to fall within this range, you can use values outside the range for special effects. For example, you could create a strong light that washes out a scene by setting the color to large values. You could also set the color to negative values to create a dark light, which actually removes light from a scene. Dark lights are useful for forcing dramatic shadows in scenes and other special effects.


Antialiasing

Antialiasing is a technique you can use to reduce the appearance of "jaggies"—the stair-step pixels used to draw any line that isn't exactly horizontal or vertical. In three-dimensional scenes, this artifact is most noticeable on the boundaries between polygons of different colors. Antialiasing effectively blends the pixels at these boundaries to produce a more natural look to the scene.

Direct3D supports two antialiasing techniques: edge antialiasing and full-surface antialiasing. Which technique is best for your application depends on your requirements for performance and visual fidelity.

  • Edge Antialiasing
  • Full-Scene Antialiasing

Note If your application will use antialiasing, it should create the render-target surface with the DDSCAPS2_HINTANTIALIASING capability flag. Applications that omit the flag might suffer from poor performance when antialiasing is enabled, or might not receive antialiasing serices at all.


Edge Antialiasing

In edge antialiasing, you render a scene, then re-render the convex silhouettes of the objects to be antialiased with lines. The system redraws those edges, blurring them to reduce artifacts.

[C++]

If a device supports edge antialiasing, it exposes the D3DPRASTERCAPS_ANTIALIASEDGES capability flag in the D3DPRIMCAPS structure (filled by calling the IDirect3DDevice7::GetCaps method). If it does, set the D3DRENDERSTATE_EDGEANTIALIAS render state to TRUE, then redraw only the edges in the scene, using IDirect3DDevice7::DrawPrimitive and either the D3DPT_LINESTRIP or D3DPT_LINELIST primitive type. The behavior of edge antialiasing is undefined for primitives other than lines, so make sure to disable the feature by setting D3DRENDERSTATE_EDGEANTIALIAS to FALSE when antialiasing is complete.

[Visual Basic]

If a device supports edge antialiasing, it exposes the D3DPRASTERCAPS_ANTIALIASEDGES capability flag in the D3DPRIMCAPS type (filled by calling the Direct3DDevice7.GetCaps method). If it does, set the D3DRENDERSTATE_EDGEANTIALIAS render state to True, then redraw only the edges in the scene, using Direct3DDevice7.DrawPrimitive and either the D3DPT_LINESTRIP or D3DPT_LINELIST primitive type. The behavior of edge antialiasing is undefined for primitives other than lines, so make sure to disable the feature by setting D3DRENDERSTATE_EDGEANTIALIAS to False when antialiasing is complete.

Redrawing every edge in your scene can work without introducing major artifacts, but it can be computationally expensive. In addition, it can be difficult to determine which edges should be antialiased. The most important edges to redraw are those between areas of very different color (for example, silhouette edges) or boundaries between very different materials. Antialiasing the edge between two polygons of roughly the same color will have no effect, yet is still computationally expensive. For these reasons, full-scene antialiasing is often preferred, given that the current hardware supports it. For more information, see Full-scene Antialiasing.


Full-Scene Antialiasing

Full-scene antialiasing refers to blurring the edges of each polygon in the scene as it is rasterized in a single pass—no second pass is required. Note that full-scene antialiasing, when supported, only affects triangles and groups of triangles; lines cannot be antialiased by using Direct3D services.

[C++]

On some hardware, full-scene antialiasing can be applied only when the application renders the polygons sorted from back to front. To find out whether this is true for the current device, retrieve the device capabilities by calling IDirect3DDevice7::GetCaps method. After the call, check the dwRasterCaps member of the associated D3DPRIMCAPS structures. If the device requires back to front rendering for antialiasing, it exposes the D3DPRASTERCAPS_ANTIALIASSORTDEPENDENT capability flag in dwRasterCaps. If the device can perform antialiasing without regard to polygon order, it will expose the D3DPRASTERCAPS_ANTIALIASSORTINDEPENDENT flag. Of course, the absence of both flags indicates that the device cannot perform full-scene antialiasing at all.

After finding out whether or not you need to sort the polygons, set the D3DRENDERSTATE_ANTIALIAS render state to D3DANTIALIAS_SORTDEPENDENT or D3DANTIALIAS_SORTINDEPENDENT and draw the scene.

When you no longer need full-scene antialiasing, disable it by setting D3DRENDERSTATE_ANTIALIAS to D3DANTIALIAS_NONE.

[Visual Basic]

On some hardware, full-scene antialiasing can be applied only when the application renders the polygons sorted from back to front. To find out whether this is true for the current device, retrieve the device capabilities by calling Direct3DDevice7.GetCaps method. After the call, check the lRasterCaps member of the associated D3DPRIMCAPS types. If the device requires back to front rendering for antialiasing, it exposes the D3DPRASTERCAPS_ANTIALIASSORTDEPENDENT capability flag in lRasterCaps. If the device can perform antialiasing without regard to polygon order, it will expose the D3DPRASTERCAPS_ANTIALIASSORTINDEPENDENT flag. Of course, the absence of both flags indicates that the device cannot perform full-scene antialiasing at all.

After finding out whether or not you need to sort the polygons, set the D3DRENDERSTATE_ANTIALIAS render state to D3DANTIALIAS_SORTDEPENDENT or D3DANTIALIAS_SORTINDEPENDENT and draw the scene.

When you no longer need full-scene antialiasing, disable it by setting D3DRENDERSTATE_ANTIALIAS to D3DANTIALIAS_NONE.


GUIDs

[C++]

Direct3D uses globally unique identifiers, or GUIDs, to identify parts of the interface. When you use the QueryInterface method to determine whether an object supports an interface, you identify the interface you're interested in by using its GUID.

To use GUIDs successfully in your application, you must either define INITGUID prior to all other include and define statements, or you must link to the Dxguid.lib library. You should define INITGUID in only one of your source modules.

Note that you use GUIDs differently depending on whether your application is written in C or C++. In C, you pass a pointer to the GUID (&IID_IDirect3D, for example), but in C++, you pass a reference to it (simply IID_IDirect3D).

[Visual Basic]

Like all of DirectX, the Direct3D component uses globally unique identifiers, or GUIDs, to identify parts of the API. DirectX for Visual Basic uses Strings to represent GUIDS where they are required—for example, when your application creates a DirectDraw7 object by calling the DirectX7.DirectDrawCreate method.

For more information, see Using GUIDs.


Performance Optimization

Every developer who creates real-time applications that use 3-D graphics is concerned about performance optimization. This section provides you with guidelines about getting the best performance from your code.

You can use the guidelines in the following sections for any Direct3D application:

  • Databases and Culling
  • Batching Primitives
  • Lighting Tips
  • Texture Size
  • General Performance Tips
  • Z-buffer Performance


Databases and Culling

Building a reliable database of the objects in your world is the key to excellent performance in Direct3D—it is more important than improvements to rasterization or hardware.

You should maintain the lowest polygon count you can possibly manage. Design for a low polygon count, building low-poly models from the start, and add polygons if you feel that you can do so without sacrificing performance later in the development process. Try to keep the total number of polygons in the neighborhood of 2500. Remember, "the fastest polygons are the ones you don't draw."


Batching Primitives

To get the best rendering performance during execution, you should try to work with primitives in batches and keep the number of render-state changes as low as possible. For example, if you have an object with two textures, group the triangles that use the first texture and follow them with the necessary render state to change the texture, then group all the triangles that use the second texture. The simplest hardware support for Direct3D is called with batches of render states and batches of primitives through the hardware abstraction layer (HAL). The more effectively the instructions are batched, the fewer HAL calls are performed during execution.


Lighting Tips

Since lights add a per-vertex cost to each rendered frame, you can achieve significant performance improvements by being careful about how you use them in your application. Most of the following tips derive from the maxim, "the fastest code is code that is never called."

  • Use as few light sources as possible. If you just need to bring up the overall level of lighting, use the ambient light instead of adding a new light source. (It's much cheaper.)
  • Directional lights are cheaper than point lights or spotlights. For directional lights, the direction to the light is fixed and doesn't need to be calculated on a per-vertex basis.
  • Spotlights can be cheaper than point lights, because the area outside of the cone of light is calculated quickly. Whether or not they are cheaper depends on how much of your scene is lit by the spotlight.
  • Use the range parameter to limit your lights to only the parts of the scene you need to illuminate. All the light types exit fairly early when they are out of range.
  • Specular highlights almost double the cost of a light—use them only when you must. Set the D3DRENDERSTATE_SPECULARENABLE render state to 0 (the default value) whenever possible. When defining materials you must set the specular power value to zero to turn off specular highlights for that material—simply setting the specular color to 0,0,0 is not enough.


Texture Size

Texture-mapping performance is heavily dependent on the speed of memory. There are a number of ways to maximize the cache performance of your application's textures.

  • Keep the textures small; the smaller the textures are, the better chance they have of being maintained in the main CPU's secondary cache.
  • Do not change the textures on a per-primitive basis. Try to keep polygons grouped in order of the textures they use.
  • Use square textures whenever possible. Textures whose dimensions are 256×256 are the fastest. If your application uses four 128×128 textures, for example, try to ensure that they use the same palette and place them all into one 256×256 texture. This technique also reduces the amount of texture swapping. Of course, you should not use 256×256 textures unless your application requires that much texturing because, as already mentioned, textures should be kept as small as possible.


General Performance Tips

You can follow a few general guidelines to increase the performance of your application.

  • Only clear when you must.
  • Minimize state changes.
  • Use perspective correction only if you must.
  • If you can use smaller textures, do so.
  • Gracefully degrade special effects that require a disproportionate share of system resources.
  • Constantly test your application's performance.
  • Ensure that your application runs well both with hardware acceleration and software emulation.


Z-Buffer Performance

Applications can increase performance when using z-buffering and texturing by ensuring that scenes are rendered from front to back. Textured z-buffered primitives are pretested against the z-buffer on a scan line basis. If a scan line is hidden by a previously rendered polygon, the system rejects it quickly and efficiently. Z-buffering can improve performance, but the technique is most useful when a scene includes a great deal of overdraw. Overdraw is the average number of times a screen pixel is written to. Overdraw is difficult to calculate exactly, but you can often make a close approximation. If the overdraw averages less than 2, you can achieve the best performance by turning z-buffering off, and rendering the scene from back-to-front.

[C++]

You can also improve the performance of your application by performing visibility testing before rendering. Direct3D Immediate Mode offers the IDirect3DDevice7::ComputeSphereVisibility method for this purpose. The ComputeSphereVisibility method provides information about the visibility of a given set of polygons. If the method reports that the geometry isn't visible, you can avoid even rendering the object.

[Visual Basic]

You can also improve the performance of your application by performing visibility testing before rendering. Direct3D Immediate Mode offers the Direct3DDevice7.ComputeSphereVisibility method for this purpose. The ComputeSphereVisibility method provides information about the visibility of a given set of polygons. If the method reports that the geometry isn't visible, you can avoid even rendering the object.

On faster personal computers, software rendering to system memory is often faster than rendering to video memory, although it has the disadvantage of not being able to use double buffering or hardware-accelerated clear operations. If your application can render to either system or video memory, and if you include a routine that tests which is faster, you can take advantage of the best approach on the current system. The Direct3D sample code in this SDK demonstrates this strategy. It is necessary to implement both methods because there is no other way to test the speed. Speeds can vary enormously from computer to computer, depending on the main-memory architecture and the type of graphics adapter being used.


Troubleshooting

This section lists common categories of problems that you may encounter when writing Direct3D programs, and what you should do to prevent them.

  • Device Creation
  • Using Lit Vertices
  • Nothing Visible
  • Debugging
  • Borland Floating-Point Initialization
  • Parameter Validation


Device Creation

If your application fails during device creation, check for the following common errors:

  • You must specify DDSCAPS_3DDEVICE when you create the DirectDraw surface.
  • If you're using a palettized device, you must attach the palette.
  • If you're using a z-buffer, you must attach it to the rendering target.
  • Make sure you check the device capabilities, particularly the render depths.
  • Check whether you are using system or video memory.
  • Ensure that the registry has not been corrupted.


Using Lit Vertices

[C++]

Applications that use lit vertices, analogous to the D3DLVERTEX structure, should disable the Direct3D lighting engine by setting the D3DRENDERSTATE_LIGHTING render state to FALSE. By default, when lighting is enabled, the system sets the color for any vertex that doesn't contain a normal vector to 0 (black), even if the input vertex contained a nonzero color value. Because lit-vertices such as D3DVERTEX don't, by their nature, contain a vertex normal, any color information passed-in to Direct3D will be lost during rendering if the lighting engine is enabled.

Obviously, vertex color is important to any application that performs its own lighting. To prevent the system from imposing the default values, make sure you set D3DRENDERSTATE_LIGHTING to FALSE.

[Visual Basic]

Applications that use lit vertices, analogous to the D3DLVERTEX type, should disable the Direct3D lighting engine by setting the D3DRENDERSTATE_LIGHTING render state to False. By default, when lighting is enabled, the system sets the color for any vertex that doesn't contain a normal vector to 0 (black), even if the input vertex contained a nonzero color value. Because lit-vertices such as D3DVERTEX don't, by their nature, contain a vertex normal, any color information passed-in to Direct3D will be lost during rendering if the lighting engine is enabled.

Obviously, vertex color is important to any application that performs its own lighting. To prevent the system from imposing the default values, make sure you set D3DRENDERSTATE_LIGHTING to False.


Nothing Visible

If your application runs but nothing is visible, check for the following common errors:

  • Ensure that your triangles are not degenerate.
  • Ensure that your triangles are not being culled.
  • Make sure that your transformations are internally consistent.
  • Check the viewport settings to be sure they will allow your triangles to be seen.


Debugging

[Visual Basic]

Note Information in this topic pertains only to applications developed in C/C++.

[C++]

Debugging a Direct3D application can be challenging. In addition to checking all the return values (a particularly important piece of advice in Direct3D programming, which is so dependent on very different hardware implementations), try the following techniques:

  • Switch to debug DLLs.
  • Force a software-only device, turning off hardware acceleration even when it is available.
  • Force surfaces into system memory.
  • Create an option to run in a window, so that you can use an integrated debugger.

The second and third options in the preceding list can help you avoid the Win16 lock which can otherwise cause your debugger to hang.

Also, try adding the following entries to WIN.INI:

[Direct3D]
debug=3
[DirectDraw]
debug=3


Borland Floating-Point Initialization

[Visual Basic]

Note Information in this topic pertains only to applications developed in C/C++.

[C++]

Compilers from the Borland company report floating-point exceptions in a manner that is incompatible with Direct3D. To solve this problem, you should include a _matherr() exception handler like the following:

// Borland floating point initialization
#include <math.h>
#include <float.h>

void initfp(void)
{
    // disable floating point exceptions
    _control87(MCW_EM,MCW_EM);
}

int _matherr(struct _exception  *e)
{
    e;               // dummy reference to catch the warning
    return 1;    // error has been handled
}


Parameter Validation

[Visual Basic]

Note Information in this topic pertains only to applications developed in C/C++.

[C++]

For performance reasons, the debug version of the Direct3D Immediate Mode runtime performs more parameter validation than the retail version, which sometimes performs no validation at all. This allows applications to perform robust debugging with the slower debug run-time component before using the faster retail version for performance tuning and final release.

Although several Direct3D Immediate Mode methods impose limits on the values that they can accept, these limits are often only checked and enforced by the debug version of the Direct3D Immediate Mode runtime. Applications must conform to these limits, or unpredictable (and highly undesirable) results can occur when running on the retail version of Direct3D. For example, the IDirect3DDevice7::DrawPrimitive method accepts a parameter (dwVertexCount) that indicates the number of vertices that the method will render. The method can only accept values between 0 and 65,535 (0x0000 and 0xFFFF). In the debug version of Direct3D, if you pass 65,536 (one more than the limit), the method will fail gracefully, printing an error message to the error log, and returning an error value to your application. Conversely, if your application makes the same error when it is running with the retail version of the runtime, behavior is undefined. For performance reasons, the method does not validate the parameters, resulting in unpredictable and completely situational behavior when they are not valid. In some cases the call might work, and in other cases it might cause a memory fault in Direct3D. If an invalid call consistently works with a particular hardware configuration and DirectX version, there is no guarantee that it will continue to function on other hardware or with future releases of DirectX.

If your application encounters unexplained failures when running with the retail Direct3D Immediate Mode run-time file, test against the debug version and look closely for cases where your application passes invalid parameters.


Direct3D Immediate Mode Tutorials

This section contains a series of tutorials, each providing step-by-step instructions for implementing the basics of Direct3D® Immediate Mode in a C/C++ or Visual Basic® application. The tutorials are written parallel to a set of sample files that are provided with this SDK in the \Samples\Multimedia\D3DIM\Tutorials directory, following their code path and providing explanations along the way. Readers are encouraged to follow along in the sample code as they move through these tutorials.

  • Direct3D Immediate Mode C/C++ Tutorials
  • Direct3D Immediate Mode Visual Basic Tutorials


Direct3D Immediate Mode C/C++ Tutorials

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

The tutorials in this section show how to use Direct3D for common tasks by dividing those tasks into required steps. In some cases, steps are organized into substeps for clarity. The following tutorials are presented here:

  • Tutorial 1: Rendering a Single Triangle
  • Tutorial 2: Adding a Depth Buffer
  • Tutorial 3: Using Alternate Primitive Styles
  • Tutorial 4: Using Device Enumeration
  • Tutorial 5: Using Texture Maps

Note The sample files in these tutorials are written in C++. If you are using a C compiler, you must make the appropriate changes to the files for them to successfully compile. At the very least, you need to add the vtable and this pointers to the interface methods.

Some comments in the included sample code might differ from the source files in the SDK. Changes are made for brevity only, and are limited to comments to avoid changing the behavior of the code.


Tutorial 1: Rendering a Single Triangle

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

To use Direct3D, you first create an application window, then create and initialize DirectDraw® and Direct3D-related objects. You use the COM interfaces that these objects implement to manipulate them and to create the subordinate objects required to render a scene. The Triangle sample project upon which this tutorial is based illustrates these tasks by rendering the simplest possible scene: a single triangle. The Triangle sample uses the following steps to set up Direct3D, render a scene, and eventually shut down:

  • Step 1: Create a Window
  • Step 2: Initialize System Objects
  • Step 3: Initialize the Scene
  • Step 4: Monitor System Messages
  • Step 5: Render and Display the Scene
  • Step 6: Shut Down

In addition to these steps, Triangle performs some standard tasks common to windowed applications. Although these tasks aren't difficult, the Triangle sample (and all other windowed samples) performs the following tasks as the needed:

  • Handle Window Movement
  • Handle Window Resizing


Step 1: Create a Window

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

The first thing any Windows® application must do when it is executed is create an application window to display a user interface. Keeping with this, when Triangle begins execution at its WinMain function, it uses the following code to perform window initialization:

INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT )
{
    // Register the window class
    WNDCLASS wndClass = { CS_HREDRAW | CS_VREDRAW, WndProc, 0, 0, hInst,
                          LoadIcon( hInst, MAKEINTRESOURCE(IDI_MAIN_ICON)),
                          LoadCursor(NULL, IDC_ARROW),
                          (HBRUSH)GetStockObject(WHITE_BRUSH), NULL,
                          TEXT("Render Window") };
    RegisterClass( &wndClass );

    // Create our main window
    HWND hWnd = CreateWindow( TEXT("Render Window"),
                              TEXT("D3D Tutorial: Drawing One Triangle"),
                              WS_OVERLAPPEDWINDOW, CW_USEDEFAULT,
                              CW_USEDEFAULT, 300, 300, 0L, 0L, hInst, 0L );
    ShowWindow( hWnd, SW_SHOWNORMAL );
    UpdateWindow( hWnd );

The preceding code is standard Windows programming, covered here mostly for thoroughness. The sample starts by defining and registering a window class called "Render Window." The window class is defined to redraw on size events, to use an application-provided icon as a resource, and to have a white background. After the class is registered, the code creates a basic top-level window that uses the registered class, with a client area of 300 pixels wide by 300 pixels tall, and has no menu or child windows. The sample uses the WS_OVERLAPPEDWINDOW window style to create a window that includes minimize, maximize, and close boxes common to windowed applications. (If the sample were to run in full-screen mode, the preferred window style is WS_EX_TOPMOST.) Once the window is created, the code calls standard Win32® functions to show and update the window.

With the application window ready, you can begin setting up the essential DirectX® objects, which is the topic of Step 2: Initialize System Objects.


Step 2: Initialize System Objects

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

After you create an application window, you can begin initializing the primary DirectX objects whose services you will draw on to render the scene. For a Direct3D application, this means creating and configuring DirectDraw, rendering surfaces, a rendering device, and a viewport. For clarity, the Triangle sample separates system object initialization code from the code for initializing the scene. As a result, geometry, application-specific data structures, and lesser Direct3D objects like materials are initialized with the scene. This isn't a requirement, but it makes for simpler code.

The Triangle sample performs system initialization in the Initialize3DEnvironment application-defined function, called from WinMain after the window is created. Although preparing these objects isn't complex, the code is a little too lengthy to discuss in one place. As a result, the steps taken by the Initialize3DEnvironment function are presented in the following substeps:

  • Step 2.1: Initialize DirectDraw
  • Step 2.2: Set Up DirectDraw Surfaces
  • Step 2.3: Initialize Direct3D
  • Step 2.4: Prepare the Viewport

Note The Triangle sample code performs initialization by calling methods from within the WinMain function, immediately after the application window is created, rather than in response to system creation messages such as WM_CREATE. It does this to avoid relying on system message ordering, which can differ across platforms.


Step 2.1: Initialize DirectDraw

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

After creating the application window, the first object you will create is the DirectDraw object, which is required to set your application's cooperative level, and to create the surfaces for display and for use as the render target of a rendering device.

The Triangle sample starts performing initialization by creating a DirectDraw object and setting the application's cooperative level, as shown in the following code:

HRESULT Initialize3DEnvironment( HWND hWnd )
{
    HRESULT hr;

    hr = DirectDrawCreateEx( NULL, (VOID**)&g_pDD, IID_IDirectDraw7, NULL );
    if( FAILED( hr ) )
        return hr;

The preceding code creates a DirectDraw object by calling the DirectDrawCreateEx DirectDraw global function. It passes NULL in the first parameter to request that the function create a DirectDraw object for the active display driver. For hardware that doesn't support GDI, such as 3-D only hardware, you should explicitly specify the globally unique identifier (GUID) of the desired driver in the first parameter. These GUIDs are normally obtained through enumeration. The second parameter is the address of a global variable that DirectDrawCreateEx fills with the address of the IDirectDraw7 interface for the DirectDraw object, and the last parameter is set to NULL to indicate that the new object will not be used with COM aggregation features.

The sample continues by setting the application's cooperative level, as follows:

    hr = g_pDD->SetCooperativeLevel( hWnd, DDSCL_NORMAL );
    if( FAILED( hr ) )
        return hr;

The sample sets the cooperative level by calling the IDirectDraw7::SetCooperativeLevel method. Setting the cooperative level effectively tells the system whether or not the application will render in full-screen mode or in a window. (Note that some hardware cannot render into a window. You can detect such hardware by checking for the absence of the DDCAPS2_CANRENDERWINDOWED capability flag when you call IDirectDraw7::GetCaps.) The code requests windowed cooperative level, also called the "normal" cooperative level, by including the DDSCL_NORMAL in the second parameter it passes to SetCooperativeLevel. The SetCooperativeLevel method can fail if another application already controls owns full-screen, exclusive mode.

Note You can include the DDSCL_FPUSETUP cooperative level flag to increase performance. For more information about this cooperative level flag, see DirectDraw Cooperative Levels and FPU Precision. For general information, see Cooperative Levels in the DirectDraw documentation.

Once you create the DirectDraw object and set the cooperative level, you're ready to prepare the surfaces that will be used to contain and display a rendered scene. The Triangle sample does this as discussed in Step 2.2: Set Up DirectDraw Surfaces.


Step 2.2: Set Up DirectDraw Surfaces

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

After you create a DirectDraw object and set the cooperative level, you can create the surfaces that your application will use to render and display a scene. Exactly how you create your surfaces depends largely on whether or not your application will run in a window or in full-screen mode.

Full-screen Application Note Applications that will run in full-screen mode can create surfaces as shown in the preceding code examples. More often, these applications should take advantage of page-flipping, a feature only available in full-screen, exclusive mode. In this case, instead of explicitly creating two surfaces, you can create a flipping chain of surfaces with a single call. For more information, see Creating Complex Surfaces and Flipping Chains.

The Triangle sample, designed to run in a window, starts by creating a primary surface, which represents the display:

    DDSURFACEDESC2 ddsd;
    ZeroMemory( &ddsd, sizeof(DDSURFACEDESC2) );
    ddsd.dwSize         = sizeof(DDSURFACEDESC2);
    ddsd.dwFlags        = DDSD_CAPS;
    ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;

    // Create the primary surface.
    hr = g_pDD->CreateSurface( &ddsd, &g_pddsPrimary, NULL );
    if( FAILED( hr ) )
        return hr;

The description for the primary surface doesn't contain information about dimensions or pixel format, as these traits are assumed to be the same as the display mode. If the current display mode is 800x600, 16-bit color, DirectDraw ensures that the primary surface matches. After creating the primary surface, you can create the render target surface. In the case of Triangle, this is a separate off-screen surface created as follows:

    ddsd.dwFlags        = DDSD_WIDTH | DDSD_HEIGHT | DDSD_CAPS;
    ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN | DDSCAPS_3DDEVICE;

    // Set the dimensions of the back buffer. Note that if our window changes
    // size, we need to destroy this surface and create a new one.
    GetClientRect( hWnd, &g_rcScreenRect );
    GetClientRect( hWnd, &g_rcViewportRect );
    ClientToScreen( hWnd, (POINT*)&g_rcScreenRect.left );
    ClientToScreen( hWnd, (POINT*)&g_rcScreenRect.right );
    ddsd.dwWidth  = g_rcScreenRect.right - g_rcScreenRect.left;
    ddsd.dwHeight = g_rcScreenRect.bottom - g_rcScreenRect.top;

    // Create the backbuffer. The most likely reason for failure is running
    // out of video memory. (A more sophisticated app should handle this.)
    hr = g_pDD->CreateSurface( &ddsd, &g_pddsBackBuffer, NULL );
    if( FAILED( hr ) )
        return hr;

The preceding code creates an off-screen surface that is equal to the dimensions of the program window. There is no need to create a larger surface, because the dimensions of the window dictate what is visible to the user. (This code also initializes two global variables that are later used to set up the viewport and track the application window size and position.) As the preceding excerpt shows, you must include the DDSCAPS_3DDEVICE capability for any surface that will be used as a render target. This capability causes the system to allocate additional internal data structures that are used only for 3-D rendering. As when creating the primary surface, the pixel format for the off-screen surface is assumed to be the same as the display mode when it isn't provided in the surface description.

Note Applications that will use a depth buffer should create one and attach it to the render target surface at this point. For simplicity, this tutorial doesn't employ a depth buffer, but they are covered in Tutorial 2: Adding a Depth Buffer and in Depth Buffers.

After creating the primary and render target surface, you can create and attach a DirectDrawClipper object to the display surface. Using a clipper frees you from attempting to handle cases when the window is partially obscured by other windows, or when the window is partially outside the display area. Clippers aren't needed for applications that run in full-screen mode. The Triangle sample uses the following code to create a clipper and associate it with the display window:

    LPDIRECTDRAWCLIPPER pcClipper;
    hr = g_pDD->CreateClipper( 0, &pcClipper, NULL );
    if( FAILED( hr ) )
        return hr;

    // Assign it to the window handle, then set
    // the clipper to the desired surface.
    pcClipper->SetHWnd( 0, hWnd );
    g_pddsPrimary->SetClipper( pcClipper );
    pcClipper->Release();

Having created the basic DirectDraw objects, you can move on to setting up the essential Direct3D objects that will render the scene. The Triangle sample performs this task in Step 2.3: Initialize Direct3D.


Step 2.3: Initialize Direct3D

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

After you create the surfaces your application will need to render and display a scene, you can begin initializing Direct3D objects by retrieving a pointer to the IDirect3D7 interface for the DirectDraw object, which is used to create all the objects you'll need to render a scene. Note that this interface is exposed by the DirectDraw object, and represents a separate set of features, not a separate object. You retrieve the IDirect3D7 interface by calling the IUnknown::QueryInterface method of the DirectDraw object. The following code from Triangle performs this task:

    // Query DirectDraw for access to Direct3D
    g_pDD->QueryInterface( IID_IDirect3D7, (VOID**)&g_pD3D );
    if( FAILED( hr) )
        return hr;

After retrieving a pointer to the IDirect3D7 interface, you can create a rendering device by calling the IDirect3D7::CreateDevice method. The CreateDevice method accepts the globally unique identifier (GUID) of the desired device, the address of the IDirectDrawSurface7 interface for the surface that the device will render to, and the address of a variable that the method will set to an IDirect3DDevice7 interface pointer if the device object is created successfully. Although the tutorial uses hard-coded GUID values, a real application should enumerate devices to get a GUID. For information about device enumeration, see Enumerating Direct3D Devices.

(The Triangle sample checks the display mode prior to creating the device. If the display is set to a palettized mode, it exits. Attempting to create a device for a palettized surface that doesn't have an associated palette will cause the CreateDevice method to fail. This is done for simplicity. A real-world application should create a render target surface and attach a palette, or require that the user set their display mode to 16-bit color or higher.)

The following code, taken from Triangle, checks the display mode, and creates a rendering device:

    // Check the display mode, and
    ddsd.dwSize = sizeof(DDSURFACEDESC2);
    g_pDD->GetDisplayMode( &ddsd );
    if( ddsd.ddpfPixelFormat.dwRGBBitCount <= 8 )
        return DDERR_INVALIDMODE;

    // The GUID here is hard coded. In a real-world application
    // this should be retrieved by enumerating devices.
    hr = g_pD3D->CreateDevice( IID_IDirect3DHALDevice, g_pddsBackBuffer,
                               &g_pd3dDevice );
    if( FAILED( hr ) )
    {
        // If the hardware GUID doesn't work, try a software device.
        hr = g_pD3D->CreateDevice( IID_IDirect3DRGBDevice, g_pddsBackBuffer,
                                   &g_pd3dDevice );
        if( FAILED( hr ) )
            return hr;
    }

The CreateDevice method can fail for many reasons. The most likely cause is when the primary display device doesn't support 3-D features. Another possibility is if the display hardware cannot render in the current display mode. These possibilities should be checked during device enumeration. To keep the code simple, Triangle attempts to create a software rendering device if the hardware device cannot be created.

Note Even though the CreateDevice method accepts a pointer to a DirectDrawSurface object, a rendering device is not a surface. Rather, it is a discrete COM object that uses a surface to contain graphics for a rendered scene.

After the device is created, you can create a viewport and assign it to the device, as described in Step 2.4: Prepare the Viewport.


Step 2.4: Prepare the Viewport

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

After you create a rendering device, you can create a viewport and assign it to the device. In short, the viewport determines how the geometry in a 3-D scene is clipped and then represented in the 2-D space of a display screen. (For a conceptual overview about viewports, see Viewports and Clipping.)

Setting up a viewport is a straight-forward process that starts with preparing the viewport parameters in a D3DVIEWPORT7 structure. The Triangle sample sets the viewport parameters to the dimensions of the render target surface:

    // Create the viewport
    DWORD dwRenderWidth  = g_rcScreenRect.right - g_rcScreenRect.left;
    DWORD dwRenderHeight = g_rcScreenRect.bottom - g_rcScreenRect.top;
    D3DVIEWPORT7 vp = { 0, 0, dwRenderWidth, dwRenderHeight, 0.0f, 1.0f };

Once the viewport structure is prepared, the Triangle application assigns it to the rendering device:

    hr = g_pd3dDevice->SetViewport( &vp );
    if( FAILED( hr ) )
        return hr;

Now that the basic DirectX objects have been created, you can start preparing the subordinate objects required to render scene, which is the topic of Step 3: Initialize the Scene.


Step 3: Initialize the Scene

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

After creating the primary Direct3D-related objects—a DirectDraw object, a rendering device, and a viewport—you can begin initializing the scene by setting up geometry, preparing materials, and configuring the transformation matrices your application will use. The Triangle sample uses an application-defined function, App_InitDeviceObjects, to perform the following steps that initialize the scene:

  • Step 3.1: Prepare Geometry
  • Step 3.2: Set Up Material and Initial Lighting States
  • Step 3.3: Prepare and Set Transformation Matrices


Step 3.1: Prepare Geometry

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

After you create the primary system objects used with DirectDraw and Direct3D, you can begin initializing the scene. The Triangle sample takes this opportunity to initialize geometry by defining vertices in an array of D3DVERTEX structures. Technically, you aren't required to set up the geometry at this time—you can do it anytime prior to calling rendering methods:

HRESULT App_InitDeviceObjects( LPDIRECT3DDEVICE7 pd3dDevice )
{
    // Data for the geometry of the triangle. Note that this tutorial only
    // uses ambient lighting, so the vertices' normals are not actually used.
    D3DVECTOR p1( 0.0f, 3.0f, 0.0f );
    D3DVECTOR p2( 3.0f,-3.0f, 0.0f );
    D3DVECTOR p3(-3.0f,-3.0f, 0.0f );
    D3DVECTOR vNormal( 0.0f, 0.0f, 1.0f );

    // Initialize the 3 vertices for the front of the triangle
    g_pvTriangleVertices[0] = D3DVERTEX( p1, vNormal, 0, 0 );
    g_pvTriangleVertices[1] = D3DVERTEX( p2, vNormal, 0, 0 );
    g_pvTriangleVertices[2] = D3DVERTEX( p3, vNormal, 0, 0 );

    // Initialize the 3 vertices for the back of the triangle
    g_pvTriangleVertices[3] = D3DVERTEX( p1, -vNormal, 0, 0 );
    g_pvTriangleVertices[4] = D3DVERTEX( p3, -vNormal, 0, 0 );
    g_pvTriangleVertices[5] = D3DVERTEX( p2, -vNormal, 0, 0 );

The preceding code fragment defines three points in 3-D space that define a triangle that sits upright in the z=0 plane. After defining the geometry to be displayed, the Triangle sample prepares material and lighting parameters in Step 3.2: Set Up Material and Initial Lighting States.


Step 3.2: Set Up Material and Initial Lighting States

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

After you create the basic 3-D rendering objects (a DirectDraw object, a rendering device, and a viewport), you've got almost all you need to render a simple scene. The next thing to do is to create and configure a material and set some initial lighting states. These can all be changed later if needed. For an introduction to these concepts, see Lighting and Materials.

The Triangle sample sets material parameters, as shown here:

    D3DMATERIAL7 mtrl;
    ZeroMemory( &mtrl, sizeof(mtrl) );
    mtrl.ambient.r = 1.0f;
    mtrl.ambient.g = 1.0f;
    mtrl.ambient.b = 0.0f;
    pd3dDevice->SetMaterial( &mtrl );

The preceding code prepares material properties, represented by a D3DMATERIAL7 structure. The code prepares the D3DMATERIAL7 structure to describe a material that will reflect the red and green components of ambient light, making it appear yellow in the scene. (This tutorial only uses ambient light, so it only sets an ambient reflectance property. A real-world application would use direct light as well as ambient light, and should set therefore set diffuse and specular reflectance properties as well.) After preparing the material properties, the code applies them in the device by calling the IDirect3DDevice7::SetMaterial method.

Note When using textures, the object material is usually omitted or colored white.

After the current material is selected, all polygons will be rendered using this material. However, before anything in the scene will be visible you need to provide some light. The code in the Triangle application sets an ambient light level by calling the IDirect3DDevice7::SetRenderState method with the D3DRENDERSTATE_AMBIENT render state for white ambient light:

    // The ambient lighting value is another state to set. Here, we are turning
    // ambient lighting on to full white.
    pd3dDevice->SetRenderState( D3DRENDERSTATE_AMBIENT, 0xffffffff );

Now that the geometry, material, and initial lighting parameters are set, the sample moves on to setting up the transformation matrices. This is covered in Step 3.3: Prepare and Set Transformation Matrices.


Step 3.3: Prepare and Set Transformation Matrices

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

Another step in setting up a simple scene involved setting the world, view, and projection matrices. The system applies these matrices to geometry to place it in the scene, adjust for the camera's location and orientation, and scale vertex data to make distant objects appear smaller than near objects. (For a conceptual overview, see the Geometry Pipeline.)

The Triangle sample starts by creating an identity matrix in a D3DMATRIX structure, then it manipulates the matrix to produce the desired transformations. Once a matrix is ready, the code assigns it to the device by calling the IDirect3DDevice7::SetTransform method with the D3DTRANSFORMSTATE_WORLD, D3DTRANSFORMSTATE_VIEW, or D3DTRANSFORMSTATE_PROJECTION values:

    // Start by setting up an identity matrix.
    D3DMATRIX mat;
    mat._11 = mat._22 = mat._33 = mat._44 = 1.0f;
    mat._12 = mat._13 = mat._14 = mat._41 = 0.0f;
    mat._21 = mat._23 = mat._24 = mat._42 = 0.0f;
    mat._31 = mat._32 = mat._34 = mat._43 = 0.0f;

    // The world matrix controls the position and orientation
    // of the polygons in world space. We'll use it later to
    // spin the triangle.
    D3DMATRIX matWorld = mat;
    pd3dDevice->SetTransform( D3DTRANSFORMSTATE_WORLD, &matWorld );

    // The view matrix defines the position and orientation of
    // the camera. Here, we are just moving it back along the z-
    // axis by 10 units.
    D3DMATRIX matView = mat;
    matView._43 = 10.0f;
    pd3dDevice->SetTransform( D3DTRANSFORMSTATE_VIEW, &matView );

    // The projection matrix defines how the 3-D scene is "projected"
    // onto the 2-D render target surface. For more information,
    // see "What Is the Projection Transformation?"

    // Set up a very simple projection that scales x and y
    // by 2, and translates z by -1.0.
    D3DMATRIX matProj = mat;
    matProj._11 =  2.0f;
    matProj._22 =  2.0f;
    matProj._34 =  1.0f;
    matProj._43 = -1.0f;
    matProj._44 =  0.0f;
    pd3dDevice->SetTransform( D3DTRANSFORMSTATE_PROJECTION, &matProj );

After setting the transformations, Triangle is done setting up the scene. The App_InitDeviceObjects application-defined function returns S_OK to the caller, the Initialize3DEnvironment application-defined function. The Initialize3DEnvironment function then returns that value to WinMain, which moves on to process system messages, as discussed in Step 4: Monitor System Messages.


Step 4: Monitor System Messages

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

After you've created the application window, created the DirectX objects, then initialized the scene, you're ready to render the scene. In most cases Windows applications monitor system messages in their message loop, and render frames whenever no messages are in queue. The Triangle sample is no different; it uses the following code for its message loop:

    BOOL bGotMsg;
    MSG  msg;
    PeekMessage( &msg, NULL, 0U, 0U, PM_NOREMOVE );
    g_bReady = TRUE;

    while( WM_QUIT != msg.message  )
    {
        // Use PeekMessage() if the app is active, so we can use idle time to
        // render the scene. Else, use GetMessage() to avoid eating CPU time.
        if( g_bActive )
            bGotMsg = PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE );
        else
            bGotMsg = GetMessage( &msg, NULL, 0U, 0U );

        if( bGotMsg )
        {
                TranslateMessage( &msg );
                DispatchMessage( &msg );
        }
        else
        {
            // Render a frame during idle time (no messages are waiting)
            if( g_bActive && g_bReady )
                Render3DEnvironment();
        }
    }

This code uses a global flag variable, g_bActive, to keep track of when it's active, and another variable, g_bReady, to indicate that all system objects are ready to render a scene. The application sets g_bActive to FALSE whenever the window isn't visible, and it sets the g_bReady variable to FALSE whenever it needs to recreate the objects used to render the scene. (The latter situation is covered in Handle Window Resizing.)

If the application is active, it checks the message queue to see if there are any pending messages. If there are messages in queue, the code dispatches them like any other Windows application. Otherwise, it calls the Render3DEnvironment application-defined function to render a frame of the scene, which is the topic of Step 5: Render and Display the Scene.


Step 5: Render and Display the Scene

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

Whenever your application isn't processing system messages, it can render a frame of a scene. The Triangle sample renders the scene in the Render3DEnvironment application-defined function called from WinMain whenever the message queue is empty. The Render3DEnvironment function subdivides the task into three substeps:

  • Step 5.1: Update the Scene
  • Step 5.2: Render the Scene
  • Step 5.3: Update the Display


Step 5.1: Update the Scene

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

Immediately after it is called, the Render3DEnvironment application-defined function in the Triangle sample calls App_FrameMove (another application-defined function). The App_FrameMove function simply updates the world matrix that Direct3D applies to the geometry to reflect a rotation around the y-axis based on an internal count value, passed to the function in the fTimeKey parameter. Because the rotation is applied once per frame, the end result looks like the model is rotating in place.

HRESULT App_FrameMove( LPDIRECT3DDEVICE7 pd3dDevice, FLOAT fTimeKey )
{
    // For this simple tutorial, we are rotating the triangle about the y-axis.
    // To do this, just set up a 4x4 matrix defining the rotation, and set it
    // as the new world transform.
    D3DMATRIX matSpin;
    matSpin._11 = matSpin._22 = matSpin._33 = matSpin._44 = 1.0f;
    matSpin._12 = matSpin._13 = matSpin._14 = matSpin._41 = 0.0f;
    matSpin._21 = matSpin._23 = matSpin._24 = matSpin._42 = 0.0f;
    matSpin._31 = matSpin._32 = matSpin._34 = matSpin._43 = 0.0f;

    matSpin._11 = (FLOAT)cos( fTimeKey );
    matSpin._33 = (FLOAT)cos( fTimeKey );
    matSpin._13 = -(FLOAT)sin( fTimeKey );
    matSpin._31 = (FLOAT)sin( fTimeKey );

    pd3dDevice->SetTransform( D3DTRANSFORMSTATE_WORLD, &matSpin );

    return S_OK;
}

In the real world, of course, your applications will do much more than apply a single rotation on a single model. (For more information rotation matrices, see Rotation in the 3-D Transformations section.)

After you update the geometry in the scene, you can render it to the render target surface, as the Triangle sample does in Step 5.2: Render the Scene.


Step 5.2: Render the Scene

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

Once the geometry has been updated to reflect the desired animation, you can render the scene. The Triangle sample takes a typical approach: the App_Render application-defined function called from the sample's Render3DEnvironment function starts by clearing the viewport:

HRESULT App_Render( LPDIRECT3DDEVICE7 pd3dDevice, D3DRECT* prcViewRect )
{
    // Clear the viewport to a blue color.
    pd3dDevice->Clear( 1UL, prcViewRect, D3DCLEAR_TARGET, 0x000000ff,
                       0L, 0L );

The preceding code calls the IDirect3DDevice7::Clear method to clear the viewport. The first two methods that the Clear method accepts are the address of an array of rectangles that describe the areas on the render target surface to be cleared, and a value that informs the method how many rectangles from the array should be cleared. In most cases, you'll use a single rectangle that covers the entire render target. The third parameter determines the method's behavior. It can clear a render-target surface, an associated depth buffer, the stencil buffer, or any combination of the three. Because this tutorial doesn't use a depth buffer, D3DCLEAR_TARGET is the only flag used. The last three parameters are set to reflect clearing values for the render target, depth buffer, and stencil buffer. The Triangle sample sets the clear color for the render target surface to blue. Because the remaining parameters aren't used in this tutorial, the code just sets them to zero. The Clear method will ignores them when the corresponding flag isn't present.

After clearing the viewport, the Triangle sample informs Direct3D that rendering will begin, renders the scene, then signals that rendering is complete, as shown here:

    // Begin the scene
    if( FAILED( pd3dDevice->BeginScene() ) )
        return E_FAIL;

    // Draw the triangle using a DrawPrimitive() call. Subsequent
    // tutorials will go into more detail on the various calls for
    // drawing polygons.
    pd3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, D3DFVF_VERTEX,
                               g_pvTriangleVertices, 6, NULL );

    // End the scene.
    pd3dDevice->EndScene();

    return S_OK;
}

The IDirect3DDevice7::BeginScene and IDirect3DDevice7::EndScene methods signal to the system when rendering is beginning or is complete. You can only call rendering methods between calls to these methods. Even if rendering methods fail, you should call EndScene before calling BeginScene again.

After rendering the scene to the off-screen render target, you can update the user's display. The tutorial sample performs this in Step 5.3: Update the Display.


Step 5.3: Update the Display

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

Once a scene has been rendered to the render-target surface, you can show the results on screen. A windowed application usually does this by blitting the content of the render-target surface to the primary surface, and a full-screen application that employs page-flipping would simply flip the surfaces in the flipping chain. The Triangle sample uses the former method because it runs in a window, using the following code:

HRESULT ShowFrame()
{
    if( NULL == g_pddsPrimary )
        return E_FAIL;

    // We are in windowed mode, so perform a blit from the backbuffer to the
    // correct position on the primary surface
    return g_pddsPrimary->Blt( &g_rcScreenRect, g_pddsBackBuffer,
                               &g_rcViewportRect, DDBLT_WAIT, NULL );
}

Note that the preceding application-defined function simply blits the entire contents of the render target surface to the window on the desktop. The tutorial tracks the destination rectangle for the blit in the g_rcScreenRect global variable. This rectangle is updated whenever the user moves the window, as covered in the Handle Window Movement section.


Step 6: Shut Down

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

At some point during execution, your application must shut down. Shutting down a DirectX application not only means that you should destroy the application window, but you also deallocate any DirectX objects your application uses and invalidate the pointers to them. The Triangle calls an application-defined function to handle this cleanup, called Cleanup3DEnvironment, when it receives a WM_DESTROY message:

HRESULT Cleanup3DEnvironment()
{
    // Cleanup any objects created for the scene
    App_DeleteDeviceObjects( g_pd3dDevice );

    // Release the DDraw and D3D objects used by the app
    if( g_pD3D )           g_pD3D->Release();
    if( g_pddsBackBuffer ) g_pddsBackBuffer->Release();
    if( g_pddsPrimary )    g_pddsPrimary->Release();

    // Do a safe check for releasing the D3DDEVICE. RefCount should be zero.
    if( g_pd3dDevice )
        if( 0 < g_pd3dDevice->Release() )
            return E_FAIL;

    // Do a safe check for releasing DDRAW. RefCount should be zero.
    if( g_pDD )
        if( 0 < g_pDD->Release() )
            return E_FAIL;

    g_pd3dDevice     = NULL;
    g_pD3D           = NULL;
    g_pddsBackBuffer = NULL;
    g_pddsPrimary    = NULL;
    g_pDD            = NULL;

    return S_OK;
}

The preceding function deallocates the DirectX objects it uses by calling the IUnknown::Release methods for each object. Because the tutorial follows COM rules, the reference counts for most objects should become zero and are automatically removed from memory.

In addition to shut down, there are times during normal execution—such as when the user changes the desktop resolution or color depth—when you might need to destroy and re-create the DirectX objects in use. As a result, it's handy to keep your application's cleanup code in one place, which can be called when the need arises.


Handle Window Movement

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

Any DirectX application that runs in a window must track the position of the client area for the window so that blits to the window will appear on the desktop in the right place. Failing to track this results in graphics appearing outside the application window—a confusing sight for the user. The Triangle sample responds to the WM_MOVE messages that the system sends to the window procedure as shown here:

 .
 .
 .
    case WM_MOVE:
        // Move messages need to be tracked to update the screen rects
        // used for blitting the backbuffer to the primary.
        if( g_bActive && g_bReady )
            OnMove( (SHORT)LOWORD(lParam), (SHORT)HIWORD(lParam) );
        break;
 .
 .
 .

The g_bActive variable is set elsewhere in the window procedure to reflect whether or not the window is active—when the window is minimized it's set to FALSE. The g_bReady variable is TRUE except when the application is in the midst of re-creating the DirectX objects it uses. If these variables are both TRUE, the OnMove application-defined function gets called:

VOID OnMove( INT x, INT y )
{
    DWORD dwWidth  = g_rcScreenRect.right - g_rcScreenRect.left;
    DWORD dwHeight = g_rcScreenRect.bottom - g_rcScreenRect.top;
    SetRect( &g_rcScreenRect, x, y, x + dwWidth, y + dwHeight );
}

This function simply recalculates the size of the global variable, g_rcScreenRect, that the tutorial uses as the destination rectangle when it updates the display in Step 5.3: Update the Display.


Handle Window Resizing

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

Any DirectX application that runs in a window must respond to any WM_SIZE messages that the system sends. The render target surface is usually kept as small as possible to conserve memory, and the smallest size is usually the size of the window client area. When window size increases, you must destroy the render target surface and the associated objects and re-create it at an appropriate size. Technically, an application could do this only when the window gets larger, and respond to situations when window size decreases by adjusting the viewport and decreasing the size of the blit accordingly. For simplicity, this tutorial destroys and re-creates the objects it uses whenever it receives a WM_SIZE message:

         .
         .
         .
        case WM_SIZE:
            // Check to see if we are losing or gaining our window.
            // Set the active flag to match.
            if( SIZE_MAXHIDE==wParam || SIZE_MINIMIZED==wParam )
                g_bActive = FALSE;
            else g_bActive = TRUE;

            // A new window size will require a new back buffer size. The
            // easiest way to achieve this is to release and re-create
            // everything. Note: if the window gets too big, we may run out
            // of video memory and need to exit. This simple app exits
            // without displaying error messages, but a real app would
            // behave itself much better.
            if( g_bActive && g_bReady )
            {
                g_bReady = FALSE;
                if( FAILED( Cleanup3DEnvironment() ) )
                    DestroyWindow( hWnd );
                if( FAILED( Initialize3DEnvironment( hWnd ) ) )
                    DestroyWindow( hWnd );
                g_bReady = TRUE;
            }
            break;
         .
         .
         .

Note that the preceding code sets a global variable to communicate to other portions of the code that the DirectX objects in use are being invalidated. In addition, this code calls the application-defined Cleanup3DEnvironment function to destroy the objects, which is also called during application shut-down. Ending the application is discussed in Step 6: Shut Down.


Tutorial 2: Adding a Depth Buffer

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

Direct3D applications often rely on depth buffers to properly display objects in a scene. For a conceptual overview, see Depth Buffers. To use depth buffering, you must enumerate supported depth-buffer formats, create a depth-buffer surface, attach it to a render-target surface, and enable depth buffering for the rendering device.

This tutorial parallels the code in the Triangle sample project which uses the most commonly supported type of depth buffer, a z-buffer. The ZBuffer sample performs the following steps to use a z-buffer:

  • Step 1: Enumerate Depth-Buffer Formats
  • Step 2: Create the Depth Buffer
  • Step 3: Attach the Depth Buffer
  • Step 4: Enable Depth Buffering

Note The code in the ZBuffer sample is nearly identical to the code in Triangle. This tutorial focuses only on the depth-buffer code unique to ZBuffer, and does not cover setting up Direct3D, rendering, shutting down, or handling Windows messages. For information on these tasks, see Tutorial 1: Rendering a Single Triangle.

Because some rendering devices require depth buffers to be located in particular places in memory, the system requires that you create and attach the depth-buffer surface to the render-target surface before you create a rendering device.


Step 1: Enumerate Depth-Buffer Formats

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

Before you can create a depth buffer you must determine what depth-buffer formats, if any, are supported by the rendering device. Call the IDirect3D7::EnumZBufferFormats method to enumerate the depth-buffer formats that the device supports. The ZBuffer sample uses the following code to enumerate depth-buffer formats:

    //-------------------------------------------------------------------------
    // Create the z-buffer AFTER creating the backbuffer and BEFORE creating
    // the d3ddevice.
    //
    // Note: before creating the z-buffer, apps may want to check the device
    // caps for the D3DPRASTERCAPS_ZBUFFERLESSHSR flag. This flag is true for
    // certain hardware that can do HSR (hidden-surface-removal) without a
    // z-buffer. For those devices, there is no need to create a z-buffer.
    //-------------------------------------------------------------------------

    DDPIXELFORMAT ddpfZBuffer;
    g_pD3D->EnumZBufferFormats( *pDeviceGUID,
                                 EnumZBufferCallback, (VOID*)&ddpfZBuffer );

The EnumZBufferFormats method accepts the globally unique identifier (GUID) of the device for which the formats will be enumerated, the address of a callback function, and the address of an arbitrary data structure that will be passed to the callback function. The callback function you provide must conform to the D3DEnumPixelFormatsCallback function prototype. The system calls the specified callback function once for each supported depth-buffer format, unless the callback function returns D3DENUMRET_CANCEL. The ZBuffer sample processes callbacks as follows:

static HRESULT WINAPI EnumZBufferCallback( DDPIXELFORMAT* pddpf,
                                           VOID* pddpfDesired )
{
    // For this tutorial, we are only interested in z-buffers, so ignore any
    // other formats (e.g. DDPF_STENCILBUFFER) that get enumerated. An app
    // could also check the depth of the z-buffer (16-bit, etc,) and make a
    // choice based on that, as well. For this tutorial, we'll take the first
    // one we get.
    if( pddpf->dwFlags == DDPF_ZBUFFER )
    {
        memcpy( pddpfDesired, pddpf, sizeof(DDPIXELFORMAT) );

        // Return with D3DENUMRET_CANCEL to end the search.
        return D3DENUMRET_CANCEL;
    }

    // Return with D3DENUMRET_OK to continue the search.
    return D3DENUMRET_OK;
}

When the system calls the callback function, it passes the address of a DDPIXELFORMAT structure that describes the pixel format of the depth buffer. The dwFlags member will contain DDPF_ZBUFFER for any pixel formats that include depth-buffer bits. If so, the dwZBufferBitDepth member includes an integer that represents the number of bits in the pixel format reserved for depth information, and the dwZBitMask member masks the relevant bits.

For simplicity, this tutorial only uses z-buffers, which are the most common type of depth buffer. It ignores any other formats (such as DDPF_STENCILBUFFER) that the system enumerates. Applications could also check the bit depth of the z-buffer (8-, 16-, 24-, 32-bit) and make a choice based on that as well. If a suitable format is found, the function copies the provided DDPIXELFORMAT structure to the address passed in the second parameter (also a DDPIXELFORMAT structure), and returns D3DENUMRET_CANCEL to stop the enumeration.

After you determine the format of the depth buffer, you can create a DirectDrawSurface that uses that format, which is the topic of Step 2: Create the Depth Buffer.


Step 2: Create the Depth Buffer

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

Now that you have chosen the depth-buffer format, you can create the DirectDrawSurface object that will become the depth buffer. The pixel format of the surface is the one determined through enumeration, but the surface dimensions must be identical to the render-target surface to which it will be attached. The ZBuffer sample uses the following code for this task:

    // If we found a good zbuffer format, then the dwSize field will be
    // properly set during enumeration. Else, we have a problem and will exit.
    if( sizeof(DDPIXELFORMAT) != ddpfZBuffer.dwSize )
        return E_FAIL;

    // Get z-buffer dimensions from the render target
    // Setup the surface desc for the z-buffer.
    ddsd.dwFlags        = DDSD_CAPS|DDSD_WIDTH|DDSD_HEIGHT|DDSD_PIXELFORMAT;
    ddsd.ddsCaps.dwCaps = DDSCAPS_ZBUFFER;
    ddsd.dwWidth        = g_rcScreenRect.right - g_rcScreenRect.left;
    ddsd.dwHeight       = g_rcScreenRect.bottom - g_rcScreenRect.top;
    memcpy( &ddsd.ddpfPixelFormat, &ddpfZBuffer, sizeof(DDPIXELFORMAT) );

    // For hardware devices, the z-buffer should be in video memory. For
    // software devices, create the z-buffer in system memory
    if( IsEqualIID( *pDeviceGUID, IID_IDirect3DHALDevice ) )
        ddsd.ddsCaps.dwCaps |= DDSCAPS_VIDEOMEMORY;
    else
        ddsd.ddsCaps.dwCaps |= DDSCAPS_SYSTEMMEMORY;

    // Create and attach a z-buffer. Real apps should be able to handle an
    // error here (DDERR_OUTOFVIDEOMEMORY may be encountered). For this
    // tutorial, though, we are simply going to exit ungracefully.
    if( FAILED( hr = g_pDD->CreateSurface( &ddsd, &g_pddsZBuffer, NULL ) ) )
        return hr;

The preceding code simply prepares a DDSURFACEDESC2 structure for the depth buffer, using the dimensions of the render-target surface calculated from previously set global variables. The pixel format information retrieved during the previous step, Step 1: Enumerate Depth-Buffer Formats, is copied into the surface description.

Note A hardware device can use a depth buffer regardless of its location in memory. When using a hardware device, it's best to let the device determine the best location for the buffer by omitting the DDSCAPS_VIDEOMEMORY and DDSCAPS_SYSTEMMEMORY surface capability flags. However, a software device can only be created if the depth buffer exists in system memory. The preceding code checks for this possibility and includes the DDSCAPS_SYSTEMMEMORY flag if necessary.

Once the surface description is ready, the code calls the IDirectDraw7::CreateSurface method to create the new depth-buffer surface. After the depth buffer is created, it can be attached to the surface that will be used as the render target, as described in Step 3: Attach the Depth Buffer.


Step 3: Attach the Depth Buffer

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

Once the depth buffer is created, you need to attach it to the surface that will be used as the render target. Do this by calling the IDirectDrawSurface7::AddAttachedSurface method of the render-target surface. The ZBuffer sample performs this with the following code:

    // Attach the z-buffer to the back buffer.
    if( FAILED( hr = g_pddsBackBuffer->AddAttachedSurface( g_pddsZBuffer ) ) )
        return hr;

Once the depth buffer is attached to the render-target surface, the system will automatically use the depth buffer whenever depth buffering is enabled, as discussed in Step 4: Enable Depth Buffering.


Step 4: Enable Depth Buffering

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

After attaching the depth buffer to the render-target surface, you can create a rendering device from the render target. Given a rendering device, you enable depth buffering by setting the D3DRENDERSTATE_ZENABLE render state for the device. The D3DZBUFFERTYPE enumerated type includes members to set the depth-buffer render state. The D3DZB_TRUE member (or TRUE) enables z-buffering. The ZBuffer sample enables z-buffering during scene rendering in the App_Render application-defined function. The following is the appropriate excerpt from App_Render:

    // Enable z-buffering. (Note: we don't really need to do this every frame.)
    pd3dDevice->SetRenderState( D3DRENDERSTATE_ZENABLE, TRUE );

Although this tutorial enables depth-buffering each frame, it is not necessary to do so. A real-world application would likely set the D3DRENDERSTATE_ZENABLE render state during scene initialization, only changing to disable depth buffering or to choose another type of depth buffering.

Note The D3DZBUFFERTYPE enumerated type includes the D3DZB_USEW value to enable w-based depth comparisons on compliant hardware. For more information, see Depth Buffers.


Tutorial 3: Using Alternate Primitive Styles

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

The Using Alternate Primitive Styles tutorial demonstrates how to render polygons using the various draw primitive calls provided by Direct3D. The primitives in this tutorial are polygons, which are closed, three-dimensional (3-D) objects identified by at least three vertices.

Specifically, this tutorial demonstrates how to prepare the geometry for a series of primitives (a series of wall segments, a cone, and a cube); it illustrates how to rotate the viewpoint; and it uses matrix concatenation to perform a 3-D transformation: translating, rotating, and scaling a cube.

  • Step 1: Initialize the Scene Geometry
  • Step 2: Render and Display the Scene

For more information on 3-D primitives, see 3-D Primitives.

Note The code in the DrawPrims application is similar to the code in the Triangle application. This tutorial focuses only on the geometric preparation and rendering code unique to the DrawPrims application, and does not cover setting up Direct3D, shutting down, or processing system events. For information on these tasks, see Tutorial 1: Rendering a Single Triangle.

The Using Alternate Primitive Styles tutorial uses a depth buffer to store depth information for the scene. To use depth buffering, you must enumerate supported depth-buffer formats, create a depth-buffer surface, attach the depth-buffer surface to a render-target surface, and enable depth buffering for the rendering device. For information on these tasks, see Tutorial 2: Adding a Depth Buffer.


Step 1: Initialize the Scene Geometry

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

This tutorial prepares the geometry for the primitives in the application-defined App_InitDeviceObjects method. App_InitDeviceObjects defines a series of vertices for each object; retaining each primitive's vertex information in globally defined data structures. Vertex information is used by the DrawPrimitive Methods during rendering.

Technically, you are not required to set up the geometry at this time—you can do it anytime prior to calling the rendering methods.

  • Step 1.1: Prepare the Wall Segments
  • Step 1.2: Prepare the Cone
  • Step 1.3: Prepare the Cube

For more information on primitive types, see Primitive Types.

For more information on specifying vertices in Direct3D, see Vertex Formats.

Note The order in which the geometry is prepared for specific primitives does not effect the layout of objects in your scene.


Step 1.1: Prepare the Wall Segments

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

The Using Alternate Primitive Styles tutorial describes the wall segments in your scene with D3DVERTEX structures, which are untransformed and unlit vertices. When you use untransformed and unlit vertices, you effectively request that Direct3D use its own internal algorithms to perform transformation and lighting operations.

You can define each wall segment in 3-D space by calculating and saving the information for a pair of vertices, as demonstrated in the following code from the DrawPrims application:

HRESULT App_InitDeviceObjects( LPDIRECT3DDEVICE7 pd3dDevice )
{
    DWORD i;

    for( i=0; i<NUM_WALL_SIDES; i++ )
    {
        FLOAT x = (FLOAT)sin( 2*g_PI*i/(NUM_WALL_SIDES-1) );
        FLOAT z = (FLOAT)cos( 2*g_PI*i/(NUM_WALL_SIDES-1) );

        g_pvWall[2*i+0] = D3DVERTEX( 10.0f * D3DVECTOR( x, -0.1f, z ),
                          D3DVECTOR( -x, 0, -z ), 0, 0 );
        g_pvWall[2*i+1] = D3DVERTEX( 10.0f * D3DVECTOR( x, 0.1f, z ),
                          D3DVECTOR( -x, 0, -z ), 0, 0 );

    }

The preceding code fills an array of D3DVERTEX structures, g_pvWall., with vertex component data. The code locates the x- and z- coordinates of the vertex by using trigonometric functions. The D3DVERTEX structure requires that you specify your coordinates in model coordinates. Since we have used untransformed and unlit vertices, the system will apply world, view, and projection transformations to the model coordinates to properly position them within your scene. Also, the x-, y-, and z-coordinates of the vertex are scaled by a value of ten to properly size the wall segments.

After defining the geometry for the wall segments in the scene, you can move on to preparing another geometric primitive for your scene, a cone. Again, note that the order in which specific objects are defined is not critical.

Defining a cone in 3-D space is demonstrated in Step 1.2: Prepare the Cone.


Step 1.2: Prepare the Cone

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

To prepare the geometry for a cone, you only need to declare a position vector and a normal vector. Therefore, the cone object in the DrawPrims application is defined with the following programmer-defined structure:

struct MyFlexibleVertex
{
    D3DVECTOR vPosition;
    D3DVECTOR vNormal;
};

You define the tip of the cone with the following code fragment:

    g_pvCone[0].vPosition = D3DVECTOR( 0, CONE_HEIGHT/2, 0 );
    g_pvCone[0].vNormal   = Normalize( D3DVECTOR( 0, 1, 0 ) );

You compute each side of the cone with the following trigonometric functions:

    for( i=0; i<NUM_CONE_SIDES; i++ )
    {
        FLOAT x = (FLOAT)sin( 2*g_PI*i/(NUM_CONE_SIDES-1) );
        FLOAT y = -CONE_HEIGHT/2;
        FLOAT z = (FLOAT)cos( 2*g_PI*i/(NUM_CONE_SIDES-1) );
        g_pvCone[i+1].vPosition = CONE_RADIUS * D3DVECTOR( x, y, z );

You calculate the position vector of each side of the cone with the following code fragment:

    g_pvCone[i+1].vNormal   = Normalize( D3DVECTOR( x, 0.5f, z ) );
    }

After defining the wall segments and the cone in geometric space, you can move on to preparing the cube. This process is described in Step 1.3: Prepare the Cube.


Step 1.3: Prepare the Cube

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

The cube will be represented as an indexed primitive; thus; the cube will be rendered by indexing into an array of vertices. Specifically, the following indices will be used to index into the cube's vertex list during rendering:

    WORD* pwIndex = g_pwCubeIndices;
    *pwIndex++ = 1;  *pwIndex++ = 2;  *pwIndex++ = 3;
    *pwIndex++ = 2;  *pwIndex++ = 1;  *pwIndex++ = 0;
    *pwIndex++ = 4;  *pwIndex++ = 5;  *pwIndex++ = 6;
    *pwIndex++ = 6;  *pwIndex++ = 5;  *pwIndex++ = 7;
    *pwIndex++ = 3;  *pwIndex++ = 2;  *pwIndex++ = 6;
    *pwIndex++ = 3;  *pwIndex++ = 6;  *pwIndex++ = 7;
    *pwIndex++ = 0;  *pwIndex++ = 1;  *pwIndex++ = 4;
    *pwIndex++ = 4;  *pwIndex++ = 1;  *pwIndex++ = 5;
    *pwIndex++ = 2;  *pwIndex++ = 0;  *pwIndex++ = 4;
    *pwIndex++ = 2;  *pwIndex++ = 4;  *pwIndex++ = 6;
    *pwIndex++ = 1;  *pwIndex++ = 3;  *pwIndex++ = 5;
    *pwIndex++ = 5;  *pwIndex++ = 3;  *pwIndex++ = 7;

After defining the geometry for all of your objects in the scene, you can render and display the scene, which is the topic of Step 2: Render and Display the Scene.


Step 2: Render and Display the Scene

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

To properly display and manipulate your objects in a scene, you need to define the viewpoint of your scene, create the view matrix, perform any necessary transformations, and, of course, render the completed scene. These tasks are explained in the following steps:

  • Step 2.1: Define the Viewpoint
  • Step 2.2: Create and Set the View Matrix
  • Step 2.3: Perform the 3-D Transformation
  • Step 2.4: Render the Scene

For more information on rendering primitives, see Rendering Primitives.


Step 2.1: Define the Viewpoint

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

This tutorial uses the application-defined subroutine App_FrameMove to rotate the viewpoint around in a circle. The viewpoint is most conveniently defined by three D3DVECTOR structures: an eye point, a look-at point, and a vector defining the up direction:

HRESULT App_FrameMove( LPDIRECT3DDEVICE7 pd3dDevice, FLOAT fTimeKey )
{
    D3DVECTOR vEyePt    = D3DVECTOR( 5*sinf( fTimeKey), 3, 5*cosf( fTimeKey ) );
    D3DVECTOR vLookatPt = D3DVECTOR( 4*sinf( fTimeKey+0.1f), 2.5, 4*cosf( fTimeKey+0.1f ) );
    D3DVECTOR vUpVec    = D3DVECTOR( 0, 1, 0 );

You use the three vectors to create a new view matrix:

    D3DMATRIX matView;
    SetViewMatrix( matView, vEyePt, vLookatPt, vUpVec );

The preceding code creates a new view matrix for the device by passing the eye point, the look-at point, and the vector defining the up direction to the programmer-defined SetViewMatrix method, which is explained in Step 2.2: Create and Set the View Matrix.


Step 2.2: Create and Set the View Matrix

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

Given an eye point, a look-at point, and an up vector, you can manually build a 4x4 view matrix for your application. First, get the z basis vector, which points straight ahead:

HRESULT SetViewMatrix( D3DMATRIX& mat, D3DVECTOR& vFrom, D3DVECTOR& vAt,
                       D3DVECTOR& vWorldUp )
{
    // Get the z basis vector, which points straight ahead. This is the
    // difference from the eyepoint to the lookat point.
    D3DVECTOR vView = vAt - vFrom;

The z basis vector is the difference from the eye point to the look-at point. You should normalize the z basis vector before using it in your calculations:

    FLOAT fLength = Magnitude( vView );
    if( fLength < 1e-6f )
        return E_INVALIDARG;

    // Normalize the z basis vector
    vView /= fLength;

The preceding code uses the Magnitude function to return the absolute value of the view vector; the Magnitude function is available to programmers who define D3D_OVERLOADS in their projects. For more information on the helper functions provided by the D3D_OVERLOADS C++ extensions, see D3D_OVERLOADS Helper Functions.

Now, you can retrieve the dot product and calculate the projection of the z basis vector onto the up vector. The resulting projection is the y basis vector:

    FLOAT fDotProduct = DotProduct( vWorldUp, vView );

    D3DVECTOR vUp = vWorldUp - fDotProduct * vView;

Note DotProduct is a function defined in D3D_OVERLOADS.

The following code fragment normalizes the y-basis vector:

    vUp /= fLength;

To find the x basis vector, determine the cross product of the y and z basis vectors:

    D3DVECTOR vRight = CrossProduct( vUp, vView );

Note CrossProduct is a function defined in D3D_OVERLOADS.

At this point, you have enough information to begin building the new view matrix. In the following code, the first three rows contain the basis vectors used to rotate the view to point at the look-at point:

    mat._11 = vRight.x;  mat._12 = vUp.x;  mat._13 = vView.x;  mat._14 = 0.0f;
    mat._21 = vRight.y;  mat._22 = vUp.y;  mat._23 = vView.y;  mat._24 = 0.0f;
    mat._31 = vRight.z;  mat._32 = vUp.z;  mat._33 = vView.z;  mat._34 = 0.0f;

Now, you set the translation values. Note that rotations are still about the eye point:

    mat._41 = - DotProduct( vFrom, vRight );
    mat._42 = - DotProduct( vFrom, vUp );
    mat._43 = - DotProduct( vFrom, vView );
    mat._44 = 1.0f;

After setting the translation values, control returns to the calling application-defined function, App_FrameMove. You can put the new view matrix into effect by calling the IDirect3DDevice7::SetTransform method:

    pd3dDevice->SetTransform( D3DTRANSFORMSTATE_VIEW, &matView );

The cube's vertices are transformed by the programmer-defined function, TransformVertices, which is explained in Step 2.3: Perform the 3-D Transformation.


Step 2.3: Perform the 3-D Transformation

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

Your scene is nearly completed; however, you still need to manually rotate, transform, and scale the cube's vertices. First, fill the array of D3DTLVERTEX structures, g_pvCube, with untransformed data for the cube. Note that the first three parameters represent the untransformed position of each vertex in screen coordinates:

    g_pvCube[0] = D3DTLVERTEX( D3DVECTOR(-1,-1,-1 ), 0, 0xffffffff, 0, 0, 0 );
    g_pvCube[1] = D3DTLVERTEX( D3DVECTOR( 1,-1,-1 ), 0, 0xff00ffff, 0, 0, 0 );
    g_pvCube[2] = D3DTLVERTEX( D3DVECTOR(-1, 1,-1 ), 0, 0xffff00ff, 0, 0, 0 );
    g_pvCube[3] = D3DTLVERTEX( D3DVECTOR( 1, 1,-1 ), 0, 0xff0000ff, 0, 0, 0 );
    g_pvCube[4] = D3DTLVERTEX( D3DVECTOR(-1,-1, 1 ), 0, 0xffffff00, 0, 0, 0 );
    g_pvCube[5] = D3DTLVERTEX( D3DVECTOR( 1,-1, 1 ), 0, 0xff00ff00, 0, 0, 0 );
    g_pvCube[6] = D3DTLVERTEX( D3DVECTOR(-1, 1, 1 ), 0, 0xffff0000, 0, 0, 0 );
    g_pvCube[7] = D3DTLVERTEX( D3DVECTOR( 1, 1, 1 ), 0, 0xff000000, 0, 0, 0 );

Now, call the programmer-defined function TransformVertices to manually transform the cube's eight vertices:

    TransformVertices( pd3dDevice, g_pvCube, 8 );

However, before implementing your 3-D transformation, you will need to retrieve the height and width of the viewport. This information is used to scale the transformed vertices to fit the render window:

HRESULT TransformVertices( LPDIRECT3DDEVICE7 pd3dDevice,
                           D3DTLVERTEX* pvVertices, DWORD dwNumVertices )
{
    // Get the width and height of the viewport. This is needed to scale the
    // transformed vertices to fit the render window.
    D3DVIEWPORT7 vp;
    pd3dDevice->GetViewport( &vp );
    DWORD dwClipWidth  = vp.dwWidth/2;
    DWORD dwClipHeight = vp.dwHeight/2;

Direct3D uses matrices to perform transformations. In order to execute a 3-D transformation, you need to retrieve the values of the current matrix set. You do this by calling IDirect3DDevice7::GetTransform on the rendering device:

    D3DMATRIX matWorld, matView, matProj;
    pd3dDevice->GetTransform( D3DTRANSFORMSTATE_WORLD,      &matWorld );
    pd3dDevice->GetTransform( D3DTRANSFORMSTATE_VIEW,       &matView );
    pd3dDevice->GetTransform( D3DTRANSFORMSTATE_PROJECTION, &matProj );

You use matrix multiplication to concatenate the matrices:

    D3DMATRIX matTemp = matWorld * matView;
    D3DMATRIX matSet = matTemp * matProj;

In the preceding code, a composite matrix, matSet, is calculated to represent the product of the desired transformations. During concatenation, ensure that the matrices are multiplied in the order in which you want them to operate.

For more information on matrix concatenation, see Matrix Concatenation.

Now, you transform each vertex through the current matrix set:

    for( DWORD i=0; i<dwNumVertices; i++ )
    {
        // Get the untransformed vertex position
        FLOAT x = pvVertices[i].sx;
        FLOAT y = pvVertices[i].sy;
        FLOAT z = pvVertices[i].sz;

        // Transform it through the current matrix set
        FLOAT xp = matSet._11*x + matSet._21*y + matSet._31*z + matSet._41;
        FLOAT yp = matSet._12*x + matSet._22*y + matSet._32*z + matSet._42;
        FLOAT zp = matSet._13*x + matSet._23*y + matSet._33*z + matSet._43;
        FLOAT wp = matSet._14*x + matSet._24*y + matSet._34*z + matSet._44;

Finally, scale the vertices to screen coordinates. In the following code, the first step flattens the coordinates from 3-D space to 2-D device coordinates by dividing each coordinate by the wp value. Then, the x- and y-components are transformed from device coordinates to screen coordinates.

        pvVertices[i].sx  = ( 1.0f + (xp/wp) ) * dwClipWidth;
        pvVertices[i].sy  = ( 1.0f - (yp/wp) ) * dwClipHeight;
        pvVertices[i].sz  = zp / wp;
        pvVertices[i].rhw = wp;
    }

For more information on 3-D transformations, see 3-D Transformations.

Note Device coordinates range from -1 to +1 in the viewport. Also, the sz-coordinate will be used in the z-buffer.

Now that you have transformed the cube's eight vertices, you can render a frame of the completed the scene. This is shown in Step 2.4: Render the Scene.


Step 2.4: Render the Scene

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

The following IDirect3DDevice7::DrawPrimitive call draws a wall segment composed of a D3DVERTEX-type triangle strip:

    pd3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, D3DFVF_VERTEX,
                               g_pvWall, NUM_WALL_VERTICES, NULL );

The following DrawPrimitive call draws a cone which is a triangle fan of custom, flexible vertices:

    pd3dDevice->DrawPrimitive( D3DPT_TRIANGLEFAN, D3DFVF_XYZ|D3DFVF_NORMAL,
                               g_pvCone, NUM_CONE_VERTICES, NULL );

Lastly, the following IDirect3DDevice7::DrawIndexedPrimitive call draws a cube which is composed of application transformed and lit, indexed vertices:

    pd3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, D3DFVF_TLVERTEX,
                                      g_pvCube, NUM_CUBE_VERTICES,
                                      g_pwCubeIndices, NUM_CUBE_INDICES, NULL );


Tutorial 4: Using Device Enumeration

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

Device enumeration is useful because it allows applications to query hardware for the Direct3D devices that the hardware supports. As a result, you can build applications that take advantage of particular hardware configurations, or you can let the user choose a particular configuration supported by their system's hardware. The Using Device Enumeration tutorial enumerates the drivers, display modes, and devices on your system and then creates a list of supported display modes for each device.

Basically, device enumeration can be partitioned into two broad steps: (1) initiating and completing device enumeration and (2) selecting an enumerated device.

The Device Enumeration tutorial mirrors this process with the following sections:

  • Step 1: Initiate and Complete Device Enumeration
  • Step 2: Select an Enumerated Device

For more information on Direct3D devices, see Direct3D Devices.

For more information on device enumeration, see Enumerating Direct3D Devices.

Note The code in the Enumeration application is similar to the code in the Triangle application. This tutorial focuses only on the device enumeration code unique to the Enumeration application, and does not cover setting up Direct3D, preparing scene geometry, shutting down, or processing system events. For information on these tasks, see Tutorial 1: Rendering a Single Triangle.

The Device Enumeration tutorial uses a depth buffer to store depth information for the scene. To use depth buffering, you must enumerate supported depth-buffer formats, create a depth-buffer surface, attach the depth-buffer surface to a render-target surface, and enable depth buffering for the rendering device. For information on these tasks, see Tutorial 2: Adding a Depth Buffer.

The Device Enumeration tutorial draws a series of cone primitives. For more information on how to draw primitives, see Tutorial 3: Using Alternate Primitive Styles.


Step 1: Initiate and Complete Device Enumeration

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

The Enumeration application uses the following structure to hold information about the enumerated Direct3D devices:

struct D3DDEVICEINFO
{
    // D3D Device info
    CHAR           strDesc[40];
    GUID*          pDeviceGUID;
    D3DDEVICEDESC7 ddDeviceDesc;
    BOOL           bHardware;

    // DDraw Driver info
    GUID*          pDriverGUID;
    DDCAPS         ddDriverCaps;
    DDCAPS         ddHELCaps;

    // DDraw Mode Info
    DDSURFACEDESC2 ddsdMode;
    BOOL           bFullscreen;

    // For internal use (apps should not need these)
    GUID           guidDevice;
    GUID           guidDriver;
    DDSURFACEDESC2 ddsdModes[100];
    DWORD          dwNumModes;
    DWORD          dwCurrentMode;
    BOOL           bDesktopCompatible;
};

The Enumeration application initiates enumeration with the following call:

INT UserDlgSelectDriver( HWND hwndParent )
{
    // Enumerate drivers, devices, and modes
    DirectDrawEnumerateEx( DriverEnumCallback, NULL,
                           DDENUM_ATTACHEDSECONDARYDEVICES |
                           DDENUM_DETACHEDSECONDARYDEVICES |
                           DDENUM_NONDISPLAYDEVICES );

In the preceding code, the DirectDrawEnumerateEx method is used to enumerate the drivers, devices, and display modes available on the system. The first parameter, DriverEnumCallback, is the address of a DDEnumCallbackEx function that will be called with a description of each enumerated DirectDraw-enabled HAL.

The process of enumerating devices for your application can be broken down into the following steps:

  • Step 1.1: Enumerate Driver Information
  • Step 1.2: Enumerate Display Mode Information
  • Step 1.3: Enumerate Device Information

The first step for an application that uses device enumeration is to retrieve a reference to the DirectDraw driver. Driver enumeration is explained in Step 1.1: Enumerate Driver Information.

For more information on starting device enumeration, see Starting Device Enumeration.


Step 1.1: Enumerate Driver Information

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

The Enumeration application uses the following application-defined callback function to enumerate all of the DirectDraw devices installed on the system:

static BOOL WINAPI DriverEnumCallback( GUID* pGUID, LPSTR strDesc,
                                       LPSTR strName, VOID*, HMONITOR )

The first parameter, pGUID, is the address of the unique identifier of the DirectDraw object. The next two parameters are strings that describe and name the driver. For more information on this function, consult the DDEnumCallbackEx topic in the SDK reference.

Before you can enumerate driver information, you need to create a display driver. You can use the globally-unique identifier (GUID) that is passed into the DriverEnumCallback application-defined callback function to create a display driver for your application:

hr = DirectDrawCreateEx( pGUID, (VOID**)&pDD, IID_IDirectDraw7, NULL );

The NULL argument indicates that the active display driver should be used. At this point, the Enumeration application creates an IDirect3D7 object, which will be used to enumerate all of the Direct3D devices.

You can copy the driver data to a D3DDEVICEINFO structure, so that driver information can be passed to your application-defined callback functions:

    // Copy data to a device info structure
    ZeroMemory( &d3dDeviceInfo, sizeof(D3DDEVICEINFO) );
    strncpy( d3dDeviceInfo.strDesc, strDesc, 39 );
    d3dDeviceInfo.ddDriverCaps.dwSize = sizeof(DDCAPS);
    d3dDeviceInfo.ddHELCaps.dwSize    = sizeof(DDCAPS);
    pDD->GetCaps( &d3dDeviceInfo.ddDriverCaps, &d3dDeviceInfo.ddHELCaps );
    d3dDeviceInfo.pDriverGUID = pGUID;

Consult the following code sample and note that the ddsdModes member of the D3DDEVICEINFO structure is an array of DDSURFACEDESC2 types that will describe (list) the supported display modes for a particular device. Eventually, you will want to display a combo box to the user that lists the current display mode (windowed) followed by a list of the supported full-screen display modes for each device.

Note The graphical user interface (GUI) design and structure of the Enumeration application is not explained in this tutorial, refer to the code in the SDK for this information.

The following code sample retrieves the display mode information for the current display mode settings:

    if( ( NULL == d3dDeviceInfo.pDriverGUID ) &&
        ( d3dDeviceInfo.ddDriverCaps.dwCaps2 & DDCAPS2_CANRENDERWINDOWED ) )
    {
        // Get the current display depth
        DEVMODE devmode;
        devmode.dmSize = sizeof(DEVMODE);
        EnumDisplaySettings( NULL, ENUM_CURRENT_SETTINGS, &devmode );

        // Set up the mode info
        DDSURFACEDESC2* pMode = &d3dDeviceInfo.ddsdModes[0];
        pMode->ddpfPixelFormat.dwRGBBitCount = devmode.dmBitsPerPel;
        pMode->dwWidth  = 0;
        pMode->dwHeight = 0;

        d3dDeviceInfo.dwNumModes = 1;
    }

The preceding code sample illustrates how to fill the first element of the ddsdModes array with the current display settings. The remaining elements of the ddsdModes array will be filled after the full-screen display modes have been enumerated and selected for each device. Note that the EnumDisplaySettings method is used to obtain information about the current display depth. The depth settings are then saved in a DEVMODE structure, which are then copied into the ddpfPixelFormat.dwRGBBitCount member of the first element of the ddsdModes array:

        pMode->ddpfPixelFormat.dwRGBBitCount = devmode.dmBitsPerPel;

Now, that you have enumerated the DirectDraw drivers on your system and saved the current display settings, you are ready to enumerate display modes.

The details of display mode enumeration are illustrated in Step 1.2: Enumerate Display Mode Information.


Step 1.2: Enumerate Display Mode Information

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

The IDirectDraw7::EnumDisplayModes method enumerates all of the display modes that the hardware exposes through the DirectDraw object. The Enumeration application calls the EnumDisplayModes function with the following parameters:

    // Enumerate the fullscreen display modes.
    pDD->EnumDisplayModes( 0, NULL, &d3dDeviceInfo, ModeEnumCallback );

The NULL argument specifies that all modes should be enumerated. The third parameter, &d3dDeviceInfo, is the address of the D3DDEVICEINFO structure containing driver information, which is passed to each enumeration member. The fourth parameter is the address of an EnumModesCallback2 callback function, ModeEnumCallback, that the enumeration procedure will call for every mode that the hardware exposes:

static HRESULT WINAPI ModeEnumCallback( DDSURFACEDESC2* pddsd,
                                        VOID* pParentInfo )
{
    // Copy the mode into the driver's list of supported modes
    D3DDEVICEINFO* pDriverInfo = (D3DDEVICEINFO*)pParentInfo;
    pDriverInfo->ddsdModes[pDriverInfo->dwNumModes++] = (*pddsd);

    return DDENUMRET_OK;
}

In the preceding code, the first parameter, pddsd, is a read-only DDSURFACEDESC2 structure that contains information on the display mode that can be created. The pParentInfo parameter (application-defined data representing the display driver) is cast to a D3DDEVICEINFO structure, so that it can be safely referenced. After all of the display modes have been enumerated, you are ready to enumerate the Direct3D devices. This step is explained in Step 1.3: Enumerate Device Information.


Step 1.3: Enumerate Device Information

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

The IDirect3D7::EnumDevices method enumerates all of the Direct3D device drivers installed on the system. The Enumeration application calls the EnumDevices function with the following parameters:

    pD3D->EnumDevices( DeviceEnumCallback, &d3dDeviceInfo );

The first argument, DeviceEnumCallback, is the address of a D3DEnumDevicesCallback7 callback function that will be called every time a Direct3D device is submitted for enumeration. The second parameter is a reference to a D3DDEVICEINFO structure, describing the device under enumeration.

For every device that is enumerated, the following function is called:

static HRESULT WINAPI DeviceEnumCallback(LPSTR strDesc,
                                  LPSTR strName, D3DDEVICEDESC7* pDesc,
                                  VOID* pParentInfo )
{

The first two parameters are the string description and name of the device. The third parameter, pDesc, is the address of a D3DDEVICEDESC7 structure the describes the hardware capabilities of the Direct3D device. For more information on this function, see the D3DEnumDevicesCallback7 topic in the SDK reference.

You can set up the device information for the device under enumeration with the following code:

    D3DDEVICEINFO* pDriverInfo = (D3DDEVICEINFO*)pParentInfo;
    D3DDEVICEINFO* pDeviceInfo = &g_d3dDevices[g_dwNumDevices];
    memcpy( &pDeviceInfo->ddDeviceDesc, pDesc, sizeof(D3DDEVICEDESC7) );
    pDeviceInfo->guidDevice   = pDesc->deviceGUID;
    pDeviceInfo->pDeviceGUID  = &pDeviceInfo->guidDevice;
    pDeviceInfo->bHardware    = pDesc->dwDevCaps & D3DDEVCAPS_HWRASTERIZATION;
    pDeviceInfo->dwNumModes   = 0;
    pDeviceInfo->ddDriverCaps = pDriverInfo->ddDriverCaps;
    pDeviceInfo->ddHELCaps    = pDriverInfo->ddHELCaps;

In the preceding code, the D3DDEVICEINFO structure, pDeviceInfo, is filled with the capabilities of the device. Note that pParentInfo is cast to a D3DDEVICEINFO type, so that the driver GUID and description can be extracted from it.

Now that you have the device information, copy the driver GUID and description for the device into the D3DDEVICEINFO structure holding the device information:

        pDeviceInfo->guidDriver  = pDriverInfo->guidDriver;
        pDeviceInfo->pDriverGUID = &pDeviceInfo->guidDriver;
        strncpy( pDeviceInfo->strDesc, pDriverInfo->strDesc, 39 );

After you have enumerated your display driver, display modes, and devices you can select an enumerated device to be used by your application, which is the topic of Step 2: Select an Enumerated Device.


Step 2: Select an Enumerated Device

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

Selecting an enumerated device usually consists of the following steps:

  • Step 2.1: Retrieve the Device
  • Step 2.2: Test the Device

For more information on selecting enumerated devices, see Selecting An Enumerated Device.


Step 2.1: Retrieve the Device

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

Before you can test a device, you must retrieve the device that you want to test. The following section explains how to retrieve device information, so that you can test the device for all of its supported display settings.

 for( DWORD i=0; i<pDriverInfo->dwNumModes; i++ )
    {
        DDSURFACEDESC2 ddsdMode = pDriverInfo->ddsdModes[i];
        DWORD dwModeDepth = ddsdMode.ddpfPixelFormat.dwRGBBitCount;
        DWORD dwBitDepth  = pDeviceInfo->ddDeviceDesc.dwDeviceRenderBitDepth;
        BOOL  bCompatible = FALSE;

The preceding variable assignments retrieve a video mode description for the device, retrieve the bits per pixel support in the returned video mode description, and retrieve the device's rendering bit depth. This information will be used to test the capabilities of the device.

Now that you have the information on the device that you want to test, you can test the device. This step is explained in Step 2.2: Test the Device.


Step 2.2: Test the Device

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

The following code fragment checks the display mode for compatibility with the device, while skipping all 8-bit modes:

        if( (32==dwModeDepth) && (dwBitDepth&DDBD_32) ) bCompatible = TRUE;
        if( (24==dwModeDepth) && (dwBitDepth&DDBD_24) ) bCompatible = TRUE;
        if( (16==dwModeDepth) && (dwBitDepth&DDBD_16) ) bCompatible = TRUE;

Specifically, the preceding code fragment checks to see if the video mode of the specified device is compatible with the rendering depth of the device under enumeration.

If the device is compatible, it is accepted and copied into the array of device-supported display modes:

       if( bCompatible )
            pDeviceInfo->ddsdModes[pDeviceInfo->dwNumModes++] = ddsdMode;
    }

After this loop terminates and all of the devices have been enumerated, the array of display modes, ddsdModes, will hold a list of display modes that meet the specified criteria, all other display modes will be ignored.


Tutorial 5: Using Texture Maps

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

This tutorial explains how to draw a simple 3-D scene using textures. In essence, a Direct3D texture is a bitmap of pixel colors; as a result, any bitmap image can be applied to a Direct3D primitive. Textures are a simple, powerful way to add realism to your 3-D objects without altering their geometry. In this way, textures can be used to enhance a primitive with patterns and illusions of color, roughness, transparency, and smoothness. Specifically, the Using Texture Maps tutorial explains how to create textures from file-based bitmaps and how to render a cube primitive with textures.

Note that texture handles are now obsolete in Direct3D; rather, you create and use textures through interface pointers to the texture surfaces. For more information, see Texture Interfaces and Texture Handles.

In order to add textures to the primitives in your 3-D scenes, complete the following steps:

  • Step 1: Prepare a Textured Surface
  • Step 2: Create a Textured Surface
  • Step 3: Render a Textured Primitive

Direct3D supports an extensive texturing feature set, providing developers with easy access to advanced texturing techniques and strategies. For more information on textures and how they can be used and optimized in Direct3D, see Textures.

Note The code in the Texture application is similar to the code in the Triangle application. This tutorial focuses only on the texturing code unique to the Texture application, and does not cover setting up Direct3D, preparing scene geometry, shutting down, or processing system events. For information on these tasks, see Tutorial 1: Rendering a Single Triangle.

The Texture tutorial draws a cube primitive. For more information on how to draw primitives, see Tutorial 3: Using Alternate Primitive Styles.

The Texture tutorial uses enumeration to enumerate the texture formats. For more information on enumeration techniques and principles, see Tutorial 4: Using Device Enumeration.


Step 1: Prepare a Textured Surface

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

To properly prepare a system-managed texture in a 3-D scene, follow these steps:

  • Step 1.1: Set the Texture Coordinates
  • Step 1.2: Prepare the Texture Surface
  • Step 1.3: Enable Texture Management
  • Step 1.4: Enumerate the Texture Formats

Before creating a texture for a primitive, you need to define the vertices of the primitive along its texture coordinates. This task is defined in Step 1.1: Set the Texture Coordinates.


Step 1.1: Set the Texture Coordinates

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

Direct3D represents textures as two-dimensional arrays of color values. Each element in the array is referred to as a texel. You can identify a texel through column and row numbers, which are labeled U and V, respectively.

Your application can assign texture coordinates directly to vertices by initializing a D3DVERTEX structure with values describing the texture coordinates of the vertex. The following code fragment, taken from the Texture application, creates a set of four vertices describing the front face of a cube:

    *pVertices++ = D3DVERTEX( D3DVECTOR(-1.0f, 1.0f,-1.0f), n0, 0.0f, 0.0f );
    *pVertices++ = D3DVERTEX( D3DVECTOR( 1.0f, 1.0f,-1.0f), n0, 1.0f, 0.0f );
    *pVertices++ = D3DVERTEX( D3DVECTOR(-1.0f,-1.0f,-1.0f), n0, 0.0f, 1.0f );
    *pVertices++ = D3DVERTEX( D3DVECTOR( 1.0f,-1.0f,-1.0f), n0, 1.0f, 1.0f );

For each D3DVERTEX assignment, the first argument defines a vertex, the second argument defines the orientation of the vertex normal vector (for the definition of the normal, see the Texture application code in the SDK), and the next two arguments represent the texture coordinates of the vertex. In this case, you want the application to map the entire bitmap texture onto the front face of a cube, so you will use the following texture coordinates: (0, 0), (1, 0), (0, 1), and (1, 1).

For more information on texture coordinates, see Texture Coordinates.

You should employ the same procedures defined previously for the back, top, bottom, right, and left faces of the cube. See the Texture application code in the SDK for information on how to do this.

The Texture application implements the programmer-defined function CreateTexture to return an IDirectDrawSurface7 object as a texture surface object:

    g_pddsTexture1 = CreateTexture( pd3dDevice, "tree1.bmp" );
    g_pddsTexture2 = CreateTexture( pd3dDevice, "tex1.bmp" );
    g_pddsTexture3 = CreateTexture( pd3dDevice, "earth.bmp" );

In the preceding code, three texture surface objects are created from the following file-based bitmaps: "tree1.bmp, " "tex1.bmp," and "earth.bmp." In each function call, the first argument passed, pd3dDevice, is a reference to the rendering device for the application. The returned texture surface objects (g_pddsTexture1 , g_pddsTexture2 , and g_pddsTexture3) will be set to the cube primitive during rendering.

Now, you can look at the programmer-defined function CreateTexture in detail, to see how texture surface objects are prepared and created. The initial step of this process is illustrated in Step 1.2: Prepare the Texture Surface.


Step 1.2: Prepare the Texture Surface

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

In general, before preparing the actual texture surface, you need to create a handle to the bitmap and load the texture file into it. However, in order to create a handle to the bitmap, you need to ensure that your application can find your bitmap file ("tree1.bmp", "tex1.bmp", and "earth.bmp"). As a first step, check the executable's resource for the bitmap file:

    HBITMAP hbm = (HBITMAP)LoadImage( GetModuleHandle(NULL), strName,
                              IMAGE_BITMAP, 0, 0,
                              LR_CREATEDIBSECTION);

In the preceding LoadImage function call, the first argument is a handle to the file used to the create the calling process, in other words, the executable's resource. You want this first parameter to return a handle to an instance of the module that contains the image to be loaded. The second parameter identifies the bitmap image to load. The third, fourth, and fifth parameters specify to load a bitmap type and to use the actual width and height of the bitmap image. The final argument, a load flag, loads a bitmap without mapping it to the colors of the display device.

For more information on LoadImage, see the Platform SDK.

If the Texture application did not find the file by using the handle to the file used to create the calling process, the Texture application tries to load the bitmap image as a file. Note that a real-world application would try to find the bitmap by searching through multiple file paths.

      hbm = (HBITMAP)LoadImage( NULL, strName, IMAGE_BITMAP, 0, 0,
                                LR_LOADFROMFILE|LR_CREATEDIBSECTION );

In the preceding LoadImage function call, the handle of the instance containing the image is not specified, but the LR_LOADFROMFILE load flag is included to indicate that the strName parameter is the name of the file that contains the bitmap image.

The work of preparing and creating the texture is done with the following call to the programmer-defined function CreateTextureFromBitmap. Note that you pass the function a reference to the rendering device and a handle to the bitmap that you want to use as the texture:

    return CreateTextureFromBitmap( pd3dDevice, hbm );

Note that CreateTextureFromBitmap retrieves the device capabilities, so that it can check to see if the device has any constraints when using textures:

    D3DDEVICEDESC7 ddDesc;
    ddDesc.dwSize = sizeof(D3DDEVICEDESC7);
    if( FAILED( pd3dDevice->GetCaps( &ddDesc ) ) )
        return NULL;

In the preceding code, a D3DDEVICEDESC7 structure, ddDesc, is initialized. Then, the IDirect3DDevice7::GetCaps method is used to retrieve a description of the rendering device.

Now, retrieve the bitmap that you want to use as a texture by using the GetObject function, so that you can extract the width and height of the bitmap graphics object:

    BITMAP bm;
    GetObject( hbm, sizeof(BITMAP), &bm );
    DWORD dwWidth  = (DWORD)bm.bmWidth;
    DWORD dwHeight = (DWORD)bm.bmHeight;

The BITMAP structure is a GDI structure that defines a bitmap, for more information see the Platform SDK.

The GetObject function is a GDI function that obtains information about a specified graphics object, for more information see the Platform SDK.

You can use a DDSURFACEDESC2 structure to describe the texture surface. At this point, you can set up the new surface description for the texture:

    DDSURFACEDESC2 ddsd;
    ZeroMemory( &ddsd, sizeof(DDSURFACEDESC2) );
    ddsd.dwSize          = sizeof(DDSURFACEDESC2);
    ddsd.dwFlags         = DDSD_CAPS|DDSD_HEIGHT|DDSD_WIDTH|
                           DDSD_PIXELFORMAT|DDSD_TEXTURESTAGE;
    ddsd.ddsCaps.dwCaps  = DDSCAPS_TEXTURE;
    ddsd.dwWidth         = dwWidth;
    ddsd.dwHeight        = dwHeight;

By setting the control flags, specifically DDSCAPS_TEXTURE, you inform the system that the surface describes a texture surface. Now, you are ready to enable automatic texture management. This step is explained in Step 1.3: Enable Texture Management.


Step 1.3: Enable Texture Management

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

Before creating the texture surface object, you should turn on texture management for the device. Note that you are using the texture manage attribute, so that Direct3D will take care of the complicated details of texture management.

You can turn on texture management for hardware devices with the following code fragment:

    if( ddDesc.deviceGUID == IID_IDirect3DHALDevice )
        ddsd.ddsCaps.dwCaps2 = DDSCAPS2_TEXTUREMANAGE;
    else if( ddDesc.deviceGUID == IID_IDirect3DTnLHalDevice )
        ddsd.ddsCaps.dwCaps2 = DDSCAPS2_TEXTUREMANAGE;
    else
        ddsd.ddsCaps.dwCaps |= DDSCAPS_SYSTEMMEMORY;

For more information on texture management, see Automatic Texture Management.

Now, use ddDesc (a D3DDEVICEDESC7 structure containing a description of the rendering device) to check device capabilities. You should adjust the width and the height of the surface description, if the driver requires it:

    if( ddDesc.dpcTriCaps.dwTextureCaps & D3DPTEXTURECAPS_POW2 )
    {
        for( ddsd.dwWidth=1;  dwWidth>ddsd.dwWidth;   ddsd.dwWidth<<=1 );
        for( ddsd.dwHeight=1; dwHeight>ddsd.dwHeight; ddsd.dwHeight<<=1 );
    }
    if( ddDesc.dpcTriCaps.dwTextureCaps & D3DPTEXTURECAPS_SQUAREONLY )
    {
        if( ddsd.dwWidth > ddsd.dwHeight ) ddsd.dwHeight = ddsd.dwWidth;
        else                               ddsd.dwWidth  = ddsd.dwHeight;
    }

Now that you have enabled texture management and ensured that the surface description is compatible with the driver, you can enumerate the texture formats. This process is defined in Step 1.4: Enumerate the Texture Formats.


Step 1.4: Enumerate the Texture Formats

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

Enumerating texture formats gives your application the power to select a supported texture format for the rendering device. The IDirect3DDevice7::EnumTextureFormats method is used to query the current driver for a list of supported texture formats:

    pd3dDevice->EnumTextureFormats( TextureSearchCallback, &ddsd.ddpfPixelFormat );

In the preceding function call, the TextureSearchCallback parameter is the address of the application-defined D3DEnumPixelFormatsCallback callback function that will be called for each texture format in the enumeration process.

In the following code excerpt, taken from the TextureSearchCallback callback function, the loop is looking for a device-supported texture pixel format. Specifically, the code searches for a 16-bit texture. Note that all other formats, such as alpha textures, are ignored:

    if( pddpf->dwFlags & (DDPF_LUMINANCE|DDPF_BUMPLUMINANCE|DDPF_BUMPDUDV) )
        return DDENUMRET_OK;

    // Skip any FourCC formats
    if( pddpf->dwFourCC != 0 )
        return DDENUMRET_OK;

    // Skip alpha modes
    if( pddpf->dwFlags&DDPF_ALPHAPIXELS )
        return DDENUMRET_OK;

    // We only want 16-bit formats, so skip all others
    if( pddpf->dwRGBBitCount != 16 )
        return DDENUMRET_OK;

    // We found a good match. Copy the current pixel format to our output
    // parameter
    memcpy( (DDPIXELFORMAT*)param, pddpf, sizeof(DDPIXELFORMAT) );

    // Return with DDENUMRET_CANCEL to end enumeration.
    return DDENUMRET_CANCEL;
}

Now that a texture format supported by the rendering device has been selected from the enumeration of texture formats, TextureEnum, you can create a surface for the texture. This step is detailed in Step 2: Create a Textured Surface.


Step 2: Create a Textured Surface

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

Creating a textured surface from a prepared surface entails the following steps:

  • Step 2.1: Retrieve the Render Target
  • Step 2.2: Create the New Surface
  • Step 2.3: Copy to the Render Surface

Texture surface objects are simply DirectDraw surface object. For more information on texture surfaces, see Texture Surface Objects.

Before creating a textured surface, you need to retrieve the device's render target. This process is explained in Step 2.1: Retrieve the Render Target.


Step 2.1: Retrieve the Render Target

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

At this point, you need to retrieve the device's render target, so that you can use the render target to get a pointer to a DirectDraw object. Then, you need to retrieve the DirectDraw interface, so that you can create a surface.

    LPDIRECTDRAWSURFACE7 pddsRender;
    LPDIRECTDRAW7        pDD;
    pd3dDevice->GetRenderTarget( &pddsRender );
    pddsRender->GetDDInterface( (VOID**)&pDD );
    pddsRender->Release();

The preceding code uses the IDirect3DDevice7::GetRenderTarget method to retrieve a pointer to the DirectDraw surface that is being used as a render target. Then, the IDirectDrawSurface7::GetDDInterface method is used to retrieve an interface to the DirectDraw object that was used to create the render target surface.

After retrieving the render target and a pointer to the DirectDraw interface, you can create the surface for your texture. This is explained in Step 2.2: Create the New Surface.


Step 2.2: Create the New Surface

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

Create a new surface for the texture by using the IDirectDraw7::CreateSurface method:

    if( FAILED( hr = pDD->CreateSurface( &ddsd, &pddsTexture, NULL ) ) )
    {
        pDD->Release();
        return NULL;
    }

The first parameter in the CreateSurface method is the address of the DDSURFACEDESC2 structure describing the surface texture object. After the call completes, the second parameter will be set to a the IDirectDrawSurface7 interface pointer for your texture surface

The surface that you will use as your texture surface has now been created, you are ready to copy the bitmap to the texture surface. This step is explained in Step 2.3: Copy to the Render Surface.


Step 2.3: Copy to the Render Surface

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

In order to copy the bitmap to the texture surface, create a device context (DC) for the bitmap and a DC for the surface.

Note A DC is a GDI structure that stores, retrieves, and modifies the attributes of graphics objects and specifies graphic modes. The DC for the surface contains information that controls the display of graphics on the rendering device. The graphics objects stored in the DC for the bitmap is the bitmap for copying.

You can retrieve the DC for the bitmap with the following code fragment:

    HDC hdcBitmap = CreateCompatibleDC( NULL );
    if( NULL == hdcBitmap )
    {
        pddsTexture->Release();
        return NULL;
    }
    SelectObject( hdcBitmap, hbm );

The CreateCompatibleDC function is a GDI function that creates a memory DC compatible with the specified device (the application's current screen setting). For more information, see the Platform SDK.

Now, you can retrieve the DC for the surface:

    HDC hdcTexture;
    if( SUCCEEDED( pddsTexture->GetDC( &hdcTexture ) ) )
    {

In the preceding code, the IDirectDrawSurface7::GetDC method returns the DC for the surface.

Complete the process of copying the bitmap image to the surface with the following code:

        BitBlt( hdcTexture, 0, 0, bm.bmWidth, bm.bmHeight, hdcBitmap,
                0, 0, SRCCOPY );
        pddsTexture->ReleaseDC( hdcTexture );
    }
    DeleteDC( hdcBitmap );

    // Return the newly created texture
    return pddsTexture;
}

The BitBlt function is a graphics device interface (GDI) function that performs a bit-block transfer of color data from the specified source DC (hdcBitmap) into the destination DC (hdcTexture), for more information see the Platform SDK.

Now that you have created a new surface for your texture, you can use that texture during the rendering of the primitives. This task is illustrated in Step 3: Render a Textured Primitive.


Step 3: Render a Textured Primitive

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See Direct3D Immediate Mode Visual Basic Tutorials.

[C++]

The only difference between rendering a textured primitive and a non-textured primitive is that you have to set the texture during the rendering of a textured primitive.

The following code excerpt from the Texture application draws the front and back faces of a cube, using the textured surface g_pddsTexture1:

    pd3dDevice->SetTexture( 0, g_pddsTexture1 );
    pd3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, D3DFVF_VERTEX,
                               g_pCubeVertices+0, 4, NULL );
    pd3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, D3DFVF_VERTEX,
                               g_pCubeVertices+4, 4, NULL );

The IDirect3DDevice7::SetTexture method assigns a texture to a given stage for the device. Since this tutorial does not use multiple texture blending, the first parameter of SetTexture is 0, specifying a value of 0 for the stage identifier. The second parameter identifies the IDirectDrawSurface7 object being set as the texture.

You should employ the same procedures for the top and bottom faces of the cube, and the left and right faces of the cube, setting g_pddsTexture2 and g_pddsTexture3, respectively. See the Texture application code in the SDK for information on how to do this.

For more information on textured rendering, see Rendering with Texture Surfaces.

For more information on multiple texture blending, see Multiple Texture Blending.


Direct3D Immediate Mode Visual Basic Tutorials

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

The Microsoft® Visual Basic® tutorials in this section show how to create simple Direct3D® applications to do common tasks. These tutorials use many of the Direct3D sample files that are also provided with the DirectX® SDK. The following tutorials are presented here:

  • Tutorial 1: Rendering a Single Triangle
  • Tutorial 2: Adding a Depth Buffer
  • Tutorial 3: Using Alternate Primitive Styles
  • Tutorial 4: Using Device Enumeration
  • Tutorial 5: Using Texture Maps


Tutorial 1: Rendering a Single Triangle

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

To use Direct3D in Visual Basic, you first create a form for your application window, then you create and initialize a series of DirectDraw® and Direct3D related objects. You manipulate these objects through their defined methods, which are also used to initialize subordinate objects required to render a complete scene.

This tutorial illustrates the steps needed to display the simplest possible scene: a single triangle. After helping you set the properties for your main form, the Triangle tutorial details how to properly initialize DirectDraw and Direct3D, including the rendering of the Direct3DDevice object, the lighting, the viewport, the material, and the model's geometry. Then, the tutorial focuses on a pair of subroutines that demonstrate how to render the triangle frame-by-frame, incrementally rotating the triangle about the y-axis.

In the Triangle tutorial, the following steps are used to set up DirectDraw, to set up Direct3D, and to render a scene:

  • Step 1: Create a Form
  • Step 2: Initialize System Objects
  • Step 3: Initialize the Scene
  • Step 4: Execute the Rendering Loop
  • Step 5: Shut Down

Note The Visual Basic code in the Triangle tutorial application separates the DirectDraw and Direct3D initialization code from the application specific code; although this is not necessary, it partitions the code into logical, well-defined units.


Step 1: Create a Form

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

A Visual Basic form serves as your application window. Set the properties for your form in the following manner:

BorderStyle     =   1  'Fixed Single
Caption         =   "Triangle"
ClientHeight    =   3195
ClientLeft      =   5415
ClientTop       =   3300
ClientWidth     =   3720
LinkTopic       =   "Form1"
MaxButton       =   0   'False
MinButton       =   0   'False
ScaleHeight     =   213
ScaleMode       =   0  'User
ScaleWidth      =   254
StartUpPosition =   3  'Windows Default

To show your application window, include the following line in your Form_Load procedure:

    Me.Show

With the application window ready, you can begin setting up the main DirectX objects, which is the topic of Step 2: Initialize System Objects.


Step 2: Initialize System Objects

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

After you create an application window, you can begin initializing the essential DirectX objects you need to render the scene. For a Direct3D application, this entails creating and configuring DirectDraw, rendering surfaces, a rendering device, and a viewport.

The Triangle tutorial application performs system initialization in the InitDDraw application-defined subroutine, called from the Form_Load procedure. The steps executed in the InitDDraw subroutine are presented in the following sub-steps:

  • Step 2.1: Initialize DirectDraw
  • Step 2.2: Set Up DirectDraw Surfaces
  • Step 2.3: Initialize Direct3D
  • Step 2.4: Prepare the Viewport


Step 2.1: Initialize DirectDraw

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

After creating the application window, the first object that you will create is the DirectDraw object, which is required to set your application's cooperative level. The same DirectDraw object will be used to create both the surface for displaying your scene and the render target for your application's rendering device.

The Triangle tutorial application begins initialization by creating a DirectDraw object, as shown in the following code:

Private Sub InitDDraw()
    ' Create the DirectDraw object and set the application
    ' cooperative level.
    Set g_dd = g_dx.DirectDrawCreate("")

The preceding code creates a DirectDraw object by calling the DirectDrawCreate global function. It passes an empty string to request that the function create a DirectDraw object for the active display driver. For hardware that doesn't support GDI, such as 3-D only hardware, you should explicitly specify the globally unique identifier (GUID) of the desired driver.

The Triangle tutorial application sets the cooperative level by calling the DirectDraw7.SetCooperativeLevel method. Setting the cooperative level tells the system whether or not the application will render in full-screen mode or in a normal window. (Note that some hardware cannot render into a window. You can detect such hardware by checking for the absence of the DDCAP2_CANRENDERWINDOWED capability flag when you call DirectDraw7.GetCaps.) The preceding code requests windowed cooperative level, also called the "normal" cooperative level, by including the DDSCL_NORMAL flag in the second parameter passed to SetCooperativeLevel. The SetCooperativeLevel method can fail if another application already owns full-screen, exclusive mode.

The following code shows how to set the application's cooperative level:

    g_dd.SetCooperativeLevel Me.hWnd, DDSCL_NORMAL

Once you create the DirectDraw object and set the cooperative level, you are ready to prepare the surfaces that will be used to contain and display a rendered scene. The Triangle tutorial does this in Step 2.2: Set Up DirectDraw Surfaces.


Step 2.2: Set Up DirectDraw Surfaces

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

After you create a DirectDraw object and set the cooperative level, you can create the surfaces that your application will use to render and display a scene. Exactly how you create your surface depends largely on whether or not your application will run in a window or in full-screen mode.

Full-screen Application Note Applications that will run in full-screen mode can create surfaces as shown in the preceding code examples. Most often, these applications should take advantage of page flipping, a feature only available in full-screen, exclusive mode. Using full-screen mode is the topic of a subsequent tutorial. In this case, instead of explicitly creating two surfaces, you can create a flipping chain of surfaces with a single call. For more information, see Creating Complex Surfaces and Flipping Chains.

The Triangle tutorial application, designed to run in a window, starts by creating a primary surface that functions as the display:

    ' Prepare and create the primary surface.
    g_ddsd.lFlags = DDSD_CAPS
    g_ddsd.ddsCaps.lCaps = DDSCAPS_PRIMARYSURFACE

    Set g_ddsPrimary = g_dd.CreateSurface(g_ddsd)

The description for the primary surface does not contain information about dimensions or pixel format, these traits are assumed to be the same as the display mode. For example, if the current display mode is 800×600, 16-bit color, DirectDraw ensures that the primary surface matches. After creating the primary surface, you can create the render-target surface. In the case of the tutorial application, the render-target surface is a separate off-screen surface created as follows:

    ' Now create the render-target surface. We are reusing g_ddsd here.
    g_ddsd.lFlags = DDSD_HEIGHT Or DDSD_WIDTH Or DDSD_CAPS
    g_ddsd.ddsCaps.lCaps = DDSCAPS_OFFSCREENPLAIN Or DDSCAPS_3DDEVICE

    ' Use the size of the form to determine the size of the render target
    ' and viewport rectangle.
    g_dx.GetWindowRect Me.hWnd, g_rcDest

    ' Set the dimensions of the surface description
    g_ddsd.lWidth = g_rcDest.Right - g_rcDest.Left
    g_ddsd.lHeight = g_rcDest.Bottom - g_rcDest.Top

    ' Create the render-target surface
    Set g_ddsBackBuffer = g_dd.CreateSurface(g_ddsd)

    ' Cache the dimensions of the render target. We'll use
    ' it for blitting operations.
    With g_rcSrc
        .Left = 0: .Top = 0
        .Bottom = g_ddsd.lHeight
        .Right = g_ddsd.lWidth
    End With

The preceding code creates an off-screen surface equal to the dimensions of the application window. The off-screen surface is used to cache the image that will later be blitted to the primary surface. There is no need to create a larger surface, because the dimensions of the window dictate what is visible to the user. (This code also initializes a global variable, g_rcDest, that is used to set up the viewport and to track the application window size and position.) As the preceding code excerpt shows, you must include the DDSCAPS_3DDEVICE capability for any surface that will be used as a render target. This capability instructs the system to allocate additional internal data structures for 3-D rendering. As when creating the primary surface, the pixel format for the off-screen surface is assumed to be the same as the display mode when it is not provided in the surface description.

Note Applications that will use a depth buffer should create one and attach it to the render target surface at this point. For simplicity, this tutorial does not employ a depth buffer, but they are covered in Tutorial 2: Adding a Depth Buffer and in Depth Buffers.

After creating the primary and render-target surface, you can create and attach a DirectDrawClipper object to the display surface. Using a clipper defines your screen boundaries, freeing you from handling cases when the window is partially obscured by other windows, or when the window is partially outside of the display area. Thus, clippers are not needed for applications that run in full-screen mode. The Triangle tutorial application uses the following code to create a clipper and associate it with the display window:

    ' Create a DirectDrawClipper and attach it to the primary surface.
    Dim pcClipper As DirectDrawClipper

    Set pcClipper = g_dd.CreateClipper(0)
    pcClipper.SetHWnd Me.hWnd

    g_ddsPrimary.SetClipper pcClipper

Having created the basic DirectDraw objects, you can move on to setting up the essential Direct3D objects that will be needed to render the scene. The Triangle tutorial demonstrates this task in Step 2.3: Initialize Direct3D.


Step 2.3: Initialize Direct3D

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

After you create the surfaces that your application requires to render and to display a scene, you can begin initializing Direct3D objects by creating a Direct3D7 object, which is used to create all the other objects you will need to render a scene. You create the Direct3D7 object by calling DirectDraw7.GetDirect3D. The following code from the Triangle tutorial application performs this task:

Sub InitD3D()
    Dim d3d As Direct3D7
    Dim ddsd As DDSURFACEDESC2

    ' Retrieve a reference to the Direct3D7 class from the
    ' DirectDraw7 object.
    Set d3d = g_dd.GetDirect3D

After creating a Direct3D7 object, you should create a rendering device to call the Direct3D7.CreateDevice method. The CreateDevice method accepts the globally unique identifier (GUID) of the desired device and the DirectDrawSurface7 object, g_ddsBackBuffer, that the device will render to. This surface must have been created as a 3-D device by using the DDSCAPS_3DDEVICE capability.

Although the tutorial application uses hard-coded GUID values, a real-world application should enumerate devices to get a GUID. For information about device enumeration, see Enumerating Direct3D Devices.

(The application in the Triangle tutorial checks the display mode prior to creating the device. If the display is set to a palettized mode, the application exits. Attempting to create a device for a palettized surface that does not have an associated palette will cause the CreateDevice method to fail. This is done for simplicity, A real-world application should create a render-target surface and attach a palette, or require that the user set their display mode to 16-bit color or higher.)

The following code, taken from the tutorial application, checks the display mode:

    g_dd.GetDisplayMode ddsd

    If ddsd.ddpfPixelFormat.lRGBBitCount <= 8 Then
        MsgBox "This application does not support screen display " & _
               "modes lower than 16-bit."
        End
    End If

Then the tutorial application creates a rendering device:

    Set g_d3dDevice = d3d.CreateDevice("IID_IDirect3DHALDevice", g_ddsBackBuffer)

The call to Direct3D7.CreateDevice can fail for many reasons. The most likely cause is when the primary display device does not support 3-D features. Another possibility is if the display hardware cannot render in the current display mode. These possibilities should be checked during device enumeration. To keep the code simple, the Triangle tutorial application attempts to create a software rendering device if the hardware device cannot be created.

Note Even though the CreateDevice method accepts a DirectDrawSurface7 object, it creates a device object that is separate from a DirectDraw surface object. The device uses a DirectDraw surface as a rendering target.

After the device is created, you can create a viewport object and assign it to the device, as described in Step 2.4: Prepare the Viewport.


Step 2.4: Prepare the Viewport

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

After you create a rendering device, you can create a viewport object and assign it to the rendering device. In short, the viewport determines how the geometry in a 3-D scene is clipped and then represented in the 2-D space of a display screen. For a conceptual overview about viewports, see Viewports and Clipping.

Setting up a viewport is a straight-forward process that starts with preparing the viewport parameters in a D3DVIEWPORT7 type. The Triangle tutorial application sets the viewport parameters to the dimensions of the render target surface, with a standard range of minimum and maximum depth values into which the scene will be rendered, 0.0 and 1.0, respectively:

Dim VPDesc As D3DVIEWPORT7

    VPDesc.lWidth = g_rcDest.Right - g_rcDest.Left
    VPDesc.lHeight = g_rcDest.Bottom - g_rcDest.Top
    VPDesc.minz = 0#
    VPDesc.maxz = 1#

Once the viewport parameter type is ready, the tutorial application sets the viewport parameters for the rendering device:

    g_d3dDevice.SetViewport VPDesc

Now, cache the viewport parameters in a RECT type; you will use this information later during clearing operations.

With g_d3drcViewport(0)
        .X1 = 0: .Y1 = 0
        .X2 = VPDesc.lWidth
        .Y2 = VPDesc.lHeight
    End With

Now that the basic DirectX objects have been created, you can start preparing the subordinate objects required to render the scene, which is the topic of Step 3: Initialize the Scene.


Step 3: Initialize the Scene

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

After creating the primary Direct3D-related objects—a DirectDraw object, a rendering device, and a viewport—you can begin initializing the scene by preparing the materials, configuring the transformation matrices, and setting up the geometry for your application. The Triangle tutorial application performs the following steps, initializing the scene:

  • Step 3.1: Set Up Material and Initial Lighting States
  • Step 3.2: Prepare and Set Transformation Matrices
  • Step 3.3: Prepare the Geometry


Step 3.1: Set Up Material and Initial Lighting States

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

After you create the basic 3-D rendering objects (a DirectDraw object, a rendering device, and a viewport), you nearly have all that you need to render a simple scene. The next thing to do is to set some initial lighting states and to create and configure a material. If necessary, these settings can all be changed later. For an introduction to these concepts, see Lighting and Materials.

The code applies an initial lighting state to the rendering device, g_d3dDevice, by calling the Direct3DDevice7.SetRenderState method.

    g_d3dDevice.SetRenderState D3DRENDERSTATE_AMBIENT, _
                               g_dx.CreateColorRGBA(1#, 1#, 1#, 1#)

In its first parameter, SetRenderState passes in the D3DRENDERSTATE_AMBIENT flag, associating the call with the ambient light color setting for the scene. The second argument uses the DirectX7.CreateColorRGBA method to set the red, green, and blue color values of the ambient light to 1.0, 1.0, and 1.0, respectively. The resulting light emits a white light. Lights do not use the alpha component, which is also set to 1.0 in this case.

Use a D3DMATERIAL7 type to specify material properties:

    Dim mtrl As D3DMATERIAL7

    mtrl.Ambient.r = 1#: mtrl.Ambient.g = 1#: mtrl.Ambient.b = 0#

    ' Commit the material to the device.
    g_d3dDevice.SetMaterial mtrl

When created, a new material has no properties and cannot be used in rendering. The preceding code sets material properties in a D3DMATERIAL7 type, describing a material that will reflect the red and green components of ambient light, making the material appear yellow in the scene. (The Triangle tutorial only uses ambient light, so it only sets an ambient reflectance property. A real-world application would use direct light as well as ambient light, and should therefore set diffuse and specular reflectance properties as well.)

Note When using textures, the object material is usually omitted or colored white.

Now that the material, and initial lighting parameters are set, the Triangle tutorial code sets up the transformation matrices. This is covered in Step 3.2: Prepare and Set Transformation Matrices.


Step 3.2: Prepare and Set Transformation Matrices

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

Another step in setting up a simple scene involves setting the world, view, and projection matrices. The system applies these matrices to the model's geometry in order to place the model in the scene, to adjust for the camera's location and orientation, and to scale the vertex data—making distant objects appear smaller than near objects. (For a conceptual overview, see the Geometry Pipeline.)

To create the world matrix, declare a D3DMATRIX type, matWorld, and create an identity matrix from it. Then, use the Direct3DDevice7.SetTransform method with the D3DTRANSFORMSTATE_WORLD flag to define the matrix for the world view.

    ' The world matrix controls the position and orientation of the polygons
    ' in world space. We'll use it later to spin the triangle.
    Dim matWorld As D3DMATRIX

    g_dx.IdentityMatrix matWorld
    g_d3dDevice.SetTransform D3DTRANSFORMSTATE_WORLD, matWorld

To create the view matrix, declare a D3DMATRIX type, matView, and create an identity matrix from it. Then, pass the camera coordinates into the DirectX7.ViewMatrix method to create the view matrix. Use the SetTransform method to define the view matrix for the rendering device.

    ' The view matrix defines the position and orientation of the camera.
    ' Here, we are just moving it back along the z-axis by 15 units.
    Dim matView  As D3DMATRIX

    g_dx.IdentityMatrix matView

    Call g_dx.ViewMatrix(matView, MakeVector(0, 0, -15), MakeVector(0, 0, 0), _
                         MakeVector(0, 1, 0), 0)

    g_d3dDevice.SetTransform D3DTRANSFORMSTATE_VIEW, matView

The preceding code uses a private, application-defined function, MakeVector, to transform three points into a D3DVECTOR type:

Private Function MakeVector(a As Double, b As Double, c As Double) As D3DVECTOR
    Dim vecOut As D3DVECTOR

    With vecOut
        .x = a
        .y = b
        .z = c
    End With

    MakeVector = vecOut
End Function

To create the projection matrix, declare a D3DMATRIX type, matProj, and create an identity matrix from it. Then, pass the clipping planes and the field of view angle into the DirectX7.ProjectionMatrix method to create the projection matrix. Use the SetTransform method to define the projection matrix for the rendering device.

    ' The projection matrix defines how the 3-D scene is "projected" onto the
    ' 2-D render target (the backbuffer surface). Refer to the docs for more
    ' info about projection matrices.
    Dim matProj As D3DMATRIX

    g_dx.IdentityMatrix matProj

    Call g_dx.ProjectionMatrix(matProj, 1, 1000, pi / 2)
    g_d3dDevice.SetTransform D3DTRANSFORMSTATE_PROJECTION, matProj

In the preceding code, the second parameter passed to ProjectionMatrix represents the distance to the near clipping plane in application-specific units, while the third parameter represents the distance to the far clipping plane in application-specific units. The fourth parameter is the field of view angle in radians.

After you have prepared the materials and configured the transformation matrices, you can set up the geometry for your scene. This step is covered in Step 3.3: Prepare the Geometry.


Step 3.3: Prepare the Geometry

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

The Triangle tutorial code initializes the geometry in the application-defined InitGeometry subroutine by defining four D3DVECTOR types; a vector type is used for each of the three points used to define the triangle, and for the one point used to define the normal in 3-D space. Technically, you are not required to set up the geometry at this time—you can do it anytime prior to calling the rendering methods:

Private Sub InitGeometry()

    ' Set up the geometry for the triangle.
    Dim p1 As D3DVECTOR, _
        p2 As D3DVECTOR, _
        p3 As D3DVECTOR, _
        vNormal As D3DVECTOR

    ' Set values for three points used to define a triangle.
    p1.x = 0#: p1.y = 5#: p1.z = 0#
    p2.x = 5#: p2.y = -5#: p2.z = 0#
    p3.x = -5#: p3.y = -5#: p3.z = 0#

    ' Create a normal vector--shared by the points of the
    ' triangle--that points toward the viewpoint. Note that
    ' we reverse the Z coordinate for the normal of the points
    ' that define the backside of the triangle.
    vNormal.x = 0#: vNormal.y = 0#: vNormal.z = -1#

The DirectX7.CreateD3DVertex method uses the members of a D3DVECTOR type to fill D3DVERTEX types by using the individual values that represent discrete vertex components. Fill the global D3DVERTEX type array, g_TriangleVert, with the triangle's vertex information:

 ' Create the 3 vertices for the front of the triangle.
    g_dx.CreateD3DVertex p1.x, p1.y, p1.z, vNormal.x, vNormal.y, vNormal.z, 0, 0, _
                         g_TriangleVert(0)
    g_dx.CreateD3DVertex p2.x, p2.y, p2.z, vNormal.x, vNormal.y, vNormal.z, 0, 0, _
                         g_TriangleVert(1)
    g_dx.CreateD3DVertex p3.x, p3.y, p3.z, vNormal.x, vNormal.y, vNormal.z, 0, 0, _
                         g_TriangleVert(2)

' Now do the same for the back of the triangle.
    g_dx.CreateD3DVertex p3.x, p3.y, p3.z, vNormal.x, vNormal.y, -vNormal.z, 0, 0, _
                         g_TriangleVert(3)
    g_dx.CreateD3DVertex p2.x, p2.y, p2.z, vNormal.x, vNormal.y, -vNormal.z, 0, 0, _
                         g_TriangleVert(4)
    g_dx.CreateD3DVertex p1.x, p1.y, p1.z, vNormal.x, vNormal.y, -vNormal.z, 0, 0, _
                         g_TriangleVert(5)

The preceding code fragment locates three points in 3-D space that define a triangle standing upright in the z=0 plane. After creating all the Direct3D-related objects, initializing the scene, and defining the geometry for your scene, you can render your scene as described in Step 4: Execute the Rendering Loop.


Step 4: Execute the Rendering Loop

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

After you have created the application window, created the DirectX objects, and initialized the scene, you are ready to render the scene. The rendering loop in the Triangle tutorial code renders the scene by calling the application-defined subroutines RenderScene and FrameMove :

    Do While g_bRunning = True
        CNT = CNT + 1
        RenderScene
        FrameMove (CNT / 360)

        g_dx.GetWindowRect Me.hWnd, g_rcDest

        j = g_ddsPrimary.Blt(g_rcDest, g_ddsBackBuffer, g_rcSrc, DDBLT_WAIT)
        If j <> DD_OK Then
            MsgBox "Couldn't copy the source rectangle to the destination surface." & _
                    Chr$(13) & Hex(j)
            End
        End If
        DoEvents
    Loop

Although the rendering loop appears to be infinite, it terminates when the Form_Unload procedure is triggered. For more information, see Step 5: Shut Down.

The rendering loop subdivides the scene rendering task into the following steps:

  • Step 4.1: Update the Scene
  • Step 4.2: Render the Scene
  • Step 4.3: Update the Display
  • Step 4.4: Call DoEvents


Step 4.1: Update the Scene

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

Before a scene is rendered it must be updated. Immediately after RenderScene returns, FrameMove is called (another application-defined subroutine). FrameMove simply updates the world matrix that Direct3D applies to the geometry of the model. The application reflects a rotation around the y-axis based on an internal count value, passed to FrameMove in the stepValue parameter. Since the rotation is applied once per frame, the end result looks like the model is rotating in place.

Private Sub FrameMove(stepVal As Single)
    Dim matSpinY As D3DMATRIX

    Call g_dx.RotateYMatrix(matSpinY, stepVal)
    Call g_d3dDevice.SetTransform(D3DTRANSFORMSTATE_WORLD, matSpinY)
End Sub

In the real-world, of course, your applications will do much more than apply a single rotation on a single model. (For more information on rotation matrices, see Rotation in the 3-D Transformations section.)

After you update the model's geometry in the scene, you can render it to the render target surface, as the Triangle tutorial application illustrates in Step 4.2: Render the Scene.


Step 4.2: Render the Scene

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

Once the model's geometry has been updated to reflect the desired animation, you can render the scene. The Triangle tutorial code takes a typical approach: the RenderScene application-defined subroutine starts by clearing the viewport:

Private Sub RenderScene()
    ' Clear the viewport to a blue color.
    g_d3dDevice.Clear 1, g_d3drcViewport(), D3DCLEAR_TARGET, &HFF, 0, 0

The preceding code calls the Direct3DDevice7.Clear method to clear the viewport. The first two arguments accepted by the Clear method are the array of rectangles describing the area or areas on the render target to be cleared and the value that informs the method how many rectangles from the array should be cleared. In most cases, as in the Triangle tutorial application, you will use a single rectangle that covers the entire render target. The third argument determines the method's behavior. Clear can clear the render-target surface, the associated depth buffer, the stencil buffer, or any combination of the three. Because this tutorial does not use a depth buffer, D3DCLEAR_TARGET is the only flag used. The last three parameters are set to reflect clearing values for the render target, depth buffer, and stencil buffer, respectively. The Triangle tutorial set the clear color for the render target surface to blue. Since the remaining parameters are not used in this tutorial, the code sets them to zero. The Clear method will ignore arguments when the corresponding flag is not specified.

After clearing the viewport, the tutorial code informs Direct3D that rendering will begin, renders the scene, then signals that rendering is complete, as shown here:

    ' Begin the scene, render the triangle, then complete the scene
    g_d3dDevice.BeginScene
        Call g_d3dDevice.DrawPrimitive(D3DPT_TRIANGLELIST, D3DFVF_VERTEX, _
                                       g_TriangleVert(0), 6, D3DDP_DEFAULT)
    g_d3dDevice.EndScene

The Direct3DDevice7.BeginScene and Direct3DDevice7.EndScene methods notify the system when rendering is beginning or is complete. You can only call rendering methods between calls to these methods. Even if rendering methods fail, you should call EndScene before calling BeginScene again.

After rendering the scene to the off-screen render target, you can update the user's display. The Triangle tutorial application demonstrates this in Step 4.3: Update the Display.


Step 4.3: Update the Display

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

Once a scene has been rendered to the render-target surface, you can show the results on screen. A windowed application usually does this by blitting the content of the render-target surface to the primary surface. A full screen application that employs page-flipping would simply flip the surfaces in the flipping chain. Because it runs in a window, the Triangle tutorial application uses the former method, using the following code:

        g_dx.GetWindowRect Me.hWnd, g_rcDest

        j = g_ddsPrimary.Blt(g_rcDest, g_ddsBackBuffer, g_rcSrc, DDBLT_WAIT)

The preceding DirectDrawSurface7.Blt method simply blits the entire contents of the render target surface to the window on the desktop. This tutorial code tracks the destination rectangle for the blit in the g_rcDest global variable.

While your application is running, you will need to ensure that control is relinquished to the operating system periodically, which is the topic of Step 4.4: Call DoEvents.


Step 4.4: Call DoEvents

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

You can use the DoEvents function to enable the operating system to raise events that apply to your application. In this manner, your application will render individual frames of the scene after the operating system has processed the events in its queue. The Triangle application uses the following line of code to clear the events queue:

    DoEvents

After this call completes, the application returns to the top of the while loop, calling the application-defined subroutines RenderScene and FrameMove, respectively—rendering a single frame of the scene.

Now that you have your application running, you can go to the final step in the tutorial, Step 5: Shut Down.


Step 5: Shut Down

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

For the Triangle tutorial, the application shut-down code is straight-forward:

Private Sub Form_Unload(Cancel As Integer)
    g_bRunning = False
End Sub

In the preceding code, the Form_Unload procedure sets the global variable, g_bRunning to false, which terminates the rendering loop.


Tutorial 2: Adding a Depth Buffer

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

Direct3D applications often rely on depth buffers to properly display objects in a scene. For a conceptual overview, see Depth Buffers. To use depth buffering you must enumerate supported depth-buffer formats, create a depth-buffer surface, attach the depth-buffer surface to a render-target surface, and enable depth buffering for the rendering device.

The ZBuffer tutorial application performs the following steps to use a z-buffer:

  • Step 1: Enumerate Depth-Buffer Formats
  • Step 2: Create the Depth Buffer
  • Step 3: Attach the Depth Buffer
  • Step 4: Enable Depth Buffering

A z-buffer holds the state for every pixel rendered, indicating what depth the rendered pixel is supposed to represent. In this way, when pixels are rendered on top of each other, the rendered pixel can decide if it should be placed behind the pixel that has already been rendered.

Note The code in the ZBuffer tutorial application is nearly identical to the code in the Triangle tutorial application. This tutorial focuses only on the depth-buffer code unique to ZBuffer, and does not cover setting up Direct3D, rendering, shutting down, or processing events raised by the application. For information on these tasks, see Tutorial 1: Rendering a Single Triangle.

Because some rendering devices require depth buffers to be located in particular places in memory, the system requires that you create and attach the depth-buffer surface to the render-target surface before you create a rendering device.


Step 1: Enumerate Depth-Buffer Formats

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

Before you can create a depth buffer, you must determine what depth-buffer formats, if any, are supported by the rendering device. Call the Direct3D7.GetEnumZBufferFormats method to enumerate the depth-buffer formats that the device supports. The ZBuffer application uses the following code to enumerate depth-buffer formats:

    ' Create the z-buffer after creating the backbuffer and before creating the
    ' Direct3D device. Note: before creating the z-buffer, applications may want to check
    ' the device capabilities for the D3DPRASTERCAPS_ZBUFFERLESSHSR flag. This flag is true
    ' for certain hardware that can do HSR (hidden-surface removal) without a z-buffer.
    ' For those devices, there is no need to create a z-buffer.
    '
    Dim ddpfZBuffer As DDPIXELFORMAT
    Dim d3dEnumPFs As Direct3DEnumPixelFormats

    Set g_d3d = g_dd.GetDirect3D
    Set d3dEnumPFs = g_d3d.GetEnumZBufferFormats("IID_IDirect3DRGBDevice")

The GetEnumZBufferFormats method accepts the globally unique identifier (GUID) of the device for which the formats will be enumerated. The ZBuffer application uses a hard-coded GUID; however, a real-world application would implement a testing mechanism to determine the GUID of the rendering device, either IID_IDirect3DRGBDevice or IID_IDirect3DHALDevice.

Now that the formats for the device have been enumerated, you can cycle through each of the supported depth-buffer formats:

    Dim I As Long

    For I = 1 To d3dEnumPFs.GetCount()
        Call d3dEnumPFs.GetItem(I, ddpfZBuffer)
        If ddpfZBuffer.lFlags = DDPF_ZBUFFER Then
            Exit For
        End If
    Next I

When Direct3DEnumPixelFormats.GetItem is called, it passes as its second argument a DDPIXELFORMAT type describing the pixel format of the depth buffer. The lFlags member will contain DDPF_ZBUFFER for any pixel formats that include depth-buffer bits. As its first argument, GetItem takes an index into the array of the enumerated formats. If a suitable format is found, GetItem saves the pixel format into the ddpfZBuffer parameter, a DDPIXELFORMAT type, and the loop is terminated.

For simplicity, this tutorial only uses z-buffers, which are the most common type of depth buffer. It ignores any other formats (such as DDPF_STENCILBUFFER) that the system enumerates. Applications could also check the bit depth of the z-buffer (8-, 16-, 24-, 32-bit) and make a choice based on that as well.

After you determine the format of the depth buffer, you can create a DirectDrawSurface to use that format, which is the topic of Step 2: Create the Depth Buffer.


Step 2: Create the Depth Buffer

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

Now that you have chosen the depth-buffer format, you can create the DirectDrawSurface object that will become the depth buffer. The pixel format of the surface is the one determined through enumeration, but the surface dimensions must be identical to the render-target surface to which it will be attached. The ZBuffer application uses the following code for this task:

    g_ddsd.lFlags = DDSD_CAPS Or DDSD_WIDTH Or DDSD_HEIGHT Or DDSD_PIXELFORMAT
    g_ddsd.ddsCaps.lCaps = DDSCAPS_ZBUFFER
    g_ddsd.lWidth = g_rcDest.Right - g_rcDest.Left
    g_ddsd.lHeight = g_rcDest.Bottom - g_rcDest.Top
    g_ddsd.ddpfPixelFormat = ddpfZBuffer

The preceding code simply prepares a DDSURFACEDESC2 type for the depth buffer, using the dimensions of the render-target surface calculated from previously set global variables. Finally, the pixel format information retrieved during the previous step, Step 1: Enumerate Depth-Buffer Formats, is copied into the surface description:

    g_ddsd.ddpfPixelFormat = ddpfZBuffer

Note A hardware device can use a depth buffer regardless of its location in memory. When using a hardware device, it is best to let the device determine the best location for the buffer by omitting the DDSCAPS_VIDEOMEMORY and DDSCAPS_SYSTEMMEMORY surface capability flags. However, a software device can only be created if the depth buffer exists in system memory. In the following code, the ZBuffer tutorial application sets the DDSCAPS_SYSTEMMEMORY flag; although, your application should implement a simple searching mechanism to determine whether your application should allocate the surface memory in system memory or in display memory.

    ' Specify DDSCAPS_VIDEOMEMORY if your surface exists in display memory.
    ' See the SDK documentation for more information.
    g_ddsd.ddsCaps.lCaps = g_ddsd.ddsCaps.lCaps Or DDSCAPS_SYSTEMMEMORY

Once the surface description is ready, the code calls the DirectDraw7.CreateSurface method to create the new depth-buffer surface:

    Set g_ddsZBuffer = g_dd.CreateSurface(g_ddsd)

After the depth buffer is created, it can be attached to the surface that will be used as the render target, as described in Step 3: Attach the Depth Buffer.


Step 3: Attach the Depth Buffer

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

Once the depth buffer is created, you need to attach it to the surface that will be used as the render target. Do this by calling the DirectDrawSurface7.AddAttachedSurface method of the render-target surface. The ZBuffer application performs this with the following code:

    ' Attach the z-buffer surface to the back buffer surface.
    g_ddsBackBuffer.AddAttachedSurface g_ddsZBuffer

Once the depth buffer is attached to the render-target surface, the system will automatically use the depth buffer whenever depth buffering is enabled, as discussed in Step 4: Enable Depth Buffering.


Step 4: Enable Depth Buffering

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

After attaching the depth buffer to the render-target surface, you can create a rendering device from the render target. Given a rendering device, you enable depth buffering by setting the D3DRENDERSTATE_ZENABLE render state for the device. The CONST_D3DZBUFFERTYPE enumerated type includes members to set the depth-buffering render state. The D3DZB_TRUE member (or True), enables z-buffering. The ZBuffer tutorial application enables z-buffering during scene rendering in the RenderScene application-defined subroutine. The following is the appropriate excerpt from RenderScene:

    g_d3dDevice.SetRenderState D3DRENDERSTATE_ZENABLE, D3DZB_TRUE

Although this tutorial enables depth-buffering for each frame, it is not necessary to do so. A real-world application would likely set the D3DRENDERSTATE_ZENABLE render state during scene initialization, only changing to disable depth buffering or to choose another type of depth buffering.

Note The CONST_D3DZBUFFERTYPE enumerated type includes the D3DZB_USEW value to enable w-based depth comparisons on compliant hardware. For more information, see Depth Buffers.


Tutorial 3: Using Alternate Primitive Styles

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

The Using Alternate Primitive Styles tutorial demonstrates how to render polygons using the various draw primitive calls provided by Direct3D for Visual Basic. The primitives in this tutorial are polygons, which are closed, three-dimensional (3-D) objects identified by at least three vertices. The tutorial uses the DrawPrims application.

Specifically, this tutorial demonstrates how to prepare the geometry for a series of primitives (a series of wall segments, a cone, and a cube), how to rotate the viewpoint, and how to use matrix concatenation to perform a 3-D transformation: translating, rotating, and scaling a cube.

  • Step 1: Initialize the Scene Geometry
  • Step 2: Render and Display the Scene

For more information on 3-D primitives, see 3-D Primitives.

Note The code in the DrawPrims application is similar to the code in the Triangle application. This tutorial focuses only on the geometric preparation and rendering code unique to the DrawPrims application, and does not cover setting up Direct3D, shutting down, or processing system events. For information on these tasks, see Tutorial 1: Rendering a Single Triangle.

The Using Alternate Primitive Styles tutorial uses a depth buffer to store depth information for the scene. To use depth buffering, you must enumerate supported depth-buffer formats, create a depth-buffer surface, attach the depth-buffer surface to a render-target surface, and enable depth buffering for the rendering device. For information on these tasks, see Tutorial 2: Adding a Depth Buffer.


Step 1: Initialize the Scene Geometry

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

This tutorial prepares the geometry for the primitives in the application-defined InitGeometry subroutine. InitGeometry defines a series of vertices for each object; retaining each primitive's vertex information in globally defined data structures. Vertex information is used by the DrawPrimitive Methods during rendering.

Technically, you are not required to set up the geometry at this time—you can do it anytime prior to calling the rendering methods.

  • Step 1.1: Prepare the Wall Segments
  • Step 1.2: Prepare the Cone
  • Step 1.3: Prepare the Cube

For more information on primitive types, see Primitive Types.

For more information on specifying vertices in Direct3D, see Vertex Formats.

Note The order in which the geometry is prepared for specific primitives does not effect the layout of objects in your scene.


Step 1.1: Prepare the Wall Segments

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

The Using Alternate Primitive Styles tutorial describes the wall segments in your scene with D3DVERTEX types, which are untransformed and unlit vertices. When you use untransformed and unlit vertices, you effectively request that Direct3D use its own internal algorithms to perform transformation and lighting operations.

You can define each wall segment in 3-D space by calculating and saving the information for a pair of vertices, as demonstrated in the following code from the DrawPrims application:

Private Sub InitGeometry()

    ' Set up the wall geometry.
    Dim x As Double, _
        y As Double, _
        z As Double

    Dim i As Integer

    For i = 0 To NUM_WALL_SIDES - 1
        x = Sin(2 * pi * i / (NUM_WALL_SIDES - 1))
        z = Cos(2 * pi * i / (NUM_WALL_SIDES - 1))

        Call g_dx.CreateD3DVertex(x * 10#, -0.1 * 10#, z * 10#, -x, 0, -z, 0, 0, g_vWall(2 * i + 0))
        Call g_dx.CreateD3DVertex(x * 10#, 0.1 * 10#, z * 10#, -x, 0, -z, 0, 0, g_vWall(2 * i + 1))

    Next i

In the preceding code, the DirectX7.CreateD3DVertex method is used to fill an array of D3DVERTEX types, g_vWall, with vertex component data. The code locates the x- and z- coordinates of the vertex by using trigonometric functions. The CreateD3DVertex method requires that you specify your coordinates in model coordinates. Since we have used untransformed and unlit vertices, the system will apply world, view, and projection transformations to the model coordinates to properly position them within your scene. Also, the x-, y-, and z-coordinates of the vertex are scaled by a value of ten to properly size the wall segments.

After defining the geometry for the wall segments in the scene, you can move on to preparing another geometric primitive for your scene, a cone. Again, note that the order in which specific objects are defined is not critical.

Defining a cone in 3-D space is demonstrated in Step 1.2: Prepare the Cone.


Step 1.2: Prepare the Cone

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

To prepare the geometry for a cone, you only need to declare a position vector and a normal vector. Therefore, the cone object in the DrawPrims application is defined with the following programmer-defined type:

Private Type MyFlexibleVertex
    vPosition As D3DVECTOR
    vNormal As D3DVECTOR
End Type

You can define the tip of the cone with the following code fragment:

    Dim vectorNorm As D3DVECTOR

    g_vCone(0).vPosition = MakeVector(0, CONE_HEIGHT / 2, 0)

    vectorNorm = MakeVector(0, 1, 0)
    Call g_dx.vectorNormalize(vectorNorm)
    g_vCone(0).vNormal = vectorNorm

You can compute each side of the cone with the following trigonometric functions:

    For i = 0 To NUM_CONE_SIDES - 1
        x = Sin(2 * pi * i / (NUM_CONE_SIDES - 1))
        y = -CONE_HEIGHT / 2
        z = Cos(2 * pi * i / (NUM_CONE_SIDES - 1))

        g_vCone(i + 1).vPosition = MakeVector(x * CONE_RADIUS, y * CONE_RADIUS, z * CONE_RADIUS)

You can calculate the position vector of each side of the cone with the following code fragment:

        vectorNorm = MakeVector(x, 0.5, z)
        Call g_dx.vectorNormalize(vectorNorm)
        g_vCone(i + 1).vNormal = vectorNorm
   Next i

After defining the wall segments and the cone in geometric space, you can move on to preparing the cube. This process is described in Step 1.3: Prepare the Cube.


Step 1.3: Prepare the Cube

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

The cube will be represented as an indexed primitive; thus; the cube will be rendered by indexing into an array of vertices. Specifically, the following indices will be used to index into the cube's vertex list during rendering:

g_nCubeIndices(0) = 1: g_nCubeIndices(1) = 2: g_nCubeIndices(2) = 3
g_nCubeIndices(3) = 2: g_nCubeIndices(4) = 1: g_nCubeIndices(5) = 0
g_nCubeIndices(6) = 4: g_nCubeIndices(7) = 5: g_nCubeIndices(8) = 6
g_nCubeIndices(9) = 6: g_nCubeIndices(10) = 5: g_nCubeIndices(11) = 7
g_nCubeIndices(12) = 3: g_nCubeIndices(13) = 2: g_nCubeIndices(14) = 6
g_nCubeIndices(15) = 3: g_nCubeIndices(16) = 6: g_nCubeIndices(17) = 7
g_nCubeIndices(18) = 0: g_nCubeIndices(19) = 1: g_nCubeIndices(20) = 4
g_nCubeIndices(21) = 4: g_nCubeIndices(22) = 1: g_nCubeIndices(23) = 5
g_nCubeIndices(24) = 2: g_nCubeIndices(25) = 0: g_nCubeIndices(26) = 4
g_nCubeIndices(27) = 2: g_nCubeIndices(28) = 4: g_nCubeIndices(29) = 6
g_nCubeIndices(30) = 1: g_nCubeIndices(31) = 3: g_nCubeIndices(32) = 5
g_nCubeIndices(33) = 5: g_nCubeIndices(34) = 3: g_nCubeIndices(35) = 7

After defining the geometry for all of your objects in the scene, you can render and display the scene, which is the topic of Step 2: Render and Display the Scene.


Step 2: Render and Display the Scene

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

To properly display and manipulate your objects in a scene, you need to update the view of your scene, perform any necessary transformations, and, of course, render the completed scene. These tasks are explained in the following steps:

  • Step 2.1: Update the Scene
  • Step 2.2: Perform the 3-D Transformation
  • Step 2.3: Render the Scene

For more information on rendering primitives, see Rendering Primitives.


Step 2.1: Update the Scene

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

This tutorial uses the application-defined subroutine FrameMove to rotate the viewpoint around in a circle. The viewpoint is most conveniently defined by three D3DVECTOR types: an eye point, a look-at point, and a vector defining the up direction, as shown in the following code:

    Dim vEyePt As D3DVECTOR, _
        vLookatPt As D3DVECTOR, _
        vUpVec As D3DVECTOR

    vEyePt = MakeVector(5 * Sin(stepVal), 3, 5 * Cos(stepVal))
    vLookatPt = MakeVector(4 * Sin(stepVal + 0.1), 2.5, 4 * Cos(stepVal + 0.1))
    vUpVec = MakeVector(0, 1, 0)

Now, you can use the three vectors to create and set a new view matrix:

     Dim matView As D3DMATRIX

    Call g_dx.ViewMatrix(matView, vEyePt, vLookatPt, vUpVec, stepVal / 360)

    g_d3dDevice.SetTransform D3DTRANSFORMSTATE_VIEW, matView

The preceding code creates a new view matrix for each rendered frame of the scene by passing the new location of the camera to the DirectX7.ViewMatrix method. Next the Direct3DDevice7.SetTransform method sets the newly-generated view matrix for the device. The value of stepValue (passed into the application-defined method, FrameMove) rotates the viewpoint one degree at a time. As a result, the wall segments and the cone appear to rotate 360 degrees.

At this point, you have nearly completed your scene; however, you still need to manually rotate, transform, and scale the cube's vertices. First, use the DirectX7.CreateD3DTLVertex method to fill the array of D3DTLVERTEX types with untransformed data for the cube. Note that the first three parameters of DirectX7.CreateD3DTLVertex represent the untransformed position of each vertex in screen coordinates:

    g_dx.CreateD3DTLVertex -1, -1, -1, 0, &HFFFFFF, 0, 0, 0, g_vCube(0)
    g_dx.CreateD3DTLVertex 1, -1, -1, 0, &HFF&, 0, 0, 0, g_vCube(1)
    g_dx.CreateD3DTLVertex -1, 1, -1, 0, &HFF00&, 0, 0, 0, g_vCube(2)
    g_dx.CreateD3DTLVertex 1, 1, -1, 0, &HFF0000, 0, 0, 0, g_vCube(3)
    g_dx.CreateD3DTLVertex -1, -1, 1, 0, &HFFFF&, 0, 0, 0, g_vCube(4)
    g_dx.CreateD3DTLVertex 1, -1, 1, 0, &HFF0066, 0, 0, 0, g_vCube(5)
    g_dx.CreateD3DTLVertex -1, 1, 1, 0, &H9966FF, 0, 0, 0, g_vCube(6)
    g_dx.CreateD3DTLVertex 1, 1, 1, 0, &HFF00FF, 0, 0, 0, g_vCube(7)

Now, you can let the application transform the cube's eight vertices:

    Call TransformVertices(g_d3dDevice, g_vCube, NUM_CUBE_VERTICES)

The cube's vertices are transformed by the application-defined function, TransformVertices, which is explained in Step 2.2: Perform the 3-D Transformation.


Step 2.2: Perform the 3-D Transformation

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

The Using Alternate Primitive Styles tutorial uses geometric transformation to define the location of the cube relative to the other objects in the scene, to rotate the cube, and to scale the cube in the scene.

Before implementing your 3-D transformation, you will need to retrieve the height and width of the viewport. This information is used to scale the transformed vertices to fit the render window:

Private Sub TransformVertices(d3dDevice As Direct3DDevice7, vVertices() As D3DTLVERTEX, nNumVertices As Integer)

    Dim vp As D3DVIEWPORT7
    Dim nClipWidth As Integer
    Dim nClipHeight As Integer

    ' Get the height and width of the viewport. This is needed to scale the transformed vertices
    ' to fit the render window.
    d3dDevice.GetViewport vp
    nClipWidth = vp.lWidth / 2
    nClipHeight = vp.lHeight / 2

Direct3D uses matrices to perform transformations. In order to execute a 3-D transformation, you need to retrieve the values of the current matrix set. You do this by calling Direct3DDevice7.GetTransform on the rendering device:

    d3dDevice.GetTransform D3DTRANSFORMSTATE_WORLD, matWorld
    d3dDevice.GetTransform D3DTRANSFORMSTATE_VIEW, matView
    d3dDevice.GetTransform D3DTRANSFORMSTATE_PROJECTION, matProj

You use matrix multiplication to concatenate the matrices:

    Dim matSet As D3DMATRIX

    g_dx.IdentityMatrix matSet

    ' Concatenate the matrices.
    g_dx.MatrixMultiply matSet, matWorld, matView
    g_dx.MatrixMultiply matSet, matSet, matProj

In the preceding code, a composite matrix, matSet, is calculated to representing the product of the desired transformations. During concatenation, ensure that the matrices are multiplied in the order in which you want them to operate.

For more information on matrix concatenation, see Matrix Concatenation.

Now, you transform each vertex through the current matrix set:

    For i = 0 To nNumVertices - 1
        ' Get the untransformed vertex position.
        x = vVertices(i).sx
        y = vVertices(i).sy
        z = vVertices(i).sz

        xp = matSet.rc11 * x + matSet.rc21 * y + matSet.rc31 * z + matSet.rc41
        yp = matSet.rc12 * x + matSet.rc22 * y + matSet.rc32 * z + matSet.rc42
        zp = matSet.rc13 * x + matSet.rc23 * y + matSet.rc33 * z + matSet.rc43
        wp = matSet.rc14 * x + matSet.rc24 * y + matSet.rc34 * z + matSet.rc44

Finally, scale the vertices to screen coordinates. In the following code, the first step flattens the coordinates from 3-D space to 2-D device coordinates by dividing each coordinate by the wp value. Then, the x- and y-components are transformed from device coordinates to screen coordinates.

        vVertices(i).sx = (1# + (xp / wp)) * nClipWidth
        vVertices(i).sy = (1# - (yp / wp)) * nClipHeight
        vVertices(i).sz = zp / wp
        vVertices(i).rhw = wp
   Next i

For more information on 3-D transformations, see 3-D Transformations.

Note Device coordinates range from -1 to +1 in the viewport. Also, the sz-coordinate will be used in the z-buffer.

Now that you have transformed the cube's eight vertices, you can render a frame of the completed the scene. This is shown in Step 2.3: Render the Scene.


Step 2.3: Render the Scene

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

The following Direct3DDevice7.DrawPrimitive call draws a wall segment composed of a D3DVERTEX type triangle strip:

    Call g_d3dDevice.DrawPrimitive(D3DPT_TRIANGLESTRIP, D3DFVF_VERTEX, g_vWall(0), _
         NUM_WALL_VERTICES, D3DDP_DEFAULT)

The following DrawPrimitive call draws a cone which is a triangle fan of custom, flexible vertices:

    Call g_d3dDevice.DrawPrimitive(D3DPT_TRIANGLEFAN, D3DFVF_XYZ Or D3DFVF_NORMAL, g_vCone(0), _
         NUM_CONE_VERTICES, D3DDP_DEFAULT)

Lastly, the following Direct3DDevice7.DrawIndexedPrimitive call draws a cube which is composed of application transformed and lit, indexed vertices:

    Call g_d3dDevice.DrawIndexedPrimitive(D3DPT_TRIANGLELIST, D3DFVF_TLVERTEX, g_vCube(0), _
         NUM_CUBE_VERTICES, g_nCubeIndices, NUM_CUBE_INDICES, D3DDP_DEFAULT)


Tutorial 4: Using Device Enumeration

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

Device enumeration is useful because it allows applications to query hardware for the Direct3D devices that the hardware supports. As a result, you can build applications that take advantage of particular hardware configurations, or you can let the user choose a particular configuration supported by their system's hardware. The Using Device Enumeration tutorial enumerates the drivers, display modes, and devices on your system and then creates a list of supported display modes for each device.

Basically, device enumeration can be partitioned into two broad steps: (1) initiating and completing device enumeration and (2) selecting an enumerated device.

The Using Device Enumeration tutorial mirrors this process with the following sections:

  • Step 1: Initiate and Complete Device Enumeration
  • Step 2: Select an Enumerated Device

For more information on Direct3D devices, see Direct3D Devices.

For more information on device enumeration, see Enumerating Direct3D Devices.

Note The code in the Enumeration application is similar to the code in the Triangle application. This tutorial focuses only on the device enumeration code unique to the Enumeration application, and does not cover setting up Direct3D, preparing scene geometry, shutting down, or processing system events. For information on these tasks, see Tutorial 1: Rendering a Single Triangle.

The Using Device Enumeration tutorial uses a depth buffer to store depth information for the scene. To use depth buffering, you must enumerate supported depth-buffer formats, create a depth-buffer surface, attach the depth-buffer surface to a render-target surface, and enable depth buffering for the rendering device. For information on these tasks, see Tutorial 2: Adding a Depth Buffer.

The Using Device Enumeration tutorial draws a series of cone primitives. For more information on how to draw primitives, see Tutorial 3: Using_Alternate Primitive Styles.


Step 1: Initiate and Complete Device Enumeration

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

A Visual Basic application initiates enumeration by retrieving a reference to an enumerator class. For the Using Device Enumeration tutorial, you need to declare references to the following enumerator classes:

  • DirectDrawEnum
  • DirectDrawEnumModes
  • Direct3DEnumDevices

The process of enumerating devices for your application can be broken down into the following steps:

  • Step 1.1: Enumerate Driver Information
  • Step 1.2: Enumerate Display Mode Information
  • Step 1.3: Enumerate Device Information

The first step for an application that uses device enumeration is to retrieve a reference to a DirectDraw driver. The Enumeration sample uses the following application-defined subroutine call to enumerate the drivers that can be used by DirectDraw:

    ' Get driver information.
    EnumDriver

Driver enumeration is explained in Step 1.1: Enumerate Driver Information.

For more information on starting device enumeration, see Starting Device Enumeration.


Step 1.1: Enumerate Driver Information

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

Create a display driver for your application by calling DirectX7.DirectDrawCreate on the global DirectX7 object:

    Set g_dd = g_dx.DirectDrawCreate("")

Now, you can retrieve driver information. For this simple tutorial we are just using the primary display driver:

    Set g_ddEnum = g_dx.GetDDEnum()

    For i = 1 To g_ddEnum.GetCount()
        g_sDriverGUID = g_ddEnum.GetDescription(i)
    Next I

The preceding code fragment uses the DirectX7.GetDDEnum method to create a DirectDrawEnum object. Then, the DirectDrawEnum object, g_ddEnum, is used to enumerate the video driver display adapters installed on the system. When the primary display driver is found, DirectDrawEnum.GetDescription is used to return the driver description of the specified DirectDraw device.

The Enumeration sample application uses the following application-defined subroutine call to perform display mode enumeration:

    ' Enumerate the display modes.
    EnumModes

The details of display mode enumeration are illustrated in Step 1.2: Enumerate Display Mode Information.


Step 1.2: Enumerate Display Mode Information

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

You can use the DirectDraw7.GetDisplayModesEnum method to return a reference to a DirectDrawEnumModes class. The retrieved display mode information is contained in a DDSURFACEDESC2 type, g_enumInfo:

    Set g_ddEnumModes = g_dd.GetDisplayModesEnum(DDEDM_DEFAULT, g_enumInfo)

In the preceding code the DDEDM_DEFAULT flag tells the application to perform a normal enumeration of the display modes. For more information on available options, see the CONST_DDEDMFLAGS topic in the SDK reference. Now that you have enumerated the DirectDraw driver and the display modes, you can move on to enumerating the devices. The Enumeration application uses the following application-defined subroutine to enumerate the devices:

    ' Enumerate the devices.
    EnumDevices

Device enumeration is explained in Step 1.3: Enumerate Device Information.


Step 1.3: Enumerate Device Information

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

Before you can begin device enumeration, you need to retrieve the Direct3D object for the current display device:

    Set g_d3d = g_dd.GetDirect3D()

Now, retrieve a reference to the Direct3DEnumDevices class by calling the Direct3D7.GetDevicesEnum method:

    Set g_d3dEnumDevices = g_d3d.GetDevicesEnum()
    For i = 1 To g_d3dEnumDevices.GetCount()
        cmbDevice.AddItem g_d3dEnumDevices.GetName(i)
    Next

The preceding code sample places the user-friendly name of each enumerated device into a combo box, cmbDevice. After you have a reference to the Direct3DEnumDevices class, you can call methods that return the number of enumerated devices and information about each device:

Call the Direct3DEnumDevices.GetCount method to return the number of enumerated devices. Note that the first device is at index 1, not index 0.

Call the Direct3DEnumDevices.GetGuid method to return a text string representation of the globally-unique identifier (GUID) for an enumerated device.

Call the Direct3DEnumDevices.GetName and Direct3DEnumDevices.GetDescription methods to return text strings that contain the name and user-friendly description of the device.

Call the Direct3DEnumDevices.GetDesc method to retrieve a description of the capabilities for the device, in the form of a D3DDEVICEDESC7 type.

After you have enumerated your display driver, display modes, and devices you can select an enumerated device to be used by your application, which is the topic of Step 2: Select an Enumerated Device.


Step 2: Select an Enumerated Device

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

Selecting an enumerated device usually consists of the following steps:

  • Step 2.1: Retrieve the Device
  • Step 2.2: Test the Device

The Enumeration application uses the following application-defined subroutine call to select an enumerated device and build a list of display modes that are supported by that device:

    ' Select an enumerated device and build a list of supported display modes
    ' for that device.
    SelectDisplayModes

The process of retrieving an enumerated device is defined in Step 2.1: Retrieve the Device.

For more information on selecting enumerated devices, see Select an Enumerated Device.


Step 2.1: Retrieve the Device

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

Before you can test a device, you must retrieve the device that you want to test. The following section explains how to retrieve the current display settings and how to retrieve a device reference, so that you can test the device for all of its supported display settings.

The Enumeration sample uses the DirectDraw7.GetDisplayMode method to retrieve the current display mode information in a DDSURFACEDESC2 type:

    g_dd.GetDisplayMode desc
    currMode = desc.ddpfPixelFormat.lRGBBitCount

The preceding code saves the bits per pixel setting of the current display in currMode. Then, the Enumeration sample adds the current display mode to a combo box, cmbMode, that is displayed to the user:

    cmbMode.Clear
    cmbMode.AddItem Str(currMode) + "-bit Display Window"

Now, to retrieve the device that you want to test, determine which device has been selected by the user in the combo box, cmbDevice, by using the Direct3DEnumDevices.GetDesc method:

 Call g_d3dEnumDevices.GetDesc(cmbDevice.ListIndex + 1, deviceDesc)

In the preceding code, a DDSURFACEDESC2 type, deviceDesc, is used to hold surface description information for the device that you want to test. This is the device that you will use to build a list of supported display modes. Ultimately, you will place these supported display modes into a combo box, so that the user can choose the display mode for the Enumeration application.

Note The design and structure of the graphical user interface (GUI) of the Enumeration application is not discussed in this tutorial. To gain an understanding of how the code samples in the Using Device Enumeration tutorial interact with the GUI, you should consult the complete Enumeration application code in the SDK.

Now that you have a reference to the device that you want to test, you can test the device. This step is explained in Step 2.2: Test the Device.


Step 2.2: Test the Device

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

The following code fragment illustrates a way to determine device capabilities. The Enumeration application uses the following algorithm to choose a supported display mode for the given device:

  1. Return a video mode description for the specified element in the DirectDrawEnumModes object.
  2. Retrieve the bits per pixel support in the returned video mode description.
  3. Retrieve the given device's rendering depth.
  4. Check to see if the video mode of the specified element in the DirectDrawEnumModes object is compatible with the given device's rendering depth. If it is, then accept the display mode; otherwise, reject it. Skip all 8-bit modes.

The Enumeration application executes the following code to implement the algorithm:

    For j = 1 To g_ddEnumModes.GetCount()
        ' We have not tested this display mode yet, so assume it is not compatible.
        bCompatible = False
        ' Step 1:
        g_ddEnumModes.GetItem j, g_enumInfo

        ' Step 2:
        modeDepth = g_enumInfo.ddpfPixelFormat.lRGBBitCount

        ' Step 3:
        bitDepth = deviceDesc.lDeviceRenderBitDepth

        ' Step 4:
        If (32 = modeDepth) And (bitDepth And DDBD_32) Then bCompatible = True
        If (24 = modeDepth) And (bitDepth And DDBD_24) Then bCompatible = True
        If (16 = modeDepth) And (bitDepth And DDBD_16) Then bCompatible = True

        ' Populate the combo box with only the display modes that we want.
        If bCompatible Then
            cmbMode.AddItem Str(g_enumInfo.lWidth) + " x" + Str(g_enumInfo.lHeight) + " x" + Str(g_enumInfo.ddpfPixelFormat.lRGBBitCount)
        End If
    Next j

After this algorithm completes, the combo box, cmbMode, will hold a list display modes that meet the specified criteria, all other display modes will be ignored.


Tutorial 5: Using Texture Maps

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

This tutorial explains how to draw a simple three-dimensional (3-D) scene using textures. In essence, a Direct3D texture is a bitmap of pixel colors; as a result, any bitmap image can be applied to a Direct3D primitive. Textures are a simple, powerful way to add realism to your 3-D objects without altering their geometry. In this way, textures can be used to enhance a primitive with patterns and illusions of color, roughness, transparency, and smoothness. Specifically, the Using Texture Maps tutorial explains how to create textures from file-based bitmaps and how to render a cube primitive with textures.

Note that texture handles are not used in Direct3D for Visual Basic; rather, you obtain a reference to the texture surface object when you create the texture surface

In order to add textures to the primitives in your 3-D scenes, complete the following steps:

  • Step 1: Create a Textured Surface
  • Step 2: Render a Textured Primitive

Direct3D supports an extensive texturing feature set, providing developers with easy access to advanced texturing techniques and strategies. For more information on textures and how they can be used and optimized in Direct3D, see Textures.

Note The code in the Texture application is similar to the code in the Triangle application. This tutorial focuses only on the texturing code unique to the Texture application, and does not cover setting up Direct3D, preparing scene geometry, shutting down, or processing system events. For information on these tasks, see Tutorial 1: Rendering a Single Triangle.

The Texture tutorial draws a cube primitive. For more information on how to draw primitives, see Tutorial 3: Using_Alternate Primitive Styles.

The Texture tutorial uses enumeration to enumerate the texture formats. For more information on enumeration techniques and principles, see Tutorial 4: Using Device Enumeration.


Step 1: Create a Textured Surface

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

Direct3D for Visual Basic greatly simplifies the task of creating and managing textures. To prepare, create, and implement system-managed textures in your 3-D scene, follow these steps:

  • Step 1.1: Set the Texture Coordinates
  • Step 1.2: Prepare the Texture Surface
  • Step 1.3: Enumerate the Texture Formats
  • Step 1.4: Create a New Surface for the Texture

Before creating a texture for a primitive, you need to define the vertices of your primitive along with its texture coordinates. This task is defined in Step 1.1: Set the Texture Coordinates.


Step 1.1: Set the Texture Coordinates

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

Direct3D represents textures as two dimensional arrays of color values. Each element in the array is referred to as a texel. You can access a texel through column and row numbers, which are labeled U and V, respectively.

Your application can assign texture coordinates directly to the vertices by using the DirectX7.CreateD3DVertex method. The following code fragment, taken from the Texture application, creates a set of four vertices describing the front face of a cube:

    g_dx.CreateD3DVertex -1, 1, -1, 0, 0, -1, 0, 0, vertices(0)
    g_dx.CreateD3DVertex 1, 1, -1, 0, 0, -1, 1, 0, vertices(1)
    g_dx.CreateD3DVertex -1, -1, -1, 0, 0, -1, 0, 1, vertices(2)
    g_dx.CreateD3DVertex 1, -1, -1, 0, 0, -1, 1, 1, vertices(3)

For each CreateD3DVertex method call, the first three arguments define a vertex, the second three arguments define the orientation of the vertex normal vector, and the next two arguments represent the texture coordinates of the vertex. In this case, you want the application to map the entire bitmap texture onto the front face of the cube, so you will use the following texture coordinates: (0, 0), (1, 0), (0, 1), and (1, 1).

For more information on texture coordinates, see Texture Coordinates.

You should employ the same procedures for the back, top, bottom, right, and left faces of the cube. See the Texture application code in the SDK for information on how to do this.

The Texture application uses the programmer-defined function CreateTextureSurface to return a DirectDrawSurface7 object. The returned texture surface object will be set to the primitive during rendering:

    Set g_ddsTexture1 = CreateTextureSurface("tree1.bmp")
    Set g_ddsTexture2 = CreateTextureSurface("tex1.bmp")
    Set g_ddsTexture3 = CreateTextureSurface("earth.bmp")

In the preceding code, three texture surface objects are created from the following bitmap files: ("tree1.bmp, " "tex1.bmp," and "earth.bmp").

Note In order to run the Texture application, you need to ensure that your Visual Basic application can find your texture files ("tree1.bmp", "tex1.bmp", and "earth.bmp"). The Texture application looks for these files in the same folder that contains your Texture application's project file (.vbp).

Now, you can look at the programmer-defined subroutine CreateTextureSurface in detail, to see how texture surface objects are prepared and created. The initial step of this process is illustrated in Step 1.2: Prepare the Texture Surface.


Step 1.2: Prepare the Texture Surface

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

You can use a DDSURFACEDESC2 type to describe the texture surface:

Public Function CreateTextureSurface(sFile As String) As DirectDrawSurface7
    Dim ddsTexture As DirectDrawSurface7
    Dim i As Long
    Dim bIsFound As Boolean

    ' Prepare the texture surface.
    Dim ddsd As DDSURFACEDESC2

    ddsd.lFlags = DDSD_CAPS Or DDSD_HEIGHT Or DDSD_WIDTH Or DDSD_PIXELFORMAT Or DDSD_TEXTURESTAGE

Now, you are ready to enumerate the texture formats. This step is explained in Step 1.3: Enumerate the Texture Formats.


Step 1.3: Enumerate the Texture Formats

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

Before you enumerate your textures, you need to declare a Direct3DEnumPixelFormats object:

    Dim TextureEnum As Direct3DEnumPixelFormats

Then, you can call the Direct3DDevice7.GetTextureFormatsEnum method on the rendering device to return a Direct3DEnumPixelFormats object:

    Set TextureEnum = g_d3dDevice.GetTextureFormatsEnum()

Now, you can call methods on the Direct3DEnumPixelFormats object, TextureEnum, to retrieve information about the pixel formats that the device supports for textures.

In the following code excerpt from the Texture application, the loop is looking for a device-supported texture pixel format. Specifically, the code looks for a 16-bit texture. Note that all other formats, such as alpha textures, are ignored:

    For i = 1 To TextureEnum.GetCount()
        bIsFound = True
        Call TextureEnum.GetItem(i, ddsd.ddpfPixelFormat)

        With ddsd.ddpfPixelFormat
            ' Skip unusual modes.
            If .lFlags And (DDPF_LUMINANCE Or DDPF_BUMPLUMINANCE Or DDPF_BUMPDUDV) Then bIsFound = False

            ' Skip any FourCC formats.
            If .lFourCC <> 0 Then bIsFound = False

            'Skip alpha modes.
            If .lFlags And DDPF_ALPHAPIXELS Then bIsFound = False

            'We only want 16-bit formats, so skip all others.
            If .lRGBBitCount <> 16 Then bIsFound = False
        End With

        If bIsFound Then Exit For

    Next i

Now that a texture format supported by the rendering device has been selected from the enumeration of texture formats, TextureEnum, you can create a surface for the texture. This step is detailed in Step 1.4: Create a New Surface for the Texture.


Step 1.4: Create a New Surface for the Texture

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

Before creating the texture surface object, you should turn on texture management for the device with the DDSCAPS2_TEXTUREMANAGE flag:

    ddsd.ddsCaps.lCaps = DDSCAPS_TEXTURE
    ddsd.ddsCaps.lCaps2 = DDSCAPS2_TEXTUREMANAGE
    ddsd.lTextureStage = 0

Also, by setting the control flag DDSCAPS_TEXTURE, you inform the system that the surface describes a texture surface.

For more information on texture management, see Automatic Texture Management.

Now that automatic texture management has been enabled, and you have set the DDSCAPS_TEXTURE flag, you can create a new surface for the texture and return it:

    Set ddsTexture = g_dd.CreateSurfaceFromFile(sFile, ddsd)

    ' Return the newly created texture.
    Set CreateTextureSurface = ddsTexture

For more information on texture surfaces, see Texture Surface Objects.

Since you have created a new surface for your texture, you can use that texture during rendering of the primitives. This step is done in Step 2: Render a Textured Primitive.


Step 2: Render a Textured Primitive

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C/C++ Tutorials.

[Visual Basic]

The only difference between rendering a textured primitive and a non-textured primitive is that you have to set the texture during the rendering of a textured primitive.

The following code excerpt from the Texture application draws the front and back faces of a cube, using the texture surface g_ddsTexture1:

    g_d3dDevice.SetTexture 0, g_ddsTexture1
    Call g_d3dDevice.DrawPrimitive(D3DPT_TRIANGLESTRIP, D3DFVF_VERTEX, g_vCube(0), _
         4, D3DDP_DEFAULT)
    Call g_d3dDevice.DrawPrimitive(D3DPT_TRIANGLESTRIP, D3DFVF_VERTEX, g_vCube(4), _
         4, D3DDP_DEFAULT)

You should employ the same procedures for the top and bottom faces of the cube, and the left and right faces of the cube, setting g_ddsTexture2 and g_ddsTexture3, respectively. See the Texture application code in the SDK for information on how to do this.

The Direct3DDevice7.SetTexture method assigns a texture to a given stage for a device. Since this tutorial does not use multiple texture blending, the first parameter of SetTexture is 0, specifying a value of 0 for the stage identifier. The second parameter identifies the DirectDrawSurface7 object being set as the texture.

For more information on textured rendering, see Rendering with Texture Surfaces.

For more information on multiple texture blending, see Multiple Texture Blending.


Direct3D Immediate Mode Reference

This section contains reference information for the application programming interface (API) elements provided by Microsoft® Direct3D® Immediate Mode in C/C++ and Microsoft® Visual Basic® programming languages. Reference material is organized by language:

  • Direct3D Immediate Mode C/C++ Reference
  • Direct3D Immediate Mode Visual Basic Reference


Direct3D Immediate Mode C/C++ Reference

This section contains reference information for the API elements provided by Direct3D Immediate Mode. Reference material is divided into the following categories:

  • Interfaces
  • D3D_OVERLOADS
  • Callback Functions
  • Macros
  • Structures
  • Enumerated Types
  • Other Types
  • Flexible Vertex Format Flags
  • Return Values


Interfaces

This section contains reference information for the COM interfaces provided by Direct3D Immediate Mode. The primary interfaces used with Direct3D Immediate Mode are the following:

  • IDirect3D7
  • IDirect3DDevice7
  • IDirect3DVertexBuffer7

Note: Direct3D no longer requires a discrete interface for textures. All the texture-related methods in Direct3D now accept pointers to the IDirectDrawSurface7 interface, as long as the surface was created with texture capabilities (DDSCAPS_TEXTURE).

Applications that require execute buffers must use the legacy interfaces provided by previous releases of DirectX.

Some stub methods that were exposed in previous releases of DirectX are no longer exposed. For more information, see Unimplemented Methods.

The new IDirect3DDevice7 interface includes methods that render the IDirect3DLight, IDirect3DMaterial3, and IDirect3DViewport3 interfaces obsolete. For details, see Obsolete Interfaces. Documentation for these interfaces is available through previous releases of DirectX.


IDirect3D7

Applications use the methods of the IDirect3D7 interface to create Direct3D objects and set up the environment. This section is a reference to the methods of this interface. For a conceptual overview, see Direct3D Interfaces.

The IDirect3D7 interface is obtained by calling the QueryInterface method from a DirectDraw object.

The methods of the IDirect3D7 interface can be organized into the following groups:

Creation | CreateDevice
 | CreateVertexBuffer
Enumeration | EnumDevices
 | EnumZBufferFormats
Miscellaneous | EvictManagedTextures

The IDirect3D7 interface simplifies the IDirect3D3 interface by eliminating the need for creation methods for objects other than devices and vertex buffers. In contrast to the IDirect3D3 interface, the IDirect3D3::CreateLight, IDirect3D3::CreateMaterial, and IDirect3D3::CreateViewport methods are not present in IDirect3D7. The functionality provided by these methods is now offered by the IDirect3DDevice7 interface.

The IDirect3D7 interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECT3D7, LPDIRECT3D3, LPDIRECT3D2, and LPDIRECT3D types are defined as pointers to the IDirect3D7, IDirect3D3, IDirect3D2, and IDirect3D interfaces:

typedef struct IDirect3D    *LPDIRECT3D;
typedef struct IDirect3D2   *LPDIRECT3D2;
typedef struct IDirect3D3   *LPDIRECT3D3;
typedef struct IDirect3D7   *LPDIRECT3D7;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

Accessing Direct3D, Direct3D and DirectDraw


IDirect3D7::CreateDevice

The IDirect3D7::CreateDevice method creates a Direct3D device to be used with the DrawPrimitive methods.

HRESULT CreateDevice(
  REFCLSID rclsid,
  LPDIRECTDRAWSURFACE7 lpDDS,
  LPDIRECT3DDEVICE7 *  lplpD3DDevice,
);

Parameters

rclsid
Class identifier for the new device. This value can be IID_IDirect3DTnLHalDevice, IID_IDirect3DHALDevice, IID_IDirect3DMMXDevice, or IID_IDirect3DRGBDevice. The IID_IDirect3DRampDevice, used for the ramp emulation device, is not supported by interfaces later than IDirect3D2. To use ramp emulation, you must use the legacy IDirect3D2 interface.
lpDDS
Address of the IDirectDrawSurface7 interface for the DirectDrawSurface object that is the device's rendering target. The surface must have been created as a 3-D device by using the DDSCAPS_3DDEVICE capability.
lplpD3DDevice
Address of a pointer to the new IDirect3DDevice7 interface when the method returns.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value is an error. The method returns DDERR_INVALIDPARAMS if one of the arguments is invalid.

Remarks

All rendering devices created by a given Direct3D object share the same physical resources. Although your application can create multiple rendering devices from a single Direct3D object, because they share the same hardware, extreme performance penalties will be incurred.

In the legacy IDirect3D3 interface, this method accepted pointers to the IDirectDrawSurface4 and IDirect3DDevice3 interfaces.

When you call IDirect3D7::CreateDevice, you create a device object that is separate from a DirectDraw surface object. This device uses a DirectDraw surface as a rendering target.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7, Creating a Direct3D Device, Direct3D Devices


IDirect3D7::CreateVertexBuffer

The IDirect3D7::CreateVertexBuffer method creates a vertex buffer object.

HRESULT CreateVertexBuffer(
  LPD3DVERTEXBUFFERDESC    lpVBDesc,
  LPDIRECT3DVERTEXBUFFER7* lplpD3DVertexBuffer,
  DWORD dwFlags
);

Parameters

lpVBDesc
Address of a D3DVERTEXBUFFERDESC structure that describes the format and number of vertices that the vertex buffer receives.
lplpD3DVertexBuffer
Address of a variable to receive a pointer to a IDirect3DVertexBuffer7 interface for the new vertex buffer.
dwFlags
No flags are currently defined for this method. This parameter must be 0.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values:

CLASS_E_NOAGGREGATION
D3DERR_INVALIDVERTEXFORMAT
D3DERR_VBUF_CREATE_FAILED
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY

Remarks

This method was introduced with the IDirect3D3 interface. As part of IDirect3D3, this method accepted a pointer to the legacy IDirect3DVertexBuffer interface and accepted flags in the dwFlags parameter.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DVertexBuffer7, Vertex Buffers


IDirect3D7::EnumDevices

The IDirect3D7::EnumDevices method enumerates all Direct3D device drivers installed on the system.

HRESULT EnumDevices(
  LPD3DENUMDEVICESCALLBACK7 lpEnumDevicesCallback,
  LPVOID lpUserArg
);

Parameters

lpEnumDevicesCallback
Address of the D3DEnumDevicesCallback7 callback function that the enumeration procedure calls every time a match is found.
lpUserArg
Address of application-defined data passed to the callback function.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

In the IDirect3D3 interface, this method accepted a pointer to a D3DEnumDevicesCallback function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.


IDirect3D7::EnumZBufferFormats

The IDirect3D7::EnumZBufferFormats method enumerates the supported depth-buffer formats for a specified device.

HRESULT EnumZBufferFormats(
  REFCLSID riidDevice,
  LPD3DENUMPIXELFORMATSCALLBACK lpEnumCallback,
  LPVOID   lpContext
);

Parameters

riidDevice
Reference to a globally unique identifier for the device whose depth-buffer formats are enumerated.
lpEnumCallback
Address of a D3DEnumPixelFormatsCallback callback function that is called for each supported depth-buffer format.
lpContext
Application-defined data that is passed to the callback function.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOZBUFFERHW
DDERR_OUTOFMEMORY

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.


IDirect3D7::EvictManagedTextures

The IDirect3D7::EvictManagedTextures method evicts all managed textures from local or nonlocal video memory.

HRESULT EvictManagedTextures();

Parameters

None.

Return Values

This method returns D3D_OK.

Remarks

This method causes Direct3D to remove any texture surfaces created with the DDSCAPS2_TEXTUREMANAGE or DDSCAPS2_D3DTEXTUREMANAGE flags from local or nonlocal video memory.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

Automatic Texture Management


IDirect3DDevice7

The IDirect3DDevice7 interface provides methods enabling applications to perform DrawPrimitive-based rendering, in contrast to the IDirect3DDevice interface, which applications use to work with execute buffers. You can create a Direct3DDevice object and retrieve a pointer to this interface by calling the IDirect3D7::CreateDevice method.

For a conceptual overview, see Direct3D Devices and the DrawPrimitive Methods.

The methods of the IDirect3DDevice7 interface can be organized into the following groups:

Information | GetCaps
 | GetDirect3D
 | GetInfo
Device states | ApplyStateBlock
 | BeginStateBlock
 | CaptureStateBlock
 | CreateStateBlock
 | DeleteStateBlock
 | EndStateBlock
 | GetClipStatus
 | GetRenderState
 | GetRenderTarget
 | GetStateData
 | GetTransform
 | SetClipStatus
 | SetRenderState
 | SetRenderTarget
 | SetStateData
 | SetTransform
Lighting and materials | GetLight
 | GetLightEnable
 | GetMaterial
 | LightEnable
 | SetLight
 | SetMaterial
Miscellaneous | ComputeSphereVisibility
 | MultiplyTransform
Rendering | DrawIndexedPrimitive
 | DrawIndexedPrimitiveStrided
 | DrawIndexedPrimitiveVB
 | DrawPrimitive
 | DrawPrimitiveStrided
 | DrawPrimitiveVB
Scenes | BeginScene
 | EndScene
Textures | EnumTextureFormats
 | GetTexture
 | GetTextureStageState
 | Load
 | PreLoad
 | SetTexture
 | SetTextureStageState
 | ValidateDevice
User-defined clip planes | GetClipPlane
 | SetClipPlane
Viewports | Clear
 | GetViewport
 | SetViewport

The IDirect3DDevice7 interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

This interface extends the IDirect3DDevice3 interface by including methods for device-state blocks. Device-state blocks accelerate the common sequences of state changes that your application requires. In addition, the IDirect3DDevice7 interface includes methods to work with viewports, lights, and materials within the device that supersede the IDirect3DViewport3, IDirect3DMaterial3, and IDirect3DLight interfaces.

Many of the methods common to this interface and its predecessor, IDirect3DDevice3, accept slightly different parameters. Wherever an IDirect3DDevice3 interface method might accept an IDirectDrawSurface3 interface pointer as a parameter, the methods in the IDirect3DDevice7 interface accept an IDirectDrawSurface7 interface pointer instead. Methods that previously accepted pointers to an IDirect3DVertexBuffer or IDirect3DTexture2 interface now accept IDirect3DVertexBuffer7 or IDirectDrawSurface7 interface pointers instead. The methods for viewports, materials, and lighting that were added to the interface accept pointers to new structures, as described in the reference page for each new method.

This interface is not intended to be used with execute buffers and therefore does not contain any execute-buffer-related methods. For information about execute buffers, see the documentation provided with a previous release of DirectX. Legacy documentation is provided with this SDK and available for download from http://www.microsoft.com/directx.

You can use the LPDIRECT3DDEVICE2, LPDIRECT3DDEVICE3, or LPDIRECT3DDEVICE7 data types to declare a variable that contains a pointer to an IDirect3DDevice2, IDirect3DDevice3, or IDirect3DDevice7 interface. The D3d.h header file declares these data types with the following code:

typedef struct IDirect3DDevice2    *LPDIRECT3DDEVICE2;
typedef struct IDirect3DDevice3    *LPDIRECT3DDEVICE3;
typedef struct IDirect3DDevice7    *LPDIRECT3DDEVICE7;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

Direct3D Devices, Rendering


IDirect3DDevice7::ApplyStateBlock

The IDirect3DDevice7::ApplyStateBlock method applies an existing device-state block to the rendering device.

HRESULT ApplyStateBlock(
  DWORD dwBlockHandle
);

Parameters

dwBlockHandle
Handle to the device state block to be executed, as returned by a previous call to the IDirect3DDevice7::EndStateBlock method.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values:

D3DERR_INBEGINSTATEBLOCK
D3DERR_INVALIDSTATEBLOCK

Remarks

Applications cannot apply a device state block while recording another block.

This method was introduced with the IDirect3DDevice7 interface.

As with all operations that affect the state of the rendering device, it is recommend that you apply state blocks during scene rendering—that is, after calling the IDirect3DDevice7::BeginScene method and before calling IDirect3DDevice7::EndScene.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::BeginStateBlock, IDirect3DDevice7::EndStateBlock, IDirect3DDevice7::CaptureStateBlock, IDirect3DDevice7::CreateStateBlock, IDirect3DDevice7::DeleteStateBlock, State Blocks


IDirect3DDevice7::BeginScene

The IDirect3DDevice7::BeginScene method begins a scene. Applications must call this method before performing any rendering and must call IDirect3DDevice7::EndScene when rendering is complete and before calling IDirect3DDevice7::BeginScene again.

HRESULT BeginScene();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value is an error. For a complete list of Direct3D Immediate Mode error values and descriptions, see Return Values.

Remarks

If the BeginScene method fails, the device was unable to begin the scene, and there is no need to call the IDirect3DDevice7::EndScene method. In fact, calls to the IDirect3DDevice7::EndScene method will fail if the previous call to BeginScene failed.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::EndScene, Beginning and Ending a Scene


IDirect3DDevice7::BeginStateBlock

The IDirect3DDevice7::BeginStateBlock method signals Direct3D to begin recording a device state block.

HRESULT BeginStateBlock();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values:

D3DERR_INBEGINSTATEBLOCK
DDERR_OUTOFMEMORY

Remarks

This method was introduced with the IDirect3DDevice7 interface.

Applications can ensure that all recorded states are valid by calling the IDirect3DDevice7::ValidateDevice method prior to calling this method.

The following methods can be recorded in a state block (that is, after calling IDirect3DDevice7::BeginStateBlock and before IDirect3DDevice7::EndStateBlock):

  • IDirect3DDevice7::LightEnable
  • IDirect3DDevice7::SetClipPlane
  • IDirect3DDevice7::SetLight
  • IDirect3DDevice7::SetMaterial
  • IDirect3DDevice7::SetRenderState
  • IDirect3DDevice7::SetTexture
  • IDirect3DDevice7::SetTextureStageState
  • IDirect3DDevice7::SetTransform
  • IDirect3DDevice7::SetViewport

The ordering of state changes in a state block is not guaranteed. If the same state is specified multiple times in a state block, only the last value is used.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::ApplyStateBlock, IDirect3DDevice7::EndStateBlock, IDirect3DDevice7::CaptureStateBlock, IDirect3DDevice7::CreateStateBlock, IDirect3DDevice7::DeleteStateBlock, State Blocks


IDirect3DDevice7::CaptureStateBlock

The IDirect3DDevice7::CaptureStateBlock method updates the values within an existing state block to the values currently set for the device.

HRESULT CaptureStateBlock(
  DWORD dwBlockHandle
);

Parameters

dwBlockHandle
Handle to the state block into which the current device state is captured.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be a standard error code, or D3DERR_INBEGINSTATEBLOCK if a state block is currently being recorded.

Remarks

This method captures updated values for states within an existing state block. It does not capture the entire state of the device. For more information, see Capturing State Blocks.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::ApplyStateBlock, IDirect3DDevice7::BeginStateBlock, IDirect3DDevice7::CreateStateBlock, IDirect3DDevice7::EndStateBlock, IDirect3DDevice7::DeleteStateBlock, State Blocks, Capturing State Blocks


IDirect3DDevice7::CreateStateBlock

The IDirect3DDevice7::CreateStateBlock method creates a new state block that contains the current values for all device states, vertex-related states, or pixel-related states.

HRESULT CreateStateBlock(
  D3DSTATEBLOCKTYPE d3dsbType,
  LPDWORD lpdwBlockHandle
);

Parameters

d3dsbType
Type of state data that the method should capture. This parameter can be set to one of the values defined in the D3DSTATEBLOCKTYPE enumerated type.
lpdwBlockHandle
Address of a variable to contain the state block handle if the method succeeds.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values:

D3DERR_INBEGINSTATEBLOCK
DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY

Remarks

Vertex-related device states typically refer to those states that affect how the system processes vertices. Pixel-related states generally refer to device states that affect how the system processes pixel or depth-buffer data during rasterization. Some states are contained in both groups. For information about the states in each group, see Creating Predefined State Blocks.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::ApplyStateBlock, IDirect3DDevice7::BeginStateBlock, IDirect3DDevice7::CaptureStateBlock, IDirect3DDevice7::EndStateBlock, IDirect3DDevice7::DeleteStateBlock, State Blocks


IDirect3DDevice7::Clear

The IDirect3DDevice7::Clear method clears the viewport (or a set of rectangles in the viewport) to a specified RGBA color, clears the depth buffer, and erases the stencil buffer. This method supersedes the clearing methods exposed by the legacy IDirect3DViewport3 interface.

HRESULT Clear(
  DWORD     dwCount,
  LPD3DRECT lpRects,
  DWORD     dwFlags,
  DWORD     dwColor,
  D3DVALUE  dvZ,
  DWORD     dwStencil
);

Parameters

dwCount
Number of rectangles in the array at lpRects. If you set lpRects to NULL, this parameter must be set to 0.
lpRects
Array of D3DRECT structures that describe the rectangles to be cleared. Set a rectangle to the dimensions of the rendering target to clear the entire surface. Each rectangle uses screen coordinates that correspond to points on the render target surface. Coordinates are clipped to the bounds of the viewport rectangle. This parameter can be set to NULL to indicate that the entire viewport rectangle is to be cleared.
dwFlags
Flags indicating which surfaces should be cleared. This parameter can be any combination of the following flags, but at least one flag must be used:
D3DCLEAR_TARGET
Clear the rendering target to the color in the dwColor parameter.
D3DCLEAR_STENCIL
Clear the stencil buffer to the value in the dwStencil parameter.
D3DCLEAR_ZBUFFER
Clear the depth buffer to the value in the dvZ parameter.
dwColor
A 32-bit RGBA color value to which the render target surface is cleared.
dvZ
New z value that this method stores in the depth buffer. This parameter can be in the range from 0.0 through 1.0 (for z-based or w-based depth buffers). A value of 0.0 represents the nearest distance to the viewer, and 1.0 the farthest distance.
dwStencil
Integer value to store in each stencil-buffer entry. This parameter can be in the range from 0 through 2n–1, where n is the bit depth of the stencil buffer.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values:

D3DERR_STENCILBUFFER_NOTPRESENT
D3DERR_VIEWPORTHASNODEVICE
D3DERR_ZBUFFER_NOTPRESENT
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

This method was introduced with the IDirect3DDevice7 interface.

This method fails if you specify the D3DCLEAR_ZBUFFER or D3DCLEAR_STENCIL flags when the render target does not have an attached depth buffer. Similarly, if you specify the D3DCLEAR_STENCIL flag when the depth-buffer format does not contain stencil buffer information, this method fails.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.


IDirect3DDevice7::ComputeSphereVisibility

The IDirect3DDevice7::ComputeSphereVisibility method calculates the visibility (complete, partial, or no visibility) of an array of spheres within the current viewport for this device.

HRESULT ComputeSphereVisibility(
  LPD3DVECTOR lpCenters,
  LPD3DVALUE  lpRadii,
  DWORD       dwNumSpheres,
  DWORD       dwFlags,
  LPDWORD     lpdwReturnValues
);

Parameters

lpCenters
Array of D3DVECTOR structures describing the center point for each sphere, in world-space coordinates.
lpRadii
Array of D3DVALUE variables that represent the radius for each sphere.
dwNumSpheres
Number of spheres. This value must be greater than 0.
dwFlags
Not currently used; set to 0.
lpdwReturnValues
Array of DWORD values. The array need not be initialized, but it must be large enough to contain a DWORD for each sphere being tested. When the method returns, each element in the array contains a combination of flags that describe the visibility of that sphere within the current viewport for this device. If a sphere is completely visible, the corresponding entry in lpdwReturnValues is 0. The following flags can be combined and present in the array:

Basic Clipping Flags

D3DCLIP_BACK
All vertices are clipped by the back plane of the viewing frustum.
D3DCLIP_BOTTOM
All vertices are clipped by the bottom plane of the viewing frustum.
D3DCLIP_FRONT
All vertices are clipped by the front plane of the viewing frustum.
D3DCLIP_LEFT
All vertices are clipped by the left plane of the viewing frustum.
D3DCLIP_RIGHT
All vertices are clipped by the right plane of the viewing frustum.
D3DCLIP_TOP
All vertices are clipped by the top plane of the viewing frustum.
D3DCLIP_GEN0 through D3DCLIP_GEN5
All vertices are clipped by a corresponding application-defined clipping plane.

Combination and General Flags

D3DSTATUS_CLIPINTERSECTIONALL
Combination of all CLIPINTERSECTION flags.
D3DSTATUS_CLIPUNIONALL
Combination of all CLIPUNION flags.
D3DSTATUS_DEFAULT
Combination of D3DSTATUS_CLIPINTERSECTIONALL and D3DSTATUS_ZNOTVISIBLE flags. This value is the default.
D3DSTATUS_ZNOTVISIBLE
Indicates that the rendered primitive is not visible. This flag is set or cleared by the system when rendering with z-checking enabled (see D3DRENDERSTATE_ZVISIBLE).

Clip Intersection Flags

D3DSTATUS_CLIPINTERSECTIONBACK
Logical And of the clip flags for the vertices compared to the back clipping plane of the viewing frustum.
D3DSTATUS_CLIPINTERSECTIONBOTTOM
Logical And of the clip flags for the vertices compared to the bottom of the viewing frustum.
D3DSTATUS_CLIPINTERSECTIONFRONT
Logical And of the clip flags for the vertices compared to the front clipping plane of the viewing frustum.
D3DSTATUS_CLIPINTERSECTIONGEN0 through D3DSTATUS_CLIPINTERSECTIONGEN5
Logical And of the clip flags for application-defined clipping planes.
D3DSTATUS_CLIPINTERSECTIONLEFT
Logical And of the clip flags for the vertices compared to the left side of the viewing frustum.
D3DSTATUS_CLIPINTERSECTIONRIGHT
Logical And of the clip flags for the vertices compared to the right side of the viewing frustum.
D3DSTATUS_CLIPINTERSECTIONTOP
Logical And of the clip flags for the vertices compared to the top of the viewing frustum.

Clip Union Flags

D3DSTATUS_CLIPUNIONBACK
Equal to D3DCLIP_BACK.
D3DSTATUS_CLIPUNIONBOTTOM
Equal to D3DCLIP_BOTTOM.
D3DSTATUS_CLIPUNIONFRONT
Equal to D3DCLIP_FRONT.
D3DSTATUS_CLIPUNIONGEN0 through D3DSTATUS_CLIPUNIONGEN5
Equal to D3DCLIP_GEN0 through D3DCLIP_GEN5.
D3DSTATUS_CLIPUNIONLEFT
Equal to D3DCLIP_LEFT.
D3DSTATUS_CLIPUNIONRIGHT
Equal to D3DCLIP_RIGHT.
D3DSTATUS_CLIPUNIONTOP
Equal to D3DCLIP_TOP.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values:

D3DERR_INVALIDMATRIX
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

Sphere visibility is computed by back-transforming the viewing frustum to the model space, using the inverse of the combined world, view, or projection matrices. If the combined matrix cannot be inverted (if the determinant is 0), the method fails, returning D3DERR_INVALIDMATRIX.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.


IDirect3DDevice7::DeleteStateBlock

The IDirect3DDevice7::DeleteStateBlock method deletes a previously recorded device state block.

HRESULT DeleteStateBlock (
  DWORD dwBlockHandle
);

Parameters

dwBlockHandle
Handle to the device state block to be deleted, as returned by a previous call to the IDirect3DDevice7::EndStateBlock method.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values:

D3DERR_INBEGINSTATEBLOCK
D3DERR_INVALIDSTATEBLOCK

Remarks

Applications cannot delete a device state block while another is being recorded.

This method was introduced with the IDirect3DDevice7 interface.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::ApplyStateBlock, IDirect3DDevice7::BeginStateBlock, IDirect3DDevice7::CaptureStateBlock, IDirect3DDevice7::CreateStateBlock, IDirect3DDevice7::EndStateBlock, State Blocks


IDirect3DDevice7::DrawIndexedPrimitive

The IDirect3DDevice7::DrawIndexedPrimitive method renders the specified geometric primitive, based on indexing into an array of vertices.

HRESULT DrawIndexedPrimitive(
  D3DPRIMITIVETYPE d3dptPrimitiveType,
  DWORD  dwVertexTypeDesc,
  LPVOID lpvVertices,
  DWORD  dwVertexCount,
  LPWORD lpwIndices,
  DWORD  dwIndexCount,
  DWORD  dwFlags
);

Parameters

d3dptPrimitiveType
Type of primitive to be rendered by this command. This must be one of the members of the D3DPRIMITIVETYPE enumerated type.

The D3DPT_POINTLIST member of D3DPRIMITIVETYPE is not indexed.

dwVertexTypeDesc
A combination of flexible vertex format flags that describes the vertex format for this set of primitives.
lpvVertices
Pointer to the list of vertices to be used in the primitive sequence.
dwVertexCount
Defines the number of vertices in the list.

This parameter is used differently from the dwVertexCount parameter in the IDirect3DDevice7::DrawPrimitive method. In that method, the dwVertexCount parameter gives the number of vertices to draw, but here it gives the total number of vertices in the array pointed to by the lpvVertices parameter. When you call IDirect3DDevice7::DrawIndexedPrimitive, you specify the number of vertices to draw in the dwIndexCount parameter.

lpwIndices
Pointer to a list of WORDs that are to be used to index into the specified vertex list when creating the geometry to render.
dwIndexCount
Specifies the number of indices provided for creating the geometry. The maximum number of indices allowed is D3DMAXNUMVERTICES (0xFFFF).
dwFlags
Zero to render the primitive without waiting, or the following flag:
D3DDP_WAIT
Causes the method to wait until the polygons have been rendered before it returns, instead of returning as soon as the polygons have been sent to the card. (On scene-capture cards, the method returns as soon as the card responds.) This flag is typically used for debugging. Applications should not attempt to use this flag to ensure that a scene is up to date before continuing.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values:

D3DERR_INVALIDRAMPTEXTURE
D3DERR_INVALIDPRIMITIVETYPE
D3DERR_INVALIDVERTEXTYPE
DDERR_INVALIDPARAMS
DDERR_WASSTILLDRAWING

Remarks

Make sure that the vertices being rendered match the vertex format that you specify. For performance reasons, Direct3D does not attempt to verify that vertex size and stride match the provided flexible vertex format. If a mismatch occurs, a memory fault is likely to result.

This method, unlike its predecessor in previous interfaces, does not accept the D3DDP_DONOTCLIP, D3DDP_DONOTLIGHT, and D3DDP_DONOTUPDATEEXTENTS flags in the dwFlags parameter. The functionality offered by these flags is now available through the D3DRENDERSTATE_CLIPPING, D3DRENDERSTATE_LIGHTING, and D3DRENDERSTATE_EXTENTS render states.

Do not use this method to render very small subsets of vertices from extremely large vertex arrays. This method transforms every vertex in the provided buffer, regardless of the location or number of vertices being rendered. Thus, if you pass an array that contains thousands of vertices, but only intend to render hundreds, your application's performance suffers dramatically. If you need to render a small number of vertices from a large buffer, use the Direct3D vertex buffer rendering methods. For more information, see Vertex Buffers.

This method differs from its counterpart in the IDirect3DDevice2 interface in that it accepts a flexible vertex format descriptor, rather than a member of the D3DVERTEXTYPE enumerated type as the second parameter. If you attempt to use one of the members of D3DVERTEXTYPE, the method fails, returning DDERR_INVALIDPARAMS. For more information, see Vertex Formats.

In current versions of DirectX, IDirect3DDevice7::DrawIndexedPrimitive can sometimes generate an update rectangle that is larger than it needs to be. If a large number of vertices need to be processed, this can have a negative impact on the performance of your application. If you are using D3DTLVERTEX vertices and the system is processing more vertices than you need, use the D3DDP_DONOTCLIP and D3DDP_DONOTUPDATEEXTENTS flags to solve the problem.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::DrawPrimitive, IDirect3DDevice7::DrawPrimitiveStrided, IDirect3DDevice7::DrawPrimitiveVB, IDirect3DDevice7::DrawIndexedPrimitiveStrided, IDirect3DDevice7::DrawIndexedPrimitiveVB


IDirect3DDevice7::DrawIndexedPrimitiveStrided

The IDirect3DDevice7::DrawIndexedPrimitiveStrided method renders a geometric primitive, based on indexing into an array of strided vertices. For more information, see Strided Vertex Format.

HRESULT DrawIndexedPrimitiveStrided(
  D3DPRIMITIVETYPE d3dptPrimitiveType,
  DWORD  dwVertexTypeDesc,
  LPD3DDRAWPRIMITIVESTRIDEDDATA lpVertexArray,
  DWORD  dwVertexCount,
  LPWORD lpwIndices,
  DWORD  dwIndexCount,
  DWORD  dwFlags
);

Parameters

d3dptPrimitiveType
Type of primitive to be rendered by this command. This must be one of the members of the D3DPRIMITIVETYPE enumerated type.

The D3DPT_POINTLIST member of D3DPRIMITIVETYPE is not indexed.

dwVertexTypeDesc
A combination of flexible vertex format flags that describes the vertex format for this primitive.
lpVertexArray
Address of a D3DDRAWPRIMITIVESTRIDEDDATA structure that contains pointers and memory strides for the vertex components of this primitive, in the format specified by the flags in dwVertexTypeDesc.
dwVertexCount
Defines the number of vertices in the list.

This parameter is used differently from the dwVertexCount parameter in the IDirect3DDevice7::DrawPrimitive method. In that method, the dwVertexCount parameter gives the number of vertices to draw, but here it gives the total number of vertices in the array pointed to by the lpVertexArray parameter. When you call IDirect3DDevice7::DrawIndexedPrimitiveStrided, you specify the number of vertices to draw in the dwIndexCount parameter.

lpwIndices
Pointer to a list of WORDs that are to be used to index into the specified vertex list when creating the geometry to render.
dwIndexCount
Specifies the number of indices provided for creating the geometry. The maximum number of indices allowed is D3DMAXNUMVERTICES (0xFFFF).
dwFlags
Zero to render the primitive without waiting, or the following flag:
D3DDP_WAIT
Causes the method to wait until the polygons have been rendered before it returns, instead of returning as soon as the polygons have been sent to the card. (On scene-capture cards, the method returns as soon as the card responds.) This flag is typically used for debugging. Applications should not attempt to use this flag to ensure that a scene is up to date before continuing.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values:

D3DERR_INVALIDRAMPTEXTURE
D3DERR_INVALIDPRIMITIVETYPE
D3DERR_INVALIDVERTEXTYPE
DDERR_INVALIDPARAMS
DDERR_WASSTILLDRAWING

Remarks

Be sure that the vertices being rendered match the vertex format that you specify. For performance reasons, Direct3D does not attempt to verify that vertex size and stride match the provided flexible vertex format. If a mismatch occurs, a memory fault is likely to result.

This method, unlike its predecessor in previous interfaces, does not accept the D3DDP_DONOTCLIP, D3DDP_DONOTLIGHT, and D3DDP_DONOTUPDATEEXTENTS flags in the dwFlags parameter. The functionality offered by these flags is now available through the D3DRENDERSTATE_CLIPPING, D3DRENDERSTATE_LIGHTING, and D3DRENDERSTATE_EXTENTS render states.

This method does not support transformed vertices. Therefore, if you include the D3DFVF_XYZRHW vertex format descriptor in the dwVertexTypeDesc parameter, the method fails, returning D3DERR_INVALIDVERTEXTYPE.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::DrawPrimitive, IDirect3DDevice7::DrawPrimitiveStrided, IDirect3DDevice7::DrawPrimitiveVB, IDirect3DDevice7::DrawIndexedPrimitive, IDirect3DDevice7::DrawIndexedPrimitiveVB, Strided Vertex Format


IDirect3DDevice7::DrawIndexedPrimitiveVB

The IDirect3DDevice7::DrawIndexedPrimitiveVB method renders a geometric primitive based on indexing into an array of vertices within a vertex buffer.

HRESULT DrawIndexedPrimitiveVB(
  D3DPRIMITIVETYPE        d3dptPrimitiveType,
  LPDIRECT3DVERTEXBUFFER7 lpd3dVertexBuffer,
  DWORD  dwStartVertex,
  DWORD  dwNumVertices,
  LPWORD lpwIndices,
  DWORD  dwIndexCount,
  DWORD  dwFlags
);

Parameters

d3dptPrimitiveType
Type of primitive to be rendered by this command. This must be one of the members of the D3DPRIMITIVETYPE enumerated type.

The D3DPT_POINTLIST member of D3DPRIMITIVETYPE is not indexed.

lpd3dVertexBuffer
Address of the IDirect3DVertexBuffer7 interface for the vertex buffer that contains the array of vertices. Vertices can be transformed or untransformed, optimized or unoptimized.
dwStartVertex
Index of the first vertex in the vertex buffer to be rendered.
dwNumVertices
Total number of vertices in the vertex buffer to be rendered.
lpwIndices
Address of an array of WORDs that is used to index into the vertices in the vertex buffer. The values in the array must index vertices within the range [0, dwNumVertices – 1].
dwIndexCount
The number of indices in the array at lpwIndices. The maximum number of indices allowed is D3DMAXNUMVERTICES (0xFFFF).
dwFlags
Zero to render the primitive without waiting, or the following flag:
D3DDP_WAIT
Causes the method to wait until the polygons have been rendered before it returns, instead of returning as soon as the polygons have been sent to the card. (On scene-capture cards, the method returns as soon as the card responds.) This flag is typically used for debugging. Applications should not attempt to use this flag to ensure that a scene is up to date before continuing.

Return Values

If the method succeeds, the return value is DD_OK.

If the method fails, the return value can be one of the following values:

D3DERR_INVALIDPRIMITIVETYPE
D3DERR_INVALIDVERTEXTYPE
D3DERR_VERTEXBUFFERLOCKED
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_WASSTILLDRAWING

Remarks

Be sure that the vertices being rendered match the vertex format that you specify. For performance reasons, Direct3D does not attempt to verify that vertex size and stride match the provided flexible vertex format. If a mismatch occurs, a memory fault is likely to result.

This method, unlike its predecessor in previous interfaces, does not accept the D3DDP_DONOTCLIP, D3DDP_DONOTLIGHT, and D3DDP_DONOTUPDATEEXTENTS flags in the dwFlags parameter. The functionality offered by these flags is now available through the D3DRENDERSTATE_CLIPPING, D3DRENDERSTATE_LIGHTING, and D3DRENDERSTATE_EXTENTS render states.

Software devices—MMX and RGB devices—cannot render from a video memory (local or nonlocal) vertex buffer. To render a vertex buffer, using a software device, the vertex buffer must exist in system memory. Hardware devices can render from system memory or video memory vertex buffers.

You cannot render from a locked vertex buffer; calls to the IDirect3DDevice7::DrawIndexedPrimitiveVB or IDirect3DDevice7::DrawPrimitiveVB method, using a locked buffer fail, returning D3DERR_VERTEXBUFFERLOCKED.

In the IDirect3DDevice3 interface, this method accepted a pointer to the legacy IDirect3DVertexBuffer interface.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::DrawPrimitive, IDirect3DDevice7::DrawPrimitiveStrided, IDirect3DDevice7::DrawPrimitiveVB, IDirect3DDevice7::DrawIndexedPrimitive, IDirect3DDevice7::DrawIndexedPrimitiveStrided


IDirect3DDevice7::DrawPrimitive

The IDirect3DDevice7::DrawPrimitive method renders the specified array of vertices as a sequence of geometric primitives of the specified type.

HRESULT DrawPrimitive(
  D3DPRIMITIVETYPE dptPrimitiveType,
  DWORD  dwVertexTypeDesc,
  LPVOID lpvVertices,
  DWORD  dwVertexCount,
  DWORD  dwFlags
);

Parameters

dptPrimitiveType
Type of primitive to be rendered by this command. This must be one of the members of the D3DPRIMITIVETYPE enumerated type.
dwVertexTypeDesc
A combination of flexible vertex format flags that describes the vertex format used for this set of primitives.
lpvVertices
Pointer to the array of vertices to be used in the primitive sequence.
dwVertexCount
The number of vertices in the array. The maximum number of vertices allowed is D3DMAXNUMVERTICES (0xFFFF).
dwFlags
Zero to render the primitive without waiting, or the following flag:
D3DDP_WAIT
Causes the method to wait until the polygons have been rendered before it returns, instead of returning as soon as the polygons have been sent to the card. (On scene-capture cards, the method returns as soon as the card responds.) This flag is typically used for debugging. Applications should not attempt to use this flag to ensure that a scene is up to date before continuing.

Return Values

If the method succeeds, the return value is DD_OK.

If the method fails, the return value can be one of the following values:

D3DERR_INVALIDRAMPTEXTURE
D3DERR_INVALIDPRIMITIVETYPE
D3DERR_INVALIDVERTEXTYPE
DDERR_INVALIDPARAMS
DDERR_WASSTILLDRAWING

Remarks

Be sure that the vertices being rendered match the vertex format that you specify. For performance reasons, Direct3D does not attempt to verify that vertex size and stride match the provided flexible vertex format. If a mismatch occurs, a memory fault is likely to result.

This method, unlike its predecessor in previous interfaces, does not accept the D3DDP_DONOTCLIP, D3DDP_DONOTLIGHT, and D3DDP_DONOTUPDATEEXTENTS flags in the dwFlags parameter. The functionality offered by these flags is now available through the D3DRENDERSTATE_CLIPPING, D3DRENDERSTATE_LIGHTING, and D3DRENDERSTATE_EXTENTS render states.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::DrawPrimitiveStrided, IDirect3DDevice7::DrawPrimitiveVB, IDirect3DDevice7::DrawIndexedPrimitive, IDirect3DDevice7::DrawIndexedPrimitiveStrided, IDirect3DDevice7::DrawIndexedPrimitiveVB


IDirect3DDevice7::DrawPrimitiveStrided

The IDirect3DDevice7::DrawPrimitiveStrided method renders the specified array of strided vertices as a sequence of geometric primitives. For more information, see Strided Vertex Format.

HRESULT DrawPrimitiveStrided(
  D3DPRIMITIVETYPE dptPrimitiveType,
  DWORD  dwVertexTypeDesc,
  LPD3DDRAWPRIMITIVESTRIDEDDATA lpVertexArray,
  DWORD  dwVertexCount,
  DWORD  dwFlags
);

Parameters

dptPrimitiveType
Type of primitive to be rendered by this command. This must be one of the members of the D3DPRIMITIVETYPE enumerated type.
dwVertexTypeDesc
A combination of flexible vertex format flags that describes the vertex format.
lpVertexArray
Address of a D3DDRAWPRIMITIVESTRIDEDDATA structure that contains pointers and memory strides for the vertex components for this primitive, in the format specified by the flags in dwVertexTypeDesc.
dwVertexCount
Number of vertices in the array at lpVertexArray. The maximum number of vertices allowed is D3DMAXNUMVERTICES (0xFFFF).
dwFlags
Zero to render the primitive without waiting, or the following flag:
D3DDP_WAIT
Causes the method to wait until the polygons have been rendered before it returns, instead of returning as soon as the polygons have been sent to the card. (On scene-capture cards, the method returns as soon as the card responds.) This flag is typically used for debugging. Applications should not attempt to use this flag to ensure that a scene is up to date before continuing.

Return Values

If the method succeeds, the return value is DD_OK.

If the method fails, the return value can be one of the following values:

D3DERR_INVALIDRAMPTEXTURE
D3DERR_INVALIDPRIMITIVETYPE
D3DERR_INVALIDVERTEXTYPE
DDERR_INVALIDPARAMS
DDERR_WASSTILLDRAWING

Remarks

Be sure that the vertices being rendered match the vertex format that you specify. For performance reasons, Direct3D does not attempt to verify that vertex size and stride match the provided flexible vertex format. If a mismatch occurs, a memory fault is likely to result.

This method, unlike its predecessor in previous interfaces, does not accept the D3DDP_DONOTCLIP, D3DDP_DONOTLIGHT, and D3DDP_DONOTUPDATEEXTENTS flags in the dwFlags parameter. The functionality offered by these flags is now available through the D3DRENDERSTATE_CLIPPING, D3DRENDERSTATE_LIGHTING, and D3DRENDERSTATE_EXTENTS render states.

This method does not support transformed vertices. Therefore, if you include the D3DFVF_XYZRHW vertex format descriptor in the dwVertexTypeDesc parameter, the method fails, returning D3DERR_INVALIDVERTEXTYPE.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::DrawPrimitive, IDirect3DDevice7::DrawPrimitiveVB, IDirect3DDevice7::DrawIndexedPrimitive, IDirect3DDevice7::DrawIndexedPrimitiveStrided, IDirect3DDevice7::DrawIndexedPrimitiveVB, Strided Vertex Format


IDirect3DDevice7::DrawPrimitiveVB

The IDirect3DDevice7::DrawPrimitiveVB method renders an array of vertices in a vertex buffer as a sequence of geometric primitives.

HRESULT DrawPrimitiveVB(
  D3DPRIMITIVETYPE        d3dptPrimitiveType,
  LPDIRECT3DVERTEXBUFFER7 lpd3dVertexBuffer,
  DWORD dwStartVertex,
  DWORD dwNumVertices,
  DWORD dwFlags
);

Parameters

d3dptPrimitiveType
Type of primitive to be rendered by this command. This must be one of the members of the D3DPRIMITIVETYPE enumerated type.
lpd3dVertexBuffer
Address of the IDirect3DVertexBuffer7 interface for the vertex buffer that contains the array of vertices. Vertices can be transformed or untransformed, optimized or unoptimized.
dwStartVertex
Index value of the first vertex in the primitive. The highest possible starting index is D3DMAXNUMVERTICES (0xFFFF). In debug builds, specifying a starting index value that exceeds this limit causes the method to fail and return DDERR_INVALIDPARAMS.
dwNumVertices
Number of vertices to be rendered. The maximum number of vertices allowed is D3DMAXNUMVERTICES (0xFFFF).
dwFlags
Zero to render the primitive without waiting, or the following flag:
D3DDP_WAIT
Causes the method to wait until the polygons have been rendered before it returns, instead of returning as soon as the polygons have been sent to the card. (On scene-capture cards, the method returns as soon as the card responds.) This flag is typically used for debugging. Applications should not attempt to use this flag to ensure that a scene is up to date before continuing.

Return Values

If the method succeeds, the return value is DD_OK.

If the method fails, the return value can be one of the following values:

D3DERR_INVALIDRAMPTEXTURE
D3DERR_INVALIDPRIMITIVETYPE
D3DERR_INVALIDVERTEXTYPE
D3DERR_VERTEXBUFFERLOCKED
DDERR_INVALIDPARAMS
DDERR_WASSTILLDRAWING

Remarks

Be sure that the vertices being rendered match the vertex format that you specify. For performance reasons, Direct3D does not attempt to verify that vertex size and stride match the provided flexible vertex format. If a mismatch occurs, a memory fault is likely to result.

This method, unlike its predecessor in previous interfaces, does not accept the D3DDP_DONOTCLIP, D3DDP_DONOTLIGHT, and D3DDP_DONOTUPDATEEXTENTS flags in the dwFlags parameter. The functionality offered by these flags is now available through the D3DRENDERSTATE_CLIPPING, D3DRENDERSTATE_LIGHTING, and D3DRENDERSTATE_EXTENTS render states.

Software devices—MMX and RGB devices—cannot render from a video memory (local or nonlocal) vertex buffer. To render a vertex buffer, using a software device, the vertex buffer must exist in system memory. Hardware devices can render from system memory or video memory vertex buffers.

You cannot render from a locked vertex buffer; calls to the IDirect3DDevice7::DrawIndexedPrimitiveVB or IDirect3DDevice7::DrawPrimitiveVB method, using a locked buffer fail, returning D3DERR_VERTEXBUFFERLOCKED.

In the IDirect3DDevice3 interface, this method accepted a pointer to the legacy IDirect3DVertexBuffer interface.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::DrawPrimitive, IDirect3DDevice7::DrawPrimitiveStrided, IDirect3DDevice7::DrawIndexedPrimitive, IDirect3DDevice7::DrawIndexedPrimitiveStrided, IDirect3DDevice7::DrawIndexedPrimitiveVB


IDirect3DDevice7::EndScene

The IDirect3DDevice7::EndScene method ends a scene that was begun by calling the IDirect3DDevice7::BeginScene method.

HRESULT EndScene();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value is an error.

Remarks

When this method succeeds, the scene has been rendered, and the device surface holds the rendered scene.

When scene rendering begins successfully, you must call this method before you can call the IDirect3DDevice7::BeginScene method to start rendering another scene. (If a prior call to BeginScene method fails, the scene did not begin, and this method should not be called.)

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::BeginScene, Beginning and Ending a Scene


IDirect3DDevice7::EndStateBlock

The IDirect3DDevice7::EndStateBlock method signals Direct3D to stop recording a device state block and retrieve a handle to the state block.

HRESULT EndStateBlock(
  LPDWORD lpdwBlockHandle
);

Parameters

lpdwBlockHandle
Address of a variable to be filled with the handle to the completed device state block. This value is used with the IDirect3DDevice7::ApplyStateBlock and IDirect3DDevice7::DeleteStateBlock methods.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values:

D3DERR_NOTINBEGINSTATEBLOCK
DDERR_INVALIDPARAMS

Remarks

This method was introduced with the IDirect3DDevice7 interface.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::ApplyStateBlock, IDirect3DDevice7::BeginStateBlock, IDirect3DDevice7::CaptureStateBlock, IDirect3DDevice7::CreateStateBlock, IDirect3DDevice7::DeleteStateBlock, State Blocks


IDirect3DDevice7::EnumTextureFormats

The IDirect3DDevice7::EnumTextureFormats method queries the current driver for a list of supported texture formats.

HRESULT EnumTextureFormats(
  LPD3DENUMPIXELFORMATSCALLBACK lpd3dEnumPixelProc,
  LPVOID lpArg
);

Parameters

lpd3dEnumPixelProc
Address of the D3DEnumPixelFormatsCallback callback function that the enumeration procedure calls for each texture format.
lpArg
Address of application-defined data passed to the callback function.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

In the IDirect3DDevice2 interface, this method accepts a pointer to the legacy D3DEnumTextureFormatsCallback function, not a D3DEnumPixelFormatsCallback.

This method might not enumerate newly implemented texture formats on some devices. Applications that require a texture format that is not enumerated can attempt to create a surface of that format. If the creation attempt succeeds, the format is supported.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.


IDirect3DDevice7::GetCaps

The IDirect3DDevice7::GetCaps method retrieves the capabilities of the Direct3D device.

HRESULT GetCaps(
  LPD3DDEVICEDESC7 lpD3DDevDesc,
);

Parameters

lpD3DDevDesc
Address of the D3DDEVICEDESC7 structure to contain the hardware features of the device.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

This method does not retrieve the capabilities of the display device. To retrieve this information, use the IDirectDraw7::GetCaps method.

In previous versions of this interface, this method simultaneously retrieved capabilities for hardware abstraction layer (HAL) devices and hardware emulation layer (HEL) devices by accepting pointers to the legacy D3DDEVICEDESC structure. In the IDirect3DDevice7 interface, this method only retrieves the capabilities of the device on which the method is called.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.


IDirect3DDevice7::GetClipPlane

The IDirect3DDevice7::GetClipPlane method retrieves the coefficients of a user-defined clipping plane for the device.

HRESULT GetClipPlane(
  DWORD dwIndex,
  D3DVALUE* pPlaneEquation
);

Parameters

dwIndex
Index of the clipping plane for which the plane equation coefficients are retrieved.
pPlaneEquation
Address of a four-element array of values that represent the coefficients of the clipping plane, in the form of the general plane equation. See remarks.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value is DDERR_INVALIDPARAMS. This error indicates that the value in dwIndex exceeds the maximum clipping plane index supported by the device or that the array at pPlaneEquation is not large enough to contain four floating-point values.

Remarks

The coefficients that this method reports take the form of the general plane equation. If the values in the array at pPlaneEquation were labeled A, B, C, and D in the order that they appear in the array, they would fit into the general plane equation so that Ax + By + Cz + D = 0. A point with homogeneous coordinates (x, y, z, w) is visible in the half space of the plane if Ax + By + Cz + Dw >= 0. Points that exist on or behind the clipping plane are clipped from the scene.

The plane equation used by this method exists in world space and is set by a previous call to the IDirect3DDevice7::SetClipPlane method.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::SetClipPlane, D3DRENDERSTATE_CLIPPLANEENABLE, User-defined Clip Planes


IDirect3DDevice7::GetClipStatus

The IDirect3DDevice7::GetClipStatus method gets the current clip status.

HRESULT GetClipStatus(
  LPD3DCLIPSTATUS lpD3DClipStatus
);

Parameters

lpD3DClipStatus
Address of a D3DCLIPSTATUS structure that describes the current clip status.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value is an error. The method returns DDERR_INVALIDPARAMS if one of the arguments is invalid.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::SetClipStatus


IDirect3DDevice7::GetDirect3D

The IDirect3DDevice7::GetDirect3D method retrieves the Direct3D object for this device.

HRESULT GetDirect3D(
  LPDIRECT3D7 *lplpD3D
);

Parameters

lplpD3D
Address that receives a pointer to the Direct3D object's IDirect3D7 interface when the method returns.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value is an error. For a list of possible return values, see Direct3D Immediate Mode Return Values.

Remarks

In previous versions of this interface, this method accepted a pointer to the legacy IDirect3D3 interface.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.


IDirect3DDevice7::GetInfo

The IDirect3DDevice7::GetInfo method retrieves information about the rendering device. Information can pertain to Direct3D or the underlying device driver.

HRESULT GetInfo(
  DWORD  dwDevInfoID,
  LPVOID pDevInfoStruct,
  DWORD  dwSize
);

Parameters

dwDevInfoID
Flags indicating the type of device information structure at pDevInfoStruct. This parameter can be set to one of the following flags:
D3DDEVINFOID_TEXTUREMANAGER
The structure at pDevInfoStruct is a D3DDEVINFO_TEXTUREMANAGER structure that contains information about the texture management being performed by the driver. If the driver does not manage textures, information about texture management performed by Direct3D is retrieved.
D3DDEVINFOID_D3DTEXTUREMANAGER
The structure at pDevInfoStruct is a D3DDEVINFO_TEXTUREMANAGER structure that contains information about texture management that is performed by Direct3D.
D3DDEVINFOID_TEXTURING
The structure at pDevInfoStruct is a D3DDEVINFO_TEXTURING structure that contains information about texturing activity of the application.
pDevInfoStruct
Address of a structure that receives the specified device information if the call succeeds. The type of structure, and how the data it contains is to be interpreted, is determined by the flag in dwDevInfoID.
dwSize
Size of the structure at pDevInfoStruct, in bytes.

Return Values

If the method succeeds, the return value is D3D_OK. This method returns S_FALSE on retail builds of DirectX.

If the method fails, the return value can be one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

This method makes it possible for drivers to declare specific information types, and corresponding structures, that are not documented in this SDK.

This method executes synchronously and can negatively impact your application's performance when it executes slowly. Do not call this method during scene rendering (between calls to IDirect3DDevice7::BeginScene and IDirect3DDevice7::EndScene).

This method is intended to be used for performance tracking and debugging during product development (on the debug version of DirectX). The method can succeed, returning S_FALSE, without retrieving device data. This occurs when the retail version of the DirectX runtime is installed on the host system.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

D3DDEVINFO_TEXTUREMANAGER


IDirect3DDevice7::GetLight

The IDirect3DDevice7::GetLight method retrieves a set of lighting properties that this device uses.

HRESULT GetLight(
  DWORD dwLightIndex,
  LPD3DLIGHT7 lpLight
);

Parameters

dwLightIndex
Zero-based index of the lighting property set to be retrieved.
lpLight
Address of a D3DLIGHT7 structure that is filled with the retrieved lighting-parameter set.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value is an error. The method returns DDERR_INVALIDPARAMS if the lpLight parameter is invalid.

Remarks

This method was introduced with the IDirect3DDevice7 interface.

Unlike its predecessors, the IDirect3DDevice7 interface does not use light objects. This method, and its use of the D3DLIGHT7 structure to describe a set of lighting properties, replaces the lighting semantics used by previous versions of the device interface.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::SetLight, IDirect3DDevice7::GetLightEnable, IDirect3DDevice7::LightEnable


IDirect3DDevice7::GetLightEnable

The IDirect3DDevice7::GetLightEnable method retrieves the activity status—enabled or disabled—for a set of lighting parameters within a device.

HRESULT GetLightEnable(
  DWORD dwLightIndex,
  BOOL* pbEnable
);

Parameters

dwLightIndex
Zero-based index of the set of lighting parameters that are the target of this method.
pbEnable
Address of a variable to be filled with the status of the specified lighting parameters. After the call, a nonzero value at this address indicates that the specified lighting parameters are enabled; a value of 0 indicates that they are disabled.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value is an error. For a complete list of Direct3D Immediate Mode error values and descriptions, see Return Values.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::GetLight, IDirect3DDevice7::LightEnable, IDirect3DDevice7::SetLight


IDirect3DDevice7::GetMaterial

The IDirect3DDevice7::GetMaterial method retrieves the current material properties for the device.

HRESULT GetMaterial(
  LPD3DMATERIAL7 lpMaterial
);

Parameters

lpMaterial
Address of a D3DMATERIAL7 structure to be filled with the currently set material properties.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value is an error. The method returns DDERR_INVALIDPARAMS if the lpMaterial parameter is invalid.

Remarks

This method was introduced with the IDirect3DDevice7 interface.

Unlike its predecessors, the IDirect3DDevice7 interface does not use material handles. This method, and its use of the D3DMATERIAL7 structure to describe material properties, replaces the material-handle semantics used by previous versions of the device interface.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::SetMaterial


IDirect3DDevice7::GetRenderState

The IDirect3DDevice7::GetRenderState method gets a single Direct3DDevice rendering-state parameter.

HRESULT GetRenderState(
  D3DRENDERSTATETYPE dwRenderStateType,
  LPDWORD lpdwRenderState
);

Parameters

dwRenderStateType
Device state variable that is being queried. This parameter can be any of the members of the D3DRENDERSTATETYPE enumerated type.
lpdwRenderState
Address of a variable that receives the Direct3DDevice render state when the method returns.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value is an error. The method returns DDERR_INVALIDPARAMS if one of the arguments is invalid.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::SetRenderState


IDirect3DDevice7::GetRenderTarget

The IDirect3DDevice7::GetRenderTarget method retrieves a pointer to the DirectDraw surface that is being used as a render target.

HRESULT GetRenderTarget(
  LPDIRECTDRAWSURFACE7 *lplpRenderTarget
);

Parameters

lplpRenderTarget
Address that receives a pointer to the IDirectDrawSurface7 interface of the render target surface for this device.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value is an error. The method returns DDERR_INVALIDPARAMS if one of the arguments is invalid.

Remarks

In the IDirect3DDevice3 interface, this method accepted a pointer to the legacy IDirectDrawSurface4 interface.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::SetRenderTarget


IDirect3DDevice7::GetStateData

The IDirect3DDevice7::GetStateData method is not implemented.

HRESULT GetStateData(
  DWORD dwState,
  LPVOID* lplpStateData
);

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.


IDirect3DDevice7::GetTexture

The IDirect3DDevice7::GetTexture method retrieves a texture assigned to a given stage for a device.

HRESULT GetTexture(
  DWORD dwStage,
  LPDIRECTDRAWSURFACE7 * lplpTexture
);

Parameters

dwStage
Stage identifier of the texture to be retrieved. Stage identifiers are zero-based. Currently, devices can have up to eight set textures, so the maximum allowable value allowed for dwStage is 7.
lplpTexture
Address of a variable to be filled with a pointer to the specified texture's IDirectDrawSurface7 interface if the call succeeds.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

In the legacy IDirect3DDevice3 interface, this method accepts a pointer to an IDirect3DTexture2 interface.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::SetTexture, IDirect3DDevice7::GetTextureStageState, IDirect3DDevice7::SetTextureStageState, Textures


IDirect3DDevice7::GetTextureStageState

The IDirect3DDevice7::GetTextureStageState method retrieves a state value for a currently assigned texture.

HRESULT GetTextureStageState(
  DWORD   dwStage,
  D3DTEXTURESTAGESTATETYPE dwState,
  LPDWORD lpdwValue
);

Parameters

dwStage
Stage identifier of the texture for which the state is retrieved. Stage identifiers are zero-based. Currently, devices can have up to eight set textures, so the maximum allowable value allowed for dwStage is 7.
dwState
Texture state to be retrieved. This parameter can be any member of the D3DTEXTURESTAGESTATETYPE enumerated type.
lpdwValue
Address of a variable to be filled with the retrieved state value. The meaning of the retrieved value is determined by the dwState parameter.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::SetTextureStageState, IDirect3DDevice7::GetTexture, IDirect3DDevice7::SetTexture, Textures


IDirect3DDevice7::GetTransform

The IDirect3DDevice7::GetTransform method gets a matrix describing a transformation state.

HRESULT GetTransform(
  D3DTRANSFORMSTATETYPE dtstTransformStateType,
  LPD3DMATRIX lpD3DMatrix
);

Parameters

dtstTransformStateType
Device state variable that is being modified. This parameter can be any of the members of the D3DTRANSFORMSTATETYPE enumerated type.
lpD3DMatrix
Address of a D3DMATRIX structure describing the transformation.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value is an error. The method returns DDERR_INVALIDPARAMS if one of the arguments is invalid.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::SetTransform


IDirect3DDevice7::GetViewport

The IDirect3DDevice7::GetViewport method retrieves the viewport parameters currently set for the device.

HRESULT GetViewport(
  LPD3DVIEWPORT7 lpViewport
);

Parameters

lpViewport
Address of a D3DVIEWPORT7 structure to be filled with the current viewport parameters if the call succeeds.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value is an error. The method returns DDERR_INVALIDPARAMS if the lpViewport parameter is invalid.

Remarks

This method was introduced with the IDirect3DDevice7 interface.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::SetViewport


IDirect3DDevice7::LightEnable

The IDirect3DDevice7::LightEnable method enables or disables a set of lighting parameters within a device.

HRESULT LightEnable(
  DWORD dwLightIndex,
  BOOL bEnable
);

Parameters

dwLightIndex
Zero-based index of the set of lighting parameters that are the target of this method.
bEnable
Value indicating if the set of lighting parameters are being enabled or disabled. Set this parameter to TRUE to enable lighting with the parameters at the specified index, or FALSE to disable it.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value is an error. For a complete list of Direct3D Immediate Mode error values and descriptions, see Return Values.

Remarks

If you supply a value for dwLightIndex outside the range of the light property sets currently assigned within the device, the LightEnable method creates a light source with the following properties and sets its enabled state to the value specified in bEnable:

Member | Default
dltType | D3DLIGHT_DIRECTIONAL
dcvDiffuse | (R:1, G:1, B:1, A:0)
dcvSpecular | (R:0, G:0, B:0, A:0)
dcvAmbient | (R:0, G:0, B:0, A:0)
dvPosition | (0, 0, 0)
dvDirection | (0, 0, 1)
dvRange | 0
dvFalloff | 0
dvAttenuation0 | 0
dvAttenuation1 | 0
dvAttenuation2 | 0
dvTheta | 0
dvPhi | 0

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::GetLight, IDirect3DDevice7::GetLightEnable, IDirect3DDevice7::SetLight, Lighting and Materials


IDirect3DDevice7::Load

The IDirect3DDevice7::Load method loads a rectangular area of a source texture to a specified point in a destination texture or to faces within a cubic environment map.

HRESULT Load(
  LPDIRECTDRAWSURACE7 lpDestTex,
  LPPOINT lpDestPoint,
  LPDIRECTDRAWSURACE7 lpSrcTex,
  LPRECT lprcSrcRect,
  DWORD dwFlags
);

Parameters

lpDestTex
Address of the IDirectDrawSurface7 interface of the texture that receives image data from the source texture. The destination texture can be a cubic environment map. For complex texture surfaces like cubic envionment maps and mipmaps, this must point to the top-level surface.
lpDestPoint
Address of a POINT structure that describes the point at which the method loads the image data onto the destination texture. Set this parameter to NULL when the destination point should be the origin of the destination texture.
lpSrcTex
Address of the IDirect3DTexture7 interface of the texture that contains the image data to be loaded. For complex texture surfaces like cubic envionment maps and mipmaps, this must point to the top-level surface.
lprcSrcRect
Address of a RECT structure that describes the area within the source texture that the method loads. Set this parameter to NULL when the source rectangle should cover the entire source texture.
dwFlags
Value indicating, in the case of a cubic environment map, which face of the destination texture is to receive the image data. This can be any combination of the following flags.
0
Required if the destination texture is a managed texture.
DDSCAPS2_CUBEMAP_ALLFACES
All faces should be loaded with the image data within the source texture.
DDSCAPS2_CUBEMAP_NEGATIVEX, DDSCAPS2_CUBEMAP_NEGATIVEY, or DDSCAPS2_CUBEMAP_NEGATIVEZ
The negative x, y, or z faces should receive the image data.
DDSCAPS2_CUBEMAP_POSITIVEX, DDSCAPS2_CUBEMAP_POSITIVEY, or DDSCAPS2_CUBEMAP_POSITIVEZ
The positive x, y, or z faces should receive the image data.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

The destination texture can be used with any rendering device, not just the one that created it. On hardware devices, the load operation is hardware-accelerated.

Loading textures into video memory by calling this method is preferred over blit operations.

This method copies all mip-levels, cubemap faces, palettes and color keys from the source texture to the destination texture.

When using this method to load mipmaps, the following special points apply:

  • The destination texture surface can be a subset of the mip-levels contained in the source texture. In this case, only the mip-levels common to both textures are copied. This is useful in implementing texture LOD. You can create a video memory texture with only two mip-levels, then use this method to copy those levels from a source texture that comprises the entire set of mip-levels.
  • The source and destination surface pointers must point to top-level surfaces.
  • When loading a subrectangle of a mipmap, the subrectangle refers to the top-level surface in the mipmap chain, and is divided by two for each lower mip-level.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.


IDirect3DDevice7::MultiplyTransform

The IDirect3DDevice7::MultiplyTransform method multiplies a device's world, view, or projection matrices by a specified matrix. The multiplication order is lpD3DMatrix times dtstTransformStateType.

HRESULT MultiplyTransform(
  D3DTRANSFORMSTATETYPE dtstTransformStateType,
  LPD3DMATRIX lpD3DMatrix
);

Parameters

dtstTransformStateType
A member of the D3DTRANSFORMSTATETYPE enumerated type that identifies which device matrix is to be modified. The most common setting, D3DTRANSFORMSTATE_WORLD, modifies the world matrix, but you can specify that the method modify the view or projection matrices, if needed.
lpD3DMatrix
Address of a D3DMATRIX structure that modifies the current transformation.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value is an error. The method returns DDERR_INVALIDPARAMS if one of the arguments is invalid.

Remarks

An application might use the MultiplyTransform method to work with hierarchies of transformations. For example, the geometry and transformations describing an arm might be arranged in the following hierarchy:

shoulder_transformation
    upper_arm geometry
    elbow transformation
        lower_arm geometry
        wrist transformation
            hand geometry

An application might use the following series of calls to render this hierarchy. (Not all the parameters are shown in this pseudocode.)

IDirect3DDevice7::SetTransform(D3DTRANSFORMSTATE_WORLD,
    shoulder_transform)
IDirect3DDevice7::DrawPrimitive(upper_arm)
IDirect3DDevice7::MultiplyTransform(D3DTRANSFORMSTATE_WORLD,
    elbow_transform)
IDirect3DDevice7::DrawPrimitive(lower_arm)
IDirect3DDevice7::MultiplyTransform(D3DTRANSFORMSTATE_WORLD,
    wrist_transform)
IDirect3DDevice7::DrawPrimitive(hand)

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::DrawPrimitive, IDirect3DDevice7::SetTransform


IDirect3DDevice7::PreLoad

The IDirect3DDevice7::Preload method instructs the Direct3D texture manager to load a managed texture into video memory.

HRESULT PreLoad(
  LPDIRECTDRAWSURFACE7 lpddsTexture
);

Parameters

lpddsTexture
Address of the IDirectDrawSurface7 interface for the texture surface to be loaded into memory.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

This method forces the system to load a managed texture into video memory. If sufficient video memory is not available, the system removes other textures to regain memory, then loads the texture. The texture being loaded must be a managed texture (created with the DDSCAPS2_TEXTUREMANAGE or DDSCAPS2_D3DTEXTUREMANAGE flags). If not, the method fails and returns DDERR_INVALIDPARAMS.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

Automatic Texture Management


IDirect3DDevice7::SetClipPlane

The IDirect3DDevice7::SetClipPlane method sets the coefficients of a user-defined clipping plane for the device.

HRESULT SetClipPlane(
  DWORD dwIndex,
  D3DVALUE* pPlaneEquation
);

Parameters

dwIndex
Index of the clipping plane for which the plane equation coefficients are to be set.
pPlaneEquation
Address of a four-element array of values that represent the coefficients of the clipping plane, in the form of the general plane equation. See remarks.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value is DDERR_INVALIDPARAMS. This error indicates that the value in dwIndex exceeds the maximum clipping plane index supported by the device or that the array at pPlaneEquation is not large enough to contain four floating-point values.

Remarks

The coefficients that this method sets take the form of the general plane equation. If the values in the array at pPlaneEquation were labeled A, B, C, and D in the order that they appear in the array, they would fit into the general plane equation so that Ax + By + Cz + D = 0. A point with homogeneous coordinates (x, y, z, w) is visible in the half space of the plane if Ax + By + Cz + Dw >= 0. Points that exist on or behind the clipping plane are clipped from the scene.

The plane equation used by this method exists in world space.

This method does not enable the clipping plane equation being set. To enable a clipping plane, set the corresponding bit in the DWORD value applied to the D3DRENDERSTATE_CLIPPLANEENABLE render state.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::GetClipPlane, D3DRENDERSTATE_CLIPPLANEENABLE, User-defined Clip Planes


IDirect3DDevice7::SetClipStatus

The IDirect3DDevice7::SetClipStatus method sets the current clip status.

HRESULT SetClipStatus(
  LPD3DCLIPSTATUS lpD3DClipStatus
);

Parameters

lpD3DClipStatus
Address of a D3DCLIPSTATUS structure that describes the new settings for the clip status.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value is an error. The method returns DDERR_INVALIDPARAMS if one of the arguments is invalid.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::GetClipStatus


IDirect3DDevice7::SetLight

The IDirect3DDevice7::SetLight method assigns a set of lighting properties for this device.

HRESULT SetLight(
  DWORD dwLightIndex,
  LPD3DLIGHT7 lpLight
);

Parameters

dwLightIndex
Zero-based index of the set of lighting properties to be set. If a set of lighting properties already exists at this index, it is overwritten by the new properties in lpLight.
lpLight
Address of a D3DLIGHT7 structure that contains the lighting-parameters to be set.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values:

DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY

Remarks

This method was introduced with the IDirect3DDevice7 interface.

Unlike its predecessors, the IDirect3DDevice7 interface does not use light objects. This method, and its use of the D3DLIGHT7 structure to describe a set of lighting properties, replaces the lighting semantics used by previous versions of the device interface.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::GetLight, IDirect3DDevice7::GetLightEnable, IDirect3DDevice7::LightEnable


IDirect3DDevice7::SetMaterial

The IDirect3DDevice7::SetMaterial method sets the material properties for the device.

HRESULT SetMaterial(
  LPD3DMATERIAL7 lpMaterial
);

Parameters

lpMaterial
Address of a D3DMATERIAL7 structure that describes the material properties to be set.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value is an error. The method returns DDERR_INVALIDPARAMS if the lpMaterial parameter is invalid.

Remarks

This method was introduced with the IDirect3DDevice7 interface.

Unlike its predecessors, the IDirect3DDevice7 interface does not use material handles. This method, and its use of the D3DMATERIAL7 structure to describe material properties, replaces the material-handle semantics used by previous versions of the device interface.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::GetMaterial


IDirect3DDevice7::SetRenderState

The IDirect3DDevice7::SetRenderState method sets a single Direct3DDevice render-state parameter.

HRESULT SetRenderState(
  D3DRENDERSTATETYPE dwRenderStateType,
  DWORD dwRenderState
);

Parameters

dwRenderStateType
Device state variable that is being modified. This parameter can be any of the members of the D3DRENDERSTATETYPE enumerated type.
dwRenderState
New value for the Direct3DDevice render state. The meaning of this parameter is dependent on the value specified for dwRenderStateType. For example, if dwRenderStateType were D3DRENDERSTATE_SHADEMODE, the second parameter would be one of the members of the D3DSHADEMODE enumerated type.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value is an error. The method returns DDERR_INVALIDPARAMS if one of the arguments is invalid.

Remarks

Applications should use the IDirect3DDevice7::SetTextureStageState method to set texture states, rather than the legacy texture-related render states.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::GetRenderState, IDirect3DDevice7::SetTransform, About Render States


IDirect3DDevice7::SetRenderTarget

The IDirect3DDevice7::SetRenderTarget method permits the application to easily route rendering output to a new DirectDraw surface as a render target.

HRESULT SetRenderTarget(
  LPDIRECTDRAWSURFACE7 lpNewRenderTarget,
  DWORD dwFlags
);

Parameters

lpNewRenderTarget
Address of a IDirectDrawSurface7 interface for the surface object that is the new rendering target. This surface must be created with the DDSCAPS_3DDEVICE capability.
dwFlags
Not currently used; set to 0.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value is an error. The error can be one of the following values:

DDERR_INVALIDPARAMS
DDERR_INVALIDSURFACETYPE

Remarks

Do not use this method to set a new render target surface with a depth buffer if the current render target does not have a depth buffer. Likewise, you cannot use this method to switch from a nondepth-buffered render target to a depth-buffered render target. Attempts to do this fail in debug builds and can exhibit unreliable behavior in retail builds. Since both the new and the old render targets use depth buffers, the depth buffer attached to the new render target replaces the previous depth buffer for the context.

Unlike this method's implementation in previous interfaces, IDirect3DDevice7::SetRenderTarget does not invalidate the current material or viewport for the device.

Capabilities do not change with changes in the properties of the render target surface. Both the Direct3D hardware abstraction layer (HAL) and the software rasterizers have only one opportunity to expose capabilities to the application. The system cannot expose different sets of capabilities, depending on the format of the destination surface.

If more than one depth buffer is attached to the render target, this function fails.

In the IDirect3DDevice3 interface, this method accepted a pointer to the legacy IDirectDrawSurface4 interface.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::GetRenderTarget


IDirect3DDevice7::SetStateData

The IDirect3DDevice7::SetStateData method is not implemented.

HRESULT SetStateData(
  DWORD dwState,
  LPVOID lpStateData
);

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.


IDirect3DDevice7::SetTexture

The IDirect3DDevice7::SetTexture method assigns a texture to a given stage for a device.

HRESULT SetTexture(
  DWORD dwStage,
  LPDIRECTDRAWSURFACE7 lpTexture
);

Parameters

dwStage
Stage identifier to which the texture is to be set. Stage identifiers are zero-based. Currently, devices can have up to eight set textures, so the maximum allowable value allowed for dwStage is 7.
lpTexture
Address of the IDirectDrawSurface7 interface for the texture being set. For complex textures, such as mipmaps and cubic environment maps, this parameter must point to the top-level surface.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

This method method increments the reference count of the texture surface being assigned. When the texture is no longer needed, you should set the texture at the appropriate stage to NULL. If you fail to do this, the surface will not be released, resulting in a memory leak.

Software devices do not support assigning a texture to more than one texture stage at a time.

In the legacy IDirect3DDevice3 interface, this method accepted a pointer to an IDirect3DTexture2 interface.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::GetTexture, IDirect3DDevice7::GetTextureStageState, IDirect3DDevice7::SetTextureStageState, Textures


IDirect3DDevice7::SetTextureStageState

The IDirect3DDevice7::SetTextureStageState method sets the state value for a currently assigned texture.

HRESULT SetTextureStageState(
  DWORD dwStage,
  D3DTEXTURESTAGESTATETYPE dwState,
  DWORD dwValue
);

Parameters

dwStage
Stage identifier of the texture for which the state value is to be set. Stage identifiers are zero-based. Currently, devices can have up to eight set textures, so the maximum allowable value allowed for dwStage is 7.
dwState
Texture state to be set. This parameter can be any member of the D3DTEXTURESTAGESTATETYPE enumerated type.
dwValue
State value to be set. The meaning of this value is determined by the dwState parameter.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

Applications should use this method to set texture states, rather than the legacy texture-related render states. For more information, see About Render States.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::GetTextureStageState, IDirect3DDevice7::GetTexture, IDirect3DDevice7::SetTexture, Textures


IDirect3DDevice7::SetTransform

The IDirect3DDevice7::SetTransform method sets a single Direct3DDevice transformation-related state.

HRESULT SetTransform(
  D3DTRANSFORMSTATETYPE dtstTransformStateType,
  LPD3DMATRIX lpD3DMatrix
);

Parameters

dtstTransformStateType
Device-state variable that is being modified. This parameter can be any of the members of the D3DTRANSFORMSTATETYPE enumerated type.
lpD3DMatrix
Address of a D3DMATRIX structure that modifies the current transformation.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value is an error. The method returns DDERR_INVALIDPARAMS if one of the arguments is invalid.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::GetTransform, IDirect3DDevice7::SetRenderState


IDirect3DDevice7::SetViewport

The IDirect3DDevice7::SetViewport method sets the viewport parameters for the device.

HRESULT SetViewport(
  LPD3DVIEWPORT7 lpViewport
);

Parameters

lpViewport
Address of a D3DVIEWPORT7 structure that contains the viewport parameters to be set.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value is an error. The method returns DDERR_INVALIDPARAMS if the lpViewport parameter is invalid.

Remarks

This method was introduced with the IDirect3DDevice7 interface.

If the viewport parameters described by the D3DVIEWPORT7 structure describe a region that cannot exist within the render target surface, the method fails, returning DDERR_INVALIDPARAMS.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::GetViewport


IDirect3DDevice7::ValidateDevice

The IDirect3DDevice7::ValidateDevice method reports the device's ability to render the currently set texture-blending operations and arguments in a single pass.

HRESULT ValidateDevice(
  LPDWORD lpdwPasses
);

Parameters

lpdwPasses
Address to be filled with the number of rendering passes to complete the desired effect through multipass rendering.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
D3DERR_CONFLICTINGTEXTUREFILTER
D3DERR_CONFLICTINGTEXTUREPALETTE
D3DERR_TOOMANYOPERATIONS
D3DERR_UNSUPPORTEDALPHAARG
D3DERR_UNSUPPORTEDALPHAOPERATION
D3DERR_UNSUPPORTEDCOLORARG
D3DERR_UNSUPPORTEDCOLOROPERATION
D3DERR_UNSUPPORTEDFACTORVALUE
D3DERR_UNSUPPORTEDTEXTUREFILTER
D3DERR_WRONGTEXTUREFORMAT

Remarks

Current hardware does not necessarily implement all possible combinations of operations and arguments. You can determine whether a particular blending operation can be performed with given arguments by setting up the desired blending operation, then calling the ValidateDevice method.

The ValidateDevice method uses the currently set render states, textures, and texture-stage states to perform validation at the time of the call. Any changes to these factors after the call invalidate the previous result, and the method must be called again before rendering a scene.

Using diffuse iterated values, either as an argument or as an operation (D3DTA_DIFFUSE or D3DTOP_BLENDDIFFUSEALPHA) is rarely supported on current hardware. Most hardware can only introduce iterated color data at the last texture operation stage.

Try to specify the texture (D3DTA_TEXTURE) for each stage as the first argument, rather than the second argument.

Many cards do not support use of diffuse or scalar values at arbitrary texture stages. Often, these are only available at the first or last texture-blending stage.

Many cards do not have a blending unit associated with the first texture that is capable of more than replicating alpha to color channels or inverting the input. Therefore, your application might need to use only the second texture stage, if possible. On such hardware, the first unit is presumed to be in its default state, which has the first color argument set to D3DTA_TEXTURE with the D3DTOP_SELECTARG1 operation.

Operations on the output alpha that are more intricate than, or substantially different from, the color operations are less likely to be supported.

Some hardware does not support simultaneous use of both D3DTA_TFACTOR and D3DTA_DIFFUSE.

Many cards do not support simultaneous use of multiple textures and mipmapped trilinear filtering. If trilinear filtering has been requested for a texture involved in multitexture blending operations and validation fails, turn off trilinear filtering, and revalidate. In this case, you might want to perform multipass rendering instead.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DDevice7::GetTextureStageState, IDirect3DDevice7::SetTextureStageState


IDirect3DVertexBuffer7

Applications use the methods of the IDirect3DVertexBuffer7 interface to manipulate a collection of vertices for use with the IDirect3DDevice7::DrawPrimitiveVB and IDirect3DDevice7::DrawIndexedPrimitiveVB rendering methods. This section is a reference to the methods of this interface. For a conceptual overview, see Vertex Buffers.

The methods of the IDirect3DVertexBuffer interface can be organized into the following groups:

Information | GetVertexBufferDesc
Vertex data | Lock
 | Optimize
 | ProcessVertices
 | ProcessVerticesStrided
 | Unlock

The IDirect3DVertexBuffer7 interface extends the IDirect3DVertexBuffer interface by adding the IDirect3DVertexBuffer7::ProcessVerticesStrided method, which supports the strided vertex format.

The IDirect3DVertexBuffer7 interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECT3DVERTEXBUFFER7 and LPDIRECT3DVERTEXBUFFER data types are defined as pointers to the IDirect3DVertexBuffer7 and IDirect3DVertexBuffer interfaces:

typedef struct IDirect3DVertexBuffer *LPDIRECT3DVERTEXBUFFER;
typedef struct IDirect3DVertexBuffer7 *LPDIRECT3DVERTEXBUFFER7;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

Vertex Buffers


IDirect3DVertexBuffer7::GetVertexBufferDesc

The IDirect3DVertexBuffer7::GetVertexBufferDesc method retrieves a description of the vertex buffer.

HRESULT GetVertexBufferDesc(
  LPD3DVERTEXBUFFERDESC lpVBDesc
);

Parameters

lpVBDesc
Address of a D3DVERTEXBUFFERDESC structure to be filled with a description of the vertex buffer.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be DDERR_INVALIDPARAMS or another error value.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.


IDirect3DVertexBuffer7::Lock

The IDirect3DVertexBuffer::Lock methods locks a vertex buffer and obtains a pointer to the vertex buffer memory.

HRESULT Lock(
  DWORD   dwFlags,
  LPVOID* lplpData,
  LPDWORD lpdwSize
);

Parameters

dwFlags
Flags indicating how the vertex buffer memory should be locked.
DDLOCK_EVENT
Not currently implemented.
DDLOCK_NOSYSLOCK
If possible, do not take the Win16Mutex (also known as Win16Lock).
DDLOCK_READONLY
Indicates that the memory being locked is only to be read from.
DDLOCK_SURFACEMEMORYPTR
Indicates that a valid memory pointer to the vertex buffer is returned; this is the default.
DDLOCK_WAIT
If a lock cannot be obtained immediately, the method retries until a lock is obtained or another error occurs.
DDLOCK_WRITEONLY
Indicates that the memory being locked is only to be written to.
DDLOCK_DISCARDCONTENTS
New for DirectX 7.0. Used only with Direct3D vertex-buffer locks. Indicates that no assumptions are made about the contents of the vertex buffer during this lock. This enables Direct3D or the driver to provide an alternative memory area as the vertex buffer. This is useful when you plan to clear the contents of the vertex buffer and fill in new data.
DDLOCK_NOOVERWRITE
New for DirectX 7.0. Used only with Direct3D vertex-buffer locks. Indicates that no vertices that were referred to in vertex-buffer DrawPrimitive calls since the start of the frame (or the last lock without this flag) are modified during the lock. This can be useful when you want only to append data to the vertex buffer.
lplpData
Address of a variable that receives the address of the vertex buffer memory if the call succeeds.
lpdwSize
Address of a variable that receives the size of the vertex buffer memory at lplpData. Set to NULL if the buffer size is not needed.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values:

D3DERR_VERTEXBUFFEROPTIMIZED
DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY
DDERR_SURFACEBUSY
DDERR_SURFACELOST

Remarks

After locking the vertex buffer, you can access the memory until a corresponding call to IDirect3DVertexBuffer7::Unlock.

You cannot render from a locked vertex buffer; calls to the IDirect3DDevice7::DrawIndexedPrimitiveVB or IDirect3DDevice7::DrawPrimitiveVB method using a locked buffer fail, returning D3DERR_VERTEXBUFFERLOCKED.

This method often causes the system to hold the Win16Mutex until you call the IDirect3DVertexBuffer7::Unlock method. GUI debuggers cannot operate while the Win16Mutex is held.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DVertexBuffer7::Unlock, Accessing the Contents of a Vertex Buffer


IDirect3DVertexBuffer7::Optimize

The IDirect3DVertexBuffer7::Optimize method converts an unoptimized vertex buffer into an optimized vertex buffer.

HRESULT Optimize(
  LPDIRECT3DDEVICE7 lpD3DDevice,
  DWORD dwFlags
);

Parameters

lpD3DDevice
Address of the IDirect3DDevice7 interface of the device for which this vertex buffer is to be optimized.
dwFlags
Not currently used; set to 0.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values:

D3DERR_VERTEXBUFFEROPTIMIZED
D3DERR_VERTEXBUFFERLOCKED
DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY

Remarks

In the legacy IDirect3DVertexBuffer interface, this method accepted a pointer to the IDirect3DDevice3 interface.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

Optimizing a Vertex Buffer, Vertex Buffers


IDirect3DVertexBuffer7::ProcessVertices

The IDirect3DVertexBuffer::ProcessVertices method processes untransformed vertices into a transformed or optimized vertex buffer.

HRESULT ProcessVertices(
  DWORD dwVertexOp,
  DWORD dwDestIndex,
  DWORD dwCount,
  LPDIRECT3DVERTEXBUFFER7 lpSrcBuffer,
  DWORD dwSrcIndex,
  LPDIRECT3DDEVICE7       lpD3DDevice,
  DWORD dwFlags
);

Parameters

dwVertexOp
Flags defining how the method processes the vertices as they are transferred from the source buffer. You can specify any combination of the following flags:
D3DVOP_CLIP
Transform the vertices, and clip any vertices that exist outside the viewing frustum. This flag cannot be used with vertex buffers that do not contain clipping information (for example, those created with the D3DVBCAPS_DONOTCLIP flag).
D3DVOP_EXTENTS
Transform the vertices, then update the extents of the screen rectangle when the vertices are rendered. Using this flag can potentially help performance, but the extents returned by IDirect3DDevice7::GetClipStatus are not updated to account for the vertices when they are rendered.
D3DVOP_LIGHT
Light the vertices.
D3DVOP_TRANSFORM
Transform the vertices, using the world, view, and projection matrices. This flag must always be set.
dwDestIndex
Index into the destination vertex buffer (this buffer) where the vertices are placed after processing.
dwCount
Number of vertices in the source buffer to process.
lpSrcBuffer
Address of the IDirect3DVertexBuffer7 interface for the source vertex buffer.
dwSrcIndex
Index of the first vertex in the source buffer to be processed.
lpD3DDevice
Address of the IDirect3DDevice7 interface for the device to be used to transform the vertices.
dwFlags
Processing options. Set this parameter to 0 for default processing. Set to D3DPV_DONOTCOPYDATA to prevent the system from copying vertex data not affected by the current vertex operation into the destination buffer. For more information, see Processing Vertices.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values:

D3DERR_INVALIDVERTEXFORMAT
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY
DDERR_SURFACEBUSY
DDERR_SURFACELOST

Remarks

Always include the D3DVOP_TRANSFORMED flag in the dwVertexOp parameter. If you do not, the method fails, returning DDERR_INVALIDPARAMS.

In the legacy IDirect3DVertexBuffer interface, this method accepted pointers to the IDirect3DDevice3 and IDirect3DVertexBuffer interfaces.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

Processing Vertices, Vertex Buffers


IDirect3DVertexBuffer7::ProcessVerticesStrided

The IDirect3DVertexBuffer::ProcessVerticesStrided method processes untransformed strided vertices into a transformed or optimized vertex buffer.

HRESULT ProcessVerticesStrided(
  DWORD dwVertexOp,
  DWORD dwDestIndex,
  DWORD dwCount,
  LPD3DDRAWPRIMITIVESTRIDEDDATA lpVertexArray,
  DWORD dwSrcIndex,
  LPDIRECT3DDEVICE7 lpD3DDevice,
  DWORD dwFlags
);

Parameters

dwVertexOp
Flags defining how the method processes the vertices as they are transferred from the source buffer. You can specify any combination of the following flags:
D3DVOP_CLIP
Transform the vertices, and clip any vertices that exist outside the viewing frustum. This flag cannot be used with vertex buffers that do not contain clipping information (for example, those created with the D3DVBCAPS_DONOTCLIP flag).
D3DVOP_EXTENTS
Transform the vertices, then update the extents of the screen rectangle when the vertices are rendered. Using this flag can potentially help performance, but the extents returned by IDirect3DDevice7::GetClipStatus are not updated to account for the vertices when they are rendered.
D3DVOP_LIGHT
Light the vertices.
D3DVOP_TRANSFORM
Transform the vertices, using the world, view, and projection matrices. This flag must always be set.
dwDestIndex
Index into the destination vertex buffer (this buffer) where the vertices are placed after processing.
dwCount
Number of vertices in the source buffer to process.
lpVertexArray
Array of D3DDRAWPRIMITIVESTRIDEDDATA structures that contains the vertices for this primitive.
dwSrcIndex
Index of the first vertex in the source buffer to be processed.
lpD3DDevice
Address of the IDirect3DDevice7 interface for the device to be used to transform the vertices.
dwFlags
Processing options. Set this parameter to 0 for default processing. Set to D3DPV_DONOTCOPYDATA to prevent the system from copying vertex data not affected by the current vertex operation into the destination buffer. For more information, see Processing Vertices.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values:

D3DERR_INVALIDVERTEXFORMAT
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY
DDERR_SURFACEBUSY
DDERR_SURFACELOST

Remarks

Always include the D3DVOP_TRANSFORMED flag in the dwVertexOp parameter. If you do not, the method fails, returning DDERR_INVALIDPARAMS.

This method was introduced with the IDirect3DVertexBuffer7 interface.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DVertexBuffer7::ProcessVertices, Processing Vertices, Vertex Buffers


IDirect3DVertexBuffer7::Unlock

The IDirect3DVertexBuffer7::Unlock method unlocks a previously locked vertex buffer.

HRESULT Unlock();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values:

D3DERR_VERTEXBUFFERUNLOCKFAILED
DDERR_GENERIC
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_SURFACEBUSY
DDERR_SURFACELOST

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3d.h.

See Also

IDirect3DVertexBuffer7::Lock, Accessing the Contents of a Vertex Buffer


Unimplemented Methods

The following methods were present in previous versions of DirectX, but are not implemented in the most recent versions of their interfaces. In some cases, entire interfaces were rendered obsolete. These interfaces are documented in previous versions of DirectX.

Former stub methods. These methods were never implemented and are not supported in any interface.
IDirect3D::Initialize

IDirect3DMaterial::Initialize

IDirect3DMaterial::Reserve

IDirect3DMaterial::Unreserve

IDirect3DTexture::Initialize

IDirect3DTexture::Unload

Obsolete methods. These methods are not supported in the most recent versions of their interfaces.
IDirect3D3::CreateLight

IDirect3D3::CreateMaterial

IDirect3D3::CreateViewport

IDirect3DDevice3::GetStats

IDirect3DDevice3::GetLightState

IDirect3DDevice3::SetLightState

Superseded viewport methods. The following methods are superseded by the IDirect3DDevice7::GetViewport and IDirect3DDevice7::SetViewport methods.
IDirect3DDevice3::AddViewport

IDirect3DDevice3::DeleteViewport

IDirect3DDevice3::GetCurrentViewport

IDirect3DDevice3::NextViewport

IDirect3DDevice3::SetCurrentViewport

Obsolete single-vertex rendering methods. The following methods are not supported in the IDirect3DDevice7 interface.
IDirect3DDevice3::Begin

IDirect3DDevice3::BeginIndexed

IDirect3DDevice3::End

IDirect3DDevice3::Index

IDirect3DDevice3::Vertex


Obsolete Interfaces

The IDirect3DDevice and IDirect3DExecuteBuffer interfaces that support rendering with execute buffers are obsolete. For information about these interfaces, see the documentation provided with a previous release of DirectX. Legacy documentation is provided with this SDK and available for download from http://www.microsoft.com/directx.

The IDirect3DLight, IDirect3DMaterial3 and IDirect3DViewport3 interfaces are not supported by interfaces more recent than the IDirect3DDevice3 interface. The functionality offered by the superseded interfaces is now offered within the device interface itself (IDirect3DDevice7).

The IDirect3DLight interface is obsolete. The functionality provided by the interface is now present within the IDirect3DDevice7 interface. To summarize the relationship between the two interfaces:

IDirect3DLight::GetLight and IDirect3DLight::GetLight
Superseded by the IDirect3DDevice7::GetLight and IDirect3DDevice7::SetLight methods.
IDirect3DLight::Initialize
Not supported.

The following are the methods of the obsolete IDirect3DMaterial3 interface. Where appropriate, correlations have been drawn to methods of the IDirect3DDevice7 interface.

IDirect3DMaterial3::GetHandle
Not supported. Material handles are not used by the IDirect3DDevice7 interface.
IDirect3DMaterial3::GetMaterial and IDirect3DMaterial3::SetMaterial
Superseded by the IDirect3DDevice7::GetMaterial and IDirect3DDevice7::SetMaterial methods.

The following list contains methods from the obsolete IDirect3DViewport3 interface. Similar to the material-related methods in the preceding list, equivalent methods within IDirect3DDevice7 are noted.

IDirect3DViewport3::GetBackground and IDirect3DViewport3::SetBackground
Not supported. Background materials are not used by the IDirect3DDevice7 interface.
IDirect3DViewport3::GetBackgroundDepth, IDirect3DViewport3::GetBackgroundDepth2, IDirect3DViewport3::SetBackgroundDepth, and IDirect3DViewport3::SetBackgroundDepth2
Not supported.
IDirect3DViewport3::AddLight, IDirect3DViewport3::NextLight, and IDirect3DViewport3::DeleteLight
Parameters for individual lights are accessed through the IDirect3DDevice7::GetLight and IDirect3DDevice7::SetLight methods. Lights are individually enabled and disabled through the IDirect3DDevice7::GetLightEnable and IDirect3DDevice7::LightEnable methods.
IDirect3DViewport3::LightElements
Not supported.
IDirect3DViewport3::Clear and IDirect3DViewport3::Clear2
Superseded by the IDirect3DDevice7::Clear method.
IDirect3DViewport3::GetViewport, IDirect3DViewport3::GetViewport2, IDirect3DViewport3::SetViewport, and IDirect3DViewport3::SetViewport2
Superseded by the IDirect3DDevice7::GetViewport and IDirect3DDevice7::SetViewport methods.
IDirect3DViewport3::Initialize
Not supported.
IDirect3DViewport3::TransformVertices
Not supported. Use vertex buffers to manually transform vertices.


D3D_OVERLOADS

C++ programmers who define D3D_OVERLOADS can use the extensions documented here to simplify their code in Direct3D Immediate Mode applications. The use of D3D_OVERLOADS was introduced with Microsoft® DirectX® 5.0. This section is a reference to the D3D_OVERLOADS extensions.

These extensions must be defined with C++ linkage. If D3D_OVERLOADS is defined and the inclusion of D3dtypes.h or D3d.h is surrounded by extern "C", link errors result. For example, the following syntax would generate link errors because of C linkage of D3D_OVERLOADS functionality:

#define D3D_OVERLOADS
extern "C" {
#include <d3d.h>
};

The D3D_OVERLOADS extensions can be organized into the following groups:

Constructors | D3DLVERTEX
 | D3DTLVERTEX
 | D3DVECTOR
 | D3DVERTEX
Operators | Access Grant Operators
 | Addition Operator
 | Assignment Operators
 | Bitwise Equality Operator
 | D3DMATRIX
 | Division Operator
 | Multiplication Operator
 | Subtraction Operator
 | Unary Operators
 | Vector Dominance Operators
Helper functions | CrossProduct
 | DotProduct
 | Magnitude
 | Max
 | Maximize
 | Min
 | Minimize
 | Normalize
 | SquareMagnitude


D3D_OVERLOADS Constructors

This section contains reference information for the constructors provided by the D3D_OVERLOADS C++ extensions.

  • D3DLVERTEX
  • D3DTLVERTEX
  • D3DVECTOR
  • D3DVERTEX

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 5.0 or later.
Header: Declared in d3d.h.


D3DLVERTEX Constructors

The D3D_OVERLOADS constructors for the D3DLVERTEX structure offer a convenient way for C++ programmers to create lit vertices.

_D3DLVERTEX() { }
_D3DLVERTEX(const D3DVECTOR& v,
            D3DCOLOR _color, D3DCOLOR _specular,
            float _tu, float _tv)
    { x = v.x; y = v.y; z = v.z; dwReserved = 0;
      color = _color; specular = _specular;
      tu = _tu; tv = _tv;
    }

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 5.0 or later.
Header: Declared in d3d.h.


D3DTLVERTEX Constructors

The D3D_OVERLOADS constructors for the D3DTLVERTEX structure offer a convenient way for C++ programmers to create transformed and lit vertices.

_D3DTLVERTEX() { }
_D3DTLVERTEX(const D3DVECTOR& v, float _rhw,
             D3DCOLOR _color, D3DCOLOR _specular,
             float _tu, float _tv)
    { sx = v.x; sy = v.y; sz = v.z; rhw = _rhw;
      color = _color; specular = _specular;
      tu = _tu; tv = _tv;
    }

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 5.0 or later.
Header: Declared in d3d.h.


D3DVECTOR Constructors

The D3D_OVERLOADS constructors for the D3DVECTOR structure offer a convenient way for C++ programmers to create vectors.

_D3DVECTOR() { }
_D3DVECTOR(D3DVALUE f);
_D3DVECTOR(D3DVALUE _x, D3DVALUE _y, D3DVALUE _z);
_D3DVECTOR(const D3DVALUE f[3]);

These constructors are defined as follows:

inline _D3DVECTOR::_D3DVECTOR(D3DVALUE f)
    {    x = y = z = f; }

inline _D3DVECTOR::_D3DVECTOR(D3DVALUE _x, D3DVALUE _y, D3DVALUE _z)
    {     x = _x; y = _y; z = _z; }

inline _D3DVECTOR::_D3DVECTOR(const D3DVALUE f[3])
    {     x = f[0]; y = f[1]; z = f[2]; }

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 5.0 or later.
Header: Declared in d3d.h.


D3DVERTEX Constructors

The D3D_OVERLOADS constructors for the D3DVERTEX structure offer a convenient way for C++ programmers to create lit vertices.

_D3DVERTEX() { }
_D3DVERTEX(const D3DVECTOR& v, const D3DVECTOR& n, float _tu, float _tv)
    { x = v.x; y = v.y; z = v.z;
      nx = n.x; ny = n.y; nz = n.z;
      tu = _tu; tv = _tv;
    }

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 5.0 or later.
Header: Declared in d3d.h.


D3D_OVERLOADS Operators

This section contains reference information for the operators provided by the D3D_OVERLOADS C++ extensions.

  • Access Grant Operators
  • Addition Operator
  • Assignment Operators
  • Bitwise Equality Operator
  • D3DMATRIX
  • Division Operator
  • Multiplication Operator
  • Subtraction Operator
  • Unary Operators
  • Vector Dominance Operators

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 5.0 or later.
Header: Declared in d3d.h.


Access Grant Operators (D3D_OVERLOADS)

The bracket ("[ ]") operators are overloaded operators for the D3D_OVERLOADS extensions. You can use empty brackets ("[ ]") for access grants, "v[0]" to access the x component of a vector, "v[1]" to access the y component, and "v[2]" to access the z component. These operators are defined as follows:

const D3DVALUE&operator[ ](int i) const;
D3DVALUE&operator[ ](int i);

inline const D3DVALUE&
_D3DVECTOR::operator[ ](int i) const
{
    return (&x)[i];
}

inline D3DVALUE&
_D3DVECTOR::operator[ ](int i)
{
    return (&x)[i];
}

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 5.0 or later.
Header: Declared in d3d.h.


Addition Operator (D3D_OVERLOADS)

This binary operator is an overloaded operator for the D3D_OVERLOADS extensions. The addition operator is defined as follows:

_D3DVECTOR operator + (const _D3DVECTOR& v1, const _D3DVECTOR& v2);

inline _D3DVECTOR
operator + (const _D3DVECTOR& v1, const _D3DVECTOR& v2)
{
   return _D3DVECTOR(v1.x+v2.x, v1.y+v2.y, v1.z+v2.z);
}

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 5.0 or later.
Header: Declared in d3d.h.


Assignment Operators (D3D_OVERLOADS)

The assignment operators are overloaded operators for the D3D_OVERLOADS extensions. Both scalar and vector forms of the "*=" and "/=" operators are implemented. (In the vector form, multiplication and division are memberwise.)

_D3DVECTOR& operator += (const _D3DVECTOR& v);
_D3DVECTOR& operator -= (const _D3DVECTOR& v);
_D3DVECTOR& operator *= (const _D3DVECTOR& v);
_D3DVECTOR& operator /= (const _D3DVECTOR& v);
_D3DVECTOR& operator *= (D3DVALUE s);
_D3DVECTOR& operator /= (D3DVALUE s);

The assignment operators are defined as follows:

inline _D3DVECTOR&
_D3DVECTOR::operator += (const _D3DVECTOR& v)
{
   x += v.x;   y += v.y;   z += v.z;
   return *this;
}

inline _D3DVECTOR&
_D3DVECTOR::operator -= (const _D3DVECTOR& v)
{
   x -= v.x;   y -= v.y;   z -= v.z;
   return *this;
}

inline _D3DVECTOR&
_D3DVECTOR::operator *= (const _D3DVECTOR& v)
{
   x *= v.x;   y *= v.y;   z *= v.z;
   return *this;
}

inline _D3DVECTOR&
_D3DVECTOR::operator /= (const _D3DVECTOR& v)
{
   x /= v.x;   y /= v.y;   z /= v.z;
   return *this;
}

inline _D3DVECTOR&
_D3DVECTOR::operator *= (D3DVALUE s)
{
   x *= s;   y *= s;   z *= s;
   return *this;
}

inline _D3DVECTOR&
_D3DVECTOR::operator /= (D3DVALUE s)
{
   x /= s;   y /= s;   z /= s;
   return *this;
}

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 5.0 or later.
Header: Declared in d3d.h.


Bitwise Equality Operator (D3D_OVERLOADS)

This binary operator is an overloaded operator for the D3D_OVERLOADS extensions. The bitwise equality operator is defined as follows:

int operator == (const _D3DVECTOR& v1, const _D3DVECTOR& v2);

inline int
operator == (const _D3DVECTOR& v1, const _D3DVECTOR& v2)
{
   return v1.x==v2.x && v1.y==v2.y && v1.z == v2.z;
}

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 5.0 or later.
Header: Declared in d3d.h.


D3DMATRIX (D3D_OVERLOADS)

The D3D_OVERLOADS implementation of the D3DMATRIX structure implements a parentheses ("()") operator. This operator offers convenient access to values in the matrix for C++ programmers. Instead of having to refer to the structure members by name, C++ programmers can refer to them by row and column number and index these numbers, as needed.

typedef struct _D3DMATRIX {
#if (defined __cplusplus) && (defined D3D_OVERLOADS)
    union {
        struct {
#endif

            D3DVALUE        _11, _12, _13, _14;
            D3DVALUE        _21, _22, _23, _24;
            D3DVALUE        _31, _32, _33, _34;
            D3DVALUE        _41, _42, _43, _44;

#if (defined __cplusplus) && (defined D3D_OVERLOADS)
        };
        D3DVALUE m[4][4];
    };
    _D3DMATRIX() { }

    D3DVALUE& operator()(int iRow, int iColumn) { return m[iRow][iColumn]; }
    const D3DVALUE& operator()(int iRow, int iColumn) const { return m[iRow][iColumn]; }
#endif
} D3DMATRIX, *LPD3DMATRIX;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 5.0 or later.
Header: Declared in d3d.h.

See Also

D3DMATRIX


Division Operator (D3D_OVERLOADS)

This binary operator is an overloaded operator for the D3D_OVERLOADS extensions. Both scalar and vector forms of this operator are implemented. The division operator is defined as follows:

_D3DVECTOR operator / (const _D3DVECTOR& v, D3DVALUE s);
_D3DVECTOR operator / (const _D3DVECTOR& v1, const _D3DVECTOR& v2);

inline _D3DVECTOR
operator / (const _D3DVECTOR& v1, const _D3DVECTOR& v2)
{
   return _D3DVECTOR(v1.x/v2.x, v1.y/v2.y, v1.z/v2.z);
}

inline _D3DVECTOR
operator / (const _D3DVECTOR& v, D3DVALUE s)
{
   return _D3DVECTOR(v.x/s, v.y/s, v.z/s);
}

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 5.0 or later.
Header: Declared in d3d.h.


Multiplication Operator (D3D_OVERLOADS)

This binary operator is an overloaded operator for the D3D_OVERLOADS extensions. Both scalar and vector forms of this operator are implemented. The multiplication operator is defined as follows:

_D3DVECTOR operator * (const _D3DVECTOR& v, D3DVALUE s);
_D3DVECTOR operator * (D3DVALUE s, const _D3DVECTOR& v);
_D3DVECTOR operator * (const _D3DVECTOR& v1, const _D3DVECTOR& v2);

inline _D3DVECTOR
operator * (const _D3DVECTOR& v1, const _D3DVECTOR& v2)
{
   return _D3DVECTOR(v1.x*v2.x, v1.y*v2.y, v1.z*v2.z);
}

inline _D3DVECTOR
operator * (const _D3DVECTOR& v, D3DVALUE s)
{
   return _D3DVECTOR(s*v.x, s*v.y, s*v.z);
}

inline _D3DVECTOR
operator * (D3DVALUE s, const _D3DVECTOR& v)
{
   return _D3DVECTOR(s*v.x, s*v.y, s*v.z);
}

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 5.0 or later.
Header: Declared in d3d.h.


Subtraction Operator (D3D_OVERLOADS)

This binary operator is an overloaded operator for the D3D_OVERLOADS extensions. The subtraction operator is defined as follows:

_D3DVECTOR operator - (const _D3DVECTOR& v1, const _D3DVECTOR& v2);

inline _D3DVECTOR
operator - (const _D3DVECTOR& v1, const _D3DVECTOR& v2)
{
   return _D3DVECTOR(v1.x-v2.x, v1.y-v2.y, v1.z-v2.z);
}

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 5.0 or later.
Header: Declared in d3dtypes.h.


Unary Operators (D3D_OVERLOADS)

The unary operators are overloaded operators for the D3D_OVERLOADS extensions. The unary operators are defined as follows:

_D3DVECTOR operator + (const _D3DVECTOR& v);
_D3DVECTOR operator - (const _D3DVECTOR& v);

inline _D3DVECTOR
operator + (const _D3DVECTOR& v)
{
   return v;
}

inline _D3DVECTOR
operator - (const _D3DVECTOR& v)
{
   return _D3DVECTOR(-v.x, -v.y, -v.z);
}

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 5.0 or later.
Header: Declared in d3dtypes.h.


Vector Dominance Operators (D3D_OVERLOADS)

These binary operators are overloaded operators for the D3D_OVERLOADS extensions. Vector v1 dominates vector v2 if any component of v1 is greater than the corresponding component of v2. Therefore, it is possible for neither of the two specified vectors to dominate the other.

int operator < (const _D3DVECTOR& v1, const _D3DVECTOR& v2);
int operator <= (const _D3DVECTOR& v1, const _D3DVECTOR& v2);

The vector-dominance operators are defined as follows:

inline int
operator < (const _D3DVECTOR& v1, const _D3DVECTOR& v2)
{
   return v1[0] < v2[0] && v1[1] < v2[1] && v1[2] < v2[2];
}

inline int
operator <= (const _D3DVECTOR& v1, const _D3DVECTOR& v2)
{
   return v1[0] <= v2[0] && v1[1] <= v2[1] && v1[2] <= v2[2];
}

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 5.0 or later.
Header: Declared in d3dtypes.h.


D3D_OVERLOADS Helper Functions

This section contains reference information for the helper functions provided by the D3D_OVERLOADS C++ extensions.

  • CrossProduct
  • DotProduct
  • Magnitude
  • Max
  • Maximize
  • Min
  • Minimize
  • Normalize
  • SquareMagnitude

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 5.0 or later.
Header: Declared in d3dtypes.h.


CrossProduct

This helper function returns the cross product of the specified vectors. CrossProduct is part of the suite of extra functionality that is available to C++ programmers who define D3D_OVERLOADS.

_D3DVECTOR CrossProduct (const _D3DVECTOR& v1, const _D3DVECTOR& v2);

This function is defined as follows:

inline _D3DVECTOR
CrossProduct (const _D3DVECTOR& v1, const _D3DVECTOR& v2)
{
    _D3DVECTOR result;

    result[0] = v1[1] * v2[2] - v1[2] * v2[1];
    result[1] = v1[2] * v2[0] - v1[0] * v2[2];
    result[2] = v1[0] * v2[1] - v1[1] * v2[0];

    return result;
}

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 5.0 or later.
Header: Declared in d3d.h.

See Also

DotProduct


DotProduct

This helper function returns the dot product of the specified vectors. DotProduct is part of the suite of extra functionality that is available to C++ programmers who define D3D_OVERLOADS.

D3DVALUE DotProduct (const _D3DVECTOR& v1, const _D3DVECTOR& v2);

This function is defined as follows:

inline D3DVALUE
DotProduct (const _D3DVECTOR& v1, const _D3DVECTOR& v2)
{
   return v1.x*v2.x + v1.y * v2.y + v1.z*v2.z;
}

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 5.0 or later.
Header: Declared in d3d.h.

See Also

CrossProduct


Magnitude

This helper function returns the absolute value of the specified vector. Magnitude is part of the suite of extra functionality that is available to C++ programmers who define D3D_OVERLOADS.

D3DVALUE Magnitude (const _D3DVECTOR& v);

This function is defined as follows:

inline D3DVALUE
Magnitude (const _D3DVECTOR& v)
{
   return (D3DVALUE) sqrt(SquareMagnitude(v));
}

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 5.0 or later.
Header: Declared in d3d.h.

See Also

SquareMagnitude


Max

This helper function returns the maximum component of the specified vector. Max is part of the suite of extra functionality that is available to C++ programmers who define D3D_OVERLOADS.

D3DVALUE Max (const _D3DVECTOR& v);

This function is defined as follows:

inline D3DVALUE
Max (const _D3DVECTOR& v)
{
   D3DVALUE ret = v.x;
   if (ret < v.y) ret = v.y;
   if (ret < v.z) ret = v.z;
   return ret;
}

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 5.0 or later.
Header: Declared in d3d.h.

See Also

Min


Maximize

This helper function returns a vector made up of the largest components of the two specified vectors. Maximize is part of the suite of extra functionality that is available to C++ programmers who define D3D_OVERLOADS.

_D3DVECTOR Maximize (const _D3DVECTOR& v1, const _D3DVECTOR& v2);

This function is defined as follows:

inline _D3DVECTOR
Maximize (const _D3DVECTOR& v1, const _D3DVECTOR& v2)
{
   return _D3DVECTOR( v1[0] > v2[0] ? v1[0] : v2[0],
                      v1[1] > v2[1] ? v1[1] : v2[1],
                      v1[2] > v2[2] ? v1[2] : v2[2]);
}

Remarks

You could use the Maximize and Minimize functions to compute the bounding box for a set of points, in a function that looks like this:

    void
    ComputeBoundingBox(const D3DVECTOR *pts, int N, D3DVECTOR *min, D3DVECTOR *max)
    {
        int i;
        *min = *max = pts[0];
        for (i = 1; i < N; i += 1)
        {
            *min = Minimize(*min, pts[i]);
            *max = Maximize(*max, pts[i]);
        }
    }

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 5.0 or later.
Header: Declared in d3d.h.

See Also

Minimize


Min

This helper function returns the minimum component of the specified vector. Min is part of the suite of extra functionality that is available to C++ programmers who define D3D_OVERLOADS.

D3DVALUE Min (const _D3DVECTOR& v);

This function is defined as follows:

inline D3DVALUE
Min (const _D3DVECTOR& v)
{
   D3DVALUE ret = v.x;
   if (v.y < ret) ret = v.y;
   if (v.z < ret) ret = v.z;
   return ret;
}

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 5.0 or later.
Header: Declared in d3d.h.

See Also

Max


Minimize

This helper function returns a vector that is made up of the smallest components of the two specified vectors. Minimize is part of the suite of extra functionality that is available to C++ programmers who define D3D_OVERLOADS.

_D3DVECTOR Minimize (const _D3DVECTOR& v1, const _D3DVECTOR& v2);

This function is defined as follows:

inline _D3DVECTOR
Minimize (const _D3DVECTOR& v1, const _D3DVECTOR& v2)
{
   return _D3DVECTOR( v1[0] < v2[0] ? v1[0] : v2[0],
                      v1[1] < v2[1] ? v1[1] : v2[1],
                      v1[2] < v2[2] ? v1[2] : v2[2]);
}

Remarks

You can use the Maximize and Minimize functions to compute the bounding box for a set of points, in a function that looks like this:

    void
    ComputeBoundingBox(const D3DVECTOR *pts, int N, D3DVECTOR *min, D3DVECTOR *max)
    {
        int i;
        *min = *max = pts[0];
        for (i = 1; i < N; i += 1)
        {
            *min = Minimize(*min, pts[i]);
            *max = Maximize(*max, pts[i]);
        }
    }

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 5.0 or later.
Header: Declared in d3d.h.

See Also

Maximize


Normalize

This helper function returns the normalized version of the specified vector (that is, a unit-length vector with the same direction as the source). Normalize is part of the suite of extra functionality that is available to C++ programmers who define D3D_OVERLOADS.

_D3DVECTOR Normalize (const _D3DVECTOR& v);

This function is defined as follows:

inline _D3DVECTOR
Normalize (const _D3DVECTOR& v)
{
   return v / Magnitude(v);
}

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 5.0 or later.
Header: Declared in d3d.h.


SquareMagnitude

This helper function returns the square of the absolute value of the specified vector. SquareMagnitude is part of the suite of extra functionality that is available to C++ programmers who define D3D_OVERLOADS.

D3DVALUE SquareMagnitude (const _D3DVECTOR& v);

This function is defined as follows:

inline D3DVALUE
SquareMagnitude (const _D3DVECTOR& v)
{
   return v.x*v.x + v.y*v.y + v.z*v.z;
}

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 5.0 or later.
Header: Declared in d3d.h.

See Also

Magnitude


Callback Functions

This section contains reference information for the callback functions that you might need to implement when you work with Direct3D Immediate Mode. The following functions are implemented:

  • D3DEnumDevicesCallback7
  • D3DEnumPixelFormatsCallback


D3DEnumDevicesCallback7

The D3DEnumDevicesCallback7 is an application-defined callback function for the IDirect3D7::EnumDevices method.

HRESULT CALLBACK D3DEnumDevicesCallback7(
  LPSTR lpDeviceDescription,
  LPSTR lpDeviceName,
  LPD3DDEVICEDESC7 lpD3DDeviceDesc,
  LPVOID lpContext
);

Parameters

lpDeviceDescription
Address of a textual description of the device.
lpDeviceName
Address of the device name.
lpD3DDeviceDesc
Address of a D3DDEVICEDESC7 structure that contains the hardware capabilities of the Direct3D device.
lpContext
Address of application-defined data passed to this callback function.

Return Values

Applications should return D3DENUMRET_OK to continue the enumeration, or D3DENUMRET_CANCEL to cancel it.

Remarks

This callback function supersedes the D3DEnumDevicesCallback callback for all interfaces later than IDirect3D3.

When determining the order in which to call callback functions, the system searches the objects highest in the hierarchy first, and then calls their callback functions in the order in which they were created.

The LPD3DENUMDEVICESCALLBACK7 data type is defined as a pointer to this callback function:

typedef HRESULT (CALLBACK * LPD3DENUMDEVICESCALLBACK7)(
  LPSTR lpDeviceDescription, LPSTR lpDeviceName,
  LPD3DDEVICEDESC7, LPVOID);

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dcaps.h.


D3DEnumPixelFormatsCallback

The D3DEnumPixelFormatsCallback is an application-defined callback function for the IDirect3D3::EnumZBufferFormats, and IDirect3DDevice3::EnumTextureFormats methods.

HRESULT CALLBACK D3DEnumPixelFormatsCallback(
  LPDDPIXELFORMAT lpDDPixFmt,
  LPVOID          lpContext
);

Parameters

lpDDPixFmt
Address of a DDPIXELFORMAT structure that describes the enumerated pixel format.
lpContext
Address of application-defined data passed to the function by the caller.

Return Values

Applications should return D3DENUMRET_OK to continue the enumeration, or D3DENUMRET_CANCEL to cancel it.

Remarks

The LPD3DENUMPIXELFORMATSCALLBACK data type is defined as a pointer to this callback function:

typedef HRESULT (WINAPI* LPD3DENUMPIXELFORMATSCALLBACK)(LPDDPIXELFORMAT lpDDPixFmt, LPVOID lpContext);

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 6.0 or later.
Header: Declared in d3dcaps.h.


Obsolete Callback Functions

The Direct3D header files declare some callback functions for backward compatibility that are obsolete or have been superseded by new callback functions. Although obsolete, documentation on these callback function is available through previous releases of DirectX. Legacy documentation is included with this SDK and is available for download from http://www.microsoft.com/directx.

D3DEnumDevicesCallback
Obsolete and superseded by the D3DEnumDevicesCallback7 callback.
D3DEnumTextureFormatsCallback
Obsolete and superseded by the D3DEnumPixelFormatsCallback callback.
D3DValidateCallback
Obsolete. Information about this function, and other topics related to execute-buffer rendering, is available with the documentation provided for previous releases of DirectX.


Macros

This section contains reference information for the macros provided by Direct3D Immediate Mode.

  • D3DCLIPPLANEn
  • D3DDivide
  • D3DFVF_TEXCOORDSIZEn
  • D3DMultiply
  • D3DRGB
  • D3DRGBA
  • D3DVAL
  • D3DVALP
  • RGB_GETBLUE
  • RGB_GETGREEN
  • RGB_GETRED
  • RGB_MAKE
  • RGB_TORGBA
  • RGBA_GETALPHA
  • RGBA_GETBLUE
  • RGBA_GETGREEN
  • RGBA_GETRED
  • RGBA_MAKE
  • RGBA_SETALPHA
  • RGBA_TORGB


D3DCLIPPLANE

DirectX SDK

D3DCLIPPLANEn

The D3DCLIPPLANEn macros define bit patterns that enable user-defined clipping planes. These macros are defined as a convenience when setting values for the D3DRENDERSTATE_CLIPPLANEENABLE render state.

#define D3DCLIPPLANE0 (1 << 0)
#define D3DCLIPPLANE1 (1 << 1)
#define D3DCLIPPLANE2 (1 << 2)
#define D3DCLIPPLANE3 (1 << 3)
#define D3DCLIPPLANE4 (1 << 4)
#define D3DCLIPPLANE5 (1 << 5)
#define D3DCLIPPLANE6 (1 << 6)
#define D3DCLIPPLANE7 (1 << 7)

Parameters

None.

Remarks

User-defined clipping planes are enabled when the DWORD value set in the D3DRENDERSTATE_CLIPPLANEENABLE render state contains one or more set bits (that is, is not 0). The value of the render-state DWORD is not important; the system does not interpret the value as a number. Rather, it parses the DWORD, enabling any clipping planes whose corresponding bit is set. Bit 0 controls the state of the first clipping plane (at index 0), bit 1 the second plane, and so on.

The bit patterns that these macros create can be combined by using a logical OR operation to simultaneously enable multiple clipping planes. Omitting one of these macros from the combination effectively disables the clipping plane at that index.

See Also

D3DRENDERSTATE_CLIPPLANEENABLE


D3DDivide

The D3DDivide macro divides two values.

D3DDivide(a, b)    (float)((double) (a) / (double) (b))

Parameters

a and b
Dividend and divisor in the expression, respectively.

Return Values

Returns the quotient of the division.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.

See Also

D3DMultiply


D3DFVF_TEXCOORDSIZEn

The D3DFVF_TEXCOORDSIZEn macros construct bit patterns that are used to identify texture coordinate formats within a flexible vertex format description. The results of these macros can be combined within a flexible vertex format description by using the OR operator.

D3DFVF_TEXCOORDSIZE1(CoordIndex) (D3DFVF_TEXTUREFORMAT1 << (CoordIndex*2 + 16))
D3DFVF_TEXCOORDSIZE2(CoordIndex) (D3DFVF_TEXTUREFORMAT2)
D3DFVF_TEXCOORDSIZE3(CoordIndex) (D3DFVF_TEXTUREFORMAT3 << (CoordIndex*2 + 16))
D3DFVF_TEXCOORDSIZE4(CoordIndex) (D3DFVF_TEXTUREFORMAT4 << (CoordIndex*2 + 16))

Parameters

CoordIndex
Value identifying the texture coordinate set at which the texture coordinate size (1-, 2-, 3-, or 4-dimensional) applies.

Remarks

The following flexible vertex format description identifies a vertex format that has a position, a normal, diffuse and specular colors, and two sets of texture coordinates. The first set of texture coordinates includes a single element, and the second set includes two elements:

DWORD dwFVF;
dwFVF = D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_DIFFUSE | D3DFVF_SPECULAR |
        D3DFVF_TEXCOORDSIZE1(0) |  \\ Uses 1-D texture coordinates for texture coordinate set 1 (index 0)
        D3DFVF_TEXCOORDSIZE2(1);   \\ And 2-D texture coordinates for texture coordinate set 2 (index 1).

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dtypes.h.


D3DMultiply

The D3DMultiply macro multiplies two values.

D3DMultiply(a, b)    ((a) * (b))

Parameters

a and b
Values to be multiplied.

Return Values

Returns the product of the multiplication.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.

See Also

D3DDivide


D3DRGB

The D3DRGB macro initializes a color with the supplied RGB values.

D3DRGB(r, g, b) \
    (0xff000000L | ( ((long)((r) * 255)) << 16) | \
    (((long)((g) * 255)) << 8) | (long)((b) * 255))

Parameters

r, g, and b
Red, green, and blue components of the color. These should be floating-point values in the range 0 through 1.

Return Values

Returns the D3DCOLOR value corresponding to the supplied RGB values.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.

See Also

D3DRGBA


D3DRGBA

The D3DRGBA macro initializes a color with the supplied RGBA values.

D3DRGBA(r, g, b, a) \
    ((((long)((a) * 255)) << 24) |
    (((long)((r) * 255)) << 16) |
    (((long)((g) * 255)) << 8) | (long)((b) * 255))

Parameters

r, g, b, and a
Red, green, blue, and alpha components of the color.

Return Values

Returns the D3DCOLOR value corresponding to the supplied RGBA values.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.

See Also

D3DRGB


D3DVAL

The D3DVAL macro creates a value whose type is D3DVALUE.

D3DVAL(val)    ((float)val)

Parameters

val
Value to be converted.

Return Values

Returns the converted value.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.

See Also

D3DVALP


D3DVALP

The D3DVALP macro creates a value of the specified precision.

D3DVALP(val, prec)    ((float)val)

Parameters

val
Value to be converted.
prec
Ignored.

Return Values

Returns the converted value.

Remarks

The precision, as implemented by the D3DVAL macro, is 16 bits for the fractional part of the value.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.

See Also

D3DVAL


RGB_GETBLUE

The RGB_GETBLUE macro retrieves the blue component of a D3DCOLOR value.

RGB_GETBLUE(rgb)    ((rgb) & 0xff)

Parameters

rgb
Color index from which the blue component is retrieved.

Return Values

Returns the blue component.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.


RGB_GETGREEN

The RGB_GETGREEN macro retrieves the green component of a D3DCOLOR value.

RGB_GETGREEN(rgb)    (((rgb) >> 8) & 0xff)

Parameters

rgb
Color index from which the green component is retrieved.

Return Values

Returns the green component.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.


RGB_GETRED

The RGB_GETRED macro retrieves the red component of a D3DCOLOR value.

RGB_GETRED(rgb)    (((rgb) >> 16) & 0xff)

Parameters

rgb
Color index from which the red component is retrieved.

Return Values

Returns the red component.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.


RGB_MAKE

The RGB_MAKE macro creates an RGB color from supplied values.

RGB_MAKE(r, g, b)    ((D3DCOLOR) (((r) << 16) |
    ((g) << 8) | (b)))

Parameters

r, g, and b
Red, green, and blue components of the color to be created. These should be integer values in the range 0 through 255.

Return Values

Returns the color.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.


RGB_TORGBA

The RGB_TORGBA macro creates an RGBA color from a supplied RGB color.

RGB_TORGBA(rgb)    ((D3DCOLOR) ((rgb) | 0xff000000))

Parameters

rgb
RGB color to be converted to an RGBA color.

Return Values

Returns the RGBA color.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.

See Also

RGBA_TORGB


RGBA_GETALPHA

The RGBA_GETALPHA macro retrieves the alpha component of an RGBA D3DCOLOR value.

RGBA_GETALPHA(rgb)    ((rgb) >> 24)

Parameters

rgb
Color index from which the alpha component is retrieved.

Return Values

Returns the alpha component.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.


RGBA_GETBLUE

The RGBA_GETBLUE macro retrieves the blue component of an RGBA D3DCOLOR value.

RGBA_GETBLUE(rgb)    ((rgb) & 0xff)

Parameters

rgb
Color index from which the blue component is retrieved.

Return Values

Returns the blue component.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.


RGBA_GETGREEN

The RGBA_GETGREEN macro retrieves the green component of an RGBA D3DCOLOR value.

RGBA_GETGREEN(rgb)    (((rgb) >> 8) & 0xff)

Parameters

rgb
Color index from which the green component is retrieved.

Return Values

Returns the green component.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.


RGBA_GETRED

The RGBA_GETRED macro retrieves the red component of an RGBA D3DCOLOR value.

RGBA_GETRED(rgb)    (((rgb) >> 16) & 0xff)

Parameters

rgb
Color index from which the red component is retrieved.

Return Values

Returns the red component.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.


RGBA_MAKE

The RGBA_MAKE macro creates an RGBA D3DCOLOR value from supplied red, green, blue, and alpha components.

RGBA_MAKE(r, g, b, a)   \
 ((D3DCOLOR) (((a) << 24) | ((r) << 16) | ((g) << 8) | (b)))

Parameters

r, g, b, and a
Red, green, blue, and alpha components of the RGBA color to be created.

Return Values

Returns the color.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.


RGBA_SETALPHA

The RGBA_SETALPHA macro sets the alpha component of an RGBA D3DCOLOR value.

RGBA_SETALPHA(rgba, x) (((x) << 24) | ((rgba) & 0x00ffffff))

Parameters

rgba
RGBA color for which the alpha component is to be set.
x
Value of alpha component to be set.

Return Values

Returns the RGBA color whose alpha component has been set.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.


RGBA_TORGB

The RGBA_TORGB macro creates an RGB D3DCOLOR value from a supplied RGBA D3DCOLOR value by stripping off the alpha component of the color.

RGBA_TORGB(rgba)    ((D3DCOLOR) ((rgba) & 0xffffff))

Parameters

rgba
RGBA color to be converted to an RGB color.

Return Values

Returns the RGB color.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.

See Also

RGB_TORGBA


Obsolete Macros

The D3DSTATE_OVERRIDE macro was used with the obsolete execute-buffer rendering architecture. Although obsolete, the Direct3D header files declare the macro for backward compatibility. For documentation about this macro and other execute-buffer topics, see the documentation provided with a previous release of DirectX. Legacy documentation is provided with this SDK and is available for download from http://www.microsoft.com/directx.


Structures

This section contains information about the following structures used with Direct3D Immediate Mode.

  • D3DCLIPSTATUS
  • D3DCOLORVALUE
  • D3DDEVICEDESC7
  • D3DDEVINFO_TEXTUREMANAGER
  • D3DDEVINFO_TEXTURING
  • D3DDP_PTRSTRIDE
  • D3DDRAWPRIMITIVESTRIDEDDATA
  • D3DLIGHT7
  • D3DLIGHTINGCAPS
  • D3DLINEPATTERN
  • D3DLVERTEX
  • D3DMATERIAL7
  • D3DMATRIX
  • D3DPRIMCAPS
  • D3DRECT
  • D3DTLVERTEX
  • D3DVECTOR
  • D3DVERTEX
  • D3DVERTEXBUFFERDESC
  • D3DVIEWPORT7

Note The memory for all DirectX structures must be initialized to 0 before use. In addition, all structures that contain a dwSize member must set the member to the size of the structure, in bytes, before use. The following example performs these tasks on a common structure, DDCAPS:

DDCAPS ddcaps; // Can't use this yet.

ZeroMemory(&ddcaps, sizeof(ddcaps));
ddcaps.dwSize = sizeof(ddcaps);

// Now the structure can be used.
.
.


D3DCLIPSTATUS

The D3DCLIPSTATUS structure describes the current clip status and extents of the clipping region. This structure was introduced in DirectX 5.0.

typedef struct _D3DCLIPSTATUS {
    DWORD dwFlags;
    DWORD dwStatus;
    float minx, maxx;
    float miny, maxy;
    float minz, maxz;
} D3DCLIPSTATUS, *LPD3DCLIPSTATUS;

Members

dwFlags
Flags describing whether this structure describes 2-D extents, 3-D extents, or the clip status. This member can be a combination of the following flags:
D3DCLIPSTATUS_STATUS
This structure describes the current clip status.
D3DCLIPSTATUS_EXTENTS2
This structure describes the current 2-D extents. This flag cannot be combined with D3DCLIPSTATUS_EXTENTS3.
D3DCLIPSTATUS_EXTENTS3
Not currently implemented.
dwStatus
Describes the current clip status. This member can be one or more of the following flags:

Combination and General Flags

D3DSTATUS_CLIPINTERSECTIONALL
Combination of all CLIPINTERSECTION flags.
D3DSTATUS_CLIPUNIONALL
Combination of all CLIPUNION flags.
D3DSTATUS_DEFAULT
Combination of D3DSTATUS_CLIPINTERSECTIONALL and D3DSTATUS_ZNOTVISIBLE flags. This value is the default.
D3DSTATUS_ZNOTVISIBLE
Indicates that the rendered primitive is not visible. This flag is set or cleared by the system when rendering with z-checking enabled (see D3DRENDERSTATE_ZVISIBLE).

Clip Intersection Flags

D3DSTATUS_CLIPINTERSECTIONBACK
Logical AND operation on the clip flags for the vertices, compared to the back clipping plane of the viewing frustum.
D3DSTATUS_CLIPINTERSECTIONBOTTOM
Logical AND operation on the clip flags for the vertices, compared to the bottom of the viewing frustum.
D3DSTATUS_CLIPINTERSECTIONFRONT
Logical AND operation on the clip flags for the vertices, compared to the front clipping plane of the viewing frustum.
D3DSTATUS_CLIPINTERSECTIONGEN0 through D3DSTATUS_CLIPINTERSECTIONGEN5
Logical AND operation on the clip flags for application-defined clipping planes.
D3DSTATUS_CLIPINTERSECTIONLEFT
Logical AND operation on the clip flags for the vertices, compared to the left side of the viewing frustum.
D3DSTATUS_CLIPINTERSECTIONRIGHT
Logical AND operation on the clip flags for the vertices, compared to the right side of the viewing frustum.
D3DSTATUS_CLIPINTERSECTIONTOP
Logical AND operation on the clip flags for the vertices, compared to the top of the viewing frustum.

Clip Union Flags

D3DSTATUS_CLIPUNIONBACK
Equal to D3DCLIP_BACK.
D3DSTATUS_CLIPUNIONBOTTOM
Equal to D3DCLIP_BOTTOM.
D3DSTATUS_CLIPUNIONFRONT
Equal to D3DCLIP_FRONT.
D3DSTATUS_CLIPUNIONGEN0 through D3DSTATUS_CLIPUNIONGEN5
Equal to D3DCLIP_GEN0 through D3DCLIP_GEN5.
D3DSTATUS_CLIPUNIONLEFT
Equal to D3DCLIP_LEFT.
D3DSTATUS_CLIPUNIONRIGHT
Equal to D3DCLIP_RIGHT.
D3DSTATUS_CLIPUNIONTOP
Equal to D3DCLIP_TOP.

Basic Clipping Flags

D3DCLIP_BACK
All vertices are clipped by the back plane of the viewing frustum.
D3DCLIP_BOTTOM
All vertices are clipped by the bottom plane of the viewing frustum.
D3DCLIP_FRONT
All vertices are clipped by the front plane of the viewing frustum.
D3DCLIP_LEFT
All vertices are clipped by the left plane of the viewing frustum.
D3DCLIP_RIGHT
All vertices are clipped by the right plane of the viewing frustum.
D3DCLIP_TOP
All vertices are clipped by the top plane of the viewing frustum.
D3DCLIP_GEN0 through D3DCLIP_GEN5
Application-defined clipping planes.
minx, maxx, miny, maxy, minz, maxz
x, y, and z extents of the current clipping region.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.

See Also

IDirect3DDevice7::GetClipStatus, IDirect3DDevice7::SetClipStatus


D3DCOLORVALUE

The D3DCOLORVALUE structure describes color values for the D3DMATERIAL7 structure.

typedef struct _D3DCOLORVALUE {
    union {
        D3DVALUE r;
        D3DVALUE dvR;
    };
    union {
        D3DVALUE g;
        D3DVALUE dvG;
    };
    union {
        D3DVALUE b;
        D3DVALUE dvB;
    };
    union {
        D3DVALUE a;
        D3DVALUE dvA;
    };
} D3DCOLORVALUE;

Members

dvR, dvG, dvB, and dvA
Values of the D3DVALUE type specifying the red, green, blue, and alpha components of a color. These values generally are in the range from 0 through 1, with 0 being black.

Remarks

You can set the members of this structure to values outside the range of 0 through 1 to implement some unusual effects. Values greater than 1 produce strong lights that tend to wash out a scene. Negative values produce dark lights, which actually remove light from a scene. For more information, see Colored Lights.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 5.0 or later.
Header: Declared in d3dtypes.h.


D3DDEVICEDESC7

The D3DDEVICEDESC7 structure contains a description of the current device. This structure is used to query the current device by such methods as IDirect3DDevice7::GetCaps.

This structure supersedes the D3DDEVICEDESC structure for all device interfaces later than IDirect3DDevice3.

typedef struct _D3DDeviceDesc7 {
    DWORD        dwDevCaps;
    D3DPRIMCAPS  dpcLineCaps;
    D3DPRIMCAPS  dpcTriCaps;
    DWORD        dwDeviceRenderBitDepth;
    DWORD        dwDeviceZBufferBitDepth;
    DWORD        dwMinTextureWidth, dwMinTextureHeight;
    DWORD        dwMaxTextureWidth, dwMaxTextureHeight;
    DWORD        dwMaxTextureRepeat;
    DWORD        dwMaxTextureAspectRatio;
    DWORD        dwMaxAnisotropy;
    D3DVALUE     dvGuardBandLeft;
    D3DVALUE     dvGuardBandTop;
    D3DVALUE     dvGuardBandRight;
    D3DVALUE     dvGuardBandBottom;
    D3DVALUE     dvExtentsAdjust;
    DWORD        dwStencilCaps;
    DWORD        dwFVFCaps;
    DWORD        dwTextureOpCaps;
    WORD         wMaxTextureBlendStages;
    WORD         wMaxSimultaneousTextures;
    DWORD        dwMaxActiveLights;
    D3DVALUE     dvMaxVertexW;
    GUID         deviceGUID;
    WORD         wMaxUserClipPlanes;
    WORD         wMaxVertexBlendMatrices;
    DWORD        dwVertexProcessingCaps;
    DWORD        dwReserved1;
    DWORD        dwReserved2;
    DWORD        dwReserved3;
    DWORD        dwReserved4;
} D3DDEVICEDESC7, *LPD3DDEVICEDESC7;

Members

dwDevCaps
Flags identifying the capabilities of the device.
D3DDEVCAPS_CANBLTSYSTONONLOCAL
Device supports blits from system-memory textures to nonlocal video-memory textures.

This flag was introduced with DirectX 7.0

D3DDEVCAPS_CANRENDERAFTERFLIP
Device can queue rendering commands after a page flip. Applications do not change their behavior if this flag is set; this capability simply means that the device is relatively fast.

This flag was introduced in DirectX 5.0.

D3DDEVCAPS_DRAWPRIMTLVERTEX
Device exports a DrawPrimitive-aware hardware abstraction layer (HAL).

This flag was introduced in DirectX 5.0.

D3DDEVCAPS_EXECUTESYSTEMMEMORY
Device can use execute buffers from system memory.
D3DDEVCAPS_EXECUTEVIDEOMEMORY
Device can use execute buffers from video memory.
D3DDEVCAPS_FLOATTLVERTEX
Device accepts floating point for post-transform vertex data.
D3DDEVCAPS_HWRASTERIZATION
Device has hardware acceleration for scene rasterization.
D3DDEVCAPS_HWTRANSFORMANDLIGHT
Device supports transformation and lighting in hardware.

This flag was introduced with DirectX 7.0.

D3DDEVCAPS_SEPARATETEXTUREMEMORIES
Device uses discrete texture memory pools for each stage. Textures must be assigned to texture stages explicitly at the time of creation by setting the dwTextureStage member of the DDSURFACEDESC2 structure to the appropriate stage identifier.
D3DDEVCAPS_SORTDECREASINGZ
Device needs data sorted for decreasing depth.
D3DDEVCAPS_SORTEXACT
Device needs data sorted exactly.
D3DDEVCAPS_SORTINCREASINGZ
Device needs data sorted for increasing depth.
D3DDEVCAPS_STRIDEDVERTICES
Device supports strided vertex data for transformation and lighting in hardware.

This flag was introduced with DirectX 7.0

D3DDEVCAPS_TEXTURENONLOCALVIDMEM
Device can retrieve textures from nonlocal video (AGP) memory.

This flag was introduced in DirectX 5.0. For more information about AGP memory, see Using Non-local Video Memory Surfaces in the DirectDraw documentation.

D3DDEVCAPS_TEXTURESYSTEMMEMORY
Device can retrieve textures from system memory.
D3DDEVCAPS_TEXTUREVIDEOMEMORY
Device can retrieve textures from device memory.
D3DDEVCAPS_TLVERTEXSYSTEMMEMORY
Device can use buffers from system memory for transformed and lit vertices.
D3DDEVCAPS_TLVERTEXVIDEOMEMORY
Device can use buffers from video memory for transformed and lit vertices.
dpcLineCaps and dpcTriCaps
D3DPRIMCAPS structures defining the device's support for line-drawing and triangle primitives.
dwDeviceRenderBitDepth
Device's rendering bit depth. This can be one or more of the following DirectDraw bit-depth constants: DDBD_8, DDBD_16, DDBD_24, or DDBD_32.
dwDeviceZBufferBitDepth
Bit depth of the device's depth-buffer. This can be one of the following DirectDraw bit-depth constants: DDBD_8, DDBD_16, DDBD_24, or DDBD_32.
dwMinTextureWidth, dwMinTextureHeight
Minimum texture width and height for this device.
dwMaxTextureWidth, dwMaxTextureHeight
Maximum texture width and height for this device.
dwMaxTextureRepeat
Full range of the integer bits of the post-normalized texture indices. If the D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE bit is set, the device defers scaling by the texture size until after the texture address mode is applied. If not set, the device scales the texture indices by the texture size (largest level of detail) prior to interpolation.
dwMaxTextureAspectRatio
Maximum texture aspect ratio supported by the hardware; this is typically a power of 2.
dwMaxAnisotropy
Maximum valid value for the D3DTSS_MAXANISOTROPY texture-stage state.
dvGuardBandLeft, dvGuardBandTop, dvGuardBandRight, and dvGuardBandBottom
The screen-space coordinates of the guard-band clipping region. Coordinates inside this rectangle but outside the viewport rectangle are automatically clipped.
dvExtentsAdjust
Number of pixels to adjust the extents rectangle outward to accommodate antialiasing kernels.
dwStencilCaps
Flags specifying supported stencil-buffer operations. Stencil operations are assumed to be valid for all three stencil-buffer operation render states (D3DRENDERSTATE_STENCILFAIL, D3DRENDERSTATE_STENCILPASS, and D3DRENDERSTATE_STENCILFAILZFAIL).
D3DSTENCILCAPS_DECR
The D3DSTENCILOP_DECR operation is supported.
D3DSTENCILCAPS_DECRSAT
The D3DSTENCILOP_DECRSAT operation is supported.
D3DSTENCILCAPS_INCR
The D3DSTENCILOP_INCR operation is supported.
D3DSTENCILCAPS_INCRSAT
The D3DSTENCILOP_INCRSAT operation is supported.
D3DSTENCILCAPS_INVERT
The D3DSTENCILOP_INVERT operation is supported.
D3DSTENCILCAPS_KEEP
The D3DSTENCILOP_KEEP operation is supported.
D3DSTENCILCAPS_REPLACE
The D3DSTENCILOP_REPLACE operation is supported.
D3DSTENCILCAPS_ZERO
The D3DSTENCILOP_ZERO operation is supported.
dwFVFCaps
Flexible vertex format capabilities:
D3DFVFCAPS_DONOTSTRIPELEMENTS
It is preferable that vertex elements not be stripped. That is, if the vertex format contains elements that are not used with the current render states, there is no need to regenerate the vertices. If this capability flag is not present, stripping extraneous elements from the vertex format provides better performance.
D3DFVFCAPS_TEXCOORDCOUNTMASK
Masks the low WORD of dwFVFCaps. These bits, cast to the WORD data type, describe the total number of texture coordinate sets that the device can simultaneously use for multiple texture blending. (You can use up to eight texture coordinate sets for any vertex, but the device can only blend using the specified number of texture coordinate sets.)
dwTextureOpCaps
Combination of flags describing the texture operations supported by this device. The following flags are defined:
D3DTEXOPCAPS_ADD
The D3DTOP_ADD texture-blending operation is supported.
D3DTEXOPCAPS_ADDSIGNED
The D3DTOP_ADDSIGNED texture-blending operation is supported.
D3DTEXOPCAPS_ADDSIGNED2X
The D3DTOP_ADDSIGNED2X texture-blending operation is supported.
D3DTEXOPCAPS_ADDSMOOTH
The D3DTOP_ADDSMOOTH texture-blending operation is supported.
D3DTEXOPCAPS_BLENDCURRENTALPHA
The D3DTOP_BLENDCURRENTALPHA texture-blending operation is supported.
D3DTEXOPCAPS_BLENDDIFFUSEALPHA
The D3DTOP_BLENDDIFFUSEALPHA texture-blending operation is supported.
D3DTEXOPCAPS_BLENDFACTORALPHA
The D3DTOP_BLENDFACTORALPHA texture-blending operation is supported.
D3DTEXOPCAPS_BLENDTEXTUREALPHA
The D3DTOP_BLENDTEXTUREALPHA texture-blending operation is supported.
D3DTEXOPCAPS_BLENDTEXTUREALPHAPM
The D3DTOP_BLENDTEXTUREALPHAPM texture-blending operation is supported.
D3DTEXOPCAPS_BUMPENVMAP
The D3DTOP_BUMPENVMAP texture-blending operation is supported.
D3DTEXOPCAPS_BUMPENVMAPLUMINANCE
The D3DTOP_BUMPENVMAPLUMINANCE texture-blending operation is supported.
D3DTEXOPCAPS_DISABLE
The D3DTOP_DISABLE texture-blending operation is supported.
D3DTEXOPCAPS_DOTPRODUCT3
The D3DTOP_DOTPRODUCT3 texture-blending operation is supported.
D3DTEXOPCAPS_MODULATE
The D3DTOP_MODULATE texture-blending operation is supported.
D3DTEXOPCAPS_MODULATE2X
The D3DTOP_MODULATE2X texture-blending operation is supported.
D3DTEXOPCAPS_MODULATE4X
The D3DTOP_MODULATE4X texture-blending operation is supported.
D3DTEXOPCAPS_MODULATEALPHA_ADDCOLOR
The D3DTOP_MODULATEALPHA_ADDCOLOR texture-blending operation is supported.
D3DTEXOPCAPS_MODULATECOLOR_ADDALPHA
The D3DTOP_MODULATECOLOR_ADDALPHA texture-blending operation is supported.
D3DTEXOPCAPS_MODULATEINVALPHA_ADDCOLOR
The D3DTOP_MODULATEINVALPHA_ADDCOLOR texture-blending operation is supported.
D3DTEXOPCAPS_MODULATEINVCOLOR_ADDALPHA
The D3DTOP_MODULATEINVCOLOR_ADDALPHA texture-blending operation is supported.
D3DTEXOPCAPS_PREMODULATE
The D3DTOP_PREMODULATE texture-blending operation is supported.
D3DTEXOPCAPS_SELECTARG1
The D3DTOP_SELECTARG1 texture-blending operation is supported.
D3DTEXOPCAPS_SELECTARG2
The D3DTOP_SELECTARG2 texture-blending operation is supported.
D3DTEXOPCAPS_SUBTRACT
The D3DTOP_SUBTRACT texture-blending operation is supported.
wMaxTextureBlendStages
Maximum number of texture-blending stages supported.
wMaxSimultaneousTextures
Maximum number of textures that can be simultaneously bound to the texture blending stages. See remarks.
dwMaxActiveLights
Maximum number of lights that can be active simultaneously.
dvMaxVertexW
Maximum W-based depth value that the device supports.
deviceGUID
Globally unique identifier (GUID) of this device: IID_IDirect3DHALDevice, IID_IDirect3DTnLHalDevice, or IID_IDirect3DRGBDevice.
wMaxUserClipPlanes
Maximum number of user-defined clipping planes supported. This member can range from 0 through D3DMAXUSERCLIPPLANES.

User-defined clipping planes are manipulated by using the IDirect3DDevice7::GetClipPlane and IDirect3DDevice7::SetClipPlane methods.

wMaxVertexBlendMatrices
Maximum number of matrices that this device can apply when performing multimatrix vertex blending.
dwVertexProcessingCaps
Vertex processing capabilities.
D3DVTXPCAPS_TEXGEN
Device can generate texture coordinates.
D3DVTXPCAPS_MATERIALSOURCE7
Device supports selectable vertex color sources. For more information, see Light Color Types and Sources.
D3DVTXPCAPS_VERTEXFOG
Device supports vertex fog.
D3DVTXPCAPS_DIRECTIONALLIGHTS
Device supports directional lights.
D3DVTXPCAPS_POSITIONALLIGHTS
Device supports positional lights (including point lights and spotlights).
D3DVTXPCAPS_NONLOCALVIEWER
Device supports orthogonal specular highlights, enabled by setting the D3DRENDERSTATE_LOCALVIEWER render state to FALSE.
dwReserved1 through dwReserved4
Reserved.

Remarks

The wMaxTextureBlendStages and wMaxSimultaneousTextures members might seem very similar, but they contain different information. The wMaxTextureBlendStages member contains the total number of texture-blending stages supported by the current device, and the wMaxSimultaneousTextures member describes how many of those stages can have textures bound to them by using the IDirect3DDevice7::SetTexture method.

When the driver fills this structure, it can set values for execute-buffer capabilities, even when the interface being used to retrieve the capabilities (such as IDirect3DDevice7) does not support execute buffers.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dcaps.h.

See Also

D3DCOLORMODEL, D3DLIGHTINGCAPS, D3DPRIMCAPS


D3DDEVINFO_TEXTUREMANAGER

The D3DDEVINFO_TEXTUREMANAGER structure contains information about the current state of the texture manager. This structure is used with the IDirect3DDevice7::GetInfo method.

typedef struct _D3DDEVINFO_TEXTUREMANAGER {
    BOOL    bThrashing;
    DWORD   dwNumEvicts;
    DWORD   dwNumVidCreates;
    DWORD   dwNumTexturesUsed;
    DWORD   dwNumUsedTexInVid;
    DWORD   dwWorkingSet;
    DWORD   dwWorkingSetBytes;
    DWORD   dwTotalManaged;
    DWORD   dwTotalBytes;
    DWORD   dwLastPri;
} D3DDEVINFO_TEXTUREMANAGER, *LPD3DDEVINFO_TEXTUREMANAGER;

Members

bThrashing
Thrashing status. TRUE if thrashing occurred during the last frame, or FALSE otherwise.
dwNumEvicts
Number of textures that were removed during the last frame.
dwNumVidCreates
Number of textures that were created in video memory during the last frame.
dwNumTexturesUsed
Total number of textures used during the last frame.
dwNumUsedTexInVid
Number of video memory textures that were used during the last frame.
dwWorkingSet
Number of textures currently resident in video memory.
dwWorkingSetBytes
Number of bytes currently allocated by textures resident in video memory.
dwTotalManaged
Total number of managed textures.
dwTotalBytes
Total number of bytes allocated for managed textures.
dwLastPri
Priority of last evicted texture.

Remarks

Use the values in dwNumUsedTexInVid and dwNumTexturesUsed to determine the percentage of textures used during the last frame that were resident in video memory (local or nonlocal). The following code fragment shows how to make this computation:

// For this example, the d3dtminfo variable is a D3DDEVINFO_TEXTUREMANAGER
// structure that has been filled by a call to IDirect3DDevice7::GetInfo.

DWORD dwHitRate;

// Retrieve the percentage of textures used that were in video memory.
dwHitRate = (d3dtminfo.dwNumUsedTexInVid * 100) / d3dtminfo.dwNumTexturesUsed;

See Also

IDirect3DDevice7::GetInfo


D3DDEVINFO_TEXTURING

The D3DDEVINFO_TEXTURING structure contains information about the texturing activity of the application. This structure is used with the IDirect3DDevice7::GetInfo method.

typedef struct _D3DDEVINFO_TEXTURING {
    DWORD   dwNumLoads;
    DWORD   dwApproxBytesLoaded;
    DWORD   dwNumPreLoads;
    DWORD   dwNumSet;
    DWORD   dwNumCreates;
    DWORD   dwNumDestroys;
    DWORD   dwNumSetPriorities;
    DWORD   dwNumSetLODs;
    DWORD   dwNumLocks;
    DWORD   dwNumGetDCs;
} D3DDEVINFO_TEXTURING, *LPD3DDEVINFO_TEXTURING;

Members

dwNumLoads
Number of times a texture has been loaded by calling the IDirect3DDevice7::Load method.
dwApproxBytesLoaded
Approximate number of bytes loaded by calls to the IDirect3DDevice7::Load method.
dwNumPreLoads
Number of times managed textures have been explicitly loaded by calling the IDirect3DDevice7::PreLoad method.
dwNumSet
Number of times textures have been set to texture-blending stages by calling the IDirect3DDevice7::SetTexture method.
dwNumCreates
Number of texture surfaces created by the application.
dwNumDestroys
Number of textures destroyed (released) by the application.
dwNumSetPriorities
Number of times texture-management priority has been set by calling the IDirectDrawSurface7::SetPriority method.
dwNumSetLODs
Number of times the maximum mipmap level of detail has been set by calling the IDirectDrawSurface7::SetLOD method.
dwNumLocks
Number of times a texture surface has been locked by calling the IDirectDrawSurface7::Lock method.
dwNumGetDCs
Number of times a device context for a texture surface has been retrieved by calling the IDirectDrawSurface7::GetDC method.

See Also

IDirect3DDevice7::GetInfo


D3DDP_PTRSTRIDE

The D3DDP_PTRSTRIDE structure contains the address of an array of flexible vertex format components and the stride to the next element in the array. This structure is contained in the D3DDRAWPRIMITIVESTRIDEDDATA structure.

typedef struct _D3DDP_PTRSTRIDE {
    LPVOID lpvData;
    DWORD  dwStride;
} D3DDP_PTRSTRIDE;

Members

lpvData
Address of an array of data.
dwStride
Memory stride between elements in the array.

Remarks

This structure can be used with a composite vertex format (like the D3DLVERTEX structure) or a distinct array of vertex components. In a composite vertex format, lpvData points to a particular component, and dwStride is the stride, in bytes, of the composite format. In an array that contains only one vertex component, dwStride is the stride of each element in the array.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 6.0 or later.
Header: Declared in d3dtypes.h.

See Also

D3DDRAWPRIMITIVESTRIDEDDATA, Strided Vertex Format


D3DDRAWPRIMITIVESTRIDEDDATA

The D3DDRAWPRIMITIVESTRIDEDDATA structure contains flexible vertex format components.

typedef struct D3DDRAWPRIMITIVESTRIDEDDATA  {
    D3DDP_PTRSTRIDE position;
    D3DDP_PTRSTRIDE normal;
    D3DDP_PTRSTRIDE diffuse;
    D3DDP_PTRSTRIDE specular;
    D3DDP_PTRSTRIDE textureCoords[D3DDP_MAXTEXCOORD];
} D3DDRAWPRIMITIVESTRIDEDDATA , *LPD3DDRAWPRIMITIVESTRIDEDDATA;

Members

position and normal
D3DDP_PTRSTRIDE structures that point to arrays of position and normal vectors for a collection of vertices (each vector is a three-element array of float values).
diffuse and specular
D3DDP_PTRSTRIDE structures that point to diffuse and specular color information for a collection of vertices. Each color component is an 8-8-8-8 RGBA value.
textureCoords
An eight-element array of D3DDP_PTRSTRIDE structures. Each element in the array is an array of texture coordinates for the collection of vertices. Your application determines which array of texture coordinates is used for a given texture stage by calling the IDirect3DDevice7::SetTextureStageState method with the D3DTSS_TEXCOORDINDEX stage state value.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 6.0 or later.
Header: Declared in d3dtypes.h.

See Also

D3DDP_PTRSTRIDE, Strided Vertex Format, Vertex Formats


D3DLIGHT7

The D3DLIGHT7 structure defines a set of lighting properties. This structure is used with the IDirect3DDevice7::GetLight and IDirect3DDevice7::SetLight methods.

typedef struct _D3DLIGHT7 {
    D3DLIGHTTYPE    dltType;
    D3DCOLORVALUE   dcvDiffuse;
    D3DCOLORVALUE   dcvSpecular;
    D3DCOLORVALUE   dcvAmbient;
    D3DVECTOR       dvPosition;
    D3DVECTOR       dvDirection;
    D3DVALUE        dvRange;
    D3DVALUE        dvFalloff;
    D3DVALUE        dvAttenuation0;
    D3DVALUE        dvAttenuation1;
    D3DVALUE        dvAttenuation2;
    D3DVALUE        dvTheta;
    D3DVALUE        dvPhi;
} D3DLIGHT7, *LPD3DLIGHT7;

Members

dltType
Type of the light source. This value is one of the members of the D3DLIGHTTYPE enumerated type.
dcvDiffuse
Diffuse color emitted by the light. This member is a D3DCOLORVALUE structure.
dcvSpecular
Specular color emitted by the light. This member is a D3DCOLORVALUE structure.
dcvAmbient
Ambient color emitted by the light. This member is a D3DCOLORVALUE structure.
dvPosition
Position of the light in world space. This member has no meaning for directional lights and is ignored in that case.
dvDirection
Direction that the light is pointing in world space. This member only has meaning for directional and spotlights. This vector need not be normalized, but it should have a nonzero length.
dvRange
Distance beyond which the light has no effect. The maximum allowable value for this member is D3DLIGHT_RANGE_MAX, which is defined as the square root of FLT_MAX. This member does not affect directional lights.
dvFalloff
Decrease in illumination between a spotlight's inner cone (the angle specified by dvTheta ) and the outer edge of the outer cone (the angle specified by dvPhi ). This feature was implemented for DirectX 5.0. For details on how dvFalloff values affect a spotlight, see Spotlight Falloff Model.

The effect of falloff on the lighting is subtle. Furthermore, a small performance penalty is incurred by shaping the falloff curve. For these reasons, most developers set this value to 1.0.

dvAttenuation0, dvAttenuation1, and dvAttenuation2
Values specifying how the light intensity changes over distance. (Attenuation does not affect directional lights.) These members represent a light's constant, linear, and quadratic attenuation factors. For information about how these attenuation values affect lighting in a scene, see Light Attenuation Over Distance. Valid values for these members range from 0.0 to infinity.
dvTheta
Angle, in radians, of a spotlight's inner cone—that is, the fully illuminated spotlight cone. This value must be in the range from 0 through the value specified by dvPhi.
dvPhi
Angle, in radians, defining the outer edge of the spotlight's outer cone. Points outside this cone are not lit by the spotlight. This value must be between 0 and pi.

Remarks

This structure, introduced with DirectX 7.0, supersedes the D3DLIGHT2 and D3DLIGHT structures used with previous versions of DirectX.

This structure differs from the D3DLIGHT2 structure in that it provides members for independent diffuse, specular, and ambient colors of a light. Each color value is used in the lighting module of Direct3D Immediate Mode to determine the lighting in a scene.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dtypes.h.

See Also

IDirect3DDevice7::GetLight, IDirect3DDevice7::SetLight, D3DLIGHTTYPE, Lighting and Materials


D3DLIGHTINGCAPS

The D3DLIGHTINGCAPS structure describes the lighting capabilities of a device. This structure is a member of the D3DDEVICEDESC7 structure.

typedef struct _D3DLIGHTINGCAPS {
    DWORD dwSize;
    DWORD dwCaps;
    DWORD dwLightingModel;
    DWORD dwNumLights;
} D3DLIGHTINGCAPS, *LPD3DLIGHTINGCAPS;

Members

dwSize
Size, in bytes, of this structure. This member must be initialized before the structure is used.
dwCaps
Flags describing the capabilities of the lighting module. The following flags are defined:
D3DLIGHTCAPS_DIRECTIONAL
Supports directional lights.
D3DLIGHTCAPS_GLSPOT
Not used.
D3DLIGHTCAPS_POINT
Supports point lights.
D3DLIGHTCAPS_SPOT
Supports spotlights.
dwLightingModel
Flags defining whether the lighting model is RGB or monochrome. The following flags are defined:
D3DLIGHTINGMODEL_MONO
Monochromatic lighting model.
D3DLIGHTINGMODEL_RGB
RGB lighting model.
dwNumLights
Number of lights that can be handled.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dcaps.h.


D3DLINEPATTERN

The D3DLINEPATTERN structure describes a line pattern. These values are used by the D3DRENDERSTATE_LINEPATTERN render state in the D3DRENDERSTATETYPE enumerated type.

typedef struct _D3DLINEPATTERN {
    WORD wRepeatFactor;
    WORD wLinePattern;
} D3DLINEPATTERN;

Members

wRepeatFactor
Number of times to repeat each series of 1s and 0s specified in the wLinePattern member. This allows an application to stretch the line pattern.
wLinePattern
Bits specifying the line pattern. For example, the following value would produce a dotted line: 1100110011001100.

Remarks

A line pattern specifies how a line is drawn. The line pattern is always the same, no matter where it is started. (This differs from stippling, which affects how objects are rendered; that is, to imitate transparency.)

The line pattern specifies up to a 16-pixel pattern of on and off pixels along the line. The wRepeatFactor member specifies how many pixels are repeated for each entry in wLinePattern.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.


D3DLVERTEX

The D3DLVERTEX structure defines an untransformed lit vertex (model coordinates with color). An application should use this structure when vertex transformations are to be handled by Direct3D. This structure contains only data and a color that would be filled by software lighting.

typedef struct _D3DLVERTEX {
    union {
        D3DVALUE x;
        D3DVALUE dvX;
    };
    union {
        D3DVALUE y;
        D3DVALUE dvY;
    };
    union {
        D3DVALUE z;
        D3DVALUE dvZ;
    };
    DWORD        dwReserved;
    union {
        D3DCOLOR color;
        D3DCOLOR dcColor;
    };
    union {
        D3DCOLOR specular;
        D3DCOLOR dcSpecular;
    };
    union {
        D3DVALUE tu;
        D3DVALUE dvTU;
    };
    union {
        D3DVALUE tv;
        D3DVALUE dvTV;
    };
} D3DLVERTEX, *LPD3DLVERTEX;

Members

dvX, dvY, and dvZ
Values of the D3DVALUE type specifying the model coordinates of the vertex.
dwReserved
Reserved; must be 0.
dcColor and dcSpecular
Values of the D3DCOLOR type specifying the color and specular component of the vertex.
dvTU and dvTV
Values of the D3DVALUE type specifying the texture coordinates of the vertex.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.

See Also

D3DTLVERTEX, D3DVERTEX


D3DMATERIAL7

The D3DMATERIAL7 structure specifies material properties in calls to the IDirect3DDevice7::GetMaterial and IDirect3DDevice7::SetMaterial methods.

typedef struct _D3DMATERIAL7 {
    union {
        D3DCOLORVALUE   diffuse;
        D3DCOLORVALUE   dcvDiffuse;
    };
    union {
        D3DCOLORVALUE   ambient;
        D3DCOLORVALUE   dcvAmbient;
    };
    union {
        D3DCOLORVALUE   specular;
        D3DCOLORVALUE   dcvSpecular;
    };
    union {
        D3DCOLORVALUE   emissive;
        D3DCOLORVALUE   dcvEmissive;
    };
    union {
        D3DVALUE        power;
        D3DVALUE        dvPower;
    };
} D3DMATERIAL7, *LPD3DMATERIAL7;

Members

dcvDiffuse, dcvAmbient, dcvSpecular, and dcvEmissive
Values specifying the diffuse color, ambient color, specular color, and emissive color of the material, respectively. These values are D3DCOLORVALUE structures.
dvPower
Value of the D3DVALUE type specifying the sharpness of specular highlights. To turn off specular highlights for a material, set this member to 0; setting the specular color components to 0 is not enough.

Remarks

This structure, introduced with DirectX 7.0, supersedes the D3DMATERIAL structure used with previous versions of DirectX.

This structure, unlike the legacy D3DMATERIAL structure, does not support texture handles (for textured viewport background) or ramp sizes for the legacy Ramp software device.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dtypes.h.

See Also

IDirect3DDevice7::GetMaterial, IDirect3DDevice7::SetMaterial, Lighting and Materials


D3DMATRIX

The D3DMATRIX structure describes a matrix for such methods as IDirect3DDevice7::MultiplyTransform, IDirect3DDevice7::GetTransform, and IDirect3DDevice7::SetTransform.

C++ programmers can use an extended version of this structure that includes a parentheses ("()") operator. For more information, see D3DMATRIX (D3D_OVERLOADS)

typedef struct _D3DMATRIX {
    D3DVALUE _11, _12, _13, _14;
    D3DVALUE _21, _22, _23, _24;
    D3DVALUE _31, _32, _33, _34;
    D3DVALUE _41, _42, _43, _44;
} D3DMATRIX, *LPD3DMATRIX;

Remarks

In Direct3D, the _34 element of a projection matrix cannot be a negative number. If your application needs to use a negative value in this location, it should scale the entire projection matrix by –1, instead.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.

See Also

IDirect3DDevice7::MultiplyTransform, IDirect3DDevice7::GetTransform, IDirect3DDevice7::SetTransform


D3DPRIMCAPS

The D3DPRIMCAPS structure defines the capabilities for each primitive type. This structure is used when creating a device and when querying the capabilities of a device. This structure defines several members of the D3DDEVICEDESC7 structure.

typedef struct _D3DPrimCaps {
    DWORD dwSize;               //Size of structure
    DWORD dwMiscCaps;           //Miscellaneous capabilities
    DWORD dwRasterCaps;         //Raster capabilities
    DWORD dwZCmpCaps;           //Z-comparison capabilities
    DWORD dwSrcBlendCaps;       //Source-blending capabilities
    DWORD dwDestBlendCaps;      //Destination-blending capa bilities
    DWORD dwAlphaCmpCaps;       //Alpha-test-comparison capabilities
    DWORD dwShadeCaps;          //Shading capabilities
    DWORD dwTextureCaps;        //Texture capabilities
    DWORD dwTextureFilterCaps;  //Texture-filtering capabilities
    DWORD dwTextureBlendCaps;   //Texture-blending capabilities
    DWORD dwTextureAddressCaps; //Texture-addressing capabilities
    DWORD dwStippleWidth;       //Stipple width
    DWORD dwStippleHeight;      //Stipple height
} D3DPRIMCAPS, *LPD3DPRIMCAPS;

Members

dwSize
Size, in bytes, of this structure. This member must be initialized before the structure is used.
dwMiscCaps
General capabilities for this primitive. This member can be one or more of the following:
D3DPMISCCAPS_CONFORMANT
The device conforms to the OpenGL standard.
D3DPMISCCAPS_CULLCCW
The driver supports counterclockwise culling through the D3DRENDERSTATE_CULLMODE state. (This applies only to triangle primitives.) This corresponds to the D3DCULL_CCW member of the D3DCULL enumerated type.
D3DPMISCCAPS_CULLCW
The driver supports clockwise triangle culling through the D3DRENDERSTATE_CULLMODE state. (This applies only to triangle primitives.) This corresponds to the D3DCULL_CW member of the D3DCULL enumerated type.
D3DPMISCCAPS_CULLNONE
The driver does not perform triangle culling. This corresponds to the D3DCULL_NONE member of the D3DCULL enumerated type.
D3DPMISCCAPS_LINEPATTERNREP
The driver can handle values other than 1 in the wRepeatFactor member of the D3DLINEPATTERN structure. (This applies only to line-drawing primitives.)
D3DPMISCCAPS_MASKPLANES
The device can perform a bitmask of color planes.
D3DPMISCCAPS_MASKZ
The device can enable and disable modification of the depth buffer on pixel operations.
dwRasterCaps
Information on raster-drawing capabilities. This member can be one or more of the following:
D3DPRASTERCAPS_ANISOTROPY
The device supports anisotropic filtering. For more information, see D3DRENDERSTATE_ANISOTROPY in the D3DRENDERSTATETYPE structure.

This flag was introduced in DirectX 5.0.

D3DPRASTERCAPS_ANTIALIASEDGES
The device can antialias lines forming the convex outline of objects. For more information, see D3DRENDERSTATE_EDGEANTIALIAS in the D3DRENDERSTATETYPE structure.

This flag was introduced in DirectX 5.0.

D3DPRASTERCAPS_ANTIALIASSORTDEPENDENT
The device supports antialiasing that is dependent on the sort order of the polygons (back-to-front or front-to-back). The application must draw polygons in the right order for antialiasing to occur. For more information, see the D3DANTIALIASMODE enumerated type.

This flag was introduced in DirectX 5.0.

D3DPRASTERCAPS_ANTIALIASSORTINDEPENDENT
The device supports antialiasing that is not dependent on the sort order of the polygons. For more information, see the D3DANTIALIASMODE enumerated type.

This flag was introduced in DirectX 5.0.

D3DPRASTERCAPS_DITHER
The device can dither to improve color resolution.
D3DPRASTERCAPS_FOGRANGE
The device supports range-based fog. In range-based fog, the distance of an object from the viewer is used to compute fog effects, not the depth of the object (that is, the z-coordinate) in the scene. For more information, see Range-based Fog.

This flag was introduced in DirectX 5.0.

D3DPRASTERCAPS_FOGTABLE
The device calculates the fog value by referring to a lookup table containing fog values that are indexed to the depth of a given pixel.
D3DPRASTERCAPS_FOGVERTEX
The device calculates the fog value during the lighting operation, places the value into the alpha component of the D3DCOLOR value given for the specular member of the D3DTLVERTEX structure and interpolates the fog value during rasterization.
D3DPRASTERCAPS_MIPMAPLODBIAS
The device supports level-of-detail (LOD) bias adjustments. These bias adjustments enable an application to make a mipmap appear crisper or less sharp than it normally would. For more information about LOD bias in mipmaps, see D3DTSS_MIPMAPLODBIAS.
D3DPRASTERCAPS_PAT
The driver can perform patterned drawing (lines or fills with D3DRENDERSTATE_LINEPATTERN or one of the D3DRENDERSTATE_STIPPLEPATTERN render states) for the primitive being queried.
D3DPRASTERCAPS_ROP2
The device can support raster operations other than R2_COPYPEN.
D3DPRASTERCAPS_STIPPLE
The device can stipple polygons to simulate translucency.
D3DPRASTERCAPS_SUBPIXEL
The device performs subpixel placement of z, color, and texture data, rather than working with the nearest integer pixel coordinate. This helps avoid bleed-through due to z imprecision and jitter of color and texture values for pixels. There is no corresponding state that can be enabled and disabled; the device either performs subpixel placement, or it does not. This bit is present only so that the you can better determine what the rendering quality will be.
D3DPRASTERCAPS_SUBPIXELX
The device is subpixel-accurate along the x-axis only and is clamped to an integer y-axis scan line. For information about subpixel accuracy, see D3DPRASTERCAPS_SUBPIXEL.
D3DPRASTERCAPS_TRANSLUCENTSORTINDEPENDENT
The device supports translucency that is not dependent on the sort order of the polygons. For more information, see D3DRENDERSTATE_TRANSLUCENTSORTINDEPENDENT.
D3DPRASTERCAPS_WBUFFER
The device supports depth buffering using w. For more information, see Depth Buffers.
D3DPRASTERCAPS_WFOG
The device supports w-based fog. W-based fog is used when a perspective projection matrix is specified, but affine projections still use z-based fog. The system considers a projection matrix that contains a nonzero value in the [3][4] element to be a perspective projection matrix.
D3DPRASTERCAPS_XOR
The device can support XOR operations. If this flag is not set but D3DPRIM_RASTER_ROP2 is set, XOR operations must still be supported.
D3DPRASTERCAPS_ZBIAS
The device supports z-bias values. These are integer values assigned to polygons that allow physically coplanar polygons to appear separate. For more information, see D3DRENDERSTATE_ZBIAS in the D3DRENDERSTATETYPE enumerated type.

This flag was introduced in DirectX 5.0.

D3DPRASTERCAPS_ZBUFFERLESSHSR
The device can perform hidden-surface removal (HSR) without requiring the application to sort polygons and without requiring the allocation of a depth-buffer. This leaves more video memory for textures. The method used to perform hidden-surface removal is hardware-dependent and is transparent to the application.

Z-bufferless HSR is performed if no depth-buffer surface is attached to the rendering-target surface and the depth-buffer comparison test is enabled (that is, when the state value associated with the D3DRENDERSTATE_ZENABLE enumeration constant is set to TRUE).

D3DPRASTERCAPS_ZFOG
The device supports z-based fog.

This flag was introduced in DirectX 7.0.

D3DPRASTERCAPS_ZTEST
The device can perform z-test operations. This effectively renders a primitive and indicates whether any z pixels have been rendered.
dwZCmpCaps
Z-buffer comparison capabilities. This member can be one or more of the following:
D3DPCMPCAPS_ALWAYS
Always pass the z test.
D3DPCMPCAPS_EQUAL
Pass the z test if the new z equals the current z.
D3DPCMPCAPS_GREATER
Pass the z test if the new z is greater than the current z.
D3DPCMPCAPS_GREATEREQUAL
Pass the z test if the new z is greater than or equal to the current z.
D3DPCMPCAPS_LESS
Pass the z test if the new z is less than the current z.
D3DPCMPCAPS_LESSEQUAL
Pass the z test if the new z is less than or equal to the current z.
D3DPCMPCAPS_NEVER
Always fail the z test.
D3DPCMPCAPS_NOTEQUAL
Pass the z test if the new z does not equal the current z.
dwSrcBlendCaps
Source-blending capabilities. This member can be one or more of the following. (The RGBA values of the source and destination are indicated by the subscripts s and d.)
D3DPBLENDCAPS_BOTHINVSRCALPHA
Source blend factor is (1–As, 1–As, 1–As, 1–As), and destination blend factor is (As, As, As, As); the destination blend selection is overridden.
D3DPBLENDCAPS_BOTHSRCALPHA
The driver supports the D3DBLEND_BOTHSRCALPHA blend mode. (This blend mode is obsolete for DirectX 6.0 and later. For more information, see D3DBLEND.)
D3DPBLENDCAPS_DESTALPHA
Blend factor is (Ad, Ad, Ad, Ad).
D3DPBLENDCAPS_DESTCOLOR
Blend factor is (Rd, Gd, Bd, Ad).
D3DPBLENDCAPS_INVDESTALPHA
Blend factor is (1–Ad, 1–Ad, 1–Ad, 1–Ad).
D3DPBLENDCAPS_INVDESTCOLOR
Blend factor is (1–Rd, 1–Gd, 1–Bd, 1–Ad).
D3DPBLENDCAPS_INVSRCALPHA
Blend factor is (1–As, 1–As, 1–As, 1–As).
D3DPBLENDCAPS_INVSRCCOLOR
Blend factor is (1–Rd, 1–Gd, 1–Bd, 1–Ad).
D3DPBLENDCAPS_ONE
Blend factor is (1, 1, 1, 1).
D3DPBLENDCAPS_SRCALPHA
Blend factor is (As, As, As, As).
D3DPBLENDCAPS_SRCALPHASAT
Blend factor is (f, f, f, 1); f = min(As, 1-Ad).
D3DPBLENDCAPS_SRCCOLOR
Blend factor is (Rs, Gs, Bs, As).
D3DPBLENDCAPS_ZERO
Blend factor is (0, 0, 0, 0).
dwDestBlendCaps
Destination-blending capabilities. This member can be the same capabilities that are defined for the dwSrcBlendCaps member.
dwAlphaCmpCaps
Alpha-test comparison capabilities. This member can include the same capability flags defined for the dwZCmpCaps member. If this member contains only the D3DPCMPCAPS_ALWAYS capability or only the D3DPCMPCAPS_NEVER capability, the driver does not support alpha tests. Otherwise, the flags identify the individual comparisons that are supported for alpha testing.
dwShadeCaps
Shading operations capabilities. It is assumed, in general, that if a device supports a given command (such as D3DOP_TRIANGLE) at all, it supports the D3DSHADE_FLAT mode (as specified in the D3DSHADEMODE enumerated type). This flag specifies whether the driver can also support Gouraud and Phong shading and whether alpha color components are supported for each of the three color-generation modes. When alpha components are not supported in a given mode, the alpha value of colors generated in that mode is implicitly 255. This is the maximum possible alpha (that is, the alpha component is at full intensity). Phong shading is not currently supported.

With the monochromatic shading modes, the blue channel of the specular component is interpreted as a white intensity. (This is controlled by the D3DRENDERSTATE_MONOENABLE render state.)

The color, specular highlights, fog, and alpha interpolants of a triangle each have capability flags that an application can use to find out how they are implemented by the device driver. These are modified by the shading mode, color model, and whether the alpha component of a color is blended or stippled. For more information, see 3-D Primitives.

This member can be one or more of the following:

D3DPSHADECAPS_ALPHAFLATBLEND
D3DPSHADECAPS_ALPHAFLATSTIPPLED
Device can support an alpha component for flat blended and stippled transparency, respectively (the D3DSHADE_FLAT state for the D3DSHADEMODE enumerated type). In these modes, the alpha color component for a primitive is provided as part of the color for the first vertex of the primitive.
D3DPSHADECAPS_ALPHAGOURAUDBLEND
D3DPSHADECAPS_ALPHAGOURAUDSTIPPLED
Device can support an alpha component for Gouraud-blended and stippled transparency, respectively (the D3DSHADE_GOURAUD state for the D3DSHADEMODE enumerated type). In these modes, the alpha color component of a primitive is provided at vertices and interpolated across a face along with the other color components.
D3DPSHADECAPS_ALPHAPHONGBLEND
D3DPSHADECAPS_ALPHAPHONGSTIPPLED
Device can support an alpha component for Phong-blended and stippled transparency, respectively (the D3DSHADE_PHONG state for the D3DSHADEMODE enumerated type). In these modes, vertex parameters are reevaluated on a per-pixel basis, applying lighting effects for the red, green, and blue color components. Phong shading is not currently supported.
D3DPSHADECAPS_COLORFLATMONO
D3DPSHADECAPS_COLORFLATRGB
Device can support colored flat shading in the D3DCOLOR_MONO and D3DCOLOR_RGB color models, respectively. In these modes, the color component for a primitive is provided as part of the color for the first vertex of the primitive. In the monochromatic lighting model, only the blue component of the color is interpolated; in the RGB lighting model, the red, green, and blue components are interpolated.
D3DPSHADECAPS_COLORGOURAUDMONO
D3DPSHADECAPS_COLORGOURAUDRGB
Device can support colored Gouraud shading in the D3DCOLOR_MONO and D3DCOLOR_RGB color models, respectively. In these modes, the color component for a primitive is provided at vertices and interpolated across a face along with the other color components. In the monochromatic lighting model, only the blue component of the color is interpolated; in the RGB lighting model, the red, green, and blue components are interpolated.
D3DPSHADECAPS_COLORPHONGMONO
D3DPSHADECAPS_COLORPHONGRGB
Device can support colored Phong shading in the D3DCOLOR_MONO and D3DCOLOR_RGB color models, respectively. In these modes, vertex parameters are reevaluated on a per-pixel basis. Lighting effects are applied for the red, green, and blue color components in the RGB model, and for the blue component only for the monochromatic model. Phong shading is not currently supported.
D3DPSHADECAPS_FOGFLAT
D3DPSHADECAPS_FOGGOURAUD
D3DPSHADECAPS_FOGPHONG
Device can support fog in the flat, Gouraud, and Phong shading modes, respectively. Phong shading is not currently supported.
D3DPSHADECAPS_SPECULARFLATMONO
D3DPSHADECAPS_SPECULARFLATRGB
Device can support specular highlights in flat shading in the D3DCOLOR_MONO and D3DCOLOR_RGB color models, respectively.
D3DPSHADECAPS_SPECULARGOURAUDMONO
D3DPSHADECAPS_SPECULARGOURAUDRGB
Device can support specular highlights in Gouraud shading in the D3DCOLOR_MONO and D3DCOLOR_RGB color models, respectively.
D3DPSHADECAPS_SPECULARPHONGMONO
D3DPSHADECAPS_SPECULARPHONGRGB
Device can support specular highlights in Phong shading in the D3DCOLOR_MONO and D3DCOLOR_RGB color models, respectively. Phong shading is not currently supported.
dwTextureCaps
Miscellaneous texture-mapping capabilities. This member can be one or more of the following:
D3DPTEXTURECAPS_ALPHA
Supports RGBA textures in the D3DTBLEND_DECAL and D3DTBLEND_MODULATE texture filtering modes. If this capability is not set, only RGB textures are supported in those modes. Regardless of the setting of this flag, alpha must always be supported in D3DTBLEND_DECALMASK, D3DTBLEND_DECALALPHA, and D3DTBLEND_MODULATEALPHA filtering modes whenever those filtering modes are available.
D3DPTEXTURECAPS_ALPHAPALETTE
Supports palettized texture surfaces whose palettes contain alpha information (see DDPCAPS_ALPHA in the DDCAPS structure).
D3DPTEXTURECAPS_BORDER
Superseded by D3DPTADDRESSCAPS_BORDER.
D3DPTEXTURECAPS_COLORKEYBLEND
The device supports alpha-blended colorkeying through the use of the D3DRENDERSTATE_COLORKEYBLENDENABLE render state.
D3DPTEXTURECAPS_CUBEMAP
Supports cubic environment mapping. This capability flag was introduced with DirectX 7.0
D3DPTEXTURECAPS_NONPOW2CONDITIONAL
Conditionally supports the use of textures with dimensions that are not powers of 2. A device that exposes this capability can use such a texture if all of the following requirements are met.
  • The texture addressing mode for the texture stage is set to D3DTADDRESS_CLAMP.
  • Texture wrapping for the texture stage is disabled (D3DRENDERSTATE_WRAPn set to 0).
  • Mipmapping is not in use. (Mipmapped textures must have dimensions that are powers of 2.)
D3DPTEXTURECAPS_PERSPECTIVE
Perspective correction is supported.
D3DPTEXTURECAPS_POW2
All nonmipmapped textures must have widths and heights specified as powers of 2. (Mipmapped textures must always have dimensions that are powers of 2.)
D3DPTEXTURECAPS_PROJECTED
Supports the D3DTTFF_PROJECTED texture transformation flag. When applied, the device divides transformed texture coordinates by the last texture coordinate.
D3DPTEXTURECAPS_SQUAREONLY
All textures must be square.
D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE
Texture indices are not scaled by the texture size prior to interpolation.

This flag was introduced with DirectX 7.0

D3DPTEXTURECAPS_TRANSPARENCY
Texture transparency is supported. (Only those texels that are not the current transparent color are drawn.)
dwTextureFilterCaps
Texture-filtering capabilities. General texture-filtering flags reflect which texture-filtering modes are supported and can be set for the D3DTSS_MAGFILTER, D3DTSS_MINFILTER, or D3DTSS_MIPFILTER texture-stage states. Per-stage filtering capabilities reflect which filtering modes are supported for texture stages when performing multiple-texture blending with the IDirect3DDevice7 interface. This member can be any combination of the following general and per-stage texture-filtering flags:
General texture-filtering flags
D3DPTFILTERCAPS_LINEAR
Bilinear filtering. Chooses the texel that has the nearest coordinates, then performs a weighted average with the four surrounding texels to determine the final color. This applies to both zooming in and zooming out. If either zooming in or zooming out is supported, both must be supported.
D3DPTFILTERCAPS_LINEARMIPLINEAR
Trilinear interpolation between mipmaps. Performs bilinear filtering on the two nearest mipmaps, then interpolates linearly between the two colors to determine a final color.
D3DPTFILTERCAPS_LINEARMIPNEAREST
Linear interpolation between two point-sample mipmaps. Chooses the nearest texel from the two closest mipmap levels, then performs linear interpolation between them.
D3DPTFILTERCAPS_MIPLINEAR
Nearest mipmapping, with bilinear filtering applied to the result. Chooses the texel from the appropriate mipmap that has the nearest coordinates, then performs a weighted average with the four surrounding texels to determine the final color.
D3DPTFILTERCAPS_MIPNEAREST
Nearest mipmapping. Chooses the texel from the appropriate mipmap with coordinates nearest to the desired pixel value.
D3DPTFILTERCAPS_NEAREST
Point sampling. The texel with coordinates nearest to the desired pixel value is used. This applies to both zooming in and zooming out. If either zooming in or zooming out is supported, both must be supported.
Per-stage texture filtering flags
D3DPTFILTERCAPS_MAGFAFLATCUBIC
The device supports per-stage flat cubic filtering for magnifying textures. The flat cubic magnification filter is represented by the D3DTFG_FLATCUBIC member of the D3DTEXTUREMAGFILTER enumerated type.
D3DPTFILTERCAPS_MAGFANISOTROPIC
The device supports per-stage anisotropic filtering for magnifying textures. The anisotropic magnification filter is represented by the D3DTFG_ANISOTROPIC member of the D3DTEXTUREMAGFILTER enumerated type.
D3DPTFILTERCAPS_MAGFGAUSSIANCUBIC
The device supports the per-stage Gaussian cubic filtering for magnifying textures. The Gaussian cubic magnification filter is represented by the D3DTFG_GAUSSIANCUBIC member of the D3DTEXTUREMAGFILTER enumerated type.
D3DPTFILTERCAPS_MAGFLINEAR
The device supports per-stage bilinear interpolation filtering for magnifying textures. The bilinear interpolation magnification filter is represented by the D3DTFG_LINEAR member of the D3DTEXTUREMAGFILTER enumerated type.
D3DPTFILTERCAPS_MAGFPOINT
The device supports per-stage point-sample filtering for magnifying textures. The point-sample magnification filter is represented by the D3DTFG_POINT member of the D3DTEXTUREMAGFILTER enumerated type.
D3DPTFILTERCAPS_MINFANISOTROPIC
The device supports per-stage anisotropic filtering for minifying textures. The anisotropic minification filter is represented by the D3DTFN_ANISOTROPIC member of the D3DTEXTUREMINFILTER enumerated type.
D3DPTFILTERCAPS_MINFLINEAR
The device supports per-stage bilinear interpolation filtering for minifying textures. The bilinear minification filter is represented by the D3DTFN_LINEAR member of the D3DTEXTUREMINFILTER enumerated type.
D3DPTFILTERCAPS_MINFPOINT
The device supports per-stage point-sample filtering for minifying textures. The point-sample minification filter is represented by the D3DTFN_POINT member of the D3DTEXTUREMINFILTER enumerated type.
D3DPTFILTERCAPS_MIPFLINEAR
The device supports per-stage trilinear interpolation filtering for mipmaps. The trilinear interpolation mipmapping filter is represented by the D3DTFP_LINEAR member of the D3DTEXTUREMIPFILTER enumerated type.
D3DPTFILTERCAPS_MIPFPOINT
The device supports per-stage point-sample filtering for mipmaps. The point-sample mipmapping filter is represented by the D3DTFP_POINT member of the D3DTEXTUREMIPFILTER enumerated type.
dwTextureBlendCaps
Not used.

In previous releases of DirectX, this member contained information about the driver's capability for applying texture-blending through the now-obsolete D3DRENDERSTATE_TEXTUREMAPBLEND render state. Information about the texture-blending capabilities for a DirectX 7.0 device is exposed in the dwTextureOpCaps member of the D3DDEVICEDESC7 structure.

dwTextureAddressCaps
Texture-addressing capabilities. This member can be one or more of the following:
D3DPTADDRESSCAPS_BORDER
Device supports setting coordinates outside the range [0.0, 1.0] to the border color, as specified by the D3DTSS_BORDERCOLOR texture-stage state.
D3DPTADDRESSCAPS_CLAMP
Device can clamp textures to addresses.
D3DPTADDRESSCAPS_INDEPENDENTUV
Device can separate the texture-addressing modes of the u and v coordinates of the texture. This ability corresponds to the D3DTSS_ADDRESSU and D3DTSS_ADDRESSV render-state values.

This flag was introduced in DirectX 5.0.

D3DPTADDRESSCAPS_MIRROR
Device can mirror textures to addresses.
D3DPTADDRESSCAPS_WRAP
Device can wrap textures to addresses.
dwStippleWidth and dwStippleHeight
Maximum width and height of the supported stipple (up to 32×32).

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dcaps.h.


D3DRECT

The D3DRECT structure is a rectangle definition.

typedef struct _D3DRECT {
    union {
        LONG x1;
        LONG lX1;
    };
    union {
        LONG y1;
        LONG lY1;
    };
    union {
        LONG x2;
        LONG lX2;
    };
    union {
        LONG y2;
        LONG lY2;
    };
} D3DRECT, *LPD3DRECT;

Members

lX1 and lY1
Coordinates of the upper-left corner of the rectangle.
lX2 and lY2
Coordinates of the lower-right corner of the rectangle.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.

See Also

IDirect3DDevice7::Clear


D3DTLVERTEX

The D3DTLVERTEX structure defines a transformed and lit vertex (screen coordinates with color).

typedef struct _D3DTLVERTEX {
    union {
        D3DVALUE sx;
        D3DVALUE dvSX;
    };
    union {
        D3DVALUE sy;
        D3DVALUE dvSY;
    };
    union {
        D3DVALUE sz;
        D3DVALUE dvSZ;
    };
    union {
        D3DVALUE rhw;
        D3DVALUE dvRHW;
    };
    union {
        D3DCOLOR color;
        D3DCOLOR dcColor;
    };
    union {
        D3DCOLOR specular;
        D3DCOLOR dcSpecular;
    };
    union {
        D3DVALUE tu;
        D3DVALUE dvTU;
    };
    union {
        D3DVALUE tv;
        D3DVALUE dvTV;
    };
} D3DTLVERTEX, *LPD3DTLVERTEX;

Parameters

dvSX, dvSY, and dvSZ
Values of the D3DVALUE type describing a vertex in screen coordinates. The largest allowable value for dvSZ is 0.99999 if you want the vertex to be within the range of z-values that are displayed.
dvRHW
Value of the D3DVALUE type that is the reciprocal of homogeneous w from homogeneous coordinates (x,y,z,w). This value is often 1 divided by the distance from the origin to the object along the z-axis.
dcColor and dcSpecular
Values of the D3DCOLOR type describing the color and specular component of the vertex.
dvTU and dvTV
Values of the D3DVALUE type describing the texture coordinates of the vertex.

Remarks

Direct3D uses the current viewport parameters (the dwX, dwY, dwWidth, and dwHeight members of the D3DVIEWPORT7 structure) to clip D3DTLVERTEX vertices. The system always clips z-coordinates to [0, 1]. To prevent the system from clipping these vertices, use the D3DDP_DONOTCLIP flag when calling rendering methods.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.

See Also

D3DLVERTEX, D3DVERTEX


D3DVECTOR

The D3DVECTOR structure defines a vector for many Direct3D and Direct3DRM methods and structures.

typedef struct _D3DVECTOR {
    union {
        D3DVALUE x;
        D3DVALUE dvX;
    };
    union {
        D3DVALUE y;
        D3DVALUE dvY;
    };
    union {
        D3DVALUE z;
        D3DVALUE dvZ;
    };
} D3DVECTOR, *LPD3DVECTOR;

Members

dvX, dvY, and dvZ
Values of the D3DVALUE type describing the vector.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.


D3DVERTEX

The D3DVERTEX structure defines an untransformed and unlit vertex (model coordinates with normal direction vector).

typedef struct _D3DVERTEX {
    union {
        D3DVALUE x;
        D3DVALUE dvX;
    };
    union {
        D3DVALUE y;
        D3DVALUE dvY;
    };
    union {
        D3DVALUE z;
        D3DVALUE dvZ;
    };
    union {
        D3DVALUE nx;
        D3DVALUE dvNX;
    };
    union {
        D3DVALUE ny;
        D3DVALUE dvNY;
    };
    union {
        D3DVALUE nz;
        D3DVALUE dvNZ;
    };
    union {
        D3DVALUE tu;
        D3DVALUE dvTU;
    };
    union {
        D3DVALUE tv;
        D3DVALUE dvTV;
    };
} D3DVERTEX, *LPD3DVERTEX;

Members

dvX, dvY, and dvZ
Values of the D3DVALUE type describing the homogeneous coordinates of the vertex.
dvNX, dvNY, and dvNZ
Values of the D3DVALUE type describing the normal coordinates of the vertex.
dvTU and dvTV
Values of the D3DVALUE type describing the texture coordinates of the vertex.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.

See Also

D3DLVERTEX, D3DTLVERTEX, D3DVALUE


D3DVERTEXBUFFERDESC

The D3DVERTEXBUFFERDESC structure describes the properties of a vertex buffer object. This structure is used with the IDirect3D7::CreateVertexBuffer and IDirect3DVertexBuffer7::GetVertexBufferDesc methods.

typedef struct _D3DVERTEXBUFFERDESC {
    DWORD dwSize;
    DWORD dwCaps;
    DWORD dwFVF;
    DWORD dwNumVertices;
} D3DVERTEXBUFFERDESC, *LPD3DVERTEXBUFFERDESC;

Members

dwSize
Size of this structure, in bytes. This member must be initialized before the structure is used.
dwCaps
Capability flags that describe the vertex buffer and identify whether the vertex buffer can contain optimized vertex data. This parameter can be any combination of the following flags:
(none)
The vertex buffer should be created in whatever memory the driver chooses, to allow efficient read operations.
D3DVBCAPS_DONOTCLIP
The vertex buffer cannot contain clipping information.
D3DVBCAPS_OPTIMIZED
The vertex buffer can contain optimized vertex data. (This flag is not used when creating a new vertex buffer.)
D3DVBCAPS_SYSTEMMEMORY
The vertex buffer should be created in system memory. Use this capability for vertex buffers to be rendered by using software devices (MMX and RGB devices).
D3DVBCAPS_WRITEONLY
Informs the system that the application only writes to the vertex buffer. Using this flag enables the driver to choose the best memory location for efficient write operations and rendering. Attempts to read from a vertex buffer that is created with this capability can result in degraded performance.
dwFVF
A combination of flexible vertex format flags that describes the vertex format of the vertices in this buffer.
dwNumVertices
The maximum number of vertices that this vertex buffer can contain. The maximum number of vertices allowed is D3DMAXNUMVERTICES (0xFFFF).

Remarks

Software devices—MMX and RGB devices—cannot render from a video memory (local or nonlocal) vertex buffer. If you want to render a vertex buffer, using a software device, the vertex buffer must exist in system memory. Hardware devices can render from system memory or video memory vertex buffers.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 6.0 or later.
Header: Declared in d3dtypes.h.

See Also

Vertex Buffer Descriptions, Vertex Buffers


D3DVIEWPORT7

The D3DVIEWPORT7 structure defines the window dimensions of a render target surface onto which a 3-D volume projects. This structure is used with the IDirect3DDevice7::GetViewport and IDirect3DDevice7::SetViewport methods.

typedef struct _D3DVIEWPORT7{
    DWORD       dwX;
    DWORD       dwY;
    DWORD       dwWidth;
    DWORD       dwHeight;
    D3DVALUE    dvMinZ;
    D3DVALUE    dvMaxZ;
} D3DVIEWPORT7, *LPD3DVIEWPORT7

Members

dwX and dwY
Pixel coordinates of the upper-left corner of the viewport on the render target surface. Unless you want to render to a subset of the surface, these members can be set to 0.
dwWidth and dwHeight
Dimensions of the viewport on the render target surface, in pixels. Unless you are rendering only to a subset of the surface, these members should be set to the dimensions of the render target surface.
dvMinZ and dvMaxZ
Values of the D3DVALUE type describing the range of depth values into which a scene is to be rendered. Most applications set these values to 0.0 and 1.0, respectively. The interpretation of the values in these members is completely different from the corresponding members in the legacy D3DVIEWPORT2 structure. Clipping in DirectX 7.0 is performed after applying the projection matrix. For more information, see Clipping Volumes and The Projection Transformation.

Remarks

This structure, introduced in DirectX 7.0, supersedes the D3DVIEWPORT2 and D3DVIEWPORT structures used with previous versions of DirectX.

The dwX, dwY, dwWidth, and dwHeight members describe the position and dimensions of the viewport on the render target surface. Usually, applications render to the entire target surface; when rendering on a 640x480 surface, these members should be 0, 0, 640, and 480, respectively. The dvMinZ and dvMaxZ are typically set to 0.0 and 1.0 but can be set to other values to achieve specific effects. For example, you might set them both to 0.0 to force the system to render objects to the foreground of a scene, or both to 1.0 to force the objects into the background.

When the viewport parameters for a device change (due to a call to the IDirect3DDevice7::SetViewport method), the driver builds a new transformation matrix.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dtypes.h.

See Also

D3DVALUE, IDirect3DDevice7::GetViewport, IDirect3DDevice7::SetViewport, Clipping Volumes, Viewports and Clipping


Obsolete Structures

The following structures are obsolete. In some cases, the functionality provided by obsolete structures is now present within the IDirect3DDevice7 interface and its related structures. To summarize the relationships:

D3DDEVICEDESC
Superseded by the D3DDEVICEDESC7 structure used with the IDirect3DDevice7::GetCaps method.
D3DHVERTEX
Not supported.
D3DFINDDEVICESEARCH and D3DFINDDEVICERESULT
Obsolete.
D3DLIGHT and D3DLIGHT2
Superseded by the D3DLIGHT7 structure used with the IDirect3DDevice7::GetLight and IDirect3DDevice7::SetLight methods.
D3DLIGHTDATA
Not supported.
D3DLIGHTINGELEMENT
Not supported.
D3DMATERIAL
Superseded by the D3DMATERIAL7 structure used with the IDirect3DDevice7::GetMaterial and IDirect3DDevice7::SetMaterial methods.
D3DSTATE
Not supported.
D3DSTATS
Not supported.
D3DTRANSFORMCAPS
Not supported.
D3DTRANSFORMDATA
Not supported.
D3DVIEWPORT and D3DVIEWPORT2
Superseded by the D3DVIEWPORT7 structure used with the IDirect3DDevice7::GetViewport and IDirect3DDevice7::SetViewport methods.

Execute-buffer rendering, and the following related structures, is considered obsolete with DirectX 7.0. For information about these structures, see the documentation provided with a previous release of DirectX. Legacy documentation is provided with this SDK and is available for download from http://www.microsoft.com/directx.

  • D3DBRANCH
  • D3DEXECUTEBUFFERDESC
  • D3DEXECUTEDATA
  • D3DINSTRUCTION
  • D3DLINE
  • D3DMATRIXLOAD
  • D3DMATRIXMULTIPLY
  • D3DPICKRECORD
  • D3DPOINT
  • D3DPROCESSVERTICES
  • D3DSPAN
  • D3DSTATUS
  • D3DTEXTURELOAD
  • D3DTRIANGLE


Enumerated Types

This section contains information about the following enumerated types used with Direct3D Immediate Mode.

  • D3DANTIALIASMODE
  • D3DBLEND
  • D3DCMPFUNC
  • D3DCULL
  • D3DFILLMODE
  • D3DFOGMODE
  • D3DLIGHTTYPE
  • D3DMATERIALCOLORSOURCE
  • D3DPRIMITIVETYPE
  • D3DRENDERSTATETYPE
  • D3DSHADEMODE
  • D3DSTATEBLOCKTYPE
  • D3DSTENCILOP
  • D3DTEXTUREADDRESS
  • D3DTEXTUREMAGFILTER
  • D3DTEXTUREMINFILTER
  • D3DTEXTUREMIPFILTER
  • D3DTEXTUREOP
  • D3DTEXTURESTAGESTATETYPE
  • D3DTEXTURETRANSFORMFLAGS
  • D3DTRANSFORMSTATETYPE
  • D3DVERTEXBLENDFLAGS
  • D3DVERTEXTYPE
  • D3DZBUFFERTYPE


D3DANTIALIASMODE

The D3DANTIALIASMODE enumerated type defines the supported antialiasing mode for the D3DRENDERSTATE_ANTIALIAS value in the D3DRENDERSTATETYPE enumerated type. These values define the settings only for full-scene antialiasing (for more information, see Antialiasing).

typedef enum _D3DANTIALIASMODE {
    D3DANTIALIAS_NONE          = 0,
    D3DANTIALIAS_SORTDEPENDENT = 1,
    D3DANTIALIAS_SORTINDEPENDENT = 2
    D3DANTIALIAS_FORCE_DWORD     = 0x7fffffff,
} D3DANTIALIASMODE;
D3DANTIALIAS_NONE
No antialiasing is performed. This is the default setting.
D3DANTIALIAS_SORTDEPENDENT
Antialiasing is dependent on the sort order of the polygons (back to front or front to back). The application must draw polygons in the right order for antialiasing to occur.
D3DANTIALIAS_SORTINDEPENDENT
Antialiasing is not dependent on the sort order of the polygons.
D3DANTIALIAS_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.


D3DBLEND

The D3DBLEND enumerated type defines the supported blend mode for the D3DRENDERSTATE_DESTBLEND values in the D3DRENDERSTATETYPE enumerated type. In the member descriptions that follow, the RGBA values of the source and destination are indicated by the subscripts s and d.

typedef enum _D3DBLEND {
    D3DBLEND_ZERO            = 1,
    D3DBLEND_ONE             = 2,
    D3DBLEND_SRCCOLOR        = 3,
    D3DBLEND_INVSRCCOLOR     = 4,
    D3DBLEND_SRCALPHA        = 5,
    D3DBLEND_INVSRCALPHA     = 6,
    D3DBLEND_DESTALPHA       = 7,
    D3DBLEND_INVDESTALPHA    = 8,
    D3DBLEND_DESTCOLOR       = 9,
    D3DBLEND_INVDESTCOLOR    = 10,
    D3DBLEND_SRCALPHASAT     = 11,
    D3DBLEND_BOTHSRCALPHA    = 12,
    D3DBLEND_BOTHINVSRCALPHA = 13,
    D3DBLEND_FORCE_DWORD   = 0x7fffffff,
} D3DBLEND;
D3DBLEND_ZERO
Blend factor is (0, 0, 0, 0).
D3DBLEND_ONE
Blend factor is (1, 1, 1, 1).
D3DBLEND_SRCCOLOR
Blend factor is (Rs, Gs, Bs, As).
D3DBLEND_INVSRCCOLOR
Blend factor is (1–Rs, 1–Gs, 1–Bs, 1–As).
D3DBLEND_SRCALPHA
Blend factor is (As, As, As, As).
D3DBLEND_INVSRCALPHA
Blend factor is (1–As, 1–As, 1–As, 1–As).
D3DBLEND_DESTALPHA
Blend factor is (Ad, Ad, Ad, Ad).
D3DBLEND_INVDESTALPHA
Blend factor is (1–Ad, 1–Ad, 1–Ad, 1–Ad).
D3DBLEND_DESTCOLOR
Blend factor is (Rd, Gd, Bd, Ad).
D3DBLEND_INVDESTCOLOR
Blend factor is (1–Rd, 1–Gd, 1–Bd, 1–Ad).
D3DBLEND_SRCALPHASAT
Blend factor is (f, f, f, 1); f = min(As, 1–Ad).
D3DBLEND_BOTHSRCALPHA
Obsolete. For DirectX 6.0 and later, you can achieve the same affect by setting the source and destination blend factors to D3DBLEND_SRCALPHA and D3DBLEND_INVSRCALPHA in separate calls.
D3DBLEND_BOTHINVSRCALPHA
Source blend factor is (1–As, 1–As, 1–As, 1–As), and destination blend factor is (As, As, As, As); the destination blend selection is overridden. This blend mode is supported only for the D3DRENDERSTATE_SRCBLEND render state.
D3DBLEND_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.


D3DCMPFUNC

The D3DCMPFUNC enumerated type defines the supported compare functions for the D3DRENDERSTATE_ZFUNC, D3DRENDERSTATE_ALPHAFUNC, and D3DRENDERSTATE_STENCILFUNC render states.

typedef enum _D3DCMPFUNC {
    D3DCMP_NEVER        = 1,
    D3DCMP_LESS         = 2,
    D3DCMP_EQUAL        = 3,
    D3DCMP_LESSEQUAL    = 4,
    D3DCMP_GREATER      = 5,
    D3DCMP_NOTEQUAL     = 6,
    D3DCMP_GREATEREQUAL = 7,
    D3DCMP_ALWAYS       = 8,
    D3DCMP_FORCE_DWORD   = 0x7fffffff,
} D3DCMPFUNC;
D3DCMP_NEVER
Always fail the test.
D3DCMP_LESS
Accept the new pixel if its value is less than the value of the current pixel.
D3DCMP_EQUAL
Accept the new pixel if its value equals the value of the current pixel.
D3DCMP_LESSEQUAL
Accept the new pixel if its value is less than or equal to the value of the current pixel.
D3DCMP_GREATER
Accept the new pixel if its value is greater than the value of the current pixel.
D3DCMP_NOTEQUAL
Accept the new pixel if its value does not equal the value of the current pixel.
D3DCMP_GREATEREQUAL
Accept the new pixel if its value is greater than or equal to the value of the current pixel.
D3DCMP_ALWAYS
Always pass the test.
D3DCMP_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.


D3DCULL

The D3DCULL enumerated type defines the supported culling modes used with the D3DRENDERSTATE_CULLMODE render state. These define how back faces are culled when rendering a geometry.

typedef enum _D3DCULL {
    D3DCULL_NONE = 1,
    D3DCULL_CW   = 2,
    D3DCULL_CCW  = 3,
    D3DCULL_FORCE_DWORD   = 0x7fffffff,
} D3DCULL;
D3DCULL_NONE
Do not cull back faces.
D3DCULL_CW
Cull back faces with clockwise vertices.
D3DCULL_CCW
Cull back faces with counterclockwise vertices.
D3DCULL_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.

See Also

D3DPRIMCAPS, D3DRENDERSTATETYPE


D3DFILLMODE

The D3DFILLMODE enumerated type contains constants describing the fill mode. These values are used by the D3DRENDERSTATE_FILLMODE render state in the D3DRENDERSTATETYPE enumerated type.

typedef enum _D3DFILLMODE {
    D3DFILL_POINT     = 1,
    D3DFILL_WIREFRAME = 2,
    D3DFILL_SOLID     = 3
    D3DFILL_FORCE_DWORD   = 0x7fffffff,
} D3DFILLMODE;
D3DFILL_POINT
Fill points.
D3DFILL_WIREFRAME
Fill wireframes. This fill mode currently does not work for clipped primitives when you are using the DrawPrimitive methods.
D3DFILL_SOLID
Fill solids.
D3DFILL_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.


D3DFOGMODE

The D3DFOGMODE enumerated type contains constants describing the fog mode. These values are used by the D3DRENDERSTATE_FOGTABLEMODE and D3DRENDERSTATE_FOGVERTEXMODE render state in the D3DRENDERSTATETYPE enumerated type.

typedef enum _D3DFOGMODE {
    D3DFOG_NONE   = 0,
    D3DFOG_EXP    = 1,
    D3DFOG_EXP2   = 2,
    D3DFOG_LINEAR = 3
    D3DFOG_FORCE_DWORD   = 0x7fffffff,
} D3DFOGMODE;
D3DFOG_NONE
No fog effect.
D3DFOG_EXP
The fog effect intensifies exponentially, according to the following formula:

D3DFOG_EXP2
The fog effect intensifies exponentially with the square of the distance, according to the following formula:

D3DFOG_LINEAR
The fog effect intensifies linearly between the start and end points, according to the following formula:

This is the only fog mode currently supported.

D3DFOG_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

In monochromatic (ramp) lighting mode, fog works properly only when the fog color is black. (If there is no lighting, any fog color works since, in this case, any fog color is effectively black.)

For more information, see Fog.

Note Fog can be considered a measure of visibility—the lower the fog value produced by one of the fog equations, the less visible an object is.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.


D3DLIGHTTYPE

The D3DLIGHTTYPE enumerated type defines the light type. This enumerated type is used with the D3DLIGHT7 structure.

typedef enum _D3DLIGHTTYPE {
    D3DLIGHT_POINT         = 1,
    D3DLIGHT_SPOT          = 2,
    D3DLIGHT_DIRECTIONAL   = 3,
    D3DLIGHT_FORCE_DWORD   = 0x7fffffff,
} D3DLIGHTTYPE;
D3DLIGHT_POINT
Light is a point source. The light has a position in space and radiates light in all directions.
D3DLIGHT_SPOT
Light is a spotlight source. This light is like a point light, except that the illumination is limited to a cone. This light type has a direction and several other parameters that determine the shape of the cone it produces. For information about these parameters, see the D3DLIGHT7 structure.
D3DLIGHT_DIRECTIONAL
Light is a directional source. This is equivalent to using a point light source at an infinite distance.
D3DLIGHT_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Directional lights are slightly faster than point light sources, but point lights look a little better. Spotlights offer interesting visual effects but are computationally expensive.

Parallel-point lights are not supported in DirectX 7.0 and later. Therefore, this enumerated type does not contain the legacy D3DLIGHT_PARALLELPOINT member.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.


D3DMATERIALCOLORSOURCE

The D3DMATERIALCOLORSOURCE enumerated type defines the location at which a color or color component must be accessed for lighting calculations.

typedef enum _D3DMATERIALCOLORSOURCE {
    D3DMCS_MATERIAL    = 0,
    D3DMCS_COLOR1      = 1,
    D3DMCS_COLOR2      = 2,
    D3DMCS_FORCE_DWORD = 0x7fffffff,
} D3DMATERIALCOLORSOURCE;
D3DMCS_MATERIAL
Use the color from the current material.
D3DMCS_COLOR1
Use the diffuse vertex color.
D3DMCS_COLOR2
Use the specular vertex color.
D3DMCS_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The values defined by this enumeration are used with the following render states:

  • D3DRENDERSTATE_DIFFUSEMATERIALSOURCE
  • D3DRENDERSTATE_SPECULARMATERIALSOURCE
  • D3DRENDERSTATE_AMBIENTMATERIALSOURCE
  • D3DRENDERSTATE_EMISSIVEMATERIALSOURCE

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dtypes.h.


D3DPRIMITIVETYPE

The D3DPRIMITIVETYPE enumerated type lists the primitives supported by DrawPrimitive methods. This type was introduced in DirectX 5.0.

typedef enum _D3DPRIMITIVETYPE {
    D3DPT_POINTLIST     = 1,
    D3DPT_LINELIST      = 2,
    D3DPT_LINESTRIP     = 3,
    D3DPT_TRIANGLELIST  = 4,
    D3DPT_TRIANGLESTRIP = 5,
    D3DPT_TRIANGLEFAN   = 6
    D3DPT_FORCE_DWORD   = 0x7fffffff,
} D3DPRIMITIVETYPE;
D3DPT_POINTLIST
Renders the vertices as a collection of isolated points.
D3DPT_LINELIST
Renders the vertices as a list of isolated straight line segments. Calls using this primitive type fail if the count is less than 2 or is odd.
D3DPT_LINESTRIP
Renders the vertices as a single polyline. Calls using this primitive type fail if the count is less than 2.
D3DPT_TRIANGLELIST
Renders the specified vertices as a sequence of isolated triangles. Each group of three vertices defines a separate triangle. Calls using this primitive type fail if the count is less than 3 or not evenly divisible by 3.

Backface culling is affected by the current winding-order render state.

D3DPT_TRIANGLESTRIP
Renders the vertices as a triangle strip. Calls using this primitive type fail if the count is less than 3. The backface-culling flag is automatically flipped on even-numbered triangles.
D3DPT_TRIANGLEFAN
Renders the vertices as a triangle fan. Calls using this primitive type fail if the count is less than 3.
D3DPT_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Using triangle strips or fans is often more efficient than using triangle lists because fewer vertices are duplicated. For more information, see Triangle Strips and Triangle Fans.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.

See Also

IDirect3DDevice7::DrawIndexedPrimitive, IDirect3DDevice7::DrawIndexedPrimitiveStrided, IDirect3DDevice7::DrawIndexedPrimitiveVB, IDirect3DDevice7::DrawPrimitive, IDirect3DDevice7::DrawPrimitiveStrided, IDirect3DDevice7::DrawPrimitiveVB, Primitive Types


D3DRENDERSTATETYPE

The D3DRENDERSTATETYPE enumerated type defines device render states that are set and retrieved through the IDirect3DDevice7::SetRenderState and IDirect3DDevice7::GetRenderState methods.

typedef enum _D3DRENDERSTATETYPE {
    D3DRENDERSTATE_ANTIALIAS          = 2,    //Antialiasing mode
    D3DRENDERSTATE_TEXTUREPERSPECTIVE = 4,    //Perspective correction
    D3DRENDERSTATE_ZENABLE            = 7,    //Enable z test
    D3DRENDERSTATE_FILLMODE           = 8,    //Fill mode
    D3DRENDERSTATE_SHADEMODE          = 9,    //Shade mode
    D3DRENDERSTATE_LINEPATTERN        = 10,   //Line pattern
    D3DRENDERSTATE_ZWRITEENABLE       = 14,   //Enable z writes
    D3DRENDERSTATE_ALPHATESTENABLE    = 15,   //Enable alpha tests
    D3DRENDERSTATE_LASTPIXEL          = 16,   //Draw last pixel in a line
    D3DRENDERSTATE_SRCBLEND           = 19,   //Blend factor for source
    D3DRENDERSTATE_DESTBLEND          = 20,   //Blend factor for destination
    D3DRENDERSTATE_CULLMODE           = 22,   //Back-face culling mode
    D3DRENDERSTATE_ZFUNC              = 23,   //Z-comparison function
    D3DRENDERSTATE_ALPHAREF           = 24,   //Reference alpha value
    D3DRENDERSTATE_ALPHAFUNC          = 25,   //Alpha-comparison function
    D3DRENDERSTATE_DITHERENABLE       = 26,   //Enable dithering
    D3DRENDERSTATE_ALPHABLENDENABLE   = 27,   //Enable alpha blending
    D3DRENDERSTATE_FOGENABLE          = 28,   //Enable fog
    D3DRENDERSTATE_SPECULARENABLE     = 29,   //Enable specular highlights
    D3DRENDERSTATE_ZVISIBLE           = 30,   //Enable z-checking
    D3DRENDERSTATE_STIPPLEDALPHA      = 33,   //Enable stippled alpha
    D3DRENDERSTATE_FOGCOLOR           = 34,   //Fog color
    D3DRENDERSTATE_FOGTABLEMODE       = 35,   //Fog mode
    D3DRENDERSTATE_FOGTABLESTART      = 36,   //Fog table start (same as D3DRENDERSTATE_FOGSTART)
    D3DRENDERSTATE_FOGTABLEEND        = 37,   //Fog table end (same as D3DRENDERSTATE_FOGEND)
    D3DRENDERSTATE_FOGTABLEDENSITY    = 38,   //Fog table density (same as D3DRENDERSTATE_FOGDENSITY)
    D3DRENDERSTATE_FOGSTART           = 36,   //Fog start (for both vertex and pixel fog)
    D3DRENDERSTATE_FOGEND             = 37,   //Fog end (for both vertex and pixel fog)
    D3DRENDERSTATE_FOGDENSITY         = 38,   //Fog density (for both vertex and pixel fog)
    D3DRENDERSTATE_EDGEANTIALIAS      = 40,   //Antialias edges
    D3DRENDERSTATE_COLORKEYENABLE     = 41,   //Enable color-key transparency
    D3DRENDERSTATE_ZBIAS              = 47,   //Z-bias
    D3DRENDERSTATE_RANGEFOGENABLE     = 48,   //Enables range-based fog
    D3DRENDERSTATE_STENCILENABLE      = 52,   //Enable or disable stenciling
    D3DRENDERSTATE_STENCILFAIL        = 53,   //Stencil operation
    D3DRENDERSTATE_STENCILZFAIL       = 54,   //Stencil operation
    D3DRENDERSTATE_STENCILPASS        = 55,   //Stencil operation
    D3DRENDERSTATE_STENCILFUNC        = 56,   //Stencil comparison function
    D3DRENDERSTATE_STENCILREF         = 57,   //Reference value for stencil test
    D3DRENDERSTATE_STENCILMASK        = 58,   //Mask value used in stencil test
    D3DRENDERSTATE_STENCILWRITEMASK   = 59,   //Stencil buffer write mask
    D3DRENDERSTATE_TEXTUREFACTOR      = 60,   //Texture factor
    D3DRENDERSTATE_WRAP0              = 128,  //Wrap flags for 1st texture coord set
       // Wrap render states 1 through 6 omitted here.
    D3DRENDERSTATE_WRAP7              = 135,  //Wrap flags for last texture coord set
    D3DRENDERSTATE_CLIPPING            = 136, //Enable or disable primitive clipping
    D3DRENDERSTATE_LIGHTING            = 137, //Enable or disable lighting
    D3DRENDERSTATE_EXTENTS             = 138, //Enable or disable updating screen extents
    D3DRENDERSTATE_AMBIENT             = 139, //Ambient color for scene
    D3DRENDERSTATE_FOGVERTEXMODE       = 140, //Fog mode for vertex fog
    D3DRENDERSTATE_COLORVERTEX         = 141, //Enable or disable per-vertex color
    D3DRENDERSTATE_LOCALVIEWER         = 142, //Enable or disable perspective specular highlights
    D3DRENDERSTATE_NORMALIZENORMALS    = 143, //Enable automatic normalization of vertex normals
    D3DRENDERSTATE_COLORKEYBLENDENABLE = 144, //Enable or disable alpha-blended color keying
    D3DRENDERSTATE_DIFFUSEMATERIALSOURCE  = 145, //Location for per-vertex diffuse color
    D3DRENDERSTATE_SPECULARMATERIALSOURCE = 146, //Location for per-vertex specular color
    D3DRENDERSTATE_AMBIENTMATERIALSOURCE  = 147, //Location for per-vertex ambient color
    D3DRENDERSTATE_EMISSIVEMATERIALSOURCE = 148, //Location for per-vertex emissive color
    D3DRENDERSTATE_VERTEXBLEND              = 151, //Multi-matrix vertex blending mode
    D3DRENDERSTATE_CLIPPLANEENABLE          = 152, //Enable one or more user-defined clipping planes
    D3DRENDERSTATE_FORCE_DWORD        = 0x7fffffff,
} D3DRENDERSTATETYPE;
D3DRENDERSTATE_ANTIALIAS
One of the members of the D3DANTIALIASMODE enumerated type specifying the desired type of full-scene antialiasing. The default value is D3DANTIALIAS_NONE. For more information, see Full-scene Antialiasing and Antialiasing States.

You can only enable full-scene antialiasing on devices that expose the D3DPRASTERCAPS_ANTIALIASSORTINDEPENDENT or D3DPRASTERCAPS_ANTIALIASSORTDEPENDENT capabilities.

D3DRENDERSTATE_TEXTUREPERSPECTIVE
TRUE to enable perspective-correct texture mapping. (See perspective correction.) The default value is TRUE. For interfaces earlier than IDirect3DDevice3, the default is FALSE. For more information, see Texture Perspective State.
D3DRENDERSTATE_ZENABLE
Depth-buffering state as one of the members of the D3DZBUFFERTYPE enumerated type. Set this state to D3DZB_TRUE to enable z-buffering, D3DZB_USEW to enable w-buffering, or D3DZB_FALSE to disable depth buffering.

The default value for this render state is D3DZB_TRUE if a depth buffer is attached to the render-target surface, and D3DZB_FALSE otherwise.

D3DRENDERSTATE_FILLMODE
One or more members of the D3DFILLMODE enumerated type. The default value is D3DFILL_SOLID.
D3DRENDERSTATE_SHADEMODE
One or more members of the D3DSHADEMODE enumerated type. The default value is D3DSHADE_GOURAUD.
D3DRENDERSTATE_LINEPATTERN
The D3DLINEPATTERN structure. The default values are 0 for wRepeatPattern, and 0 for wLinePattern.
D3DRENDERSTATE_ZWRITEENABLE
TRUE to enable writes to the depth buffer. The default value is TRUE. This member enables an application to prevent the system from updating the depth buffer with new depth values. If FALSE, depth comparisons are still made according to the render state D3DRENDERSTATE_ZFUNC (assuming that depth buffering is taking place), but depth values are not written to the buffer.
D3DRENDERSTATE_ALPHATESTENABLE
TRUE to enable alpha tests. The default value is FALSE. This member enables applications to turn off the tests that accept or reject a pixel, based on its alpha value.

The incoming alpha value is compared with the reference alpha value, using the comparison function provided by the D3DRENDERSTATE_ALPHAFUNC render state. When this mode is enabled, alpha blending occurs only if the test succeeds.

D3DRENDERSTATE_LASTPIXEL
FALSE to enable drawing the last pixel in a line or triangle. The default value is TRUE.
D3DRENDERSTATE_SRCBLEND
One of the members of the D3DBLEND enumerated type. The default value is D3DBLEND_ONE.
D3DRENDERSTATE_DESTBLEND
One of the members of the D3DBLEND enumerated type. The default value is D3DBLEND_ZERO.
D3DRENDERSTATE_CULLMODE
Specifies how back-facing triangles are to be culled, if at all. This can be set to one of the members of the D3DCULL enumerated type. The default value is D3DCULL_CCW.
D3DRENDERSTATE_ZFUNC
One of the members of the D3DCMPFUNC enumerated type. The default value is D3DCMP_LESSEQUAL. This member enables an application to accept or reject a pixel, based on its distance from the camera.

The depth value of the pixel is compared with the depth-buffer value. If the depth value of the pixel passes the comparison function, the pixel is written.

The depth value is written to the depth buffer only if the render state is TRUE.

Software rasterizers and many hardware accelerators work faster if the depth test fails, since there is no need to filter and modulate the texture if the pixel is not going to be rendered.

D3DRENDERSTATE_ALPHAREF
Value specifying a reference alpha value against which pixels are tested when alpha-testing is enabled. This is an 8-bit value placed in the low 8 bits of the DWORD render-state value. Values can range from 0x00000000 through 0x000000FF.
D3DRENDERSTATE_ALPHAFUNC
One of the members of the D3DCMPFUNC enumerated type. The default value is D3DCMP_ALWAYS. This member enables an application to accept or reject a pixel, based on its alpha value.
D3DRENDERSTATE_DITHERENABLE
TRUE to enable dithering. The default value is FALSE.
D3DRENDERSTATE_ALPHABLENDENABLE
TRUE to enable alpha-blended transparency. The default value is FALSE. This member supersedes the D3DRENDERSTATE_BLENDENABLE render state; for more information, see remarks.

Prior to DirectX 5.0, the software rasterizers used this render state to toggle both color keying and alpha blending. Currently, use the D3DRENDERSTATE_COLORKEYENABLE render state to toggle color keying. (Hardware rasterizers have always used the D3DRENDERSTATE_BLENDENABLE render state only for toggling alpha blending.)

The type of alpha blending is determined by the D3DRENDERSTATE_SRCBLEND and D3DRENDERSTATE_DESTBLEND render states. D3DRENDERSTATE_ALPHABLENDENABLE, with D3DRENDERSTATE_COLORKEYENABLE, allows fine blending control.

D3DRENDERSTATE_ALPHABLENDENABLE does not affect the texture-blending modes specified by the D3DTEXTUREBLEND enumerated type. Texture blending is logically done well before the D3DRENDERSTATE_ALPHABLENDENABLE part of the pixel pipeline. The only interaction between the two is that the alpha portions remaining in the polygon after the D3DTEXTUREBLEND phase can be used in the D3DRENDERSTATE_ALPHABLENDENABLE phase to govern interaction with the content in the frame buffer.

Applications should check the D3DDEVCAPS_DRAWPRIMTLVERTEX flag in the D3DDEVICEDESC7 structure to find out whether this render state is supported.

D3DRENDERSTATE_FOGENABLE
TRUE to enable fog blending. The default value is FALSE. For more information, see Fog Blending and Fog.
D3DRENDERSTATE_SPECULARENABLE
TRUE to enable specular highlights. The default value is FALSE. For interfaces earlier than IDirect3DDevice3, the default value is TRUE.

Specular highlights are calculated as though every vertex in the object being lit were at the object's origin. This gives the expected results as long as the object is modeled around the origin and the distance from the light to the object is relatively large.

D3DRENDERSTATE_ZVISIBLE
Not supported.
D3DRENDERSTATE_STIPPLEDALPHA
TRUE to enable stippled alpha. The default value is FALSE.

Current software rasterizers ignore this render state. Use the D3DPSHADECAPS_ALPHAFLATSTIPPLED flag in the D3DPRIMCAPS structure to discover whether the current hardware supports this render state.

D3DRENDERSTATE_FOGCOLOR
Value whose type is D3DCOLOR. The default value is 0. For more information, see Fog Color.
D3DRENDERSTATE_FOGTABLEMODE
The fog formula to be used for pixel fog. Set to one of the members of the D3DFOGMODE enumerated type. The default value is D3DFOG_NONE. For more information, see Pixel Fog.
D3DRENDERSTATE_FOGTABLESTART
Maps to D3DRENDERSTATE_FOGSTART.
D3DRENDERSTATE_FOGTABLEEND
Maps to D3DRENDERSTATE_FOGEND.
D3DRENDERSTATE_FOGTABLEDENSITY
This render state maps to the D3DRENDERSTATE_FOGDENSITY render state.
D3DRENDERSTATE_FOGSTART
Depth at which pixel or vertex fog effects begin for linear fog mode. Depth is specified in world space for vertex fog, and either device space [0.0, 1.0] or world space for pixel fog. For pixel fog, these values are in device space when the system uses z for fog calculations, and world-space when the system is using eye-relative fog (w-fog). For more information, see Fog Parameters and Eye-Relative vs. Z-based Depth.

Values for this render state are floating-point values. Because the IDirect3DDevice7::SetRenderState and IDirect3DDevice7::SetRenderState accept DWORD values, your application will must cast a variable that contains the value, as shown in the following code example.

lpd3dDevice->SetRenderState( D3DRENDERSTATE_FOGSTART, *((LPDWORD) (&fFogStart)) );
D3DRENDERSTATE_FOGEND
Depth at which pixel or vertex fog effects end for linear fog mode. Depth is specified in world space for vertex fog, and either device space [0.0, 1.0] or world space for pixel fog. For pixel fog, these values are in device space when the system uses z for fog calculations, and world-space when the system is using eye-relative fog (w-fog). For more information, see Fog Parameters and Eye-Relative vs. Z-based Depth.

Values for this render state are floating-point values.Because the IDirect3DDevice7::SetRenderState and IDirect3DDevice7::SetRenderState accept DWORD values, your application will must cast a variable that contains the value, as shown in the following code example.

lpd3dDevice->SetRenderState( D3DRENDERSTATE_FOGEND, *((LPDWORD) (&fFogEnd)) );
D3DRENDERSTATE_FOGDENSITY
Fog density for pixel or vertex fog used in the exponential fog modes (D3DFOG_EXP and D3DFOG_EXP2). Valid density values range from 0.0 through 1.0. The default value is 1.0. For more information, see Fog Parameters.

Values for this render state are floating-point values.Because the IDirect3DDevice7::SetRenderState and IDirect3DDevice7::SetRenderState accept DWORD values, your application will must cast a variable that contains the value, as shown in the following code example.

lpd3dDevice->SetRenderState( D3DRENDERSTATE_FOGDENSITY, *((LPDWORD) (&fFogDensity)) );
D3DRENDERSTATE_EDGEANTIALIAS
TRUE to antialias lines forming the convex outline of objects. The default value is FALSE. For more information, see Edge Antialiasing and Antialiasing States. If TRUE, applications should render only lines, and only to the exterior edges of polygons in a scene. The behavior is undefined if triangles or points are drawn when this render state is set. Antialiasing is performed by averaging the values of neighboring pixels. Although this is not the best way to perform antialiasing, it can be very efficient; hardware that supports this kind of operation is becoming more common.

You can only enable edge antialiasing on devices that expose the D3DPRASTERCAPS_ANTIALIASEDGES capability.

D3DRENDERSTATE_COLORKEYENABLE
TRUE to enable color-keyed transparency. The default value is FALSE. Use this render state with D3DRENDERSTATE_ALPHABLENDENABLE to implement fine blending control.

Applications should check the D3DDEVCAPS_DRAWPRIMTLVERTEX flag in the D3DDEVICEDESC7 structure to find out whether this render state is supported.

When color-keyed transparency is enabled, only texture surfaces that were created with the DDSD_CKSRCBLT flag are affected. Surfaces that were created without the DDSD_CKSRCBLT flag exhibit color-keyed transparency effects.

D3DRENDERSTATE_ZBIAS
Integer value in the range 0 through 16 that causes polygons that are physically coplanar to appear separate. Polygons with a high z-bias value appear in front of polygons with a low value, without requiring sorting for drawing order. Polygons with a value of 1 appear in front of polygons with a value of 0, and so on. The default value is 0. For more information, see Using Depth Buffers.
D3DRENDERSTATE_RANGEFOGENABLE
TRUE to enable range-based vertex fog. (The default value is FALSE, in which case the system uses depth-based fog.) In range-based fog, the distance of an object from the viewer is used to compute fog effects, not the depth of the object (that is, the z-coordinate) in the scene. In range-based fog, all fog methods work as usual, except that they use range instead of depth in the computations.

Range is the correct factor to use for fog computations, but depth is commonly used instead because range is expensive to compute and depth is generally already available. Using depth to calculate fog has the undesirable effect of having the fogginess of peripheral objects change as the viewer's eye moves—in this case, the depth changes, and the range remains constant.

This render state works only with D3DVERTEX vertices. When you specify D3DLVERTEX or D3DTLVERTEX vertices, the F (fog) component of the RGBF fog value should already be corrected for range.

Since no hardware currently supports per-pixel range-based fog, range correction is offered only for vertex fog. For more information, see Range-based Fog and Vertex Fog.

D3DRENDERSTATE_STENCILENABLE
TRUE to enable stenciling, or FALSE to disable stenciling. The default value is FALSE. For more information, see Stencil Buffers.
D3DRENDERSTATE_STENCILFAIL
Stencil operation to perform if the stencil test fails. This can be one of the members of the D3DSTENCILOP enumerated type. The default value is D3DSTENCILOP_KEEP. For more information, see Stencil Buffers.
D3DRENDERSTATE_STENCILZFAIL
Stencil operation to perform if the stencil test passes and the depth test (z-test) fails. This can be one of the members of the D3DSTENCILOP enumerated type. The default value is D3DSTENCILOP_KEEP. For more information, see Stencil Buffers.
D3DRENDERSTATE_STENCILPASS
Stencil operation to perform if both the stencil and the depth (z) tests pass. This can be one of the members of the D3DSTENCILOP enumerated type. The default value is D3DSTENCILOP_KEEP. For more information, see Stencil Buffers.
D3DRENDERSTATE_STENCILFUNC
Comparison function for the stencil test. This can be one of the members of the D3DCMPFUNC enumerated type. The default value is D3DCMP_ALWAYS.

The comparison function is used to compare the reference value to a stencil buffer entry. This comparison only applies to the bits in the reference value and stencil buffer entry that are set in the stencil mask (set by the D3DRENDERSTATE_STENCILMASK render state). If TRUE, the stencil test passes.

D3DRENDERSTATE_STENCILREF
Integer reference value for the stencil test. The default value is 0.
D3DRENDERSTATE_STENCILMASK
Mask applied to the reference value and each stencil buffer entry to determine the significant bits for the stencil test. The default mask is 0xFFFFFFFF.
D3DRENDERSTATE_STENCILWRITEMASK
Write mask applied to values written into the stencil buffer. The default mask is 0xFFFFFFFF.
D3DRENDERSTATE_TEXTUREFACTOR
Color used for multiple-texture blending with the D3DTA_TFACTOR texture-blending argument or the D3DTOP_BLENDFACTORALPHA texture-blending operation. The associated value is a D3DCOLOR variable.
D3DRENDERSTATE_WRAP0 through D3DRENDERSTATE_WRAP7
Texture-wrapping behavior for multiple sets of texture coordinates. Valid values for these render states can be any combination of the D3DWRAPCOORD_0, D3DWRAPCOORD_1, D3DWRAPCOORD_2, and D3DWRAPCOORD_3 flags. These cause the system to wrap in the direction of the first, second, third, and fourth dimensions (sometimes referred to at the s, t, r, and q directions) for a given texture. The default value for these render states is 0 (wrapping disabled in all directions). For more information, see Texture Wrapping.
D3DRENDERSTATE_CLIPPING
TRUE to enable primitive clipping by Direct3D, or FALSE to disable it. The default value is TRUE.
D3DRENDERSTATE_LIGHTING
TRUE to enable Direct3D lighting, or FALSE to disable it. The default value is TRUE. Only vertices that include a vertex normal are properly lit; vertices that do not contain a normal employ a dot product of 0 in all lighting calculations.
D3DRENDERSTATE_EXTENTS
TRUE to cause the system to update the screen extents for each rendering call, or FALSE to disable screen extent updates. The default value is FALSE.
D3DRENDERSTATE_AMBIENT
Ambient light color. This value is of type D3DCOLOR. The default value is 0. This render state is analogous to the legacy D3DLIGHTSTATE_AMBIENT lighting state.
D3DRENDERSTATE_FOGVERTEXMODE
Fog formula to be used for vertex fog. Set to one of the members of the D3DFOGMODE enumerated type. The default value is D3DFOG_NONE. For more information, see Vertex Fog. This render state is analogous to the legacy D3DLIGHTSTATE_FOGVERTEXMODE lighting state.
D3DRENDERSTATE_COLORVERTEX
TRUE to enable per-vertex color, or FALSE to disable it. The default value is TRUE. Enabling per-vertex color allows the system to include the color defined for individual vertices in its lighting calculations. This render state is analogous to the legacy D3DLIGHTSTATE_COLORVERTEX lighting state.

For more information, see the following render states:

  • D3DRENDERSTATE_DIFFUSEMATERIALSOURCE
  • D3DRENDERSTATE_SPECULARMATERIALSOURCE
  • D3DRENDERSTATE_AMBIENTMATERIALSOURCE
  • D3DRENDERSTATE_EMISSIVEMATERIALSOURCE
D3DRENDERSTATE_LOCALVIEWER
TRUE to enable camera-relative specular highlights, or FALSE to use orthogonal specular highlights. The default value is TRUE. Applications that use orthogonal projection should specify false.
D3DRENDERSTATE_NORMALIZENORMALS
TRUE to enable automatic normalization of vertex normals, or FALSE to disable it. The default value is FALSE. Enabling this feature causes the system to normalize the vertex normals for vertices after transforming them to camera space, which can be computationally expensive.
D3DRENDERSTATE_COLORKEYBLENDENABLE
TRUE to enable alpha-blended colorkeying, or FALSE to disable it. Alpha-blended colorkey mode sets the alpha and color of matching texture samples to 0. The application must set the alpha-test and alpha-blend modes to achieve the desired discard and/or alpha-blended result.
D3DRENDERSTATE_DIFFUSEMATERIALSOURCE
Diffuse color source for lighting calculations. Valid values are members of the D3DMATERIALCOLORSOURCE enumerated type. The default value is D3DMCS_COLOR1. The value for this render state is used only if the D3DRENDERSTATE_COLORVERTEX render state is set to TRUE.
D3DRENDERSTATE_SPECULARMATERIALSOURCE
Specular color source for lighting calculations. Valid values are members of the D3DMATERIALCOLORSOURCE enumerated type. The default value is D3DMCS_COLOR2.
D3DRENDERSTATE_AMBIENTMATERIALSOURCE
Ambient color source for lighting calculations. Valid values are members of the D3DMATERIALCOLORSOURCE enumerated type. The default value is D3DMCS_COLOR2.
D3DRENDERSTATE_EMISSIVEMATERIALSOURCE
Emissive color source for lighting calculations. Valid values are members of the D3DMATERIALCOLORSOURCE enumerated type. The default value is D3DMCS_MATERIAL.
D3DRENDERSTATE_VERTEXBLEND
Number of matrices to be used to perform geometry blending, if any. Valid values are members of the D3DVERTEXBLENDFLAGS enumerated type. The default value is D3DVBLEND_DISABLE. For more information see Geometry Blending.
D3DRENDERSTATE_CLIPPLANEENABLE
Enables or disables user-defined clipping planes. Valid values are any DWORD in which the status of each bit (set or not set) toggles the activation state of a corresponding user-defined clipping plane. The least significant bit (bit 0) controls the first clipping plane at index 0, and subsequent bits control the activation of clipping planes at higher indexes. If a bit is set, the system applies the appropriate clipping plane during scene rendering. The default value is 0.

The D3DCLIPPLANEn macros are declared in the D3dtypes.h header file to provide a convenient way to enable clipping planes.

D3DRENDERSTATE_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The D3DRENDERSTATE_BLENDENABLE member was superseded by the D3DRENDERSTATE_ALPHABLENDENABLE member. Its name was changed to make its meaning more explicit. To maintain compatibility with previous applications, the D3DRENDERSTATE_BLENDENABLE constant is declared as equivalent to D3DRENDERSTATE_ALPHABLENDENABLE:

#define D3DRENDERSTATE_BLENDENABLE  D3DRENDERSTATE_ALPHABLENDENABLE

Direct3D defines the D3DRENDERSTATE_WRAPBIAS constant as a convenience for applications to enable or disable texture wrapping, based on the zero-based integer of a texture coordinate set (rather than explicitly using one of the D3DRENDERSTATE_WRAPn state values). Add the D3DRENDERSTATE_WRAPBIAS value to the zero-based index of a texture coordinate set to calculate the D3DRENDERSTATE_WRAPn value that corresponds to that index, as shown in the following example:

// Enable U/V wrapping for textures that use the texture
// coordinate set at the index within the dwIndex variable.
HRESULT hr = lpD3DDevice->SetRenderState(
    dwIndex + D3DRENDERSTATE_WRAPBIAS,
    D3DWRAP_0 | D3DWRAP1);

// If dwIndex is 3, the value that results from
// the addition equals D3DRENDERSTATE_WRAP3 (131).

The declaration of D3DRENDERSTATETYPE in D3dtypes.h contains legacy render states not supported by DirectX 7.0 interfaces. For more information, see Obsolete Render States.

    D3DRENDERSTATE_TEXTUREHANDLE      = 1,    //Texture handle
    D3DRENDERSTATE_TEXTUREADDRESS     = 3,    //Texture address
    D3DRENDERSTATE_WRAPU              = 5,    //Wrap in u direction
    D3DRENDERSTATE_WRAPV              = 6,    //Wrap in v direction
    D3DRENDERSTATE_MONOENABLE         = 11,   //Enable mono rendering
    D3DRENDERSTATE_ROP2               = 12,   //Raster operation
    D3DRENDERSTATE_PLANEMASK          = 13,   //Physical plane mask
    D3DRENDERSTATE_TEXTUREMAG         = 17,   //Superseded
    D3DRENDERSTATE_TEXTUREMIN         = 18,   //Superseded
    D3DRENDERSTATE_TEXTUREMAPBLEND    = 21,   //Blend mode for map
    D3DRENDERSTATE_SUBPIXEL           = 31,   //Enable subpixel correction
    D3DRENDERSTATE_SUBPIXELX          = 32,   //Enable x subpixel correction
    D3DRENDERSTATE_STIPPLEENABLE      = 39,   //Enable stippling
    D3DRENDERSTATE_BORDERCOLOR        = 43,   //Border color
    D3DRENDERSTATE_TEXTUREADDRESSU    = 44,   //U texture address mode
    D3DRENDERSTATE_TEXTUREADDRESSV    = 45,   //V texture address mode
    D3DRENDERSTATE_MIPMAPLODBIAS      = 46,   //Mipmap LOD bias
    D3DRENDERSTATE_ANISOTROPY         = 49,   //Maximum anisotropy
    D3DRENDERSTATE_FLUSHBATCH         = 50,   //Explicit flush for DP batching (DX5 Only)
    D3DRENDERSTATE_TRANSLUCENTSORTINDEPENDENT=51, //Enable sort-independent transparency
    D3DRENDERSTATE_STIPPLEPATTERN00   = 64,   //First line of stipple pattern
       // Stipple patterns 01 through 30 omitted here.
    D3DRENDERSTATE_STIPPLEPATTERN31   = 95,   //Last line of stipple pattern

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.

See Also

IDirect3DDevice7::SetRenderState, IDirect3DDevice7::GetRenderState, Render States


D3DSHADEMODE

The D3DSHADEMODE enumerated type describes the supported shading mode for the D3DRENDERSTATE_SHADEMODE render state in the D3DRENDERSTATETYPE enumerated type.

typedef enum _D3DSHADEMODE {
    D3DSHADE_FLAT         = 1,
    D3DSHADE_GOURAUD      = 2,
    D3DSHADE_PHONG        = 3,
    D3DSHADE_FORCE_DWORD  = 0x7fffffff,
} D3DSHADEMODE;
D3DSHADE_FLAT
Flat shading mode. The color and specular component of the first vertex in the triangle are used to determine the color and specular component of the face. These colors remain constant across the triangle; that is, they are not interpolated.
D3DSHADE_GOURAUD
Gouraud shading mode. The color and specular components of the face are determined by a linear interpolation between all three of the triangle's vertices.
D3DSHADE_PHONG
Not currently supported.
D3DSHADE_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.

See Also

D3DRENDERSTATETYPE


D3DSTATEBLOCKTYPE

The D3DSTATEBLOCK enumerated type defines logical groups of device states, for use with the IDirect3DDevice7::CreateStateBlock method.

typedef enum _D3DSTATEBLOCKTYPE{
    D3DSBT_ALL           = 1,
    D3DSBT_PIXELSTATE    = 2,
    D3DSBT_VERTEXSTATE   = 3,
    D3DSBT_FORCE_DWORD   = 0xffffffff
} D3DSTATEBLOCKTYPE;
D3DSBT_ALL
Capture all device states.
D3DSBT_PIXELSTATE
Capture only pixel-related device states.
D3DSBT_VERTEXSTATE
Capture only vertex-related device states.
D3DSBT_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The D3DSBT_PIXELSTATE and D3DSBT_VERTEXSTATE values identify different logical groups of device states, though some states are common to both groups. For information about the states defined by each group, see Creating Predefined State Blocks.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dtypes.h.

See Also

IDirect3DDevice7::CreateStateBlock


D3DSTENCILOP

The D3DSTENCILOP enumerated type describes the stencil operations for the D3DRENDERSTATE_STENCILFAIL, D3DRENDERSTATE_STENCILZFAIL, and D3DRENDERSTATE_STENCILPASS render states.

typedef enum _D3DSTENCILOP {
    D3DSTENCILOP_KEEP           = 1,
    D3DSTENCILOP_ZERO           = 2,
    D3DSTENCILOP_REPLACE        = 3,
    D3DSTENCILOP_INCRSAT        = 4,
    D3DSTENCILOP_DECRSAT        = 5,
    D3DSTENCILOP_INVERT         = 6,
    D3DSTENCILOP_INCR           = 7,
    D3DSTENCILOP_DECR           = 8,
    D3DSTENCILOP_FORCE_DWORD    = 0x7fffffff
} D3DSTENCILOP;
D3DSTENCILOP_KEEP
Do not update the entry in the stencil buffer. This is the default value.
D3DSTENCILOP_ZERO
Set the stencil-buffer entry to 0.
D3DSTENCILOP_REPLACE
Replace the stencil-buffer entry with reference value.
D3DSTENCILOP_INCRSAT
Increment the stencil-buffer entry, clamping to the maximum value. See remarks for information on the maximum stencil-buffer values.
D3DSTENCILOP_DECRSAT
Decrement the stencil-buffer entry, clamping to 0.
D3DSTENCILOP_INVERT
Invert the bits in the stencil-buffer entry.
D3DSTENCILOP_INCR
Increment the stencil-buffer entry, wrapping to 0 if the new value exceeds the maximum value. See remarks for information on the maximum stencil-buffer values.
D3DSTENCILOP_DECR
Decrement the stencil-buffer entry, wrapping to the maximum value if the new value is less than 0.
D3DSTENCILOP_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Stencil-buffer entries are integer values ranging from 0 through 2n –1, where n is the bit depth of the stencil buffer.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 6.0 or later.
Header: Declared in d3dtypes.h.

See Also

D3DRENDERSTATETYPE, Stencil Buffers


D3DTEXTUREADDRESS

The D3DTEXTUREADDRESS enumerated type describes the supported texture-addressing modes when setting them with the D3DTSS_ADDRESS, D3DTSS_ADDRESSU, and D3DTSS_ADDRESSV texture-stage states.

typedef enum _D3DTEXTUREADDRESS {
    D3DTADDRESS_WRAP         = 1,
    D3DTADDRESS_MIRROR       = 2,
    D3DTADDRESS_CLAMP        = 3,
    D3DTADDRESS_BORDER       = 4,
    D3DTADDRESS_FORCE_DWORD  = 0x7fffffff,
} D3DTEXTUREADDRESS;
D3DTADDRESS_WRAP
Tile the texture at every integer junction. For example, for u values between 0 and 3, the texture is repeated three times; no mirroring is performed.
D3DTADDRESS_MIRROR
Similar to D3DTADDRESS_WRAP, except that the texture is flipped at every integer junction. For u values between 0 and 1, for example, the texture is addressed normally; between 1 and 2, the texture is flipped (mirrored); between 2 and 3, the texture is normal again, and so on.
D3DTADDRESS_CLAMP
Texture coordinates outside the range [0.0, 1.0] are set to the texture color at 0.0 or 1.0, respectively.
D3DTADDRESS_BORDER
Texture coordinates outside the range [0.0, 1.0] are set to the border color, which is a new render state corresponding to D3DRENDERSTATE_BORDERCOLOR in the D3DRENDERSTATETYPE enumerated type.
D3DTADDRESS_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

For information about using the D3DRENDERSTATE_WRAPU and D3DRENDERSTATE_WRAPV render states, see Textures.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.

See Also

D3DRENDERSTATETYPE


D3DTEXTUREMAGFILTER

The D3DTEXTUREMAGFILTER enumerated type defines texture-magnification filtering modes for a texture stage.

typedef enum _D3DTEXTUREMAGFILTER {
    D3DTFG_POINT        = 1,
    D3DTFG_LINEAR       = 2,
    D3DTFG_FLATCUBIC    = 3,
    D3DTFG_GAUSSIANCUBIC= 4,
    D3DTFG_ANISOTROPIC  = 5,
    D3DTFG_FORCE_DWORD  = 0x7fffffff,
} D3DTEXTUREMAGFILTER;
D3DTFG_POINT
Point filtering. The texel with coordinates nearest to the desired pixel value is used.
D3DTFG_LINEAR
Bilinear interpolation filtering. A weighted average of a 2×2 area of texels surrounding the desired pixel is used.
D3DTFG_FLATCUBIC
Not currently supported; do not use.
D3DTFG_GAUSSIANCUBIC
Not currently supported; do not use.
D3DTFG_ANISOTROPIC
Anisotropic texture filtering. Compensates for distortion caused by the difference in angle between the texture polygon and the plane of the screen.
D3DTFG_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Set a texture stage's magnification filter by calling the IDirect3DDevice7::SetTextureStageState method with the D3DTSS_MAGFILTER value as the second parameter and one of the members of this enumeration as the third parameter.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 6.0 or later.
Header: Declared in d3dtypes.h.

See Also

D3DTEXTUREMINFILTER, D3DTEXTUREMIPFILTER, Texture Filtering


D3DTEXTUREMINFILTER

The D3DTEXTUREMINFILTER enumerated type defines texture-minification filtering modes for a texture stage.

typedef enum _D3DTEXTUREMINFILTER {
    D3DTFN_POINT        = 1,
    D3DTFN_LINEAR       = 2,
    D3DTFN_ANISOTROPIC  = 3,
    D3DTFN_FORCE_DWORD  = 0x7fffffff,
} D3DTEXTUREMINFILTER;
D3DTFN_POINT
Point filtering. The texel with coordinates nearest to the desired pixel value is used.
D3DTFN_LINEAR
Bilinear interpolation filtering. A weighted average of a 2×2 area of texels surrounding the desired pixel is used.
D3DTFN_ANISOTROPIC
Anisotropic texture filtering. Compensates for distortion caused by the difference in angle between the texture polygon and the plane of the screen.
D3DTFN_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Set a texture stage's magnification filter by calling the IDirect3DDevice7::SetTextureStageState method with the D3DTSS_MINFILTER value as the second parameter and one of the members of this enumeration as the third parameter.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 6.0 or later.
Header: Declared in d3dtypes.h.

See Also

D3DTEXTUREMAGFILTER, D3DTEXTUREMIPFILTER, Texture Filtering


D3DTEXTUREMIPFILTER

The D3DTEXTUREMIPFILTER enumerated type defines texture mipmap filtering modes for a texture stage.

typedef enum _D3DTEXTUREMIPFILTER {
    D3DTFP_NONE         = 1,
    D3DTFP_POINT        = 2,
    D3DTFP_LINEAR       = 3,
    D3DTFP_FORCE_DWORD  = 0x7fffffff,
} D3DTEXTUREMIPFILTER;
D3DTFP_NONE
Mipmapping disabled. The rasterizer should use the magnification filter instead.
D3DTFP_POINT
Nearest-point mipmap filtering. The rasterizer uses the color from the texel of the nearest mipmap texture.
D3DTFP_LINEAR
Trilinear mipmap interpolation. The rasterizer linearly interpolates pixel color, using the texels of the two nearest mipmap textures.
D3DTFP_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Set a texture stage's magnification filter by calling the IDirect3DDevice7::SetTextureStageState method with the D3DTSS_MIPFILTER value as the second parameter and one of the members of this enumeration as the third parameter.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 6.0 or later.
Header: Declared in d3dtypes.h.

See Also

D3DTEXTUREMAGFILTER, D3DTEXTUREMIPFILTER, Texture Filtering


D3DTEXTUREOP

The D3DTEXTUREOP enumerated type defines per-stage texture-blending operations. The members of this type are used when setting color or alpha operations by using the D3DTSS_COLOROP or D3DTSS_ALPHAOP values with the IDirect3DDevice7::SetTextureStageState method.

typedef enum _D3DTEXTUREOP {
    D3DTOP_DISABLE    = 1,
    D3DTOP_SELECTARG1 = 2,
    D3DTOP_SELECTARG2 = 3,
    D3DTOP_MODULATE   = 4,
    D3DTOP_MODULATE2X = 5,
    D3DTOP_MODULATE4X = 6,
    D3DTOP_ADD        = 7,
    D3DTOP_ADDSIGNED  = 8,
    D3DTOP_ADDSIGNED2X  =  9,
    D3DTOP_SUBTRACT     = 10,
    D3DTOP_ADDSMOOTH    = 11,
    D3DTOP_BLENDDIFFUSEALPHA    = 12,
    D3DTOP_BLENDTEXTUREALPHA    = 13,
    D3DTOP_BLENDFACTORALPHA     = 14,
    D3DTOP_BLENDTEXTUREALPHAPM  = 15,
    D3DTOP_BLENDCURRENTALPHA    = 16,
    D3DTOP_PREMODULATE            = 17,
    D3DTOP_MODULATEALPHA_ADDCOLOR = 18,
    D3DTOP_MODULATECOLOR_ADDALPHA = 19,
    D3DTOP_MODULATEINVALPHA_ADDCOLOR = 20,
    D3DTOP_MODULATEINVCOLOR_ADDALPHA = 21,
    D3DTOP_BUMPENVMAP           = 22,
    D3DTOP_BUMPENVMAPLUMINANCE  = 23,
    D3DTOP_DOTPRODUCT3          = 24,
    D3DTOP_FORCE_DWORD = 0x7fffffff,
} D3DTEXTUREOP;
Control members
D3DTOP_DISABLE
Disables output from this texture stage and all stages with a higher index. To disable texture mapping, set this as the color operation for the first texture stage (stage 0). Alpha operations cannot be disabled when color operations are enabled. Setting the alpha operation to D3DTOP_DISABLE when color blending is enabled causes undefined behavior.
D3DTOP_SELECTARG1
Use this texture stage's first color or alpha argument, unmodified, as the output. This operation affects the color argument when used with the D3DTSS_COLOROP texture-stage state, and the alpha argument when used with D3DTSS_ALPHAOP.

D3DTOP_SELECTARG2
Use this texture stage's second color or alpha argument, unmodified, as the output. This operation affects the color argument when used with the D3DTSS_COLOROP texture stage state, and the alpha argument when used with D3DTSS_ALPHAOP.

Modulation members
D3DTOP_MODULATE
Multiply the components of the arguments together.

D3DTOP_MODULATE2X
Multiply the components of the arguments, and shift the products to the left 1 bit (effectively multiplying them by 2) for brightening.

D3DTOP_MODULATE4X
Multiply the components of the arguments, and shift the products to the left 2 bits (effectively multiplying them by 4) for brightening.

Addition and subtraction members
D3DTOP_ADD
Add the components of the arguments.

D3DTOP_ADDSIGNED
Add the components of the arguments with a –0.5 bias, making the effective range of values from –0.5 through 0.5.

D3DTOP_ADDSIGNED2X
Add the components of the arguments with a –0.5 bias, and shift the products to the left 1 bit.

D3DTOP_SUBTRACT
Subtract the components of the second argument from those of the first argument.

D3DTOP_ADDSMOOTH
Add the first and second arguments, then subtract their product from the sum.

Linear alpha blending members
D3DTOP_BLENDDIFFUSEALPHA, D3DTOP_BLENDTEXTUREALPHA, D3DTOP_BLENDFACTORALPHA, and D3DTOP_BLENDCURRENTALPHA
Linearly blend this texture stage, using the interpolated alpha from each vertex (D3DTOP_BLENDDIFFUSEALPHA), alpha from this stage's texture (D3DTOP_BLENDTEXTUREALPHA), a scalar alpha (D3DTOP_BLENDFACTORALPHA) set with the D3DRENDERSTATE_TEXTUREFACTOR render state, or the alpha taken from the previous texture stage (D3DTOP_BLENDCURRENTALPHA).

D3DTOP_BLENDTEXTUREALPHAPM
Linearly blend a texture stage that uses a premultiplied alpha.

Specular mapping members
D3DTOP_PREMODULATE
Modulate this texture stage with the next texture stage.
D3DTOP_MODULATEALPHA_ADDCOLOR
Modulate the color of the second argument, using the alpha of the first argument; then add the result to argument one. This operation is supported only for color operations (D3DTSS_COLOROP).

D3DTOP_MODULATECOLOR_ADDALPHA
Modulate the arguments; then add the alpha of the first argument. This operation is supported only for color operations (D3DTSS_COLOROP).

D3DTOP_MODULATEINVALPHA_ADDCOLOR
Similar to D3DTOP_MODULATEALPHA_ADDCOLOR, but use the inverse of the alpha of the first argument. This operation is supported only for color operations (D3DTSS_COLOROP).

D3DTOP_MODULATEINVCOLOR_ADDALPHA
Similar to D3DTOP_MODULATECOLOR_ADDALPHA, but use the inverse of the color of the first argument. This operation is supported only for color operations (D3DTSS_COLOROP).

Bump-mapping members
D3DTOP_BUMPENVMAP
Perform per-pixel bump mapping, using the environment map in the next texture stage (without luminance). This operation is supported only for color operations (D3DTSS_COLOROP).
D3DTOP_BUMPENVMAPLUMINANCE
Perform per-pixel bump mapping, using the environment map in the next texture stage (with luminance). This operation is supported only for color operations (D3DTSS_COLOROP).
D3DTOP_DOTPRODUCT3
Modulate the components of each argument (as signed components), add their products, then replicate the sum to all color channels, including alpha. This operation is supported for color and alpha operations.

Miscellaneous member
D3DTOP_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

In the formulas, SRGBA is the RGBA color produced by a texture operation, and Arg1 and Arg2 represent the complete RGBA color of the texture arguments. Individual components of an argument are shown with subscripts. For example, the alpha component for argument 1 would be shown as Arg1A.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 6.0 or later.
Header: Declared in d3dtypes.h.

See Also

IDirect3DDevice7::GetTextureStageState, IDirect3DDevice7::SetTextureStageState, D3DTEXTURESTAGESTATETYPE


D3DTEXTURESTAGESTATETYPE

The D3DTEXTURESTAGESTATETYPE enumerated type defines texture stage states. Members of this enumerated type are used with the IDirect3DDevice7::GetTextureStageState and IDirect3DDevice7::SetTextureStageState methods to retrieve and set texture state values.

typedef enum _D3DTEXTURESTAGESTATETYPE {
    D3DTSS_COLOROP        = 1,
    D3DTSS_COLORARG1      = 2,
    D3DTSS_COLORARG2      = 3,
    D3DTSS_ALPHAOP        = 4,
    D3DTSS_ALPHAARG1      = 5,
    D3DTSS_ALPHAARG2      = 6,
    D3DTSS_BUMPENVMAT00   = 7,
    D3DTSS_BUMPENVMAT01   = 8,
    D3DTSS_BUMPENVMAT10   = 9,
    D3DTSS_BUMPENVMAT11   = 10,
    D3DTSS_TEXCOORDINDEX  = 11,
    D3DTSS_ADDRESS        = 12,
    D3DTSS_ADDRESSU       = 13,
    D3DTSS_ADDRESSV       = 14,
    D3DTSS_BORDERCOLOR    = 15,
    D3DTSS_MAGFILTER      = 16,
    D3DTSS_MINFILTER      = 17,
    D3DTSS_MIPFILTER      = 18,
    D3DTSS_MIPMAPLODBIAS  = 19,
    D3DTSS_MAXMIPLEVEL    = 20,
    D3DTSS_MAXANISOTROPY  = 21,
    D3DTSS_BUMPENVLSCALE  = 22,
    D3DTSS_BUMPENVLOFFSET = 23,
    D3DTSS_TEXTURETRANSFORMFLAGS = 24,
    D3DTSS_FORCE_DWORD   = 0x7fffffff,
} D3DTEXTURESTAGESTATETYPE;
D3DTSS_COLOROP
The texture-stage state is a texture color blending operation identified by one of the members of the D3DTEXTUREOP enumerated type. The default value for the first texture stage (stage 0) is D3DTOP_MODULATE, and for all other stages the default is D3DTOP_DISABLE.
D3DTSS_COLORARG1
The texture-stage state is the first color argument for the stage, identified by a texture argument flag. The default argument is D3DTA_TEXTURE.
D3DTSS_COLORARG2
The texture-stage state is the second color argument for the stage, identified by a texture argument flag. The default argument is D3DTA_CURRENT.
D3DTSS_ALPHAOP
The texture-stage state is a texture alpha blending operation identified by one of the members of the D3DTEXTUREOP enumerated type. The default value for the first texture stage (stage 0) is D3DTOP_SELECTARG1, and for all other stages the default is D3DTOP_DISABLE.

For DirectX 6.0, the default behavior for this state is not described as a texture operation. Rather, the alpha blending behavior matches that of the D3DRENDERSTATE_TEXTUREMAPBLEND render state with a value of D3DTBLEND_MODULATE.

D3DTSS_ALPHAARG1
The texture-stage state is the first alpha argument for the stage, identified by a texture argument flag. The default argument is D3DTA_TEXTURE. If no texture is set for this stage, the default argument is D3DTA_DIFFUSE.
D3DTSS_ALPHAARG2
The texture-stage state is the second alpha argument for the stage, identified by a texture argument flag. The default argument is D3DTA_CURRENT.
D3DTSS_BUMPENVMAT00
The texture-stage state is a D3DVALUE for the [0][0] coefficient in a bump-mapping matrix. The default value is 0.
D3DTSS_BUMPENVMAT01
The texture-stage state is a D3DVALUE for the [0][1] coefficient in a bump-mapping matrix. The default value is 0.
D3DTSS_BUMPENVMAT10
The texture-stage state is a D3DVALUE for the [1][0] coefficient in a bump-mapping matrix. The default value is 0.
D3DTSS_BUMPENVMAT11
The texture-stage state is a D3DVALUE for the [1][1] coefficient in a bump-mapping matrix. The default value is 0.
D3DTSS_TEXCOORDINDEX
Index of the texture coordinate set to use with this texture stage. The default index is 0. Set this state to the zero-based index of the coordinate set for each vertex that this texture stage uses. (You can specify up to eight sets of texture coordinates per vertex.) If a vertex does not include a set of texture coordinates at the specified index, the system defaults to the u and v coordinates (0,0).

Additionally, applications can include (as logical Or with the index being set) one of the following flags to request that Direct3D automatically generate the input texture coordinates for a texture transformation. With the exception of D3DTSS_TCI_PASSTHRU, which resolves to zero, if any of the following values is included with the index being set, the system uses the index strictly to determine texture wrapping mode. These flags are most useful when performing environment mapping.

D3DTSS_TCI_PASSTHRU
Use the specified texture coordinates contained within the vertex format. This value resolves to zero.
D3DTSS_TCI_CAMERASPACENORMAL
Use the vertex normal, transformed to camera space, as the input texture coordinates for this stage's texture transformation.
D3DTSS_TCI_CAMERASPACEPOSITION
Use the vertex position, transformed to camera space, as the input texture coordinates for this stage's texture transformation.
D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR
Use the reflection vector, transformed to camera space, as the input texture coordinate for this stage's texture transformation. The reflection vector is computed from the input vertex position and normal vector.
D3DTSS_ADDRESS
Member of the D3DTEXTUREADDRESS enumerated type. Selects the texture-addressing method for both the u and v coordinates. The default is D3DTADDRESS_WRAP.
D3DTSS_ADDRESSU
Member of the D3DTEXTUREADDRESS enumerated type. Selects the texture-addressing method for the u coordinate. The default is D3DTADDRESS_WRAP.
D3DTSS_ADDRESSV
Member of the D3DTEXTUREADDRESS enumerated type. Selects the texture-addressing method for the v coordinate. The default value is D3DTADDRESS_WRAP.
D3DTSS_BORDERCOLOR
D3DCOLOR value that describes the color to be used for rasterizing texture coordinates outside the [0.0,1.0] range. The default color is 0x00000000.
D3DTSS_MAGFILTER
Member of the D3DTEXTUREMAGFILTER enumerated type that indicates the texture magnification filter to be used when rendering the texture onto primitives. The default value is D3DTFG_POINT.
D3DTSS_MINFILTER
Member of the D3DTEXTUREMINFILTER enumerated type that indicates the texture minification filter to be used when rendering the texture onto primitives. The default value is D3DTFN_POINT.
D3DTSS_MIPFILTER
Member of the D3DTEXTUREMIPFILTER enumerated type that indicates the texture magnification filter to be used when rendering the texture onto primitives. The default value is D3DTFP_NONE.
D3DTSS_MIPMAPLODBIAS
Level of detail bias for mipmaps. Can be used to make textures appear more chunky or more blurred. The default value is 0. Values for this state are floating-point values. Because the IDirect3DDevice7::SetTextureStageState and IDirect3DDevice7::GetTextureStageState accept DWORD values, your application will must cast a variable that contains the value, as shown in the following code example.
lpd3dDevice->SetTextureStageState( D3DTSS_MIPMAPLODBIAS, *((LPDWORD) (&fBias)) );
D3DTSS_MAXMIPLEVEL
Maximum mipmap level of detail that the application allows, expressed as an index from the top of the mipmap chain. (Lower values identify higher levels of detail within the mipmap chain). Zero, which is the default, indicates that all levels can be used. Nonzero values indicate that the application does not want to display mipmaps that have a higher level of detail than the mipmap at the specified index.
D3DTSS_MAXANISOTROPY
Maximum level of anisotropy. The default value is 1.
D3DTSS_BUMPENVLSCALE
D3DVALUE scale for bump-map luminance. The default value is 0.
D3DTSS_BUMPENVLOFFSET
D3DVALUE offset for bump-map luminance. The default value is 0.
D3DTSS_TEXTURETRANSFORMFLAGS
Member of the D3DTEXTURETRANSFORMFLAGS enumeration that controls the transformation of texture coordinates for this texture stage. The default value is D3DTTFF_DISABLE.
D3DTSS_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The valid range of values for the D3DTSS_BUMPENVMAT00, D3DTSS_BUMPENVMAT01, D3DTSS_BUMPENVMAT10, and D3DTSS_BUMPENVMAT11 bump-mapping matrix coefficients is greater than or equal to –8.0, and less than 8.0. This range, expressed in mathematical notation is [–8.0,8.0).

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 6.0 or later.
Header: Declared in d3dtypes.h.


D3DTEXTURETRANSFORMFLAGS

The D3DTEXTURETRANSFORMFLAGS enumerated type defines values used with the D3DTSS_TEXTURETRANSFORMFLAGS texture-stage state.

typedef enum _D3DTEXTURETRANSFORMFLAGS {
    D3DTTFF_DISABLE         = 0,
    D3DTTFF_COUNT1          = 1,
    D3DTTFF_COUNT2          = 2,
    D3DTTFF_COUNT3          = 3,
    D3DTTFF_COUNT4          = 4,
    D3DTTFF_PROJECTED       = 256,
    D3DTTFF_FORCE_DWORD     = 0x7fffffff,
} D3DTEXTURETRANSFORMFLAGS;
D3DTTFF_DISABLE
Texture coordinates are passed directly to the rasterizer.
D3DTTFF_COUNT1
The rasterizer should expect 1-D texture coordinates.
D3DTTFF_COUNT2
The rasterizer should expect 2-D texture coordinates.
D3DTTFF_COUNT3
The rasterizer should expect 3-D texture coordinates.
D3DTTFF_COUNT4
The rasterizer should expect 4-D texture coordinates.
D3DTTFF_PROJECTED
The texture coordinates are all divided by the last element before being passed to the rasterizer. For example, if this flag is specified with the D3DTTFF_COUNT3 flag, the first and second texture coordinates will be divided by the third coordinate before being passed to the rasterizer.
D3DTTFF_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dtypes.h.

See Also

D3DTSS_TEXTURETRANSFORMFLAGS, Texture Coordinate Transformations


D3DTRANSFORMSTATETYPE

The D3DTRANSFORMSTATETYPE enumerated type describes the transformation state values used with the IDirect3DDevice7::GetTransform and IDirect3DDevice7::SetTransform methods.

typedef enum _D3DTRANSFORMSTATETYPE {
    D3DTRANSFORMSTATE_WORLD        = 1,
    D3DTRANSFORMSTATE_VIEW         = 2,
    D3DTRANSFORMSTATE_PROJECTION   = 3,
    D3DTRANSFORMSTATE_WORLD1       = 4,
    D3DTRANSFORMSTATE_WORLD2       = 5,
    D3DTRANSFORMSTATE_WORLD3       = 6,
    D3DTRANSFORMSTATE_TEXTURE0     = 16,
    D3DTRANSFORMSTATE_TEXTURE1     = 17,
    D3DTRANSFORMSTATE_TEXTURE2     = 18,
    D3DTRANSFORMSTATE_TEXTURE3     = 19,
    D3DTRANSFORMSTATE_TEXTURE4     = 20,
    D3DTRANSFORMSTATE_TEXTURE5     = 21,
    D3DTRANSFORMSTATE_TEXTURE6     = 22,
    D3DTRANSFORMSTATE_TEXTURE7     = 23,
    D3DTRANSFORMSTATE_FORCE_DWORD  = 0x7fffffff,
} D3DTRANSFORMSTATETYPE;
D3DTRANSFORMSTATE_WORLD
Identifies the transformation matrix being set as the world transformation matrix. The default value is NULL (the identity matrix).
D3DTRANSFORMSTATE_WORLD1, D3DTRANSFORMSTATE_WORLD2, D3DTRANSFORMSTATE_WORLD3
Identifies subsequent transformation matrices that can be used to blend vertices by using the corresponding matrix and a blending (beta) weight value specified in the vertex format.
D3DTRANSFORMSTATE_VIEW
Identifies the transformation matrix being set as the view transformation matrix. The default value is NULL (the identity matrix).
D3DTRANSFORMSTATE_PROJECTION
Identifies the transformation matrix being set as the projection transformation matrix. The default value is NULL (the identity matrix).
D3DTRANSFORMSTATE_TEXTURE0 through D3DTRANSFORMSTATE_TEXTURE7
Identifies the transformation matrix being set for the specified texture stage.
D3DTRANSFORMSTATE_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.

See Also

IDirect3DDevice7::GetTransform, IDirect3DDevice7::SetTransform


D3DVERTEXBLENDFLAGS

The D3DVERTEXBLENDFLAGS enumerated type defines flags used to control the number or matrices that the system applies when performing multimatrix vertex blending. Members of this type are used with the D3DRENDERSTATE_VERTEXBLEND render state.

typedef enum _D3DVERTEXBLENDFLAGS {
    D3DVBLEND_DISABLE  = 0,
    D3DVBLEND_1WEIGHT  = 1,
    D3DVBLEND_2WEIGHTS = 2,
    D3DVBLEND_3WEIGHTS = 3,
} D3DVERTEXBLENDFLAGS;

Members

D3DVBLEND_DISABLE
Disable vertex blending; only apply the world matrix specified by the D3DTRANSFORMSTATE_WORLD transformation state.
D3DVBLEND_1WEIGHT
Enable vertex blending between the two matrices set by the D3DTRANSFORMSTATE_WORLD and D3DTRANSFORMSTATE_WORLD1 transformation states.
D3DVBLEND_2WEIGHTS
Enable vertex blending between the three matrices set by the D3DTRANSFORMSTATE_WORLD, D3DTRANSFORMSTATE_WORLD1, and D3DTRANSFORMSTATE_WORLD2 transformation states.
D3DVBLEND_3WEIGHTS
Enable vertex blending between the four matrices set by the D3DTRANSFORMSTATE_WORLD, D3DTRANSFORMSTATE_WORLD1, D3DTRANSFORMSTATE_WORLD2, and D3DTRANSFORMSTATE_WORLD3 transformation states.

Remarks

Geometry blending (multimatrix vertex blending) requires that your application use a vertex format that has blending (beta) weights for each vertex.

See Also

D3DRENDERSTATETYPE, D3DTRANSFORMSTATETYPE, IDirect3DDevice7::SetTransform, Geometry Blending


D3DVERTEXTYPE

The D3DVERTEXTYPE enumerated type lists the vertex types that are supported by the legacy IDirect3DDevice3, IDirect3DDevice2, and IDirect3DDevice interfaces. If your application uses interfaces later than IDirect3DDevice3, such as IDirect3DDevice7, the D3DVERTEXTYPE enumerated type is superseded by flexible vertex format flags.

typedef enum _D3DVERTEXTYPE {
    D3DVT_VERTEX       = 1,
    D3DVT_LVERTEX      = 2,
    D3DVT_TLVERTEX     = 3
    D3DVT_FORCE_DWORD  = 0x7fffffff,
} D3DVERTEXTYPE;
D3DVT_VERTEX
All the vertices in the array are of the D3DVERTEX type. This setting causes transformation, lighting, and clipping to be applied to the primitive as it is rendered.
D3DVT_LVERTEX
All the vertices in the array are of the D3DLVERTEX type. When used with this option, the primitive has transformations applied during rendering.
D3DVT_TLVERTEX
All the vertices in the array are of the D3DTLVERTEX type. Rasterization is applied only to this data.
D3DVT_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.

See Also

Vertex Formats


D3DZBUFFERTYPE

The D3DZBUFFERTYPE enumerated type describes depth-buffer formats for use with the D3DRENDERSTATE_ZENABLE render state.

typedef enum _D3DZBUFFERTYPE {
    D3DZB_FALSE        = 0,
    D3DZB_TRUE         = 1,
    D3DZB_USEW         = 2,
    D3DZB_FORCE_DWORD  = 0x7fffffff,
} D3DZBUFFERTYPE;
D3DZB_FALSE
Disable depth buffering.
D3DZB_TRUE
Enable z-buffering.
D3DZB_USEW
Enable w-buffering.
D3DZB_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The D3DZB_FALSE and D3DZB_TRUE values are interchangeable with the TRUE and FALSE macro values previously used with D3DRENDERSTATE_ZENABLE.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 6.0 or later.
Header: Declared in d3dtypes.h.

See Also

IDirect3DDevice7::SetRenderState, Depth Buffers


Obsolete Enumerated Types

The following enumerated types are obsolete. For information about these enumerated types, see the documentation provided with a previous release of DirectX. Legacy documentation is provided with this SDK and is available for download from http://www.microsoft.com/directx.

  • D3DOPCODE
  • D3DLIGHTSTATETYPE
  • D3DTEXTUREBLEND
  • D3DTEXTUREFILTER


Obsolete Render States

The D3DRENDERSTATETYPE enumerated type, declared in D3dtypes.h, includes many render states that became obsolete with the release of DirectX 7.0. These render states are not supported by the DirectX 7.0 interfaces and are only declared for backward compatibility with existing applications. Attempts to use these render states with the IDirect3DDevice7 interface will fail, returning DDERR_INVALIDPARAMS. Information about using these render states with legacy interfaces is provided with previous releases of the DirectX SDK. Legacy documentation is provided with this SDK and is available for download from http://www.microsoft.com/directx.

  • D3DRENDERSTATE_ANISOTROPY
  • D3DRENDERSTATE_BORDERCOLOR
  • D3DRENDERSTATE_FLUSHBATCH
  • D3DRENDERSTATE_MIPMAPLODBIAS
  • D3DRENDERSTATE_MONOENABLE
  • D3DRENDERSTATE_PLANEMASK
  • D3DRENDERSTATE_ROP2
  • D3DRENDERSTATE_STIPPLEENABLE
  • D3DRENDERSTATE_STIPPLEPATTERN00 through D3DRENDERSTATE_STIPPLEPATTERN31
  • D3DRENDERSTATE_SUBPIXEL
  • D3DRENDERSTATE_SUBPIXELX
  • D3DRENDERSTATE_TEXTUREADDRESS
  • D3DRENDERSTATE_TEXTUREADDRESSU
  • D3DRENDERSTATE_TEXTUREADDRESSV
  • D3DRENDERSTATE_TEXTUREHANDLE
  • D3DRENDERSTATE_TEXTUREMAG
  • D3DRENDERSTATE_TEXTUREMAPBLEND
  • D3DRENDERSTATE_TEXTUREMIN
  • D3DRENDERSTATE_TRANSLUCENTSORTINDEPENDENT
  • D3DRENDERSTATE_WRAPU and
  • D3DRENDERSTATE_WRAPV


Other Types

This section contains information about the following Direct3D Immediate Mode types that are neither structures nor enumerated types:

  • D3DCOLOR
  • D3DCOLORMODEL
  • D3DFIXED
  • D3DVALUE


D3DCOLOR

The D3DCOLOR type is the fundamental Direct3D color type.

typedef DWORD D3DCOLOR, D3DCOLOR, *LPD3DCOLOR;

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.

See Also

D3DRGB, D3DRGBA


D3DCOLORMODEL

The D3DCOLORMODEL type is used to define the color model in which the system runs. A driver can expose either or both flags in the dcmColorModel member of the D3DDEVICEDESC7 structure.

typedef DWORD D3DCOLORMODEL
D3DCOLOR_MONO
Use a monochromatic model (or ramp model). In this model, the blue component of a vertex color is used to define the brightness of a lit vertex.
D3DCOLOR_RGB
Use a full RGB model.

Remarks

Prior to DirectX 5.0, these values were part of an enumerated type. The enumerated type in earlier versions of DirectX had this syntax:

typedef enum _D3DCOLORMODEL {
    D3DCOLOR_MONO = 1,
    D3DCOLOR_RGB  = 2,
} D3DCOLORMODEL;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 6.0 or later.
Header: Declared in d3dtypes.h.

See Also

D3DDEVICEDESC7


D3DFIXED

The D3DFIXED type is used to represent a 16:16 fixed-point value.

typedef LONG D3DFIXED;

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 5.0 or later.
Header: Declared in d3dtypes.h.


D3DVALUE

The D3DVALUE type is the fundamental Direct3D fractional data type.

typedef float D3DVALUE, *LPD3DVALUE;

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 2.0 or later.
Header: Declared in d3dtypes.h.


Flexible Vertex Format Flags

Direct3D Immediate Mode uses flag values to describe vertex formats used for DrawPrimitive-based rendering. The D3dtypes.h header file declares the following flags to explicitly describe a vertex format and provides helper macros that act as common combinations of such flags. For more information, see About Vertex Formats.

Flexible vertex format (FVF) flags
D3DFVF_DIFFUSE
Vertex format includes a diffuse color component.
D3DFVF_NORMAL
Vertex format includes a vertex normal vector. This flag cannot be used with the D3DFVF_XYZRHW flag.
D3DFVF_SPECULAR
Vertex format includes a specular color component.
D3DFVF_XYZ
Vertex format includes the position of an untransformed vertex. This flag cannot be used with the D3DFVF_XYZRHW flag. If you use this flag, you must also specify a vertex normal, a vertex color component (D3DFVF_DIFFUSE or D3DFVF_SPECULAR), or include at least one set of texture coordinates (D3DFVF_TEX1 through D3DFVF_TEX8).
D3DFVF_XYZRHW
Vertex format includes the position of a transformed vertex. This flag cannot be used with the D3DFVF_XYZ or D3DFVF_NORMAL flags. If you use this flag, you must also specify a vertex color component (D3DFVF_DIFFUSE or D3DFVF_SPECULAR) or include at least one set of texture coordinates (D3DFVF_TEX1 through D3DFVF_TEX8).
D3DFVF_XYZB1 through D3DFVF_XYZB5
Vertex format contains position data, and a corresponding number of weighting (beta) values to be used for multimatrix vertex blending operations. Currently, Direct3D can blend with up to three weighting values (and four blending matrices).
Texture-related FVF flags
D3DFVF_TEX0 through D3DFVF_TEX8
Number of texture coordinate sets for this vertex. The actual values for these flags are not sequential.
D3DFVF_TEXTUREFORMAT1 through D3DFVF_TEXTUREFORMAT4
Number of values that define a texture coordinate set. The D3DFVF_TEXTUREFORMAT1 indicates one-dimensional texture coordinates, D3DFVF_TEXTUREFORMAT2 indicates two-dimensional texture coordinates, and so on. These flags are rarely used alone; they are used with the D3DFVF_TEXCOORDSIZEn macros.
Helper macros
D3DFVF_LVERTEX
Vertex format is equivalent to the D3DLVERTEX vertex type.
D3DFVF_TLVERTEX
Vertex format is equivalent to the D3DTLVERTEX vertex type.
D3DFVF_VERTEX
Vertex format is equivalent to the D3DVERTEX vertex type.
Mask values
D3DFVF_POSITION_MASK
Mask for position bits.
D3DFVF_RESERVED0 and D3DFVF_RESERVED2
Mask values for reserved bits in the flexible vertex format. Do not use.
D3DFVF_RESERVED1,
This bit is reserved to indicate that the system should emulate D3DLVERTEX processing. If this flag is used, the D3DFVF_XYZ, D3DFVF_DIFFUSE, D3DFVF_SPECULAR, and D3DFVF_TEX1 flags must also be used. This equates to the effect of the D3DFVF_LVERTEX helper macro.
D3DFVF_TEXCOUNT_MASK
Mask value for texture flag bits.
Miscellaneous
D3DFVF_TEXCOUNT_SHIFT
The number of bits by which to shift an integer value that identifies the number of a texture coordinates for a vertex. This value might be used as follows:
    DWORD dwNumTextures = 1;  // Vertex has only one set of coordinates.

    // Shift the value for use when creating an FVF combination.
    dwFVF = dwNumTextures<<D3DFVF_TEXCOUNT_SHIFT;

    /*
     * Now, create an FVF combination using the shifted value.
     */

The following example shows some other common flag combinations:

    // Lightweight, untransformed vertex for lit, untextured,
    // Gouraud-shaded content.
    dwFVF = ( D3DFVF_XYZ | D3DFVF_DIFFUSE );

    // Untransformed vertex for unlit, untextured, Gouraud-shaded
    // content with diffuse material color specified per vertex.
    dwFVF = ( D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_DIFFUSE );

    // Untransformed vertex for light-map-based lighting.
    dwFVF = ( D3DFVF_XYZ | D3DFVF_TEX2 );

    // Transformed vertex for light-map-based lighting
    // with shared rhw.
    dwFVF = ( D3DFVF_XYZRHW | D3DFVF_TEX2 );

    // Heavyweight vertex for unlit, colored content with two
    // sets of texture coordinates.
    dwFVF = ( D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_DIFFUSE |
              D3DFVF_SPECULAR | D3DFVF_TEX2 );

See Also

About Vertex Formats, Geometry Blending


Texture Argument Flags

Each texture stage for a device can have two texture arguments that affect the color or alpha channel of the texture. Set and retrieve texture arguments by calling the IDirect3DDevice7::SetTextureStageState and IDirect3DDevice7::GetTextureStageState methods, specifying the D3DTSS_COLORARG1, D3DTSS_COLORARG2, D3DTSS_ALPHAARG1, or D3DTSS_ALPHAARG2 member of the D3DTEXTURESTAGESTATETYPE enumerated type.

The following flags, organized as arguments and modifiers, can be used with color and alpha arguments for a texture stage. You can combine an argument flag with a modifier, but two argument flags cannot be combined.

Argument flags
D3DTA_CURRENT
The texture argument is the result of the previous blending stage. In the first texture stage (stage 0), this argument is equivalent to D3DTA_DIFFUSE. If the previous blending stage uses a bump-map texture (the D3DTOP_BUMPENVMAP operation), the system chooses the texture from the stage before the bump-map texture. (If s represents the current texture stage and s – 1 contains a bump-map texture, this argument becomes the result output by texture stage s – 2.)
D3DTA_DIFFUSE
The texture argument is the diffuse color interpolated from vertex components during Gouraud shading. If the vertex does not contain a diffuse color, the default color is 0xFFFFFFFF.
D3DTA_SELECTMASK
Mask value for all arguments; not used when setting texture arguments.
D3DTA_TEXTURE
The texture argument is the texture color for this texture stage. This is valid only for the first color and alpha arguments in a stage (the D3DTSS_COLORARG1 and D3DTSS_ALPHAARG1 members of D3DTEXTURESTAGESTATETYPE).
D3DTA_TFACTOR
The texture argument is the texture factor set in a previous call to the IDirect3DDevice7::SetRenderState with the D3DRENDERSTATE_TEXTUREFACTOR render-state value.
D3DTA_SPECULAR
The texture argument is the specular color interpolated from vertex components during Gouraud shading. If the vertex does not contain a diffuse color, the default color is 0xFFFFFFFF.
Modifier flags
D3DTA_ALPHAREPLICATE
Replicate the alpha information to all color channels before the operation completes.
D3DTA_COMPLEMENT
Invert the argument so that, if the result of the argument were referred to by the variable x, the value would be 1.0 minus x.


Return Values

Errors are represented by negative values and cannot be combined. This table lists the values that can be returned by all Direct3D Immediate Mode methods. See the individual method descriptions for lists of the values that each can return.

D3D_OK
No error occurred.
D3DERR_BADMAJORVERSION
The service that you requested is unavailable in this major version of DirectX. (A major version denotes a primary release, such as DirectX 6.0.)
D3DERR_BADMINORVERSION
The service that you requested is available in this major version of DirectX, but not in this minor version. Get the latest version of the component run time from Microsoft. (A minor version denotes a secondary release, such as DirectX 6.1.)
D3DERR_COLORKEYATTACHED
The application attempted to create a texture with a surface that uses a color key for transparency.
D3DERR_CONFLICTINGTEXTUREFILTER
The current texture filters cannot be used together.
D3DERR_CONFLICTINGTEXTUREPALETTE
The current textures cannot be used simultaneously. This generally occurs when a multitexture device requires that all palettized textures simultaneously enabled also share the same palette.
D3DERR_CONFLICTINGRENDERSTATE
The currently set render states cannot be used together.
D3DERR_DEVICEAGGREGATED
The IDirect3DDevice7::SetRenderTarget method was called on a device that was retrieved from the render target surface.
D3DERR_EXECUTE_CLIPPED_FAILED
The execute buffer could not be clipped during execution.
D3DERR_EXECUTE_CREATE_FAILED
The execute buffer could not be created. This typically occurs when no memory is available to allocate the execute buffer.
D3DERR_EXECUTE_DESTROY_FAILED
The memory for the execute buffer could not be deallocated.
D3DERR_EXECUTE_FAILED
The contents of the execute buffer are invalid and cannot be executed.
D3DERR_EXECUTE_LOCK_FAILED
The execute buffer could not be locked.
D3DERR_EXECUTE_LOCKED
The operation requested by the application could not be completed because the execute buffer is locked.
D3DERR_EXECUTE_NOT_LOCKED
The execute buffer could not be unlocked because it is not currently locked.
D3DERR_EXECUTE_UNLOCK_FAILED
The execute buffer could not be unlocked.
D3DERR_INBEGIN
The requested operation cannot be completed while scene rendering is taking place. Try again after the scene is completed and the IDirect3DDevice7::EndScene method is called.
D3DERR_INBEGINSTATEBLOCK
The operation cannot be completed while recording states for a state block. Complete recording by calling the IDirect3DDevice7::EndStateBlock method, and try again.
D3DERR_INITFAILED
A rendering device could not be created because the new device could not be initialized.
D3DERR_INVALID_DEVICE
The requested device type is not valid.
D3DERR_INVALIDCURRENTVIEWPORT
The currently selected viewport is not valid.
D3DERR_INVALIDMATRIX
The requested operation could not be completed because the combination of the currently set world, view, and projection matrices is invalid (the determinant of the combined matrix is 0).
D3DERR_INVALIDPALETTE
The palette associated with a surface is invalid.
D3DERR_INVALIDPRIMITIVETYPE
The primitive type specified by the application is invalid.
D3DERR_INVALIDRAMPTEXTURE
Ramp mode is being used, and the texture handle in the current material does not match the current texture handle that is set as a render state.
D3DERR_INVALIDSTATEBLOCK
The state block handle is invalid.
D3DERR_INVALIDVERTEXFORMAT
The combination of flexible vertex format flags specified by the application is not valid.
D3DERR_INVALIDVERTEXTYPE
The vertex type specified by the application is invalid.
D3DERR_LIGHT_SET_FAILED
The attempt to set lighting parameters for a light object failed.
D3DERR_LIGHTHASVIEWPORT
The requested operation failed because the light object is associated with another viewport.
D3DERR_LIGHTNOTINTHISVIEWPORT
The requested operation failed because the light object has not been associated with this viewport.
D3DERR_MATERIAL_CREATE_FAILED
The material could not be created. This typically occurs when no memory is available to allocate for the material.
D3DERR_MATERIAL_DESTROY_FAILED
The memory for the material could not be deallocated.
D3DERR_MATERIAL_GETDATA_FAILED
The material parameters could not be retrieved.
D3DERR_MATERIAL_SETDATA_FAILED
The material parameters could not be set.
D3DERR_MATRIX_CREATE_FAILED
The matrix could not be created. This can occur when no memory is available to allocate for the matrix.
D3DERR_MATRIX_DESTROY_FAILED
The memory for the matrix could not be deallocated.
D3DERR_MATRIX_GETDATA_FAILED
The matrix data could not be retrieved. This can occur when the matrix was not created by the current device.
D3DERR_MATRIX_SETDATA_FAILED
The matrix data could not be set. This can occur when the matrix was not created by the current device.
D3DERR_NOCURRENTVIEWPORT
The viewport parameters could not be retrieved because none have been set.
D3DERR_NOTINBEGIN
The requested rendering operation could not be completed because scene rendering has not begun. Call IDirect3DDevice7::BeginScene to begin rendering, and try again.
D3DERR_NOTINBEGINSTATEBLOCK
The requested operation could not be completed because it is only valid while recording a state block. Call the IDirect3DDevice7::BeginStateBlock method, and try again.
D3DERR_NOVIEWPORTS
The requested operation failed because the device currently has no viewports associated with it.
D3DERR_SCENE_BEGIN_FAILED
Scene rendering could not begin.
D3DERR_SCENE_END_FAILED
Scene rendering could not be completed.
D3DERR_SCENE_IN_SCENE
Scene rendering could not begin because a previous scene was not completed by a call to the IDirect3DDevice7::EndScene method.
D3DERR_SCENE_NOT_IN_SCENE
Scene rendering could not be completed because a scene was not started by a previous call to the IDirect3DDevice7::BeginScene method.
D3DERR_SETVIEWPORTDATA_FAILED
The viewport parameters could not be set.
D3DERR_STENCILBUFFER_NOTPRESENT
The requested stencil buffer operation could not be completed because there is no stencil buffer attached to the render target surface.
D3DERR_SURFACENOTINVIDMEM
The device could not be created because the render target surface is not located in video memory. (Hardware-accelerated devices require video-memory render target surfaces.)
D3DERR_TEXTURE_BADSIZE
The dimensions of a current texture are invalid. This can occur when an application attempts to use a texture that has dimensions that are not a power of 2 with a device that requires them.
D3DERR_TEXTURE_CREATE_FAILED
The texture handle for the texture could not be retrieved from the driver.
D3DERR_TEXTURE_DESTROY_FAILED
The device was unable to deallocate the texture memory.
D3DERR_TEXTURE_GETSURF_FAILED
The DirectDraw surface used to create the texture could not be retrieved.
D3DERR_TEXTURE_LOAD_FAILED
The texture could not be loaded.
D3DERR_TEXTURE_LOCK_FAILED
The texture could not be locked.
D3DERR_TEXTURE_LOCKED
The requested operation could not be completed because the texture surface is currently locked.
D3DERR_TEXTURE_NO_SUPPORT
The device does not support texture mapping.
D3DERR_TEXTURE_NOT_LOCKED
The requested operation could not be completed because the texture surface is not locked.
D3DERR_TEXTURE_SWAP_FAILED
The texture handles could not be swapped.
D3DERR_TEXTURE_UNLOCK_FAILED
The texture surface could not be unlocked.
D3DERR_TOOMANYOPERATIONS
The application is requesting more texture-filtering operations than the device supports.
D3DERR_TOOMANYPRIMITIVES
The device is unable to render the provided number of primitives in a single pass.
D3DERR_UNSUPPORTEDALPHAARG
The device does not support one of the specified texture-blending arguments for the alpha channel.
D3DERR_UNSUPPORTEDALPHAOPERATION
The device does not support one of the specified texture-blending operations for the alpha channel.
D3DERR_UNSUPPORTEDCOLORARG
The device does not support one of the specified texture-blending arguments for color values.
D3DERR_UNSUPPORTEDCOLOROPERATION
The device does not support one of the specified texture-blending operations for color values.
D3DERR_UNSUPPORTEDFACTORVALUE
The specified texture factor value is not supported by the device.
D3DERR_UNSUPPORTEDTEXTUREFILTER
The specified texture filter is not supported by the device.
D3DERR_VBUF_CREATE_FAILED
The vertex buffer could not be created. This can happen when there is insufficient memory to allocate a vertex buffer.
D3DERR_VERTEXBUFFERLOCKED
The requested operation could not be completed because the vertex buffer is locked.
D3DERR_VERTEXBUFFEROPTIMIZED
The requested operation could not be completed because the vertex buffer is optimized. (The contents of optimized vertex buffers are driver-specific and considered private.)
D3DERR_VERTEXBUFFERUNLOCKFAILED
The vertex buffer could not be unlocked because the vertex buffer memory was overrun. Be sure that your application does not write beyond the size of the vertex buffer.
D3DERR_VIEWPORTDATANOTSET
The requested operation could not be completed because viewport parameters have not yet been set. Set the viewport parameters by calling the IDirect3DDevice7::SetViewport method, and try again.
D3DERR_VIEWPORTHASNODEVICE
This value is used only by the IDirect3DDevice3 interface and its predecessors. For the IDirect3DDevice7 interface, this error value is not used.

The requested operation could not be completed because the viewport has not yet been associated with a device. Associate the viewport with a rendering device by calling the IDirect3DDevice3::AddViewport method, and try again.

D3DERR_WRONGTEXTUREFORMAT
The pixel format of the texture surface is not valid.
D3DERR_ZBUFF_NEEDS_SYSTEMMEMORY
The requested operation could not be completed because the specified device requires system-memory depth-buffer surfaces. (Software rendering devices require system-memory depth buffers.)
D3DERR_ZBUFF_NEEDS_VIDEOMEMORY
The requested operation could not be completed because the specified device requires video-memory depth-buffer surfaces. (Hardware-accelerated devices require video-memory depth buffers.)
D3DERR_ZBUFFER_NOTPRESENT
The requested operation could not be completed because the render target surface does not have an attached depth buffer.


Direct3D Immediate Mode Visual Basic Reference

This section contains reference information for the application programming interface (API) elements provided by Direct3D® Immediate Mode. Reference material is divided into the following categories:

  • Classes
  • Types
  • Enumerations
  • Flexible Vertex Format Flags
  • Texture Argument Flags
  • Error Codes


Classes

This section contains reference information for the classes provided by Direct3D Immediate Mode. The following classes are covered:

  • Direct3D7
  • Direct3DDevice7
  • Direct3DEnumDevices
  • Direct3DEnumPixelFormats
  • Direct3DVertexBuffer7


Direct3D7

Applications use the methods of the Direct3D7 class to create Direct3D objects and set up the environment. Moreover, The Direct3D7 class enables applications to create vertex buffers and enumerate texture map and depth-buffer formats. This section is a reference to the methods of this class.

The Direct3D7 class is obtained by calling the GetDirect3D method from a DirectDraw7 object.

The methods of the Direct3D7 class can be organized into the following groups:

Creation | CreateDevice
 | CreateVertexBuffer
Enumeration | GetDevicesEnum
 | GetEnumZBufferFormats
Miscellaneous | EvictManagedTextures
 | GetDirectDraw

See Also

Accessing Direct3D, Direct3D and DirectDraw


Direct3D7.CreateDevice

The Direct3D7.CreateDevice method creates a Direct3D device to be used with the DrawPrimitive methods.

object.CreateDevice( _
    guid As String, _
    surf As DirectDrawSurface7) As Direct3DDevice7

Parameters

object
Object expression that resolves to a Direct3D7 object.
guid
Guid for the new device. This value can be an enumerated GUID string or the "IID_Direct3DHALDevice" or "IID_Direct3DRGBDevice" string constants. The method also accepts "IID_Direct3DRefDevice" which creates the reference device, for use in testing or feature demonstration.
surf
A DirectDrawSurface7 object for the DirectDrawSurface object that will be the device's rendering target. The surface must have been created as a 3-D device by using the DDSCAPS_3DDEVICE capability.

Return Values

If the method succeeds, the return value is a reference to a Direct3DDevice7 object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DDERR_INVALIDPARAMS if one of the parameters is invalid.

Remarks

All rendering devices created by a given Direct3D7 object share the same physical resources. Although your application can create multiple rendering devices from a single Direct3D7 object, because they share the same hardware, extreme performance penalties will be incurred.

When you call Direct3D7.CreateDevice, you create a device object that is separate from a DirectDraw surface object. This device uses a DirectDraw surface as a rendering target.

See Also

Direct3DDevice7, Creating a Direct3D Device, Direct3D Devices


Direct3D7.CreateVertexBuffer

The Direct3D7.CreateVertexBuffer method creates a vertex buffer object.

object.CreateVertexBuffer( _
    desc As D3DVERTEXBUFFERDESC, _
    flags As CONST_D3DDPFLAGS) As Direct3DVertexBuffer7

Parameters

object
Object expression that resolves to a Direct3D7 object.
desc
A D3DVERTEXBUFFERDESC type that describes the format and number of vertices that the vertex buffer will contain.
flags
One of the constants of the CONST_D3DDPFLAGS enumeration (flexible vertex format flags) representing the clipping value. Set this parameter to 0 to create a vertex buffer that can contain clipping information for untransformed or transformed vertices, or use the D3DDP_DONOTCLIP flag to create a vertex buffer that will contain transformed vertices, but no clipping information.

Return Values

If the method succeeds, a reference to a Direct3DVertexBuffer7 object is returned.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes:

D3DERR_INVALIDVERTEXFORMAT
D3DERR_VBUF_CREATE_FAILED
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY

See Also

Direct3DVertexBuffer7, Vertex Buffers


Direct3D7.EvictManagedTextures

The Direct3D7.EvictManagedTextures method purges all managed textures from local or non-local video memory.

object.EvictManagedTextures()

Parameters

object
Object expression that resolves to a Direct3D7 object.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

Remarks

This method causes Direct3D to remove any texture surfaces created with the DDSCAPS2_TEXTUREMANAGE or DDSCAPS2_D3DTEXTUREMANAGE flags from local or non-local video memory.

See Also

Automatic Texture Management


Direct3D7.GetDevicesEnum

The Direct3D7.GetDevicesEnum method creates a Direct3DEnumDevices object.

object.GetDevicesEnum() As Direct3DEnumDevices

Parameters

object
Object expression that resolves to a Direct3D7 object.

Return Values

If the method succeeds, a Direct3DEnumDevices object is returned.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS


Direct3D7.GetDirectDraw

The Direct3D7.GetDirectDraw method retrieves the DirectDraw7 object associated with this Direct3D object.

object.GetDirectDraw() As DirectDraw7

Parameters

object
Object expression that resolves to a Direct3D7 object.

Return Values

If the method succeeds, a reference to a DirectDraw7 object is returned.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_OUTOFMEMORY

For information on trapping errors, see the Visual Basic Error Trapping topic.


Direct3D7.GetEnumZBufferFormats

The Direct3D7.GetEnumZBufferFormats method creates a Direct3DEnumPixelFormats object.

object.GetEnumZBufferFormats( _
    guid As String) As Direct3DEnumPixelFormats

Parameters

object
Object expression that resolves to a Direct3D7 object.
guid
A globally unique identifier for the device whose depth-buffer formats will be enumerated.

Return Values

If the method succeeds, a reference to a Direct3DEnumPixelFormats object is returned.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOZBUFFERHW
DDERR_OUTOFMEMORY

For information on trapping errors, see the Visual Basic Error Trapping topic.


Direct3DDevice7

The Direct3DDevice7 class provides methods enabling applications to perform DrawPrimitive-based rendering. You create a device by calling the Direct3D7.CreateDevice method.

For a conceptual overview, see Direct3D Devices and the DrawPrimitive Methods.

The methods of the Direct3DDevice7 class can be organized into the following groups:

Information | GetCaps
 | GetDirect3D
 | GetInfo
 | GetDeviceGuid
Device States | ApplyStateBlock
 | BeginStateBlock
 | CaptureStateBlock
 | CreateStateBlock
 | DeleteStateBlock
 | EndStateBlock
 | GetClipStatus
 | GetRenderState
 | GetRenderStateSingle
 | GetRenderTarget
 | GetTransform
 | SetClipStatus
 | SetRenderState
 | SetRenderStateSingle
 | SetRenderTarget
 | SetTransform
Lighting and Materials | GetMaterial
 | GetLight
 | GetLightEnable
 | LightEnable
 | SetMaterial
 | SetLight
Miscellaneous | ComputeSphereVisibility
 | MultiplyTransform
Rendering | DrawIndexedPrimitive
 | DrawIndexedPrimitiveVB
 | DrawPrimitive
 | DrawPrimitiveVB
Scenes | BeginScene
 | EndScene
Textures | GetTexture
 | GetTextureFormatsEnum
 | GetTextureStageState
 | GetTextureStageStateSingle
 | Load
 | PreLoad
 | SetTexture
 | SetTextureStageState
 | SetTextureStageStateSingle
 | ValidateDevice
User-defined clip planes | GetClipPlane
 | SetClipPlane
Viewports | Clear
 | GetViewport
 | SetViewport

This class contains methods to support more flexible vertex formats, vertex buffers, and visibility computation.

See Also

Direct3D Devices, Rendering


Direct3DDevice7.ApplyStateBlock

The Direct3DDevice7.ApplyStateBlock method applies an existing device-state block to the rendering device.

object.ApplyStateBlock( _
    blockHandle As Long)

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
blockHandle
Handle to the device state block to be applied, as returned by a previous call to the Direct3DDevice7.EndStateBlock method.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DDERR_INVALIDPARAMS to indicate that the blockHandle parameter is invalid or a macro is currently being recorded.

Remarks

Applications cannot apply a device state block while recording another block.

This method was introduced with the Direct3DDevice7 interface.

As with all operations that affect the state of the rendering device, it is recommend that you apply state blocks during scene rendering—that is, after calling the Direct3DDevice7.BeginScene method, and before calling Direct3DDevice7.EndScene.

See Also

Direct3DDevice7.BeginStateBlock, Direct3DDevice7.CaptureStateBlock, Direct3DDevice7.CreateStateBlock, Direct3DDevice7.DeleteStateBlock, Direct3DDevice7.EndStateBlock, State Blocks


Direct3DDevice7.BeginScene

The Direct3DDevice7.BeginScene method begins a scene. Applications must call this method before performing any rendering, and must call Direct3DDevice7.EndScene when rendering is complete, and before calling Direct3DDevice7.BeginScene again.

object.BeginScene()

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

Remarks

If the BeginScene method fails, the device was unable to begin the scene, and there is no need to call the Direct3DDevice7.EndScene method. In fact, calls to the Direct3DDevice7.EndScene method will fail if the previous call to BeginScene failed.

See Also

Direct3DDevice7.EndScene


Direct3DDevice7.BeginStateBlock

The Direct3DDevice7.BeginStateBlock method signals Direct3D to begin recording a device state block.

object.BeginStateBlock()

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes:

DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY

Remarks

Applications can ensure that all recorded states are valid by calling the Direct3DDevice7.ValidateDevice method prior to calling this method.

The following methods can be recorded in a state block (that is, after calling Direct3DDevice7.BeginStateBlock and before Direct3DDevice7.EndStateBlock):

  • Direct3DDevice7.LightEnable
  • Direct3DDevice7.SetClipPlane
  • Direct3DDevice7.SetLight
  • Direct3DDevice7.SetMaterial
  • Direct3DDevice7.SetRenderState
  • Direct3DDevice7.SetTexture
  • Direct3DDevice7.SetTextureStageState
  • Direct3DDevice7.SetTransform
  • Direct3DDevice7.SetViewport

The ordering of state changes in a state block is not guaranteed. If the same state is specified multiple times in a state set only the last value will be used.

See Also

Direct3DDevice7.EndStateBlock, Direct3DDevice7.CaptureStateBlock, Direct3DDevice7.CreateStateBlock, Direct3DDevice7.DeleteStateBlock, Direct3DDevice7.ApplyStateBlock, State Blocks


Direct3DDevice7.CaptureStateBlock

The Direct3DDevice7.CaptureStateBlock method updates the values within an existing state block to the values currently set for the device.

object.CaptureStateBlock( _
    blockHandle As Long)

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
blockHandle
Handle to the state block into which the current device state will be captured.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes:

D3DERR_INBEGINSTATEBLOCK
D3DERR_INOVERLAYSTATEBLOCK

Remarks

This method captures updated values for states within an existing state block. It does not capture the entire state of the device. For more information, see Capturing State Blocks.

See Also

Direct3DDevice7.ApplyStateBlock, Direct3DDevice7.BeginStateBlock, Direct3DDevice7.CreateStateBlock, Direct3DDevice7.EndStateBlock, Direct3DDevice7.DeleteStateBlock, State Blocks


Direct3DDevice7.CreateStateBlock

The Direct3DDevice7.CreateStateBlock method creates a new state block that contains the current values for all device states, vertex-related states, or pixel-related states.

object.CreateStateBlock( _
  d3dsbType As CONST_D3DSTATEBLOCKTYPE, _
  blockHandle As Long)

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
d3dsbType
Type of state data that the method should capture. This can be one of the values defined in the CONST_D3DSTATEBLOCKTYPE enumeration.
blockHandle
Variable that will contain the state block handle if the method succeeds.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes:

D3DERR_INBEGINSTATEBLOCK
DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY

Remarks

Vertex-related device states typically refer to those states that affect how the system processes vertices. Pixel-related states generally refer to device states that affect how the system processes pixel or depth-buffer data during rasterization. Some states are contained in both groups. For information about the states in each group, see Creating Predefined State Blocks.

See Also

Direct3DDevice7.ApplyStateBlock, Direct3DDevice7.BeginStateBlock, Direct3DDevice7.CaptureStateBlock, Direct3DDevice7.EndStateBlock, Direct3DDevice7.DeleteStateBlock, State Blocks


Direct3DDevice7.Clear

The Direct3DDevice7.Clear method clears the viewport (or a set of rectangles in the viewport) to a specified RGBA color, clears the depth-buffer, and erases the stencil buffer.

object.Clear( _
    count As Long, _
    recs() As D3DRECT, _
    flags As CONST_D3DCLEARFLAGS, _
    color As Long, _
    z As Single, _
    stencil As Long)

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
count
Number of rectangles in the array at recs.
recs()
Array of D3DRECT types that describe the rectangles to be cleared. Set a rectangle to the dimensions of the rendering target to clear the entire surface. Each rectangle uses screen coordinates that correspond to points on the render target surface. Coordinates are clipped to the bounds of the viewport rectangle.
flags
Flags indicating which surfaces should be cleared. This parameter can be any combination of the following flags, but at least one flag must be used:
D3DCLEAR_TARGET
Clear the rendering target to the color in the color parameter.
D3DCLEAR_STENCIL
Clear the stencil buffer to the value in the stencil parameter.
D3DCLEAR_ZBUFFER
Clear the depth-buffer to the value in the z parameter.
color
RGBA color value to which the render target surface will be cleared. You can construct an appropriate value by calling the DirectX7.CreateColorRGBA method.
z
New z-value that this method stores in the depth-buffer. This parameter can range from 0.0 to 1.0, inclusive (for z-based or w-based depth buffers). The value of 0.0 represents the nearest distance to the viewer, and 1.0 the farthest distance.
stencil
Integer value to store in each stencil buffer entry. This parameter can range from 0 to 2n-1 inclusive, where n is the bit depth of the stencil buffer.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes:

D3DERR_STENCILBUFFER_NOTPRESENT
D3DERR_VIEWPORTHASNODEVICE
D3DERR_ZBUFFER_NOTPRESENT
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

This method fails if you specify the D3DCLEAR_ZBUFFER or D3DCLEAR_STENCIL flags when the render target does not have an attached depth-buffer. Similarly, if you specify the D3DCLEAR_STENCIL flag when the depth-buffer format doesn't contain stencil buffer information, this method fails.


Direct3DDevice7.ComputeSphereVisibility

The Direct3DDevice7.ComputeSphereVisibility method calculates the visibility (complete, partial, or no visibility) of a sphere within the current viewport for this device.

object.ComputeSphereVisibility( _
    center As D3DVECTOR, _
    radius As Single) As Long

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
center
A D3DVECTOR type describing the center point for the sphere, in world-space coordinates.
radius
The radius for the sphere.

Return Values

If the method succeeds, the return value is a combination of flags from the CONST_D3DCLIPFLAGS enumeration that describe the visibility of that sphere within the current viewport for this device. If the return value is zero (some combination of the "inside" flags) the sphere is completely visible.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DDERR_GENERIC
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

For information on trapping errors, see the Visual Basic Error Trapping topic.

Remarks

Sphere visibility is computed by back transforming the viewing frustum to the model space, using the inverse of the combined world, view or projection matrices. If the combined matrix cannot be inverted (if the determinant is zero), the method fails, returning DDERR_GENERIC.


Direct3DDevice7.DeleteStateBlock

The Direct3DDevice7.DeleteStateBlock method deletes a previously recorded device state block.

object.DeleteStateBlock( _
  blockHandle As Long)

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
blockHandle
Handle to the device state block to be deleted, as returned by a previous call to the Direct3DDevice7.EndStateBlock method.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DDERR_INVALIDPARAMS to indicate that the blockHandle parameter is invalid or a macro is currently being recorded.

Remarks

Applications cannot delete a device state block while another is being recorded.

See Also

Direct3DDevice7.BeginStateBlock, Direct3DDevice7.CaptureStateBlock, Direct3DDevice7.CreateStateBlock, Direct3DDevice7.EndStateBlock, Direct3DDevice7.ApplyStateBlock, State Blocks


Direct3DDevice7.DrawIndexedPrimitive

The Direct3DDevice7.DrawIndexedPrimitive method renders the specified geometric primitive based on indexing into an array of vertices.

object.DrawIndexedPrimitive( _
    d3Dpt As CONST_D3DPRIMITIVETYPE, _
    d3dfvf As CONST_D3DFVFFLAGS, _
    vertices As Any, _
    vertexCount As Long, _
    indices() As Integer, _
    IndicesCount As Long, _
    flags As CONST_D3DDPFLAGS)

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
d3Dpt
Type of primitive to be rendered by this command. This must be one of the constants of the CONST_D3DPRIMITIVETYPE enumeration.

Note that the D3DPT_POINTLIST member of CONST_D3DPRIMITIVETYPE is not indexed.

d3dfvf
A combination of flexible vertex format flags from the CONST_D3DFVFFLAGS enumeration that describe the vertex format used.
vertices
First element in an array of vertices to be used in the primitive sequence.
vertexCount
Defines the number of vertices in the vertices array.

Notice that this parameter is used differently from the vertexCount parameter in the Direct3DDevice7.DrawPrimitive method. In that method, the vertexCount parameter gives the number of vertices to draw, but here it gives the total number of vertices in the array pointed to by the vertices parameter. When you call Direct3DDevice7.DrawIndexedPrimitive, you specify the number of vertices to draw in the IndicesCount parameter.

indices()
Array that is to be used to index into the specified vertex list when creating the geometry to render. The values in the array must index vertices within the range [0, dwNumVertices – 1].
IndicesCount
Specifies the number of indices provided for creating the geometry. The maximum number of indices allowed is 65535 (&HFFFF).
flags
One of the constants from the CONST_D3DDPFLAGS defining how the primitive is drawn.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

D3DERR_INVALIDRAMPTEXTURE
D3DERR_INVALIDPRIMITIVETYPE
D3DERR_INVALIDVERTEXTYPE
DDERR_WASSTILLDRAWING
DDERR_INVALIDPARAMS

For information on trapping errors, see the Visual Basic Error Trapping topic.

Remarks

Make sure that the vertices being rendered match the vertex format you specify. For performance reasons, Direct3D does not attempt to verify that vertex size and stride match the provided flexible vertex format. If a mismatch occurs, a memory fault is likely to result.

In current versions of DirectX, Direct3DDevice7.DrawIndexedPrimitive can sometimes generate an update rectangle that is larger than it strictly needs to be. If a large number of vertices need to be processed, this can have a negative impact on the performance of your application. If you are using D3DTLVERTEX vertices and the system is processing more vertices than you need, you should use the D3DDP_DONOTCLIP and D3DDP_DONOTUPDATEEXTENTS flags to solve the problem.

See Also

Direct3DDevice7.DrawPrimitive, Direct3DDevice7.DrawPrimitiveVB, Direct3DDevice7.DrawIndexedPrimitiveVB


Direct3DDevice7.DrawIndexedPrimitiveVB

The Direct3DDevice7.DrawIndexedPrimitiveVB method renders a geometric primitive based on indexing into an array of vertices within a vertex buffer.

object.DrawIndexedPrimitiveVB( _
    d3Dpt As CONST_D3DPRIMITIVETYPE, _
    vertexBuffer As Direct3DVertexBuffer7, _
    StartVertex As Long, _
    NumVertices As Long, _
    indexArray() As Integer, _
    indexcount As Long, _
    flags As CONST_D3DDPFLAGS)

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
d3Dpt
Type of primitive to be rendered by this command. This must be one of the constants of the CONST_D3DPRIMITIVETYPE enumeration.

Note that the D3DPT_POINTLIST member of CONST_D3DPRIMITIVETYPE is not indexed.

vertexBuffer
A Direct3DVertexBuffer7 object for the vertex buffer that contains the array of vertices. Vertices can be transformed or untransformed, optimized or unoptimized.
StartVertex
Index of the first vertex in the vertex buffer that will be rendered.
NumVertices
Total number of vertices in the vertex buffer that will be rendered.
indexArray()
An array that will be used to index into the vertices in the vertex buffer. The values in the array must index vertices within the range [StartVertex, StartVertex + NumVertices – 1].
indexcount
The number of indices in the indexArray() array. The maximum number of indices allowed is 65535 (&HFFFF).
flags
One of the constants of the CONST_D3DDPFLAGS enumeration defining how the primitive is drawn.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

D3DERR_INVALIDPRIMITIVETYPE
D3DERR_INVALIDVERTEXTYPE
D3DERR_VERTEXBUFFERLOCKED
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_WASSTILLDRAWING

For information on trapping errors, see the Visual Basic Error Trapping topic.

Remarks

Make sure that the vertices being rendered match the vertex format you specify. For performance reasons, Direct3D does not attempt to verify that vertex size and stride match the provided flexible vertex format. If a mismatch occurs, a memory fault is likely to result.

With the exception of the reference rasterizer, software devices cannot render from a video memory (local or non-local) vertex buffer. To render a vertex buffer using a software device, the vertex buffer must exist in system memory. Hardware devices can render from system memory or video memory vertex buffers.

You cannot render from a locked vertex buffer; calls to the Direct3DDevice7.DrawIndexedPrimitiveVB or Direct3DDevice7.DrawPrimitiveVB method using a locked buffer will fail, returning D3DERR_VERTEXBUFFERLOCKED.

See Also

Direct3DDevice7.DrawPrimitive, Direct3DDevice7.DrawPrimitiveVB, Direct3DDevice7.DrawIndexedPrimitive


Direct3DDevice7.DrawPrimitive

The Direct3DDevice7.DrawPrimitive method renders the specified array of vertices as a sequence of geometric primitives of the specified type.

object.DrawPrimitive( _
    d3Dpt As CONST_D3DPRIMITIVETYPE, _
    d3dfvf As CONST_D3DFVFFLAGS, _
    vertices As Any, _
    vertexCount As Long, _
    flags As CONST_D3DDPFLAGS)

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
d3Dpt
Type of primitive to be rendered by this command. This must be one of the constants of the CONST_D3DPRIMITIVETYPE enumeration.

Note that the D3DPT_POINTLIST member of CONST_D3DPRIMITIVETYPE is not indexed.

d3dfvf
A combination of flexible vertex format flags from the CONST_D3DFVFFLAGS enumeration that describe the vertex format used.
vertices
First element in an array of vertices to be used in the primitive sequence.
vertexCount
Defines the number of vertices in the vertices array. The maximum number of vertices allowed is 65535 (&HFFFF).
flags
One of the constants of the CONST_D3DDPFLAGS enumeration defining how the primitive is drawn.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

D3DERR_INVALIDRAMPTEXTURE
D3DERR_INVALIDPRIMITIVETYPE
D3DERR_INVALIDVERTEXTYPE
DDERR_WASSTILLDRAWING
DDERR_INVALIDPARAMS

For information on trapping errors, see the Visual Basic Error Trapping topic.

Remarks

Make sure that the vertices being rendered match the vertex format you specify. For performance reasons, Direct3D does not attempt to verify that vertex size and stride match the provided flexible vertex format. If a mismatch occurs, a memory fault is likely to result.

See Also

Direct3DDevice7.DrawPrimitiveVB, Direct3DDevice7.DrawIndexedPrimitive, Direct3DDevice7.DrawIndexedPrimitiveVB


Direct3DDevice7.DrawPrimitiveVB

The Direct3DDevice7.DrawPrimitiveVB method renders an array of vertices in a vertex buffer as a sequence of geometric primitives.

object.DrawPrimitiveVB( _
    d3dpt As CONST_D3DPRIMITIVETYPE, _
    vertexBuffer As Direct3DVertexBuffer7, _
    startVertex As Long, _
    numVertices As Long, _
    flags As CONST_D3DDPFLAGS)

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
d3dpt
Type of primitive to be rendered by this command. This must be one of the constants of the CONST_D3DPRIMITIVETYPE enumeration.

Note that the D3DPT_POINTLIST member of CONST_D3DPRIMITIVETYPE is not indexed.

vertexBuffer
A Direct3DVertexBuffer7 object for the vertex buffer that contains the array of vertices. Vertices can be transformed or untransformed, optimized or unoptimized.
startVertex
Index value of the first vertex in the primitive. The highest possible starting index is 65535 (&HFFFF).
numVertices
Number of vertices to be rendered. The maximum number of vertices allowed is 65535 (&HFFFF).
flags
One of the constants of the CONST_D3DDPFLAGS enumeration defining how the primitive is drawn.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

D3DERR_INVALIDRAMPTEXTURE
D3DERR_INVALIDPRIMITIVETYPE
D3DERR_INVALIDVERTEXTYPE
D3DERR_VERTEXBUFFERLOCKED
DDERR_WASSTILLDRAWING
DDERR_INVALIDPARAMS

For information on trapping errors, see the Visual Basic Error Trapping topic.

Remarks

Make sure that the vertices being rendered match the vertex format you specify. For performance reasons, Direct3D does not attempt to verify that vertex size and stride match the provided flexible vertex format. If a mismatch occurs, a memory fault is likely to result.

With the exception of the reference rasterizer, software devices cannot render from a video memory (local or non-local) vertex buffer. To render a vertex buffer using a software device, the vertex buffer must exist in system memory. Hardware devices can render from system memory or video memory vertex buffers.

You cannot render from a locked vertex buffer; calls to the Direct3DDevice7.DrawIndexedPrimitiveVB or Direct3DDevice7.DrawPrimitiveVB method using a locked buffer will fail, returning D3DERR_VERTEXBUFFERLOCKED.

See Also

Direct3DDevice7.DrawPrimitive, Direct3DDevice7.DrawIndexedPrimitive, Direct3DDevice7.DrawIndexedPrimitiveVB


Direct3DDevice7.EndScene

The Direct3DDevice7.EndScene method ends a scene that was begun by calling the Direct3DDevice7.BeginScene method.

object.EndScene()

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

Remarks

When this method succeeds, the scene has been rendered, and the device surface holds the rendered scene.

When scene rendering begins successfully, you must call this method before you can call the Direct3DDevice7.BeginScene method to start rendering another scene. (If a prior call to BeginScene method fails, the scene did not begin, and this method should not be called.)

See Also

Direct3DDevice7.BeginScene


Direct3DDevice7.EndStateBlock

The Direct3DDevice7.EndStateBlock method signals Direct3D to stop recording a device state block and retrieve the block handle.

object.EndStateBlock( _
    blockHandle As Long)

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
blockHandle
Variable that will be filled with the handle to the completed device state block. This value is used with the Direct3DDevice7.ApplyStateBlock and Direct3DDevice7.DeleteStateBlock methods.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DDERR_INVALIDPARAMS to indicate that the blockHandle parameter is invalid or that the Direct3DDevice7.BeginStateBlock method has not been called.

See Also

Direct3DDevice7.ApplyStateBlock, Direct3DDevice7.BeginStateBlock, Direct3DDevice7.CaptureStateBlock, Direct3DDevice7.CreateStateBlock, Direct3DDevice7.DeleteStateBlock, State Blocks


Direct3DDevice7.GetCaps

The Direct3DDevice7.GetCaps method retrieves the capabilities of the Direct3D device.

object.GetCaps( _
    desc As D3DDEVICEDESC7)

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
desc
A D3DDEVICEDESC7 type that will contain the hardware features of the device.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

For information on trapping errors, see the Visual Basic Error Trapping topic.

Remarks

This method does not retrieve the capabilities of the display device. To retrieve this information, use the DirectDraw7.GetCaps method.


Direct3DDevice7.GetClipPlane

The Direct3DDevice7.GetClipPlane method retrieves the coefficients of a user-defined clipping plane for the device.

object.GetClipPlane( _
  Index As Long, _
  a As Single, _
  b As Single, _
  c As Single, _
  d As Single)

Parameters

Index
Index of the clipping plane for which the plane equation coefficients are retrieved.
a, b, c, and d
Values that represent the coefficients of the clipping plane, in the form of the general plane equation. See remarks.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DDERR_INVALIDPARAMS. This error indicates that the value in Index exceeds the maximum clipping plane index supported by the device.

Remarks

The coefficients that this method reports take the form of the general plane equation. The values in a, b, c, and d would fit into the general plane equation so that Ax + By + Cz + D = 0. A point with homogeneous coordinates (x, y, z, w) is visible in the half space of the plane if Ax + By + Cz + Dw >= 0. Points that exist on or behind the clipping plane are clipped from the scene.

The plane equation used by this method exists in world space and is set by a previous call to the Direct3DDevice7.SetClipPlane method.

See Also

Direct3DDevice7.SetClipPlane, D3DRENDERSTATE_CLIPPLANEENABLE, User-defined Clip Planes


Direct3DDevice7.GetClipStatus

The Direct3DDevice7.GetClipStatus method gets the current clip status.

object.GetClipStatus(clipStatus As D3DCLIPSTATUS)

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
clipStatus
A D3DCLIPSTATUS type that describes the current clip status.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DDERR_INVALIDPARAMS if one of the parameters is invalid.

See Also

Direct3DDevice7.SetClipStatus


Direct3DDevice7.GetDeviceGuid

The Direct3DDevice7.GetDeviceGuid method retrieves the globally unique identifier (GUID) for this device, as a String.

object.GetDeviceGuid() As String

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.

Return Values

The method returns the GUID for this device, as type String.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

See Also

Direct3D Device Types


Direct3DDevice7.GetDirect3D

The Direct3DDevice7.GetDirect3D method retrieves the Direct3D object for this device.

object.GetDirect3D() As Direct3D7

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.

Return Values

If the method succeeds, a reference to a Direct3D7 object is returned.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


Direct3DDevice7.GetInfo

The Direct3DDevice7.GetInfo method retrieves information about the rendering device. Information can pertain to Direct3D or the underlying device driver.

object.GetInfo( _
    lDevInfoID As CONST_D3DDEVINFOID, _
    DevInfoType As Any, _
    lSize As Long)

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
lDevInfoID
Flag from the CONST_D3DDEVINFOID enumeration that indicate the data type of the DevInfoType parameter.
DevInfoType
Variable that will contain the specified device information if the call succeeds. The data type of this variable, and how the data it contains is to be interpreted, is determined by the flag in lDevInfoID.
lSize
Size of the type at DevInfoType, in bytes, as returned by the Len Visual Basic function.

Return Values

None.

Error Codes

If the method fails, the return value may be S_FALSE to indicate that the device does not support information queries, or one of the following error codes:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

This method makes it possible for drivers to declare specific information types, and corresponding structures, that may not be documented in this SDK.

This method executes synchronously, and it can negatively impact your application's performance when it executes slowly. Do not call this method during scene rendering (between calls to Direct3DDevice7.BeginScene and Direct3DDevice7.EndScene).

This method is intended to be used for performance tracking and debugging during product development (on the debug version of DirectX). The method can succeed without retrieving device data. This occurs when the retail version of the DirectX runtime is installed on the host system.

See Also

D3DDEVINFO_TEXTUREMANAGER


Direct3DDevice7.GetLight

The Direct3DDevice7.GetLight method retrieves a set of lighting properties used by this device.

object.GetLight( _
    LightIndex As Long, _
    Light As D3DLIGHT7)

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
LightIndex
Zero-based index of the lighting property set to be retrieved.
Light
A D3DLIGHT7 type that will be filled with the retrieved lighting-parameter set.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DDERR_INVALIDPARAMS if one of the parameters is invalid.

See Also

Direct3DDevice7.SetLight, Direct3DDevice7.GetLightEnable, Direct3DDevice7.LightEnable, Lighting and Materials


Direct3DDevice7.GetLightEnable

The Direct3DDevice7.GetLightEnable method retrieves the activity status—enabled or disabled—for a light.

object.GetLightEnable( _
    LightIndex As Long) As Boolean

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
LightIndex
Zero-based index of the set of lighting parameters that are the target of this method.

Return Values

If the method succeeds, the return value indicates the activity status of the light. The method returns True to indicate that the specified light is enabled, and False to indicate that it is disabled.

Error Codes

If the method fails, it sets Err.Number to an error code and raises an error. For a list of possible error codes, see Direct3D Immediate Mode Error Codes.

See Also

Direct3DDevice7.GetLight, Direct3DDevice7.LightEnable, Direct3DDevice7.SetLight, Lighting and Materials


Direct3DDevice7.GetMaterial

The Direct3DDevice7.GetMaterial method retrieves the current material properties for the device.

object.GetMaterial(  _
    Material As D3DMATERIAL7)

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
Material
A D3DMATERIAL7 type that will be filled with the currently set material properties.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DDERR_INVALIDPARAMS to indicate the Material parameter is invalid.

See Also

Direct3DDevice7.SetMaterial, Lighting and Materials


Direct3DDevice7.GetRenderState

The Direct3DDevice7.GetRenderState method gets a render-state value for a device.

object.GetRenderState( _
    state As CONST_D3DRENDERSTATETYPE) As Long

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
state
Device state variable that is being queried. This parameter can be any of the constants of the CONST_D3DRENDERSTATETYPE enumeration.

Return Values

If the method succeeds, the return value is the current value of the specified render state.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DDERR_INVALIDPARAMS if one of the parameters is invalid.

See Also

Direct3DDevice7.SetRenderState


Direct3DDevice7.GetRenderStateSingle

The Direct3DDevice7.GetRenderStateSingle method gets a render-state value for a device.

object.GetRenderStateSingle( _
    state As CONST_D3DRENDERSTATESINGLE) As Single

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
state
Device state variable that is being queried. This parameter can be any of the constants of the CONST_D3DRENDERSTATESINGLE enumeration.

Return Values

If the method succeeds, the return value is the current value of the specified render state.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DDERR_INVALIDPARAMS if one of the parameters is invalid.

See Also

Direct3DDevice7.SetRenderState, Direct3DDevice7.SetRenderStateSingle


Direct3DDevice7.GetRenderTarget

The Direct3DDevice7.GetRenderTarget method retrieves the DirectDrawSurface7 object that is being used as a render target.

object.GetRenderTarget() As DirectDrawSurface7

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.

Return Values

If the method succeeds, a reference to the render-target surface (a DirectDrawSurface7 object) is returned.

Error Codes

If the method fails, an error is raised and Err.Number will be set to DDERR_INVALIDPARAMS if one of the parameters is invalid.

See Also

Direct3DDevice7.SetRenderTarget


Direct3DDevice7.GetTexture

The Direct3DDevice7.GetTexture method retrieves a texture assigned to a given stage for a device.

object.GetTexture(stage As Long) As DirectDrawSurface7

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
stage
Stage identifier of the texture to be retrieved. Stage identifiers are zero-based. Currently, devices can have up to 8 set textures, so the maximum allowable value for stage is 7.

Return Values

If the method succeeds, the return value is the specified texture's DirectDrawSurface7 object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

For information on trapping errors, see the Visual Basic Error Trapping topic.

See Also

Direct3DDevice7.SetTexture, Direct3DDevice7.GetTextureStageState, Direct3DDevice7.SetTextureStageState, Textures


Direct3DDevice7.GetTextureFormatsEnum

The Direct3DDevice7.GetTextureFormatsEnum method retrieves a Direct3DEnumPixelFormats object.

object.GetTextureFormatsEnum() As Direct3DEnumPixelFormats

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.

Return Values

If the method succeeds, a reference to a Direct3DEnumPixelFormats object is returned.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

For information on trapping errors, see the Visual Basic Error Trapping topic.

Remarks

Use the methods of the Direct3DEnumPixelFormats object to retrieve information about the pixel formats that the device supports for textures.


Direct3DDevice7.GetTextureStageState

The Direct3DDevice7.GetTextureStageState method retrieves a state value for a currently assigned texture.

object.GetTextureStageState( _
    stage As Long, _
    state As CONST_D3DTEXTURESTAGESTATETYPE) As Long

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
stage
Stage identifier of the texture for which the state will be retrieved. Stage identifiers are zero-based. Currently, devices can have up to 8 set textures, so the maximum allowable value for stage is 7.
state
Texture state to be retrieved. This parameter can be any constant of the CONST_D3DTEXTURESTAGESTATETYPE enumeration.

Return Values

If the method succeeds, the return value is the state value.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

For information on trapping errors, see the Visual Basic Error Trapping topic.

See Also

Direct3DDevice7.SetTextureStageState, Direct3DDevice7.GetTexture, Direct3DDevice7.SetTexture, Textures


Direct3DDevice7.GetTextureStageStateSingle

The Direct3DDevice7.GetTextureStageStateSingle method retrieves a state value for a currently assigned texture, as type Single.

object.GetTextureStageStateSingle( _
    stage As Long, _
    state As CONST_D3DTEXTURESTAGESINGLE) As Single

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
stage
Stage identifier of the texture for which the state will be retrieved. Stage identifiers are zero-based. Currently, devices can have up to 8 set textures, so the maximum allowable value for stage is 7.
state
Texture stage state to be retrieved. This parameter can be any constant of the CONST_D3DTEXTURESTAGESINGLE enumeration.

Return Values

If the method succeeds, the return value is the state value.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

For information on trapping errors, see the Visual Basic Error Trapping topic.

See Also

Direct3DDevice7.SetTextureStageState, Direct3DDevice7.SetTextureStageStateSingle, Direct3DDevice7.GetTexture, Direct3DDevice7.SetTexture, Textures


Direct3DDevice7.GetTransform

The Direct3DDevice7.GetTransform method gets a matrix describing a transformation state.

object.GetTransform( _
    transformType As CONST_D3DTRANSFORMSTATETYPE, _
    matrix As D3DMATRIX)

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
transformType
Device state variable that is being modified. This parameter can be any of the constants of the CONST_D3DTRANSFORMSTATETYPE enumeration.
matrix
A D3DMATRIX type describing the transformation.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DDERR_INVALIDPARAMS if one of the parameters is invalid.

See Also

Direct3DDevice7.SetTransform


Direct3DDevice7.GetViewport

The Direct3DDevice7.GetViewport method retrieves the viewport parameters currently set for the device.

object.GetViewport( _
    Viewport As D3DVIEWPORT7)

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
Viewport
A D3DVIEWPORT7 type that will be filled with the current viewport parameters if the call succeeds.

Return Values

If the method fails, an error is raised and Err.Number may be set to DDERR_INVALIDPARAMS if the Viewport parameter is invalid.

See Also

Direct3DDevice7.SetViewport


Direct3DDevice7.LightEnable

The Direct3DDevice7.LightEnable method enables or disables a set of lighting parameters within a device.

object.LightEnable( _
    LightIndex As Long, _
    bEnable As Boolean)

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
LightIndex
Zero-based index of the set of lighting parameters that are the target of this method.
bEnable
Value indicating if the set of lighting parameters are being enabled or disabled. Set this parameter to nonzero to enable lighting with the parameters at the specified index or zero to disable it.

Error Codes

If the method fails, an error is raised and Err.Number is set to an error code. For a complete list of Direct3D Immediate Mode error values and descriptions, see Error Codes.

Remarks

If you supply a value for LightIndex outside the range of the light property sets currently assigned within the device, the LightEnable method creates a light source with the following properties and sets its enabled state to the value specified in Enable:

Member | Default
dltType | D3DLIGHT_DIRECTIONAL
dcvDiffuse | (R:1, G:1, B:1, A:0)
dcvSpecular | (R:0, G:0, B:0, A:0)
dcvAmbient | (R:0, G:0, B:0, A:0)
dvPosition | (0, 0, 0)
dvDirection | (0, 0, 1)
dvRange | 0
dvFalloff | 0
dvAttenuation0 | 0
dvAttenuation1 | 0
dvAttenuation2 | 0
dvTheta | 0
dvPhi | 0

See Also

Direct3DDevice7.GetLight, Direct3DDevice7.GetLightEnable, Direct3DDevice7.SetLight, Lighting and Materials


Direct3DDevice7.Load

The Direct3DDevice7.Load method loads a rectangular area of a source texture to a specified point in a destination texture or to faces within a cubic environment map.

object.Load( _
    DestTex As DirectDrawSurface7, _
    xDest As Long, _
    yDest As Long, _
    SrcTex  As DirectDrawSurface7, _
    rcSrcRect As RECT, _
    flags As Long)

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
DestTex
The DirectDrawSurface7 class that will receive image data from the source texture. For complex texture surfaces like cubic envionment maps and mipmaps, this must refer to the top-level surface.
xDest and yDest
The x- and y-coordinates of the point at which the method should load the image data onto the destination texture.
SrcTex
The DirectDrawSurface7 class that contains the image data to be loaded. For complex texture surfaces like cubic envionment maps and mipmaps, this must refer to the top-level surface.
rcSrcRect
Address of a RECT type that describes the area within the source texture that the method will load. Set this parameter to Nothing when the source rectangle should cover the entire source texture or when using this method to explicitly load a managed texture.
flags
Value indicating, in the case of a cubic environment map, which face of the destination texture is to receive the image data. This can be any combination of the following flags.
0
Required if the destination texture is a managed texture.
DDSCAPS2_CUBEMAP_ALLFACES
All faces should be loaded with the image data within the source texture.
DDSCAPS2_CUBEMAP_NEGATIVEX, DDSCAPS2_CUBEMAP_NEGATIVEY, or DDSCAPS2_CUBEMAP_NEGATIVEZ
The negative x, y, or z faces should receive the image data.
DDSCAPS2_CUBEMAP_POSITIVEX, DDSCAPS2_CUBEMAP_POSITIVEY, or DDSCAPS2_CUBEMAP_POSITIVEZ
The positive x, y, or z faces should receive the image data.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

The destination texture can be used with any rendering device, not just the one that created it. On hardware devices, the load operation is hardware-accelerated.

Loading textures into video memory by calling this method is preferred over blit operations.

This method copies mipmaps at all levels, cube-map faces, palettes and color keys from the source texture to the destination texture.

When using this method to load mipmaps, the following special points apply:

  • The destination texture surface can be a subset of the mip-levels contained in the source texture. In this case, only the mip-levels common to both textures are copied. This is useful in implementing texture LOD. You can create a video memory texture with only two mip-levels, then use this method to copy those levels from a source texture that comprises the entire set of mip-levels.
  • The source and destination surface pointers must point to top-level surfaces.
  • When loading a subrectangle of a mipmap, the subrectangle refers to the top-level surface in the mipmap chain, and is divided by two for each lower mip-level.


Direct3DDevice7.MultiplyTransform

The Direct3DDevice7.MultiplyTransform method multiplies a device's world, view, or projection matrices by a specified matrix. The multiplication order is matrix times dstTransformStateType.

object.MultiplyTransform( _
    dstTransformStateType As CONST_D3DTRANSFORMSTATETYPE, _
    matrix As D3DMATRIX)

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
dstTransformStateType
Identifies which device matrix is to be modified. This parameter can be any of the constants of the CONST_D3DTRANSFORMSTATETYPE enumeration. The most common setting, D3DTRANSFORMSTATE_WORLD, modifies the world matrix, but you can specify that the method modify the view or projection matrices if needed.
matrix
A D3DMATRIX type that modifies the current transformation.

Error Codes

If the method fails, an error is raised and Err.Number will be set. The method returns DDERR_INVALIDPARAMS if one of the parameters is invalid.

Remarks

An application might use the MultiplyTransform method to work with hierarchies of transformations. For example, the geometry and transformations describing an arm might be arranged in the following hierarchy:

shoulder_transformation
    upper_arm geometry
    elbow transformation
        lower_arm geometry
        wrist transformation
            hand geometry

An application might use the following series of calls to render this hierarchy. (Not all of the parameters are shown in this pseudocode.)

Direct3DDevice7.SetTransform(D3DTRANSFORMSTATE_WORLD,
    shoulder_transform)
Direct3DDevice7.DrawPrimitive(upper_arm)
Direct3DDevice7.MultiplyTransform(D3DTRANSFORMSTATE_WORLD,
    elbow_transform)
Direct3DDevice7.DrawPrimitive(lower_arm)
Direct3DDevice7.MultiplyTransform(D3DTRANSFORMSTATE_WORLD,
    wrist_transform)
Direct3DDevice7.DrawPrimitive(hand)

See Also

Direct3DDevice7.DrawPrimitive, Direct3DDevice7.SetTransform


Direct3DDevice7.PreLoad

The Direct3DDevice7.Preload method instructs the Direct3D texture manager to load a managed texture into video memory.

object.PreLoad( _
  Texture As DirectDrawSurface7)

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
Texture
Reference to the DirectDrawSurface7 object to be loaded into memory.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

This method forces the system to load a managed texture into video memory. If sufficient video memory is not available, the system evicts other textures to regain memory, then loads the texture. The texture being loaded must be a managed texture (created with the DDSCAPS2_TEXTUREMANAGE or DDSCAPS2_D3DTEXTUREMANAGE flags). If these requirements are not met, the method fails and returns DDERR_INVALIDPARAMS.

See Also

Automatic Texture Management


Direct3DDevice7.SetClipPlane

The Direct3DDevice7.SetClipPlane method sets the coefficients of a user-defined clipping plane for the device.

object.SetClipPlane( _
  Index As Long, _
  a As Single, _
  b As Single, _
  c As Single, _
  d As Single)

Parameters

Index
Index of the clipping plane for which the plane equation coefficients are retrieved.
a, b, c, and d
Values that represent the coefficients of the clipping plane, in the form of the general plane equation. See remarks.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DDERR_INVALIDPARAMS. This error indicates that the value in Index exceeds the maximum clipping plane index supported by the device.

Remarks

The coefficients that this method reports take the form of the general plane equation. The values in a, b, c, and d would fit into the general plane equation so that Ax + By + Cz + D = 0. A point with homogeneous coordinates (x, y, z, w) is visible in the half space of the plane if Ax + By + Cz + Dw >= 0. Points that exist on or behind the clipping plane are clipped from the scene.

The plane equation used by this method exists in world space.

This method does not enable the clipping plane equation being set. To enable a clipping plane, use the D3DRENDERSTATE_CLIPPLANEENABLE render state.

See Also

Direct3DDevice7.GetClipPlane, D3DRENDERSTATE_CLIPPLANEENABLE, User-defined Clip Planes


Direct3DDevice7.SetClipStatus

The Direct3DDevice7.SetClipStatus method sets the current clip status.

object.SetClipStatus(clipStatus As D3DCLIPSTATUS)

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
clipStatus
A D3DCLIPSTATUS type that describes the new settings for the clip status.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DDERR_INVALIDPARAMS if the clipStatus parameter is invalid.

For information on trapping errors, see the Visual Basic Error Trapping topic.

See Also

Direct3DDevice7.GetClipStatus


Direct3DDevice7.SetLight

The Direct3DDevice7.SetLight method assigns a set of lighting properties for this device.

object.SetLight( _
    LightIndex As Long, _
    Light As D3DLIGHT7)

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
LightIndex
Zero-based index of the set of lighting properties to be set. If a set of lighting properties already exists at this index, it will be overwritten by the new properties.
Light
A D3DLIGHT7 type that contains the lighting parameters to be set.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY

See Also

Direct3DDevice7.GetLight, Direct3DDevice7.GetLightEnable, Direct3DDevice7.LightEnable , Lighting and Materials.


Direct3DDevice7.SetMaterial

The Direct3DDevice7.SetMaterial method sets the material properties for the device.

object.SetMaterial( _
  mat As D3DMATERIAL7)

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
mat
A D3DMATERIAL7 type that describes the material properties to be set.

Error Codes

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value is an error. The method returns DDERR_INVALIDPARAMS if the mat parameter is invalid.

See Also

Direct3DDevice7.GetMaterial


Direct3DDevice7.SetRenderState

The Direct3DDevice7.SetRenderState method sets a value (of type Long) in a device render state.

object.SetRenderState( _
    state As CONST_D3DRENDERSTATETYPE, _
    renderstate As Long)

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
state
Device state variable that is being modified. This parameter can be any of the constants of the CONST_D3DRENDERSTATETYPE enumeration.
renderstate
New render-state value. The meaning of this parameter is dependent on the value specified for state. For example, if state were D3DRENDERSTATE_SHADEMODE, the second parameter would be one of the constants of the CONST_D3DSHADEMODE enumeration.

Error Codes

If the method fails, it sets Err.Number to an error code and raises an error. The error code is DDERR_INVALIDPARAMS if one of the parameters is invalid.

See Also

Direct3DDevice7.GetRenderState, Direct3DDevice7.SetTransform


Direct3DDevice7.SetRenderStateSingle

The Direct3DDevice7.SetRenderStateSingle method sets a value (of type Single) in a device render state.

object.SetRenderStateSingle( _
    state As CONST_D3DRENDERSTATESINGLE, _
    renderstate As Single)

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
state
Device state variable that is being modified. This parameter can be any of the constants of the CONST_D3DRENDERSTATESINGLE enumeration.
renderstate
New render-state value. The meaning of this parameter is dependent on the value specified for state. For example, if state were D3DRENDERSTATE_SHADEMODE, the second parameter would be one of the constants of the CONST_D3DSHADEMODE enumeration.

Error Codes

If the method fails, it sets Err.Number to an error code and raises an error. The error code is DDERR_INVALIDPARAMS if one of the parameters is invalid.

See Also

Direct3DDevice7.GetRenderState, Direct3DDevice7.GetRenderStateSingle, Direct3DDevice7.SetTransform


Direct3DDevice7.SetRenderTarget

The Direct3DDevice7.SetRenderTarget method permits the application to easily route rendering output to a new DirectDraw surface as a render target.

object.SetRenderTarget(surface As DirectDrawSurface7)

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
surface
A DirectDrawSurface7 object for the previously created surface object that will be the new rendering target.

Error Codes

If the method fails, an error is raised and Err.Number may be set one of the following values:

DDERR_INVALIDPARAMS
DDERR_INVALIDSURFACETYPE

For information on trapping errors, see the Visual Basic Error Trapping topic.

Remarks

Capabilities do not change with changes in the properties of the render target surface. Both the Direct3D HAL and the software rasterizers have only one opportunity to expose capabilities to the application. The system cannot expose different sets of capabilities depending on the format of the destination surface.

If a depth-buffer is attached to the new render target, it replaces the previous z-buffer for the context. Otherwise, the old z-buffer is detached and z-buffering is disabled.

If more than one depth-buffer is attached to the render target, this function fails.

See Also

Direct3DDevice7.GetRenderTarget


Direct3DDevice7.SetTexture

The Direct3DDevice7.SetTexture method assigns a texture to a given stage for a device.

object.SetTexture( _
    stage As Long, _
    texture As DirectDrawSurface7)

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
stage
Stage identifier to which the texture will be set. Stage identifiers are zero-based. Currently, devices can have up to 8 set textures, so the maximum allowable value for stage is 7.
texture
A DirectDrawSurface7 object for the texture being set. For complex textures, such as mipmaps and cubic environment maps, this parameter must be the top-level surface.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

For information on trapping errors, see the Visual Basic Error Trapping topic.

Remarks

When the texture is no longer needed, you should set the texture at the appropriate stage to Nothing. If you fail to do this, the memory for the surface may be lost when your application closes.

Software devices do not support assigning a texture to more than one texture stage at a time.

See Also

Direct3DDevice7.GetTexture, Direct3DDevice7.GetTextureStageState, Direct3DDevice7.SetTextureStageState, Textures


Direct3DDevice7.SetTextureStageState

The Direct3DDevice7.SetTextureStageState method sets the state value for a currently assigned texture.

object.SetTextureStageState( _
    stage As Long, _
    state As CONST_D3DTEXTURESTAGESTATETYPE, _
    value As Long)

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
stage
Stage identifier of the texture for which the state value will be set. Stage identifiers are zero-based. Currently, devices can have up to 8 set textures, so the maximum allowable value for stage is 7.
state
Texture state to be set. This parameter can be any constant of the CONST_D3DTEXTURESTAGESTATETYPE enumeration.
value
State value to be set. The meaning of this value is determined by the state parameter.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

Applications should use this method to set texture states in favor of the legacy texture-related render states. For more information, see About Render States.

See Also

Direct3DDevice7.GetTextureStageState, Direct3DDevice7.GetTexture, Direct3DDevice7.SetTexture, Textures


Direct3DDevice7.SetTextureStageStateSingle

The Direct3DDevice7.SetTextureStageStateSingle method sets the state value for a currently assigned texture.

object.SetTextureStageStateSingle( _
    stage As Long, _
    state As CONST_D3DTEXTURESTAGESINGLE, _
    value As Single)

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
stage
Stage identifier of the texture for which the state value will be set. Stage identifiers are zero-based. Currently, devices can have up to 8 set textures, so the maximum allowable value for stage is 7.
state
Texture state to be set. This parameter can be any constant of the CONST_D3DTEXTURESTAGESINGLE enumeration.
value
State value to be set. The meaning of this value is determined by the state parameter.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

Applications should use this method to set texture states in favor of the legacy texture-related render states. For more information, see About Render States.

See Also

Direct3DDevice7.GetTextureStageStateSingle, Direct3DDevice7.GetTextureStageState, Direct3DDevice7.GetTexture, Direct3DDevice7.SetTexture, Textures


Direct3DDevice7.SetTransform

The Direct3DDevice7.SetTransform method sets a single transformation-related state for the device.

object.SetTransform( _
    transformType As CONST_D3DTRANSFORMSTATETYPE, _
    matrix As D3DMATRIX)

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
transformType
Device state variable that is being modified. This parameter can be any of the constants of the CONST_D3DTRANSFORMSTATETYPE enumeration.
matrix
A D3DMATRIX type that modifies the current transformation.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DDERR_INVALIDPARAMS if one of the parameters is invalid.

For information on trapping errors, see the Visual Basic Error Trapping topic.

See Also

Direct3DDevice7.GetTransform, Direct3DDevice7.SetRenderState


Direct3DDevice7.SetViewport

The Direct3DDevice7.SetViewport method sets the viewport parameters for the device.

object.SetViewport( _
    viewport As D3DVIEWPORT7)

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.
viewport
A D3DVIEWPORT7 type that contains the viewport parameters to be set.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DDERR_INVALIDPARAMS to indicate that the viewport parameter is invalid.

Remarks

If the viewport parameters described by the D3DVIEWPORT7 type describe a region that cannot exist within the render target surface, the method will fail, returning DDERR_INVALIDPARAMS.

See Also

Direct3DDevice7.GetViewport


Direct3DDevice7.ValidateDevice

The Direct3DDevice7.ValidateDevice method reports the device's ability to render the currently set texture blending operations and parameters in a single pass.

object.ValidateDevice() As Long

Parameters

object
Object expression that resolves to a Direct3DDevice7 object.

Return Values

If the method succeeds, the return value is the number of rendering passes to complete the desired effect through multipass rendering.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
D3DERR_CONFLICTINGTEXTUREFILTER
D3DERR_TOOMANYOPERATIONS
D3DERR_UNSUPPORTEDALPHAARG
D3DERR_UNSUPPORTEDALPHAOPERATION
D3DERR_UNSUPPORTEDCOLORARG
D3DERR_UNSUPPORTEDCOLOROPERATION
D3DERR_UNSUPPORTEDFACTORVALUE
D3DERR_UNSUPPORTEDTEXTUREFILTER
D3DERR_WRONGTEXTUREFORMAT

Remarks

Current hardware does not necessarily implement all possible combinations of operations and arguments. You can determine whether a particular blending operation can be performed with given parameters by setting-up the desired blending operation, then calling the ValidateDevice method.

The ValidateDevice method uses the currently set render states, textures, and, texture stage states to perform validation at the time of the call. Any changes to these factors after the call invalidate the previous result, and the method must be called again before rendering a scene.

Using diffuse iterated values, either as an argument or as an operation (D3DTA_DIFFUSE or D3DTOP_BLENDDIFFUSEALPHA) is sparsely supported on current hardware. Most hardware can only introduce iterated color data at the last texture operation stage.

Try to specify the texture (D3DTA_TEXTURE) for each stage as the first parameter, in preference to the second parameter.

Many cards do not support use of diffuse or scalar values at arbitrary texture stages. Often, these are only available at the first or last texture blending stage.

Many cards do not actually have a blending unit associated with the first texture that is capable of more than replicating alpha to color channels, or inverting the input. As a result, your application might need to use only the second texture stage if possible. On such hardware, the first unit is presumed to be in its default state, which has the first color parameter set to D3DTA_TEXTURE with the D3DTOP_SELECTARG1 operation.

Operations on the output alpha that are more intricate than or substantially different from the color operations are less likely to be supported.

Some hardware does not support simultaneous use of both D3DTA_TFACTOR and D3DTA_DIFFUSE.

Many cards do not support simultaneous use of multiple textures and mipmapped trilinear filtering. If trilinear filtering has been requested for a texture involved in multitexture blending operations and validation fails, turn off trilinear filtering and revalidate. In this case, it might be best to perform multipass rendering instead.

See Also

Direct3DDevice7.GetTextureStageState, Direct3DDevice7.SetTextureStageState


Direct3DEnumDevices

Applications use the methods of the Direct3DEnumDevices class to retrieve information about the Direct3D devices present on a system. The Direct3DEnumDevices class is obtained by calling the Direct3D7.GetDevicesEnum method.

The methods of the Direct3DEnumDevices class can be organized into the following groups:

Device count | GetCount
Device information | GetDescription
 | GetGuid
 | GetDesc
 | GetName


Direct3DEnumDevices.GetCount

The Direct3DEnumDevices.GetCount method returns the number of Direct3D devices installed on the system.

object.GetCount() As Long

Parameters

object
Object expression that resolves to a Direct3DEnumDevices object.

Return Values

If the method succeeds, the number of Direct3D devices installed on the system is returned.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


Direct3DEnumDevices.GetDesc

The Direct3DEnumDevices.GetDesc method returns the capabilities of the desired Direct3D device.

object.GetDesc(index As Long, hwDesc As D3DDEVICEDESC7)

Parameters

object
Object expression that resolves to a Direct3DEnumDevices object.
index
On a system with multiple Direct3D devices, this parameter represents the specific device.
hwDesc
A D3DDEVICEDESC7 type that contains the hardware capabilities of the Direct3D device.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


Direct3DEnumDevices.GetDescription

The Direct3DEnumDevices.GetDescription method returns user-friendly description of the desired Direct3D device.

object.GetDescription(index As Long) As String

Parameters

object
Object expression that resolves to a Direct3DEnumDevices object.
index
Index of the enumerated device. This value can be between 1 and the value returned by the Direct3DEnumDevices.GetCount method.

Return Values

If the method succeeds, the return value is the user-friendly description of the enumerated device.

Error Codes

If the method fails, the method sets Err.Number to an error code and raises an error. For a list of possible error codes, see Direct3D Immediate Mode Error Codes.


Direct3DEnumDevices.GetGuid

The Direct3DEnumDevices.GetDescription method returns the globally-unique ID (GUID) of the desired Direct3D device.

object.GetGuid(index As Long) As String

Parameters

object
Object expression that resolves to a Direct3DEnumDevices object.
index
Index of the enumerated device. This value can be between 1 and the value returned by the Direct3DEnumDevices.GetCount method.

Return Values

If the method succeeds, the return value is a string label—"IID_IDirect3DHALDevice", "IID_IDirect3DTnLHalDevice", or "IID_IDirect3DRGBDevice"—that represents the globally-unique identifier of the enumerated device. This value is used to create the device with a subsequent call to the Direct3D7.CreateDevice method.

Error Codes

If the method fails, the method sets Err.Number to an error code and raises an error. For a list of possible error codes, see Direct3D Immediate Mode Error Codes.


Direct3DEnumDevices.GetName

The Direct3DEnumDevices.GetName method returns the user-friendly name of the desired Direct3D device.

object.GetName(index As Long) As String

Parameters

object
Object expression that resolves to a Direct3DEnumDevices object.
index
Index of the enumerated device. This value can be between 1 and the value returned by the Direct3DEnumDevices.GetCount method.

Return Values

If the method succeeds, the return value is the user-friendly name of the device.

Error Codes

If the method fails, the method sets Err.Number to an error code and raises an error. For a list of possible error codes, see Direct3D Immediate Mode Error Codes.


Direct3DEnumPixelFormats

Applications use the methods of the Direct3DEnumPixelFormats class to retrieve information about the pixel formats supported by a rendering device. The Direct3DEnumPixelFormats class is obtained by calling the Direct3DDevice7.GetTextureFormatsEnum and Direct3D7.GetEnumZBufferFormats methods.

This class consists of two methods.

  • GetCount
  • GetItem


Direct3DEnumPixelFormats.GetCount

The Direct3DEnumPixelFormats.GetCount method returns the number of supported pixel formats of the Direct3D device.

object.GetCount() As Long

Parameters

object
Object expression that resolves to a Direct3DEnumPixelFormats object.

Return Values

If the method succeeds, the number of supported pixel formats is returned.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


Direct3DEnumPixelFormats.GetItem

The Direct3DEnumPixelFormats.GetItem method returns the description of the specified pixel format.

object.GetItem(index As Long, _
    pixelFormat As DDPIXELFORMAT)

Parameters

object
Object expression that resolves to a Direct3DEnumPixelFormats object.
index
The specific pixel format that you want a description for.
pixelFormat
A DDPIXELFORMAT type that describes the enumerated pixel format.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


Direct3DVertexBuffer7

Applications use the methods of the Direct3DVertexBuffer7 class to manipulate a collection of vertices for use with the Direct3DDevice7.DrawPrimitiveVB and Direct3DDevice7.DrawIndexedPrimitiveVB rendering methods. This section is a reference to the methods of this class. For a conceptual overview, see Vertex Buffers.

This methods of the Direct3DVertexBuffer7 class can be organized into the following groups:

Information | GetVertexBufferDesc
Vertex data | GetVertices
 | Lock
 | Optimize
 | ProcessVertices
 | SetVertices
 | Unlock

See Also

Vertex Buffers


Direct3DVertexBuffer7.GetVertexBufferDesc

The Direct3DVertexBuffer7.GetVertexBufferDesc method retrieves a description of the vertex buffer.

object.GetVertexBufferDesc(desc As D3DVERTEXBUFFERDESC)

Parameters

object
Object expression that resolves to a Direct3DVertexBuffer7 object.
desc
A D3DVERTEXBUFFERDESC type that will be filled with a description of the vertex buffer.

Error Codes

If the method fails, an error is raised and Err.Number may be DDERR_INVALIDPARAMS or another error code.


Direct3DVertexBuffer7.GetVertices

The Direct3DVertexBuffer7.GetVertices method returns the vertices in the vertex buffer.

object.GetVertices(startIndex As Long, _
    count As Long, _
    verts As Any)

Parameters

object
Object expression that resolves to a Direct3DVertexBuffer7 object.
startIndex
Starting index within the vertex buffer at which vertices will be retrieved.
count
Number of vertices to be retrieved.
verts
First element of an array that will be filled with the retrieved vertices.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


Direct3DVertexBuffer7.Lock

The Direct3DVertexBuffer7.Lock methods locks a vertex buffer.

object.Lock(flags As CONST_DDLOCKFLAGS)

Parameters

object
Object expression that resolves to a Direct3DVertexBuffer7 object.
flags
One of the following constants from the CONST_DDLOCKFLAGS enumeration indicating how the vertex buffer memory should be locked.
DDLOCK_NOSYSLOCK
If possible, do not take the Win16Mutex (also known as Win16Lock).
DDLOCK_READONLY
Indicates that the memory being locked will only be read from.
DDLOCK_WAIT
If a lock cannot be obtained immediately, the method retries until a lock is obtained or another error occurs.
DDLOCK_WRITEONLY
Indicates that the memory being locked will only be written to.
DDLOCK_DISCARDCONTENTS
Used only with Direct3D vertex-buffer locks. Indicates that no assumptions are made about the contents of the vertex buffer during this lock. This enables Direct3D or the driver to provide an alternative memory area as the vertex buffer. This is useful when you plan to clear the contents of the vertex buffer and fill in new data.
DDLOCK_NOOVERWRITE
Used only with Direct3D vertex-buffer locks. Indicates that no vertices that were referred to in vertex-buffer DrawPrimitive calls since the start of the frame (or the last lock without this flag) are modified during the lock. This can be useful when you want only to append data to the vertex buffer.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

D3DERR_VERTEXBUFFEROPTIMIZED
DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY
DDERR_SURFACEBUSY
DDERR_SURFACELOST

For information on trapping errors, see the Visual Basic Error Trapping topic.

Remarks

While the vertex buffer is locked, you can manipulate the data within it by calling the Direct3DVertexBuffer7.GetVertices and Direct3DVertexBuffer7.SetVertices methods. After locking the vertex buffer, you can access the memory until a corresponding call to Direct3DVertexBuffer7.Unlock.

You cannot render from a locked vertex buffer; calls to the Direct3DDevice7.DrawIndexedPrimitiveVB or Direct3DDevice7.DrawPrimitiveVB method using a locked buffer will fail, returning D3DERR_VERTEXBUFFERLOCKED.

This method often causes the system to hold the Win16Mutex until you call the Direct3DVertexBuffer7.Unlock method. GUI debuggers cannot operate while the Win16Mutex is held.

See Also

Direct3DVertexBuffer7.Unlock, Accessing the Contents of a Vertex Buffer


Direct3DVertexBuffer7.Optimize

The Direct3DVertexBuffer7.Optimize method converts an unoptimized vertex buffer into an optimized vertex buffer.

object.Optimize(dev As Direct3DDevice7)

Parameters

object
Object expression that resolves to a Direct3DVertexBuffer7 object.
dev
A Direct3DDevice7 object of the device for which this vertex buffer will be optimized.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

D3DERR_VERTEXBUFFEROPTIMIZED
D3DERR_VERTEXBUFFERLOCKED
DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY

For information on trapping errors, see the Visual Basic Error Trapping topic.

See Also

Optimizing a Vertex Buffer, Vertex Buffers


Direct3DVertexBuffer7.ProcessVertices

The Direct3DVertexBuffer7.ProcessVertices method processes untransformed vertices into a transformed or optimized vertex buffer.

object.ProcessVertices( _
    vertexOp As CONST_D3DVOPFLAGS, _
    destIndex As Long, _
    count As Long, _
    srcBuffer As Direct3DVertexBuffer7, _
    srcIndex As Long, _
    dev As Direct3DDevice7, _
    flags As CONST_D3DPROCESSVERTICESFLAGS)

Parameters

object
Object expression that resolves to a Direct3DVertexBuffer7 object.
vertexOp
Flags defining how the method processes the vertices as they are transferred from the source buffer. You can specify any combination of the constants from the CONST_D3DVOPFLAGS enumeration:
destIndex
Index into the destination vertex buffer (this buffer) where the vertices will be placed after processing.
count
Number of vertices in the source buffer to process.
srcBuffer
A Direct3DVertexBuffer7 object for the source vertex buffer.
srcIndex
Index of the first vertex in the source buffer to be processed.
dev
A Direct3DDevice7 object for the device that will be used to transform the vertices.
flags
Processing options. Set this parameter to one of the members of the CONST_D3DPROCESSVERTICESFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

D3DERR_INVALIDVERTEXFORMAT
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY
DDERR_SURFACEBUSY
DDERR_SURFACELOST

For information on trapping errors, see the Visual Basic Error Trapping topic.

Remarks

You must always include the D3DVOP_TRANSFORMED flag in the vertexOp parameter. If you fail to include this flag, the method will fail, returning DDERR_INVALIDPARAMS.

See Also

Processing Vertices, Vertex Buffers


Direct3DVertexBuffer7.SetVertices

The Direct3DVertexBuffer7.SetVertices method sets the vertices in a locked vertex buffer.

object.SetVertices(startIndex As Long, _
    count As Long, _
    verts As Any)

Parameters

object
Object expression that resolves to a Direct3DVertexBuffer7 object.
startIndex
Zero-based index within the vertex buffer at which the vertices will be set.
count
Number of vertices contained in the verts array.
verts
First element of the buffer containing the vertex data.

Error Codes

If the method fails, an error is raised and Err.Number will be set to an error code. For a complete list of Direct3D Immediate Mode error values and descriptions, see Error Codes.

Remarks

You must lock a vertex buffer by calling the Direct3DVertexBuffer7.Lock method before manipulating the vertices it contains.

See Also

Direct3DVertexBuffer7.GetVertices, Direct3DVertexBuffer7.Lock


Direct3DVertexBuffer7.Unlock

The Direct3DVertexBuffer7.Unlock method unlocks a previously locked vertex buffer.

object.Unlock()

Parameters

object
Object expression that resolves to a Direct3DVertexBuffer7 object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DDERR_GENERIC
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_SURFACEBUSY
DDERR_SURFACELOST

For information on trapping errors, see the Visual Basic Error Trapping topic.

See Also

Direct3DVertexBuffer7.Lock, Accessing the Contents of a Vertex Buffer


Types

This section contains information about the following types used with Direct3D Immediate Mode.

  • D3DCLIPSTATUS
  • D3DCOLORVALUE
  • D3DDEVICEDESC7
  • D3DDEVINFO_TEXTUREMANAGER
  • D3DDEVINFO_TEXTURING
  • D3DLIGHT7
  • D3DLIGHTINGCAPS
  • D3DLINEPATTERN
  • D3DLVERTEX
  • D3DMATERIAL7
  • D3DMATRIX
  • D3DPRIMCAPS
  • D3DRECT
  • D3DTLVERTEX
  • D3DVECTOR
  • D3DVERTEX
  • D3DVERTEXBUFFERDESC
  • D3DVIEWPORT7
  • DXDRIVERINFO


D3DCLIPSTATUS

The D3DCLIPSTATUS type describes the current clip status and extents of the clipping region.

Type D3DCLIPSTATUS
    lFlags As Long
    lStatus As Long
    maxx As Single
    maxy As Single
    maxz As Single
    minx As Single
    miny As Single
    minz As Single
End Type

Members

lFlags
Flags describing whether this type describes 2-D extents, 3-D extents, or the clip status. This member can be a combination of the following flags from the CONST_D3DCLIPSTATUSFLAGS enumeration:
D3DCLIPSTATUS_STATUS
The type describes the current clip status.
D3DCLIPSTATUS_EXTENTS2
The type describes the current 2-D extents. This flag cannot be combined with D3DCLIPSTATUS_EXTENTS3.
D3DCLIPSTATUS_EXTENTS3
Not currently implemented.
lStatus
Describes the current clip status. This member can be one or more of the following constants of the CONST_D3DCLIPFLAGS enumeration:

Combination and General Flags

D3DSTATUS_CLIPINTERSECTIONALL
Combination of all CLIPINTERSECTION flags.
D3DSTATUS_CLIPUNIONALL
Combination of all CLIPUNION flags.
D3DSTATUS_DEFAULT
Combination of D3DSTATUS_CLIPINTERSECTIONALL and D3DSTATUS_ZNOTVISIBLE flags. This value is the default.
D3DSTATUS_ZNOTVISIBLE
Indicates that the rendered primitive is not visible. This flag is set or cleared by the system when rendering with z-checking enabled (see D3DRENDERSTATE_ZVISIBLE).

Clip Intersection Flags

D3DSTATUS_CLIPINTERSECTIONBACK
Logical And of the clip flags for the vertices compared to the back clipping plane of the viewing frustum.
D3DSTATUS_CLIPINTERSECTIONBOTTOM
Logical And of the clip flags for the vertices compared to the bottom of the viewing frustum.
D3DSTATUS_CLIPINTERSECTIONFRONT
Logical And of the clip flags for the vertices compared to the front clipping plane of the viewing frustum.
D3DSTATUS_CLIPINTERSECTIONGEN0 through D3DSTATUS_CLIPINTERSECTIONGEN5
Logical And of the clip flags for application-defined clipping planes.
D3DSTATUS_CLIPINTERSECTIONLEFT
Logical And of the clip flags for the vertices compared to the left side of the viewing frustum.
D3DSTATUS_CLIPINTERSECTIONRIGHT
Logical And of the clip flags for the vertices compared to the right side of the viewing frustum.
D3DSTATUS_CLIPINTERSECTIONTOP
Logical And of the clip flags for the vertices compared to the top of the viewing frustum.

Clip Union Flags

D3DSTATUS_CLIPUNIONBACK
Equal to D3DCLIP_BACK.
D3DSTATUS_CLIPUNIONBOTTOM
Equal to D3DCLIP_BOTTOM.
D3DSTATUS_CLIPUNIONFRONT
Equal to D3DCLIP_FRONT.
D3DSTATUS_CLIPUNIONGEN0 through D3DSTATUS_CLIPUNIONGEN5
Equal to D3DCLIP_GEN0 through D3DCLIP_GEN5.
D3DSTATUS_CLIPUNIONLEFT
Equal to D3DCLIP_LEFT.
D3DSTATUS_CLIPUNIONRIGHT
Equal to D3DCLIP_RIGHT.
D3DSTATUS_CLIPUNIONTOP
Equal to D3DCLIP_TOP.

Basic Clipping Flags

D3DCLIP_BACK
All vertices are clipped by the back plane of the viewing frustum.
D3DCLIP_BOTTOM
All vertices are clipped by the bottom plane of the viewing frustum.
D3DCLIP_FRONT
All vertices are clipped by the front plane of the viewing frustum.
D3DCLIP_LEFT
All vertices are clipped by the left plane of the viewing frustum.
D3DCLIP_RIGHT
All vertices are clipped by the right plane of the viewing frustum.
D3DCLIP_TOP
All vertices are clipped by the top plane of the viewing frustum.
D3DCLIP_GEN0 through D3DCLIP_GEN5
Application-defined clipping planes.
maxx, minx, maxy, miny, maxz, minz
The x, y, and z extents of the current clipping region.

See Also

Direct3DDevice7.GetClipStatus, Direct3DDevice7.SetClipStatus


D3DCOLORVALUE

The D3DCOLORVALUE type describes color values for the D3DLIGHT7 and D3DMATERIAL7 types.

Type D3DCOLORVALUE
    a As Single
    b As Single
    g As Single
    r As Single
End Type

Members

a, b, g and r
Values specifying the red, green, blue, and alpha components of a color. These values generally range from 0 to 1, with 0 being black.

Remarks

You can set the members of this type to values outside the range of 0 to 1 to implement some unusual effects. Values greater than 1 produce strong lights that tend to wash out a scene. Negative values produce dark lights, which actually remove light from a scene. For more information, see Colored Lights.


D3DDEVICEDESC7

The D3DDEVICEDESC7 type contains a description of the current device. This type is used to query the current device by such methods as Direct3DDevice7.GetCaps.

Type D3DDeviceDesc7
    dpcLineCaps As D3DPRIMCAPS
    dpcTriCaps As D3DPRIMCAPS
    dvExtentsAdjust As Single
    dvGuardBandBottom As Single
    dvGuardBandLeft As Single
    dvGuardBandRight As Single
    dvGuardBandTop As Single
    dvMaxVertexW As Single
    lDevCaps As CONST_D3DDEVICEDESCCAPS
    lDeviceRenderBitDepth As Long
    lDeviceZBufferBitDepth As Long
    lFVFCaps As CONST_D3DFVFCAPSFLAGS
    lMaxActiveLights As Long
    lMaxAnisotropy As Long
    lMaxTextureAspectRatio As Long
    lMaxTextureHeight As Long
    lMaxTextureRepeat As Long
    lMaxTextureWidth As Long
    lMinTextureHeight As Long
    lMinTextureWidth As Long
    lStencilCaps As CONST_D3DSTENCILCAPSFLAGS
    lTextureOpCaps As CONST_D3DTEXOPCAPSFLAGS
    lVertexProcessingCaps As CONST_D3DVTXPCAPS
    nMaxSimultaneousTextures As Integer
    nMaxTextureBlendStages As Integer
    nMaxUserClipPlanes As Integer
    nMaxVertexBlendMatrices As Integer
End Type

Members

dpcLineCaps and dpcTriCaps
D3DPRIMCAPS type defining the device's support for line-drawing and triangle primitives.
dvExtentsAdjust
Number of pixels to adjust the extents rectangle outward to accommodate antialiasing kernels.
dvGuardBandBottom, dvGuardBandLeft, dvGuardBandTop, and dvGuardBandRight
The screen-space coordinates of the guard-band clipping region. Coordinates inside this rectangle but outside the viewport rectangle will automatically be clipped.
dvMaxVertexW
Maximum W-based depth value that the device supports.
lDevCaps
One of the constants of the CONST_D3DDEVICEDESCCAPS enumeration identifying the capabilities of the device.
lDeviceRenderBitDepth
Device's rendering bit-depth. This can be one or more of the following constants from the CONST_DDBITDEPTHFLAGS enumeration: DDBD_8, DDBD_16, DDBD_24, or DDBD_32.
lDeviceZBufferBitDepth
Device's depth-buffer bit-depth. This can be one or more of the following constants from the CONST_DDBITDEPTHFLAGS enumeration: DDBD_8, DDBD_16, DDBD_24, or DDBD_32.
lFVFCaps
Combination of constants of the CONST_D3DFVFCAPSFLAGS that describe the vertex formats supported by this device.
lMaxActiveLights
Maximum number of lights that can be active simultaneously.
lMaxAnisotropy
Maximum valid value for D3DTSS_MAXANISOTROPY texture-stage state.
lMaxTextureAspectRatio
Maximum texture aspect ratio supported by the hardware; this will typically be a power of 2.
lMaxTextureWidth, lMaxTextureHeight
Maximum texture width and height for this device.
lMaxTextureRepeat
Full range of the integer (non-fractional) bits of the post-normalized texture indices. If the D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE flag is set, the device defers scaling by the texture size until after the texture address mode is applied. If it isn't set, the device scales the texture indices by the texture size (largest level-of-detail) prior to interpolation.
lMinTextureWidth, lMinTextureHeight
Minimum texture width and height for this device.
lStencilCaps
Constants of the CONST_D3DSTENCILCAPSFLAGS enumeration specifying supported stencil-buffer operations. Stencil operations are assumed to be valid for all three stencil-buffer operation render states (D3DRENDERSTATE_STENCILFAIL, D3DRENDERSTATE_STENCILPASS, and D3DRENDERSTATE_STENCILFAILZFAIL).
lTextureOpCaps
Combination of constants of the CONST_D3DTEXOPCAPSFLAGS enumeration describing the texture operations supported by this device.
lVertexProcessingCaps
Vertex processing capabilities, described as a combination of constants of the CONST_D3DVTXPCAPS enumeration.
nMaxSimultaneousTextures
Maximum number of textures that can be simultaneously bound to the texture blending stages for this device. See remarks.
nMaxTextureBlendStages
Maximum number of texture blending stages supported by this device.
nMaxUserClipPlanes
Maximum number of user-defined clipping planes supported. This member can range from 0 through 31.

User-defined clipping planes are manipulated by using the Direct3DDevice7.GetClipPlane and Direct3DDevice7.SetClipPlane methods.

nMaxVertexBlendMatrices
Maximum number of matrices that this device can apply when performing geometry blending.

Remarks

The nMaxTextureBlendStages and nMaxSimultaneousTextures members might seem very similar at first glance, but they contain different information. The nMaxTextureBlendStages member contains the total number of texture-blending stages supported by the current device, and the nMaxSimultaneousTextures member describes how many of those stages can have textures bound to them by using the Direct3DDevice7.SetTexture method.

See Also

CONST_D3DCOLORMODEL, D3DLIGHTINGCAPS, D3DPRIMCAPS


D3DDEVINFO_TEXTUREMANAGER

The D3DDEVINFO_TEXTUREMANAGER type contains information about the current state of the texture manager. This structure is used with the Direct3DDevice7.GetInfo method.

Type D3DDEVINFO_TEXTUREMANAGER
    bThrashing As Boolean
    lLastPri As Long
    lNumEvicts As Long
    lNumTexturesUsed As Long
    lNumUsedTexInVid As Long
    lNumVidCreates As Long
    lTotalBytes As Long
    lTotalManaged As Long
    lWorkingSet As Long
    lWorkingSetBytes As Long
End Type

Members

bThrashing
Thrashing status. This member is True if thrashing occurred during the last frame, or False otherwise.
lLastPri
Priority of last evicted texture.
lNumEvicts
Number of textures that were evicted during the last frame.
lNumTexturesUsed
Total number of textures used during the last frame.
lNumUsedTexInVid
Number of the video memory textures that were used during the last frame.
lNumVidCreates
Number of textures that were created in video memory during the last frame.
lTotalBytes
Total number of bytes allocated for managed textures.
lTotalManaged
Total number of managed textures.
lWorkingSet
Number of textures currently resident in video memory.
lWorkingSetBytes
Number of bytes currently allocated by textures resident in video memory.

Remarks

You can use the values in the lNumUsedTexInVid and lNumTexturesUsed to determine the percentage of textures used during the last frame were resident in video memory (local or non-local). The following code fragment shows how to make this computation:

' For this example, the d3dtminfo variable is a D3DDEVINFO_TEXTUREMANAGER
' structure that has been filled by a call to Direct3DDevice7.GetInfo.
Dim lHitRate As Long

' Retrieve the percentage of textures used that were in video memory.
lHitRate = (d3dtminfo.lNumUsedTexInVid * 100) / d3dtminfo.lNumTexturesUsed

See Also

Direct3DDevice7.GetInfo


D3DDEVINFO_TEXTURING

The D3DDEVINFO_TEXTURING type contains information about the texturing activity of the application. This structure is used with the Direct3DDevice7.GetInfo method.

Type D3DDEVINFO_TEXTURING
  lApproxBytesLoaded As Long
  lNumCreates As Long
  lNumDestroys As Long
  lNumGetDCs As Long
  lNumLoads As Long
  lNumLocks As Long
  lNumPreLoads As Long
  lNumSet As Long
  lNumSetLODs As Long
  lNumSetPriorities As Long
End Type

Members

lApproxBytesLoaded
Approximate number bytes loaded by calls to the Direct3DDevice7.Load method.
lNumCreates
Number of texture surfaces created by the application.
lNumDestroys
Number of textures destroyed (released) by the application.
lNumGetDCs
Number of times a device context for a texture surface has been retrieved by calling the DirectDrawSurface7.GetDC method.
lNumLoads
Number of times a texture has been loaded by calling the Direct3DDevice7.Load method.
lNumLocks
Number of times a texture surface has been locked by calling the DirectDrawSurface7.Lock method.
lNumPreLoads
Number of times managed textures have been explicitly loaded by calling the Direct3DDevice7.PreLoad method.
lNumSet
Number of times textures have been set to texture blending stages by calling the Direct3DDevice7.SetTexture method.
lNumSetLODs
Number of times the maximum mipmap level-of-detail has been set by calling the DirectDrawSurface7.SetLOD method.
lNumSetPriorities
Number of times texture-management priority has been set by calling the DirectDrawSurface7.SetPriority method.

See Also

Direct3DDevice7.GetInfo


D3DLIGHT7

The D3DLIGHT7 type defines the light type in calls to methods such as Direct3DDevice7.SetLight and Direct3DDevice7.GetLight.

Type D3DLIGHT7
    ambient As D3DCOLORVALUE
    attenuation0 As Single
    attenuation1 As Single
    attenuation2 As Single
    diffuse As D3DCOLORVALUE
    direction As D3DVECTOR
    dltType As CONST_D3DLIGHTTYPE
    falloff As Single
    phi As Single
    position As D3DVECTOR
    range As Single
    specular As D3DCOLORVALUE
    theta As Single
End Type

Members

ambient
Ambient color emitted by the light. This member is a D3DCOLORVALUE type.
attenuation0, attenuation1, and attenuation2
Values specifying how a light's intensity changes over distance. (Attenuation does not affect directional lights.) For information about how these attenuation values affect lighting in a scene, see Light Attenuation Over Distance. Valid values for these members range from 0.0 to infinity, inclusive.
diffuse
Diffuse color emitted by the light. This member is a D3DCOLORVALUE type.
direction
Direction the light is pointing in world space. This member only has meaning for directional and spotlights. This vector need not be normalized but it should have a nonzero length.
dltType
Type of the light source. This value is one of the following members of the CONST_D3DLIGHTTYPE enumeration.
falloff
Decrease in illumination between a spotlight's inner cone (the angle specified by the theta member) and the outer edge of the outer cone (the angle specified by the phi member). For details on how falloff values affect a spotlight, see Spotlight Falloff Model.

The effect of falloff on the lighting is subtle. Furthermore, a small performance penalty is incurred by shaping the falloff curve. For these reasons, most developers set this value to 1.0.

phi
Angle, in radians, defining the outer edge of the spotlight's outer cone. Points outside this cone are not lit by the spotlight. This value must be between 0 and pi.
position
Position of the light in world space. This member has no meaning for directional lights and is ignored in that case.
range
Distance beyond which the light has no effect. The maximum allowable value for this member is D3DLIGHT_RANGE_MAX, which is defined as the square root of FLT_MAX. This member does not affect directional lights.
specular
Specular color emitted by the light. This member is a D3DCOLORVALUE type.
theta
Angle, in radians, of the spotlight's inner cone — that is, the fully illuminated spotlight cone. This value must be between 0 and the value specified by the phi member.

Remarks

For more information about lights, see Lights.


D3DLIGHTINGCAPS

The D3DLIGHTINGCAPS type describes the lighting capabilities of a device. This type is a member of the D3DDEVICEDESC7 type.

Type D3DLIGHTINGCAPS
    lCaps As CONST_D3DLIGHTCAPSFLAGS
    lLightingModel As CONST_D3DLIGHTINGMODELFLAGS
    lNumLights As Long
End Type

Members

lCaps
Flags describing the capabilities of the lighting module. The following constants of the CONST_D3DLIGHTCAPSFLAGS enumeration are defined:
D3DLIGHTCAPS_DIRECTIONAL
Supports directional lights.
D3DLIGHTCAPS_POINT
Supports point lights.
D3DLIGHTCAPS_SPOT
Supports spotlights.
lLightingModel
Flags defining whether the lighting model is RGB or monochrome. The following constants of the CONST_D3DLIGHTINGMODELFLAGS enumeration are defined:
D3DLIGHTINGMODEL_MONO
Monochromatic lighting model.
D3DLIGHTINGMODEL_RGB
RGB lighting model.
lNumLights
Number of lights that can be handled.


D3DLINEPATTERN

The D3DLINEPATTERN type describes a line pattern. These values are used by the D3DRENDERSTATE_LINEPATTERN render state in the CONST_D3DRENDERSTATETYPE enumeration.

Type D3DLINEPATTERN
    linePattern Long
    repeatFactor As Long
End Type

Members

linePattern
Bits specifying the line pattern. For example, the following binary value would produce a dotted line: 1100110011001100.
repeatFactor
Number of times to duplicate each series of 1s and 0s specified in the linePattern member. This repeat factor allows an application to stretch the line pattern.

Remarks

A line pattern specifies how a line is drawn. The line pattern is always the same, no matter where it is started. (This differs from stippling, which affects how objects are rendered; that is, to imitate transparency.)

The line pattern specifies up to a 16-pixel pattern of on and off pixels along the line. The repeatFactor member specifies how many pixels are repeated for each entry in linePattern.


D3DLVERTEX

The D3DLVERTEX type defines an untransformed and lit vertex (model coordinates with color). An application should use this type when the vertex transformations will be handled by Direct3D. This type contains only data and a color that would be filled by software lighting.

Type D3DLVERTEX
    color As Long
    specular As Long
    tu As Single
    tv As Single
    x As Single
    y As Single
    z As Single
End Type

Members

color and specular
Values specifying the color and specular component of the vertex.
tu and tv
Values specifying the texture coordinates of the vertex.
x, y, and z
Values specifying the model coordinates of the vertex.

See Also

D3DTLVERTEX, D3DVERTEX


D3DMATERIAL7

The D3DMATERIAL7 type specifies material properties in calls to the Direct3DDevice7.GetMaterial and Direct3DDevice7.SetMaterial methods.

Type D3DMATERIAL7
    ambient As D3DCOLORVALUE
    diffuse As D3DCOLORVALUE
    emissive As D3DCOLORVALUE
    power As Single
    specular As D3DCOLORVALUE
End Type

Members

ambient, diffuse, emissive, and specular
Values specifying the ambient color, diffuse color, emissive color, and specular color of the material, respectively. These values are D3DCOLORVALUE types.
power
Value specifying the sharpness of specular highlights.

Remarks

To turn off specular highlights for a material, you must set the power member to 0—simply setting the specular color components to 0 is not enough.

See Also

Direct3DDevice7.GetMaterial, Direct3DDevice7.SetMaterial


D3DMATRIX

The D3DMATRIX type describes a matrix for such methods as Direct3DDevice7.MultiplyTransform, Direct3DDevice7.GetTransform, and Direct3DDevice7.SetTransform.

Type D3DMATRIX
    rc11 As Single
    rc12 As Single
    rc13 As Single
    rc14 As Single
    rc21 As Single
    rc22 As Single
    rc23 As Single
    rc24 As Single
    rc31 As Single
    rc32 As Single
    rc33 As Single
    rc34 As Single
    rc41 As Single
    rc42 As Single
    rc43 As Single
    rc44 As Single
End Type

Remarks

In Direct3D, the rc34 element of a projection matrix cannot be a negative number. If your application needs to use a negative value in this location, it should scale the entire projection matrix by -1, instead.

See Also

Direct3DDevice7.MultiplyTransform, Direct3DDevice7.GetTransform, and Direct3DDevice7.SetTransform


D3DPRIMCAPS

The D3DPRIMCAPS type defines the capabilities for each primitive type. This type is used when creating a device and when querying the capabilities of a device. This type defines several members in the D3DDEVICEDESC7 type.

Type D3DPrimCaps
    lAlphaCmpCaps As CONST_D3DCAPSCMP
    lDestBlendCaps As CONST_D3DCAPSBLEND
    lMiscCaps As CONST_D3DCAPSMISC
    lRasterCaps As CONST_D3DCAPSRASTER
    lReserved1 As Long
    lShadeCaps As CONST_D3DCAPSSHADE
    lSrcBlendCaps As CONST_D3DCAPSBLEND
    lStippleHeight As Long
    lStippleWidth As Long
    lTextureAddressCaps As CONST_D3DCAPSTEXTUREADDRESS
    lTextureCaps As CONST_D3DCAPSTEXTURE
    lTextureFilterCaps As CONST_D3DCAPSTEXTUREFILTER
    lZCmpCaps As CONST_D3DCAPSCMP
End Type

Members

lAlphaCmpCaps
Alpha-test comparison functions that the driver can perform. If this member contains only the D3DPCMPCAPS_ALWAYS capability or only the D3DPCMPCAPS_NEVER capability, the driver does not support alpha tests. Otherwise, the flags identify the individual comparisons that are supported for alpha testing. This member can be one or of the constants of the CONST_D3DCAPSCMP enumeration.
lDestBlendCaps
Combination of values from the CONST_D3DCAPSBLEND enumeration describing the destination blending capabilities.
lMiscCaps
General capabilities for this primitive. This member can be one or more of the values from the CONST_D3DCAPSMISC enumeration.
lRasterCaps
Information on raster-drawing capabilities. This member can be one or more of the constants from the CONST_D3DCAPSRASTER enumeration.
lReserved1
Reserved. Do not use.
lShadeCaps
Shading operations that the device can perform. It is assumed, in general, that if a device supports a given command (such as D3DOP_TRIANGLE) at all, it supports the D3DSHADE_FLAT mode (as specified in the CONST_D3DSHADEMODE enumeration). This flag specifies whether the driver can also support Gouraud and Phong shading and whether alpha color components are supported for each of the three color-generation modes. When alpha components are not supported in a given mode, the alpha value of colors generated in that mode is implicitly 255. This is the maximum possible alpha (that is, the alpha component is at full intensity).

The color, specular highlights, fog, and alpha interpolants of a triangle each have capability flags that an application can use to find out how they are implemented by the device driver. These are modified by the shade mode, color model, and by whether the alpha component of a color is blended or stippled. For more information, see 3-D Primitives.

This member can be one or more of the constants of the CONST_D3DCAPSSHADE enumeration.

lSrcBlendCaps
Source blending capabilities. This member can be a combination of values from the CONST_D3DCAPSBLEND enumeration describing the destination blending capabilities.
lStippleWidth and lStippleHeight
Maximum width and height of the supported stipple (up to 32×32).
lTextureAddressCaps
Texture-addressing capabilities. This member can be one or more of the constants of the CONST_D3DCAPSTEXTUREADDRESS enumeration.
lTextureCaps
Miscellaneous texture-mapping capabilities. This member can be one or more of the constants of the CONST_D3DCAPSTEXTURE enumeration.
lTextureFilterCaps
Texture-map filtering capabilities. General texture filtering flags reflect which texture filtering modes are supported and can be set for the D3DTSS_MAGFILTER, D3DTSS_MINFILTER, or D3DTSS_MIPFILTER texture stage states. This member can any combination of the general and per-stage texture filtering constants of the CONST_D3DCAPSTEXTUREFILTER enumeration.
lZCmpCaps
Z-buffer comparison functions that the driver can perform. This member can include same constants of the CONST_D3DCAPSCMP as defined for the lAlphaCmpCaps member.


D3DRECT

The D3DRECT type is a rectangle definition.

Type D3DRECT {
    x1 As Long
    x2 As Long
    y1 As Long
    y2 As Long
End Type

Members

x1 and y1
Coordinates of the upper-left corner of the rectangle.
x2 and y2
Coordinates of the lower-right corner of the rectangle.

See Also

Direct3DDevice7.Clear


D3DTLVERTEX

The D3DTLVERTEX type defines a transformed and lit vertex (screen coordinates with color).

Type D3DTLVERTEX
    color As Long
    rhw As Single
    specular As Long
    sx As Single
    sy As Single
    sz As Single
    tu As Single
    tv As Single
End Type

Members

color and specular
Values describing the color and specular component of the vertex.
rhw
Value that is the reciprocal of homogeneous w from homogeneous coordinate (x,y,z,w). This value is often 1 divided by the distance from the origin to the object along the z-axis.
sx, sy, and sz
Values describing a vertex in screen coordinates. The largest allowable value for sz is 1.0, if you want the vertex to be within the range of z-values that are displayed.
tu and tv
Values describing the texture coordinates of the vertex.

See Also

D3DLVERTEX, D3DVERTEX


D3DVECTOR

The D3DVECTOR type defines a vector for many Direct3D methods and types.

Type D3DVECTOR
    x As Single
    y As Single
    z As Single
End Type

Members

x, y, and z
Values describing the vector.

See Also

D3DLIGHT7


D3DVERTEX

The D3DVERTEX type defines an untransformed and unlit vertex (model coordinates with normal direction vector).

Type D3DVERTEX
    nx As Single
    ny As Single
    nz As Single
    tu As Single
    tv As Single
    x As Single
    y As Single
    z As Single
End Type

Members

x, y, and z
Values describing the homogeneous coordinates of the vertex.
nx, ny, and nz
Values describing the normal coordinates of the vertex.
tu and tv
Values describing the texture coordinates of the vertex.

See Also

D3DLVERTEX, D3DTLVERTEX


D3DVERTEXBUFFERDESC

The D3DVERTEXBUFFERDESC type describes the properties of a vertex buffer object. This type is used with the Direct3D7.CreateVertexBuffer and Direct3DVertexBuffer7.GetVertexBufferDesc methods.

Type D3DVERTEXBUFFERDESC
    lCaps As CONST_D3DVBCAPSFLAGS
    lFVF As CONST_D3DFVFFLAGS
    lNumVertices As Long
End Type

Members

lCaps
Capability flags that describe the vertex buffer and identify if the vertex buffer can contain optimized vertex data. This parameter can be any combination of the constants of the CONST_D3DVBCAPSFLAGS enumeration.
lFVF
A combination of constants of the CONST_D3DFVFFLAGS enumeration that describes the vertex format of the vertices in this buffer.
lNumVertices
The maximum number of vertices that this vertex buffer can contain.

Remarks

Software devices—MMX and RGB devices—cannot render from a video memory (local or non-local) vertex buffer. To render a vertex buffer using a software device, the vertex buffer must exist in system memory. Hardware devices can render from system memory or video memory vertex buffers.

See Also

Vertex Buffer Descriptions, Vertex Buffers


D3DVIEWPORT7

The D3DVIEWPORT7 type defines the window dimensions of a render target surface that a 3-D volume projects onto. This type is used with the Direct3DDevice7.GetViewport and Direct3DDevice7.SetViewport methods.

Type D3DVIEWPORT7
    lHeight As Long
    lWidth As Long
    lX As Long
    lY As Long
    maxz As Single
    minz As Single
End Type

Members

lHeight and lWidth
Dimensions of the viewport on the render target surface, in pixels. Unless you are rendering only to a subset of the surface, these members should be set to the dimensions of the render target surface.
lX and lY
Pixel coordinates of the top-left corner of the viewport on the render target surface. Unless you want to render to a subset of the surface, these members can be set to zero.
minz and maxz
Values describing the range of depth values into which a scene will be rendered. (Note that depth-based clipping in DirectX 7.0 is performed through the values in the projection matrix.) Most applications set these values to 0.0 and 1.0, respectively, but you might set them both to 0.0 to force the system to render objects to the foreground of a scene. Clipping in DirectX 7.0 is performed after applying the projection matrix. For more information, see Clipping Volumes and The Projection Transformation.

Remarks

The lX, lY, lHeight and lWidth members describe the position and dimensions of the viewport on the render target surface. Usually, applications render to the entire target surface; when rendering to a 640x480 surface, these members should be 0, 0, 640, and 480, respectively. The minz and maxz are typically set to 0.0 and 1.0, but can be set to other ranges to achieve specific effects. For example you might set them both to 0.0 to force the system to render objects to the foreground of a scene, or both to 1.0 to force the objects into the background.

When the viewport parameters for a device change (by calling Direct3DDevice7.SetViewport), the driver builds a new transformation matrix.

See Also

Direct3DDevice7.GetViewport, Direct3DDevice7.SetViewport, Clipping Volumes, Viewports and Clipping


DXDRIVERINFO

The DXDRIVERINFO type is used in the enumeration methods for DirectDraw, DirectSound and Direct3D to hold driver information.

Type DXDRIVERINFO
    strDescription As String
    strGuid As String
    strName As String
End Type

Members

strDescription
The textual description of the Direct3D device.
strGuid
The GUID that identifies the Direct3D driver being enumerated.
strName
The name of the Direct3D driver corresponding to this device.

Remarks

This type is also used in DirectDraw and DirectSound.


Enumerations

This section contains information about the following enumerations used with Direct3D Immediate Mode.

  • CONST_D3D
  • CONST_D3DANTIALIASMODE
  • CONST_D3DBLEND
  • CONST_D3DCAPSBLEND
  • CONST_D3DCAPSCMP
  • CONST_D3DCAPSMISC
  • CONST_D3DCAPSRASTER
  • CONST_D3DCAPSSHADE
  • CONST_D3DCAPSTEXTURE
  • CONST_D3DCAPSTEXTUREADDRESS
  • CONST_D3DCAPSTEXTUREFILTER
  • CONST_D3DCLEARFLAGS
  • CONST_D3DCLIPFLAGS
  • CONST_D3DCLIPPLANEFLAGS
  • CONST_D3DCLIPSTATUSFLAGS
  • CONST_D3DCMPFUNC
  • CONST_D3DCOLORMODEL
  • CONST_D3DCULL
  • CONST_D3DDEVICEDESCCAPS
  • CONST_D3DDEVICEDESCFLAGS
  • CONST_D3DDEVINFOID
  • CONST_D3DDPFLAGS
  • CONST_D3DFILLMODE
  • CONST_D3DFOGMODE
  • CONST_D3DFVFCAPSFLAGS
  • CONST_D3DFVFFLAGS
  • CONST_D3DIMERR
  • CONST_D3DLIGHTCAPSFLAGS
  • CONST_D3DLIGHTINGMODELFLAGS
  • CONST_D3DLIGHTTYPE
  • CONST_D3DMATERIALCOLORSOURCE
  • CONST_D3DPRIMITIVETYPE
  • CONST_D3DPROCESSVERTICESFLAGS
  • CONST_D3DRENDERSTATESINGLE
  • CONST_D3DRENDERSTATETYPE
  • CONST_D3DSHADEMODE
  • CONST_D3DSTATEBLOCKTYPE
  • CONST_D3DSTENCILCAPSFLAGS
  • CONST_D3DSTENCILOP
  • CONST_D3DTAFLAGS
  • CONST_D3DTEXCOORDINDEXFLAGS
  • CONST_D3DTEXOPCAPSFLAGS
  • CONST_D3DTEXTUREADDRESS
  • CONST_D3DTEXTUREMAGFILTER
  • CONST_D3DTEXTUREMINFILTER
  • CONST_D3DTEXTUREMIPFILTER
  • CONST_D3DTEXTUREOP
  • CONST_D3DTEXTURESTAGESINGLE
  • CONST_D3DTEXTURESTAGESTATETYPE
  • CONST_D3DTEXTURETRANSFORMFLAGS
  • CONST_D3DTRANSFORMSTATETYPE
  • CONST_D3DVBCAPSFLAGS
  • CONST_D3DVERTEXBLENDFLAGS
  • CONST_D3DVOPFLAGS
  • CONST_D3DVTXPCAPS
  • CONST_D3DZBUFFERTYPE


CONST_D3D

The CONST_D3D enumeration defines miscellaneous constants.

Enum CONST_D3D
    D3DDP_MAXTEXCOORD =8
    D3DRENDERSTATE_WRAPBIAS = 128
    D3DWRAPCOORD_0 = 1
    D3DWRAPCOORD_1 = 2
    D3DWRAPCOORD_2 = 4
    D3DWRAPCOORD_3 = 8
End Enum
D3DDP_MAXTEXCOORD
The maximum number of texture coordinates allowed for a vertex.
D3DRENDERSTATE_WRAPBIAS
A convenience value that can be added to a zero-based index for a texture stage to produce a valid D3DRENDERSTATE_WRAPn value for use with the Direct3DDevice7.SetRenderState and Direct3DDevice7.SetRenderState methods.
D3DWRAPCOORD_0 through D3DWRAPCOORD_3
These cause the system to wrap in the direction of the first, second, third, and fourth dimensions (sometimes referred to at the "s, t, r, and q" directions) for a given texture. These values are used with the D3DRENDERSTATE_WRAP0 through D3DRENDERSTATE_WRAP7 render states.


CONST_D3DANTIALIASMODE

The CONST_D3DANTIALIASMODE enumeration defines the supported antialiasing mode for the D3DRENDERSTATE_ANTIALIAS value in the CONST_D3DRENDERSTATETYPE enumeration. These values define the settings for antialiasing the edges of primitives. (For more information, see Antialiasing.)

Enum CONST_D3DANTIALIASMODE
    D3DANTIALIAS_NONE          = 0
    D3DANTIALIAS_SORTDEPENDENT = 1
    D3DANTIALIAS_SORTINDEPENDENT = 2
End Enum
D3DANTIALIAS_NONE
No antialiasing is performed. This is the default setting.
D3DANTIALIAS_SORTDEPENDENT
Antialiasing is dependent on the sort order of the polygons (back-to-front or front-to-back). The application must draw polygons in the right order for antialiasing to occur.
D3DANTIALIAS_SORTINDEPENDENT
Antialiasing is not dependent on the sort order of the polygons.


CONST_D3DBLEND

The CONST_D3DBLEND enumeration defines the supported blend mode for the D3DRENDERSTATE_DESTBLEND values in the CONST_D3DRENDERSTATETYPE enumeration. In the member descriptions that follow, the RGBA values of the source and destination are indicated with the subscripts s and d.

Enum CONST_D3DBLEND
    D3DBLEND_ZERO            = 1
    D3DBLEND_ONE             = 2
    D3DBLEND_SRCCOLOR        = 3
    D3DBLEND_INVSRCCOLOR     = 4
    D3DBLEND_SRCALPHA        = 5
    D3DBLEND_INVSRCALPHA     = 6
    D3DBLEND_DESTALPHA       = 7
    D3DBLEND_INVDESTALPHA    = 8
    D3DBLEND_DESTCOLOR       = 9
    D3DBLEND_INVDESTCOLOR    = 10
    D3DBLEND_SRCALPHASAT     = 11
    D3DBLEND_BOTHSRCALPHA    = 12
    D3DBLEND_BOTHINVSRCALPHA = 13
End Enum
D3DBLEND_ZERO
Blend factor is (0, 0, 0, 0).
D3DBLEND_ONE
Blend factor is (1, 1, 1, 1).
D3DBLEND_SRCCOLOR
Blend factor is (Rs, Gs, Bs, As).
D3DBLEND_INVSRCCOLOR
Blend factor is (1-Rs, 1-Gs, 1-Bs, 1-As).
D3DBLEND_SRCALPHA
Blend factor is (As, As, As, As).
D3DBLEND_INVSRCALPHA
Blend factor is (1-As, 1-As, 1-As, 1-As).
D3DBLEND_DESTALPHA
Blend factor is (Ad, Ad, Ad, Ad).
D3DBLEND_INVDESTALPHA
Blend factor is (1-Ad, 1-Ad, 1-Ad, 1-Ad).
D3DBLEND_DESTCOLOR
Blend factor is (Rd, Gd, Bd, Ad).
D3DBLEND_INVDESTCOLOR
Blend factor is (1-Rd, 1-Gd, 1-Bd, 1-Ad).
D3DBLEND_SRCALPHASAT
Blend factor is (f, f, f, 1); f = min(As, 1-Ad).
D3DBLEND_BOTHSRCALPHA
Not supported.
D3DBLEND_BOTHINVSRCALPHA
Source blend factor is (1-As, 1-As, 1-As, 1-As), and destination blend factor is (As, As, As, As); the destination blend selection is overridden.

Remarks

D3DBLEND_BOTHSRCALPHA is no longer supported in Direct3D versions for DirectX 6.0 and later. Please explicitly set both D3DBLEND_SRCALPHA and D3DBLEND_INVSRCALPHA separately.


CONST_D3DCAPSBLEND

The CONST_D3DCAPSBLEND enumeration defines the blending capabilities for a device. These values are combined in the lSrcBlendCaps and lDestBlendCaps members of the D3DPRIMCAPS type.

Enum CONST_D3DCAPSBLEND
    D3DPBLENDCAPS_BOTHINVSRCALPHA =4096
    D3DPBLENDCAPS_BOTHSRCALPHA =2048
    D3DPBLENDCAPS_DESTALPHA =64
    D3DPBLENDCAPS_DESTCOLOR =256
    D3DPBLENDCAPS_INVDESTALPHA =128
    D3DPBLENDCAPS_INVDESTCOLOR =512
    D3DPBLENDCAPS_INVSRCALPHA =32
    D3DPBLENDCAPS_INVSRCCOLOR =8
    D3DPBLENDCAPS_ONE =2
    D3DPBLENDCAPS_SRCALPHA =16
    D3DPBLENDCAPS_SRCALPHASAT =1024
    D3DPBLENDCAPS_SRCCOLOR =4
    D3DPBLENDCAPS_ZERO =1
End Enum
D3DPBLENDCAPS_BOTHINVSRCALPHA
Source blend factor is (1-As, 1-As, 1-As, 1-As) and destination blend factor is (As, As, As, As); the destination blend selection is overridden.
D3DPBLENDCAPS_BOTHSRCALPHA
Source blend factor is (As, As, As, As) and destination blend factor is (1-As, 1-As, 1-As, 1-As); the destination blend selection is overridden.
D3DPBLENDCAPS_DESTALPHA
Blend factor is (Ad, Ad, Ad, Ad).
D3DPBLENDCAPS_DESTCOLOR
Blend factor is (Rd, Gd, Bd, Ad).
D3DPBLENDCAPS_INVDESTALPHA
Blend factor is (1-Ad, 1-Ad, 1-Ad, 1-Ad).
D3DPBLENDCAPS_INVDESTCOLOR
Blend factor is (1-Rd, 1-Gd, 1-Bd, 1-Ad).
D3DPBLENDCAPS_INVSRCALPHA
Blend factor is (1-As, 1-As, 1-As, 1-As).
D3DPBLENDCAPS_INVSRCCOLOR
Blend factor is (1-Rd, 1-Gd, 1-Bd, 1-Ad).
D3DPBLENDCAPS_ONE
Blend factor is (1, 1, 1, 1).
D3DPBLENDCAPS_SRCALPHA
Blend factor is (As, As, As, As).
D3DPBLENDCAPS_SRCALPHASAT
Blend factor is (f, f, f, 1); f = min(As, 1-Ad).
D3DPBLENDCAPS_SRCCOLOR
Blend factor is (Rs, Gs, Bs, As).
D3DPBLENDCAPS_ZERO
Blend factor is (0, 0, 0, 0).


CONST_D3DCAPSCMP

The CONST_D3DCAPSCMP enumeration defines comparison capabilities for depth-buffer comparisons and alpha-testing. These flags are combined and present in the lZCmpCaps and lAlphaCmpCaps members of the D3DPRIMCAPS type.

Enum CONST_D3DCAPSCMP
    D3DPCMPCAPS_ALWAYS = 128
    D3DPCMPCAPS_EQUAL = 4
    D3DPCMPCAPS_GREATER = 16
    D3DPCMPCAPS_GREATEREQUAL = 64
    D3DPCMPCAPS_LESS = 2
    D3DPCMPCAPS_LESSEQUAL = 8
    D3DPCMPCAPS_NEVER = 1
    D3DPCMPCAPS_NOTEQUAL = 32
End Enum
D3DPCMPCAPS_ALWAYS
Always pass the comparison.
D3DPCMPCAPS_EQUAL
Pass the comparison if the new value equals the current value.
D3DPCMPCAPS_GREATER
Pass the comparison if the new value is greater than the current value.
D3DPCMPCAPS_GREATEREQUAL
Pass the comparison if the new value is greater than or equal to the current value.
D3DPCMPCAPS_LESS
Pass the comparison if the new value is less than the current value.
D3DPCMPCAPS_LESSEQUAL
Pass the comparison if the new value is less than or equal to the current value.
D3DPCMPCAPS_NEVER
Always fail the comparison.
D3DPCMPCAPS_NOTEQUAL
Pass the comparison if the new value does not equal the current value.


CONST_D3DCAPSMISC

The CONST_D3DCAPSMISC enumeration defines capability flags that are combined and found in the lMiscCaps member of the D3DPRIMCAPS type.

Enum CONST_D3DCAPSMISC
    D3DPMISCCAPS_CONFORMANT = 8
    D3DPMISCCAPS_CULLCCW = 64
    D3DPMISCCAPS_CULLCW = 32
    D3DPMISCCAPS_CULLNONE = 16
    D3DPMISCCAPS_LINEPATTERNREP = 4
    D3DPMISCCAPS_MASKPLANES = 1
    D3DPMISCCAPS_MASKZ = 2
End Enum
D3DPMISCCAPS_CONFORMANT
The device conforms to the OpenGL standard.
D3DPMISCCAPS_CULLCCW
The driver supports counterclockwise culling through the D3DRENDERSTATE_CULLMODE state. (This applies only to triangle primitives.) This corresponds to the D3DCULL_CCW constant of the CONST_D3DCULL enumeration.
D3DPMISCCAPS_CULLCW
The driver supports clockwise triangle culling through the D3DRENDERSTATE_CULLMODE state. (This applies only to triangle primitives.) This corresponds to the D3DCULL_CW constant of the CONST_D3DCULL enumeration.
D3DPMISCCAPS_CULLNONE
The driver does not perform triangle culling. This corresponds to the D3DCULL_NONE constant of the CONST_D3DCULL enumeration.
D3DPMISCCAPS_LINEPATTERNREP
Not used.
D3DPMISCCAPS_MASKPLANES
The device can perform a bitmask of color planes.
D3DPMISCCAPS_MASKZ
The device can enable and disable modification of the depth-buffer on pixel operations.


CONST_D3DCAPSRASTER

The CONST_D3DCAPSRASTER enumeration defines rasterization capability flags that are combined and present in the lRasterCaps member of the D3DPRIMCAPS type.

Enum CONST_D3DCAPSRASTER
    D3DPRASTERCAPS_ANISOTROPY = 131072
    D3DPRASTERCAPS_ANTIALIASEDGES = 4096
    D3DPRASTERCAPS_ANTIALIASSORTDEPENDENT = 1024
    D3DPRASTERCAPS_DITHER= 1
    D3DPRASTERCAPS_FOGRANGE = 65536
    D3DPRASTERCAPS_FOGTABLE = 256
    D3DPRASTERCAPS_FOGVERTEX = 128
    D3DPRASTERCAPS_MIPMAPLODBIAS = 8192
    D3DPRASTERCAPS_PAT = 8
    D3DPRASTERCAPS_ROP2 = 2
    D3DPRASTERCAPS_STIPPLE = 512
    D3DPRASTERCAPS_SUBPIXEL= 32
    D3DPRASTERCAPS_SUBPIXELX = 64
    D3DPRASTERCAPS_XOR = 4
    D3DPRASTERCAPS_ZBIAS = 16384
    D3DPRASTERCAPS_ZBUFFERLESSHSR = 32768
    D3DPRASTERCAPS_ZTEST = 16
End Enum
D3DPRASTERCAPS_ANISOTROPY
The device supports anisotropic filtering.
D3DPRASTERCAPS_ANTIALIASEDGES
The device can antialias lines forming the convex outline of objects.
D3DPRASTERCAPS_ANTIALIASSORTDEPENDENT
The device supports antialiasing that is dependent on the sort order of the polygons (back-to-front or front-to-back). The application must draw polygons in the right order for antialiasing to occur. For more information, see the CONST_D3DANTIALIASMODE enumeration.
D3DPRASTERCAPS_ANTIALIASSORTINDEPENDENT
The device supports antialiasing that is not dependent on the sort order of the polygons. For more information, see the CONST_D3DANTIALIASMODE enumeration.
D3DPRASTERCAPS_DITHER
The device can dither to improve color resolution.
D3DPRASTERCAPS_FOGRANGE
The device supports range-based fog. In range-based fog, the distance of an object from the viewer is used to compute fog effects, not the depth of the object (that is, the z-coordinate) in the scene. For more information, see Range-based Fog.
D3DPRASTERCAPS_FOGTABLE
The device calculates the fog value by referring to a lookup table containing fog values that are indexed to the depth of a given pixel.
D3DPRASTERCAPS_FOGVERTEX
The device calculates the fog value during the lighting operation, places the value into the alpha component given for the specular member of the D3DTLVERTEX type, and interpolates the fog value during rasterization.
D3DPRASTERCAPS_MIPMAPLODBIAS
The device supports level-of-detail (LOD) bias adjustments. These bias adjustments enable an application to make a mipmap appear crisper or less sharp than it normally would. For more information about LOD bias in mipmaps, see D3DTSS_MIPMAPLODBIAS .
D3DPRASTERCAPS_PAT
The driver can perform patterned drawing for the primitive being queried.
D3DPRASTERCAPS_ROP2
The device can support raster operations other than R2_COPYPEN.
D3DPRASTERCAPS_STIPPLE
The device can stipple polygons to simulate translucency.
D3DPRASTERCAPS_SUBPIXEL
The device performs subpixel placement of z, color, and texture data, rather than working with the nearest integer pixel coordinate. This helps avoid bleed-through due to z imprecision, and jitter of color and texture values for pixels. Note that there is no corresponding state that can be enabled and disabled; the device either performs subpixel placement or it does not, and this bit is present only so that the Direct3D client will be better able to determine what the rendering quality will be.
D3DPRASTERCAPS_SUBPIXELX
The device is subpixel accurate along the x-axis only and is clamped to an integer y-axis scan line.
D3DPRASTERCAPS_WBUFFER
The device supports depth buffering using w. For more information, see Depth Buffers.
D3DPRASTERCAPS_WFOG
The device supports w-based fog. W-based fog is used when a perspective projection matrix is specified, but affine projections will still use z-based fog. The system considers a projection matrix that contains a nonzero value in the [3][4] element to be a perspective projection matrix.
D3DPRASTERCAPS_XOR
The device can support XOR GDI raster operations. If this flag is not set but D3DPRIM_RASTER_ROP2 is set, then XOR operations must still be supported.
D3DPRASTERCAPS_ZBIAS
The device supports z-bias values. These are integer values assigned to polygons that allow physically coplanar polygons to appear separate. For more information, see D3DRENDERSTATE_ZBIAS in the CONST_D3DRENDERSTATETYPE enumeration.
D3DPRASTERCAPS_ZBUFFERLESSHSR
The device can perform hidden-surface removal (HSR) without requiring the application to sort polygons, and without requiring the allocation of a depth-buffer. This leaves more video memory for textures. The method used to perform hidden-surface removal is hardware-dependent and is transparent to the application.

Z-bufferless HSR is performed if no depth-buffer surface is attached to the rendering-target surface and the depth-buffer comparison test is enabled (that is, when the state value associated with the D3DRENDERSTATE_ZENABLE enumeration constant is set to True).

D3DPRASTERCAPS_ZTEST
The device can perform z-test operations. This effectively renders a primitive and indicates whether any z pixels would have been rendered.


CONST_D3DCAPSSHADE

The CONST_D3DCAPSSHADE enumeration defines polygon shading capability flags that are combined and present in the lShadeCaps member of the D3DPRIMCAPS type.

Enum CONST_D3DCAPSSHADE
    D3DPSHADECAPS_ALPHAFLATBLEND = 4096
    D3DPSHADECAPS_ALPHAFLATSTIPPLED = 8192
    D3DPSHADECAPS_ALPHAGOURAUDBLEND = 16384
    D3DPSHADECAPS_ALPHAGOURAUDSTIPPLED = 32768
    D3DPSHADECAPS_ALPHAPHONGBLEND = 65536
    D3DPSHADECAPS_ALPHAPHONGSTIPPLED = 131072
    D3DPSHADECAPS_COLORFLATMONO = 1
    D3DPSHADECAPS_COLORFLATRGB = 2
    D3DPSHADECAPS_COLORGOURAUDMONO = 4
    D3DPSHADECAPS_COLORGOURAUDRGB = 8
    D3DPSHADECAPS_COLORPHONGMONO = 16
    D3DPSHADECAPS_COLORPHONGRGB = 32
    D3DPSHADECAPS_FOGFLAT = 262144
    D3DPSHADECAPS_FOGGOURAUD = 524288
    D3DPSHADECAPS_FOGPHONG = 1048576
    D3DPSHADECAPS_SPECULARFLATMONO = 64
    D3DPSHADECAPS_SPECULARFLATRGB = 128
    D3DPSHADECAPS_SPECULARGOURAUDMONO = 256
    D3DPSHADECAPS_SPECULARGOURAUDRGB = 512
    D3DPSHADECAPS_SPECULARPHONGMONO = 1024
    D3DPSHADECAPS_SPECULARPHONGRGB = 2048
End Enum
D3DPSHADECAPS_ALPHAFLATBLEND, D3DPSHADECAPS_ALPHAFLATSTIPPLED
Device can support an alpha component for flat blended and stippled transparency, respectively (the D3DSHADE_FLAT state for the CONST_D3DSHADEMODE enumeration). In these modes, the alpha color component for a primitive is provided as part of the color for the first vertex of the primitive.
D3DPSHADECAPS_ALPHAGOURAUDBLEND, D3DPSHADECAPS_ALPHAGOURAUDSTIPPLED
Device can support an alpha component for Gouraud blended and stippled transparency, respectively (the D3DSHADE_GOURAUD state for the CONST_D3DSHADEMODE enumeration). In these modes, the alpha color component for a primitive is provided at vertices and interpolated across a face along with the other color components.
D3DPSHADECAPS_ALPHAPHONGBLEND, D3DPSHADECAPS_ALPHAPHONGSTIPPLED
Device can support an alpha component for Phong blended and stippled transparency, respectively (the D3DSHADE_PHONG state for the CONST_D3DSHADEMODE enumeration). In these modes, vertex parameters are reevaluated on a per-pixel basis, applying lighting effects for the red, green, and blue color components. Phong shading is not currently supported.
D3DPSHADECAPS_COLORFLATMONO, D3DPSHADECAPS_COLORFLATRGB
Device can support colored flat shading in the D3DCOLOR_MONO and D3DCOLOR_RGB color models, respectively. In these modes, the color component for a primitive is provided as part of the color for the first vertex of the primitive. In monochromatic lighting modes, only the blue component of the color is interpolated; in RGB lighting modes, the red, green, and blue components are interpolated.
D3DPSHADECAPS_COLORGOURAUDMONO, D3DPSHADECAPS_COLORGOURAUDRGB
Device can support colored Gouraud shading in the D3DCOLOR_MONO and D3DCOLOR_RGB color models, respectively. In these modes, the color component for a primitive is provided at vertices and interpolated across a face along with the other color components. In monochromatic lighting modes, only the blue component of the color is interpolated; in RGB lighting modes, the red, green, and blue components are interpolated.
D3DPSHADECAPS_COLORPHONGMONO, D3DPSHADECAPS_COLORPHONGRGB
Device can support colored Phong shading in the D3DCOLOR_MONO and D3DCOLOR_RGB color models, respectively. In these modes, vertex parameters are reevaluated on a per-pixel basis. Lighting effects are applied for the red, green, and blue color components in RGB mode, and for the blue component only for monochromatic mode. Phong shading is not currently supported.
D3DPSHADECAPS_FOGFLAT, D3DPSHADECAPS_FOGGOURAUD, D3DPSHADECAPS_FOGPHONG
Device can support fog in the flat, Gouraud, and Phong shading models, respectively. Phong shading is not currently supported.
D3DPSHADECAPS_SPECULARFLATMONO, D3DPSHADECAPS_SPECULARFLATRGB
Device can support specular highlights in flat shading in the D3DCOLOR_MONO and D3DCOLOR_RGB color models, respectively.
D3DPSHADECAPS_SPECULARGOURAUDMONO, D3DPSHADECAPS_SPECULARGOURAUDRGB
Device can support specular highlights in Gouraud shading in the D3DCOLOR_MONO and D3DCOLOR_RGB color models, respectively.
D3DPSHADECAPS_SPECULARPHONGMONO, D3DPSHADECAPS_SPECULARPHONGRGB
Device can support specular highlights in Phong shading in the D3DCOLOR_MONO and D3DCOLOR_RGB color models, respectively. Phong shading is not currently supported.


CONST_D3DCAPSTEXTURE

The CONST_D3DCAPSTEXTURE enumeration defines texturing capability flags that are combined and present in the lTextureCaps member of the D3DPRIMCAPS type.

Enum CONST_D3DCAPSTEXTURE {
    D3DPTEXTURECAPS_ALPHA = 4
    D3DPTEXTURECAPS_BORDER = 16
    D3DPTEXTURECAPS_COLORKEYBLEND = 4096
    D3DPTEXTURECAPS_CUBEMAP = 1024
    D3DPTEXTURECAPS_NONPOW2CONDITIONAL = 256
    D3DPTEXTURECAPS_PERSPECTIVE = 1
    D3DPTEXTURECAPS_POW2 = 2
    D3DPTEXTURECAPS_SQUAREONLY = 32
    D3DPTEXTURECAPS_TRANSPARENCY = 8
End Enum
D3DPTEXTURECAPS_ALPHA
Supports RGBA textures in the D3DTEX_DECAL and D3DTEX_MODULATE texture filtering modes. If this capability is not set, then only RGB textures are supported in those modes. Regardless of the setting of this flag, alpha must always be supported in D3DTEX_DECAL_MASK, D3DTEX_DECAL_ALPHA, and D3DTEX_MODULATE_ALPHA filtering modes whenever those filtering modes are available.
D3DPTEXTURECAPS_ALPHAPALETTE
Supports palettized texture surfaces whose palettes contain alpha information (see DDPCAPS_ALPHA in the DDCAPS type).
D3DPTEXTURECAPS_COLORKEYBLEND
The device supports alpha-blended colorkeying through the use of the D3DRENDERSTATE_COLORKEYBLENDENABLE render state.
D3DPTEXTURECAPS_CUBEMAP
Supports cubic environment mapping.
D3DPTEXTURECAPS_BORDER
Superseded by D3DPTADDRESSCAPS_BORDER.
D3DPTEXTURECAPS_PERSPECTIVE
Perspective correction is supported.
D3DPTEXTURECAPS_PROJECTED
Supports the D3DTTFF_PROJECTED texture transformation flag. When applied, the device divides transformed texture coordinates by the last texture coordinate.
D3DPTEXTURECAPS_NONPOW2CONDITIONAL
Conditionally supports the use of textures with dimensions that are not powers of two. A device that exposes this capability can use such a texture if all of the following requirements are met.
  • The texture addressing mode for the texture stage is set to D3DTADDRESS_CLAMP.
  • Texture wrapping for the texture stage is disabled (D3DRENDERSTATE_WRAPn set to zero).
  • Mipmapping is not in use. (Mipmapped textures must have dimensions that are powers of two.)
D3DPTEXTURECAPS_POW2
All nonmipmapped textures must have widths and heights specified as powers of two if this flag is set. (Note that all mipmapped textures must always have dimensions that are powers of two.)
D3DPTEXTURECAPS_SQUAREONLY
All textures must be square.
D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE
Texture indices are not scaled by the texture size prior to interpolation.
D3DPTEXTURECAPS_TRANSPARENCY
Texture transparency is supported. (Only those texels that are not the current transparent color are drawn.)


CONST_D3DCAPSTEXTUREADDRESS

The CONST_D3DCAPSTEXTUREADDRESS enumeration defines texture addressing capability flags that are combined and present in the lTextureAddressCaps member of the D3DPRIMCAPS type.

Enum CONST_D3DCAPSTEXTUREADDRESS
    D3DPTADDRESSCAPS_BORDER = 8
    D3DPTADDRESSCAPS_CLAMP = 4
    D3DPTADDRESSCAPS_INDEPENDENTUV = 16
    D3DPTADDRESSCAPS_MIRROR = 2
    D3DPTADDRESSCAPS_WRAP = 1
End Enum
D3DPTADDRESSCAPS_BORDER
Device supports setting coordinates outside the range [0.0, 1.0] to the border color, as specified by the D3DTSS_BORDERCOLOR texture stage state. This ability corresponds to the D3DTADDRESS_BORDER texture-addressing mode.
D3DPTADDRESSCAPS_CLAMP
Device can clamp textures to addresses.
D3DPTADDRESSCAPS_INDEPENDENTUV
Device can separate the texture-addressing modes of the u and v coordinates of the texture. This ability corresponds to the D3DTSS_ADDRESSU and D3DTSS_ADDRESSV render-state values.
D3DPTADDRESSCAPS_MIRROR
Device can mirror textures to addresses.
D3DPTADDRESSCAPS_WRAP
Device can wrap textures to addresses.


CONST_D3DCAPSTEXTUREFILTER

The CONST_D3DCAPSTEXTUREFILTER enumeration defines texture filtering capability flags that are combined and present in the lTextureFilterCaps of the D3DPRIMCAPS type.

Enum CONST_D3DCAPSTEXTUREFILTER
    D3DPTFILTERCAPS_LINEAR = 2
    D3DPTFILTERCAPS_LINEARMIPLINEAR = 32
    D3DPTFILTERCAPS_LINEARMIPNEAREST = 16
    D3DPTFILTERCAPS_MAGFAFLATCUBIC = 134217728
    D3DPTFILTERCAPS_MAGFANISOTROPIC = 67108864
    D3DPTFILTERCAPS_MAGFGAUSSIANCUBIC =  268435456
    D3DPTFILTERCAPS_MAGFLINEAR = 16777216
    D3DPTFILTERCAPS_MAGFPOINT = 8388608
    D3DPTFILTERCAPS_MINFANISOTROPIC = 1024
    D3DPTFILTERCAPS_MINFLINEAR = 512
    D3DPTFILTERCAPS_MINFPOINT = 256
    D3DPTFILTERCAPS_MIPFLINEAR = 131072
    D3DPTFILTERCAPS_MIPFPOINT = 65536
    D3DPTFILTERCAPS_MIPLINEAR = 8
    D3DPTFILTERCAPS_MIPNEAREST = 4
    D3DPTFILTERCAPS_NEAREST = 1
End Enum
General texture filtering flags
D3DPTFILTERCAPS_LINEAR
Bilinear filtering. Chooses the texel that has nearest coordinates, then performs a weighted average with the four surrounding texels to determine the final color. This applies to both zooming in and zooming out. If either zooming in or zooming out is supported, then both must be supported.
D3DPTFILTERCAPS_LINEARMIPLINEAR
Trilinear interpolation between mipmaps. Performs bilinear filtering on the two nearest mipmaps, then interpolates linearly between the two colors to determine a final color.
D3DPTFILTERCAPS_LINEARMIPNEAREST
Linear interpolation between two point sampled mipmaps. Chooses the nearest texel from the two closest mipmap levels, then performs linear interpolation between them.
D3DPTFILTERCAPS_MIPLINEAR
Nearest mipmapping, with bilinear filtering applied to the result. Chooses the texel from the appropriate mipmap that has nearest coordinates, then performs a weighted average with the four surrounding texels to determine the final color.
D3DPTFILTERCAPS_MIPNEAREST
Nearest mipmapping. Chooses the texel from the appropriate mipmap with coordinates nearest to the desired pixel value.
D3DPTFILTERCAPS_NEAREST
Point sampling. The texel with coordinates nearest to the desired pixel value is used. This applies to both zooming in and zooming out. If either zooming in or zooming out is supported, then both must be supported.
Per-stage texture filtering flags
D3DPTFILTERCAPS_MAGFAFLATCUBIC
The device supports per-stage flat-cubic filtering for magnifying textures. The flat-cubic magnification filter is represented by the D3DTFG_FLATCUBIC member of the CONST_D3DTEXTUREMAGFILTER enumeration.
D3DPTFILTERCAPS_MAGFANISOTROPIC
The device supports per-stage anisotropic filtering for magnifying textures. The anisotropic magnification filter is represented by the D3DTFG_ANISOTROPIC member of the CONST_D3DTEXTUREMAGFILTER enumeration.
D3DPTFILTERCAPS_MAGFGAUSSIANCUBIC
The device supports the per-stage Gaussian-cubic filtering for magnifying textures. The Gaussian-cubic magnification filter is represented by the D3DTFG_GAUSSIANCUBIC member of the CONST_D3DTEXTUREMAGFILTER enumeration.
D3DPTFILTERCAPS_MAGFLINEAR
The device supports per-stage bilinear-interpolation filtering for magnifying textures. The bilinear-interpolation magnification filter is represented by the D3DTFG_LINEAR member of the CONST_D3DTEXTUREMAGFILTER enumeration.
D3DPTFILTERCAPS_MAGFPOINT
The device supports per-stage point-sampled filtering for magnifying textures. The point-sample magnification filter is represented by the D3DTFG_POINT member of the CONST_D3DTEXTUREMAGFILTER enumeration.
D3DPTFILTERCAPS_MINFANISOTROPIC
The device supports per-stage anisotropic filtering for minifying textures. The anisotropic minification filter is represented by the D3DTFN_ANISOTROPIC member of the CONST_D3DTEXTUREMINFILTER enumeration.
D3DPTFILTERCAPS_MINFLINEAR
The device supports per-stage bilinear-interpolation filtering for minifying textures. The bilinear minification filter is represented by the D3DTFN_LINEAR member of the CONST_D3DTEXTUREMINFILTER enumeration.
D3DPTFILTERCAPS_MINFPOINT
The device supports per-stage point-sampled filtering for minifying textures. The point-sample minification filter is represented by the D3DTFN_POINT member of the CONST_D3DTEXTUREMINFILTER enumeration.
D3DPTFILTERCAPS_MIPFLINEAR
The device supports per-stage trilinear-interpolation filtering for mipmaps. The trilinear-interpolation mipmapping filter is represented by the D3DTFP_LINEAR member of the CONST_D3DTEXTUREMIPFILTER enumeration.
D3DPTFILTERCAPS_MIPFPOINT
The device supports per-stage point-sampled filtering for mipmaps. The point-sample mipmapping filter is represented by the D3DTFP_POINT member of the CONST_D3DTEXTUREMIPFILTER enumeration.


CONST_D3DCLEARFLAGS

The CONST_D3DCLEARFLAGS enumeration defines flags that are used to determine the behavior of the Direct3DDevice7.Clear method.

Enum CONST_D3DCLEARFLAGS
    D3DCLEAR_ALL = 7
    D3DCLEAR_STENCIL = 4
    D3DCLEAR_TARGET = 1
    D3DCLEAR_ZBUFFER = 2
End Enum
D3DCLEAR_ALL
Clear the rendering target, stencil buffer, and depth-buffer surfaces.
D3DCLEAR_STENCIL
Clear the stencil buffer to the value in the stencil parameter.
D3DCLEAR_TARGET
Clear the rendering target to the color in the color parameter.
D3DCLEAR_ZBUFFER
Clear the depth-buffer to the value in the z parameter.


CONST_D3DCLIPFLAGS

The CONST_D3DCLIPFLAGS enumeration defines clipping flags returned by the Direct3DDevice7.ComputeSphereVisibility method.

Enum CONST_D3DCLIPFLAGS
    D3DSTATUS_CLIPINTERSECTIONALL = 17891328
    D3DSTATUS_CLIPUNIONALL = 17891328
    D3DSTATUS_DEFAULT = 34668544
    D3DSTATUS_ZNOTVISIBLE = 16777216
    D3DSTATUS_CLIPINTERSECTIONBACK = 131072
    D3DSTATUS_CLIPINTERSECTIONBOTTOM = 32768
    D3DSTATUS_CLIPINTERSECTIONFRONT = 65536
    D3DSTATUS_CLIPINTERSECTIONGEN0 = 262144
    ' D3DSTATUS_CLIPINTERSECTIONGEN1 to D3DSTATUS_CLIPINTERSECTIONGEN4
    ' omitted here for brevity.
    D3DSTATUS_CLIPINTERSECTIONGEN5 = 8388608
    D3DSTATUS_CLIPINTERSECTIONLEFT = 4096
    D3DSTATUS_CLIPINTERSECTIONRIGHT = 8192
    D3DSTATUS_CLIPINTERSECTIONTOP = 16384
    D3DSTATUS_CLIPUNIONBACK = 32
    D3DSTATUS_CLIPUNIONBOTTOM = 8
    D3DSTATUS_CLIPUNIONFRONT = 16
    D3DSTATUS_CLIPUNIONGEN0 = 64
    ' D3DSTATUS_CLIPUNIONGEN1 to D3DSTATUS_CLIPUNIONGEN4
    ' omitted here for brevity.
    D3DSTATUS_CLIPUNIONGEN5 = 2048
    D3DSTATUS_CLIPUNIONLEFT = 1
    D3DSTATUS_CLIPUNIONRIGHT = 2
    D3DSTATUS_CLIPUNIONTOP = 4
    D3DCLIP_BACK = 32
    D3DCLIP_BOTTOM = 8
    D3DCLIP_FRONT = 16
    D3DCLIP_GEN0 = 64
    ' D3DCLIP_GEN1 to D3DCLIP_GEN4 omitted here for brevity.
    D3DCLIP_GEN5 = 2048
    D3DCLIP_LEFT = 1
    D3DCLIP_RIGHT = 2
    D3DCLIP_TOP = 4
End Enum

Combination and General Flags

D3DSTATUS_CLIPINTERSECTIONALL
Combination of all CLIPINTERSECTION flags.
D3DSTATUS_CLIPUNIONALL
Combination of all CLIPUNION flags.
D3DSTATUS_DEFAULT
Combination of D3DSTATUS_CLIPINTERSECTIONALL and D3DSTATUS_ZNOTVISIBLE flags. This value is the default.
D3DSTATUS_ZNOTVISIBLE
Indicates that the rendered primitive is not visible. This flag is set or cleared by the system when rendering with z-checking enabled (see D3DRENDERSTATE_ZVISIBLE).

Clip Intersection Flags

D3DSTATUS_CLIPINTERSECTIONBACK
Logical And of the clip flags for the vertices compared to the back clipping plane of the viewing frustum.
D3DSTATUS_CLIPINTERSECTIONBOTTOM
Logical And of the clip flags for the vertices compared to the bottom of the viewing frustum.
D3DSTATUS_CLIPINTERSECTIONFRONT
Logical And of the clip flags for the vertices compared to the front clipping plane of the viewing frustum.
D3DSTATUS_CLIPINTERSECTIONGEN0 through D3DSTATUS_CLIPINTERSECTIONGEN5
Logical And of the clip flags for application-defined clipping planes.
D3DSTATUS_CLIPINTERSECTIONLEFT
Logical And of the clip flags for the vertices compared to the left side of the viewing frustum.
D3DSTATUS_CLIPINTERSECTIONRIGHT
Logical And of the clip flags for the vertices compared to the right side of the viewing frustum.
D3DSTATUS_CLIPINTERSECTIONTOP
Logical And of the clip flags for the vertices compared to the top of the viewing frustum.

Clip Union Flags

D3DSTATUS_CLIPUNIONBACK
Equal to D3DCLIP_BACK.
D3DSTATUS_CLIPUNIONBOTTOM
Equal to D3DCLIP_BOTTOM.
D3DSTATUS_CLIPUNIONFRONT
Equal to D3DCLIP_FRONT.
D3DSTATUS_CLIPUNIONGEN0 through D3DSTATUS_CLIPUNIONGEN5
Equal to D3DCLIP_GEN0 through D3DCLIP_GEN5.
D3DSTATUS_CLIPUNIONLEFT
Equal to D3DCLIP_LEFT.
D3DSTATUS_CLIPUNIONRIGHT
Equal to D3DCLIP_RIGHT.
D3DSTATUS_CLIPUNIONTOP
Equal to D3DCLIP_TOP.

Basic Clipping Flags

D3DCLIP_BACK
All vertices are clipped by the back plane of the viewing frustum.
D3DCLIP_BOTTOM
All vertices are clipped by the bottom plane of the viewing frustum.
D3DCLIP_FRONT
All vertices are clipped by the front plane of the viewing frustum.
D3DCLIP_LEFT
All vertices are clipped by the left plane of the viewing frustum.
D3DCLIP_RIGHT
All vertices are clipped by the right plane of the viewing frustum.
D3DCLIP_TOP
All vertices are clipped by the top plane of the viewing frustum.
D3DCLIP_GEN0 through D3DCLIP_GEN5
All vertices are clipped by a corresponding application-defined clipping plane.


CONST_D3DCLIPPLANEFLAGS

The CONST_D3DCLIPPLANEFLAGS enumeration defines flags that can be combined and used with the D3DRENDERSTATE_CLIPPLANEENABLE render state.

Type CONST_D3DCLIPPLANEFLAGS
    D3DCPF_DISABLEALL = 0
    D3DCPF_ENABLEPLANE0 = 1
    '
    ' D3DCPF_ENABLEPLANE1 to D3DCPF_ENABLEPLANE30 ommitted here.
    '
    D3DCPF_ENABLEPLANE31 = -2147483648
End Type
D3DCPF_DISABLEALL
Disable all clipping planes. This flag should not be combined with other flags.
D3DCPF_ENABLEPLANE0 through D3DCPF_ENABLEPLANE31
Enable the clipping plane, or planes, at the corresponding index. These values can be combined to simultaneously enable multiple clipping planes.

See Also

CONST_D3DRENDERSTATETYPE


CONST_D3DCLIPSTATUSFLAGS

The CONST_D3DCLIPSTATUSFLAGS enumeration defines flags that are used in the D3DCLIPSTATUS type.

Enum CONST_D3DCLIPSTATUSFLAGS
    D3DCLIPSTATUS_EXTENTS2 = 2
    D3DCLIPSTATUS_EXTENTS3 = 4
    D3DCLIPSTATUS_STATUS = 1
End Enum
D3DCLIPSTATUS_EXTENTS2
The type describes the current 2-D extents. This flag cannot be combined with D3DCLIPSTATUS_EXTENTS3.
D3DCLIPSTATUS_EXTENTS3
Not currently implemented.
D3DCLIPSTATUS_STATUS
The type describes the current clip status.


CONST_D3DCMPFUNC

The CONST_D3DCMPFUNC enumeration defines the supported compare functions for the D3DRENDERSTATE_ZFUNC, D3DRENDERSTATE_ALPHAFUNC, and D3DRENDERSTATE_STENCILFUNC render states.

Enum CONST_D3DCMPFUNC
    D3DCMP_NEVER        = 1
    D3DCMP_LESS         = 2
    D3DCMP_EQUAL        = 3
    D3DCMP_LESSEQUAL    = 4
    D3DCMP_GREATER      = 5
    D3DCMP_NOTEQUAL     = 6
    D3DCMP_GREATEREQUAL = 7
    D3DCMP_ALWAYS       = 8
End Enum
D3DCMP_NEVER
Always fail the test.
D3DCMP_LESS
Accept the new pixel if its value is less than the value of the current pixel.
D3DCMP_EQUAL
Accept the new pixel if its value equals the value of the current pixel.
D3DCMP_LESSEQUAL
Accept the new pixel if its value is less than or equal to the value of the current pixel.
D3DCMP_GREATER
Accept the new pixel if its value is greater than the value of the current pixel.
D3DCMP_NOTEQUAL
Accept the new pixel if its value does not equal the value of the current pixel.
D3DCMP_GREATEREQUAL
Accept the new pixel if its value is greater than or equal to the value of the current pixel.
D3DCMP_ALWAYS
Always pass the test.


CONST_D3DCOLORMODEL

The CONST_D3DCOLORMODEL enumeration is used to define the color model in which the system will run. A driver can expose either or both flags in the CONST_COLORMODEL member of the D3DDEVICEDESC7 type.

Enum CONST_D3DCOLORMODEL
    D3DCOLOR_MONO = 1
    D3DCOLOR_RGB = 2
End Enum
D3DCOLOR_MONO
Use a monochromatic model (or ramp model). In this model, the blue component of a vertex color is used to define the brightness of a lit vertex.
D3DCOLOR_RGB
Use a full RGB model.


CONST_D3DCULL

The CONST_D3DCULL enumeration defines the supported cull modes used with the D3DRENDERSTATE_CULLMODE render state. These define how back faces are culled when rendering a geometry.

Enum CONST_D3DCULL
    D3DCULL_NONE = 1
    D3DCULL_CW   = 2
    D3DCULL_CCW  = 3
End Enum
D3DCULL_NONE
Do not cull back faces.
D3DCULL_CW
Cull back faces with clockwise vertices.
D3DCULL_CCW
Cull back faces with counterclockwise vertices.

See Also

D3DPRIMCAPS, CONST_D3DRENDERSTATETYPE


CONST_D3DDEVICEDESCCAPS

The CONST_D3DDEVICEDESCCAPS enumeration defines device capability flags that are combined and present in the lDevCaps member of the D3DDEVICEDESC7 type.

Enum CONST_D3DDEVICEDESCCAPS
    D3DDEVCAPS_CANBLTSYSTONONLOCAL = 131072
    D3DDEVCAPS_CANRENDERAFTERFLIP = 2048
    D3DDEVCAPS_DRAWPRIMTLVERTEX = 1024
    D3DDEVCAPS_FLOATTLVERTEX = 1
    D3DDEVCAPS_HWRASTERIZATION = 524288
    D3DDEVCAPS_HWTRANSFORMANDLIGHT = 65536
    D3DDEVCAPS_SEPARATETEXTUREMEMORIES = 16384
    D3DDEVCAPS_SORTDECREASINGZ = 4
    D3DDEVCAPS_SORTEXACT = 8
    D3DDEVCAPS_SORTINCREASINGZ = 2
    D3DDEVCAPS_TEXTURENONLOCALVIDMEM = 4096
    D3DDEVCAPS_TEXTURESYSTEMMEMORY = 256
    D3DDEVCAPS_TEXTUREVIDEOMEMORY = 512
    D3DDEVCAPS_TLVERTEXSYSTEMMEMORY = 64
    D3DDEVCAPS_TLVERTEXVIDEOMEMORY = 128
End Enum
D3DDEVCAPS_CANBLTSYSTONONLOCAL
Device supports blits from system-memory textures to non-local video-memory textures.
D3DDEVCAPS_CANRENDERAFTERFLIP
Device can queue rendering commands after a page flip. Applications should not change their behavior if this flag is set; this capability simply means that the device is relatively fast.
D3DDEVCAPS_DRAWPRIMTLVERTEX
Device exports a DrawPrimitive-aware HAL.
D3DDEVCAPS_FLOATTLVERTEX
Device accepts floating point for post-transform vertex data.
D3DDEVCAPS_HWRASTERIZATION
Device has hardware acceleration for scene rasterization.
D3DDEVCAPS_HWTRANSFORMANDLIGHT
Device supports transformation and lighting in hardware.
D3DDEVCAPS_SEPARATETEXTUREMEMORIES
Device uses discrete texture memory pools for each stage. Textures must be assigned to texture stages explicitly at creation-time by setting the lTextureStage member of the DDSURFACEDESC2 type to the appropriate stage identifier.
D3DDEVCAPS_SORTDECREASINGZ
Device needs data sorted for decreasing depth.
D3DDEVCAPS_SORTEXACT
Device needs data sorted exactly.
D3DDEVCAPS_SORTINCREASINGZ
Device needs data sorted for increasing depth.
D3DDEVCAPS_TEXTURENONLOCALVIDMEM
Device can retrieve textures from non-local video (AGP) memory. For more information about AGP memory, see Using Non-local Video Memory Surfaces in the DirectDraw documentation.
D3DDEVCAPS_TEXTURESYSTEMMEMORY
Device can retrieve textures from system memory.
D3DDEVCAPS_TEXTUREVIDEOMEMORY
Device can retrieve textures from device memory.
D3DDEVCAPS_TLVERTEXSYSTEMMEMORY
Device can use buffers from system memory for transformed and lit vertices.
D3DDEVCAPS_TLVERTEXVIDEOMEMORY
Device can use buffers from video memory for transformed and lit vertices.


CONST_D3DDEVICEDESCFLAGS

The CONST_D3DDEVICEDESCFLAGS enumeration defines flags that are used in the lFlags member of the D3DDEVICEDESC7 type.

Enum CONST_D3DDEVICEDESCFLAGS
    D3DDD_BCLIPPING = 16
    D3DDD_DEVCAPS = 2
    D3DDD_DEVICERENDERBITDEPTH = 128
    D3DDD_DEVICEZBUFFERBITDEPTH = 256
    D3DDD_LIGHTINGCAPS = 8
    D3DDD_LINECAPS = 32
    D3DDD_MAXBUFFERSIZE = 512
    D3DDD_MAXVERTEXCOUNT = 1024
    D3DDD_TRANSFORMCAPS = 4
    D3DDD_TRICAPS = 64
End Enum
D3DDD_BCLIPPING
The lClipping member of the D3DDEVICEDESC7 type is valid.
D3DDD_DEVCAPS
The lDevCaps member of the D3DDEVICEDESC7 type is valid.
D3DDD_DEVICERENDERBITDEPTH
The lDeviceRenderBitDepth member of the D3DDEVICEDESC7 type is valid.
D3DDD_DEVICEZBUFFERBITDEPTH
The lDeviceZBufferBitDepth member of the D3DDEVICEDESC7 type is valid.
D3DDD_LIGHTINGCAPS
The dlcLightingCaps member of the D3DDEVICEDESC7 type is valid.
D3DDD_LINECAPS
The dpcLineCaps member of the D3DDEVICEDESC7 type is valid.
D3DDD_MAXBUFFERSIZE
The lMaxBufferSize member of the D3DDEVICEDESC7 type is valid.
D3DDD_MAXVERTEXCOUNT
The lMaxVertexCount member of the D3DDEVICEDESC7 type is valid.
D3DDD_TRANSFORMCAPS
The lTransformCaps member of the D3DDEVICEDESC7 type is valid.
D3DDD_TRICAPS
The dpcTriCaps member of the D3DDEVICEDESC7 type is valid.


CONST_D3DDEVINFOID

The CONST_D3DDEVINFOID enumeration defines flags used with the Direct3DDevice7.GetInfo method.

Enum CONST_D3DDEVINFOID
    D3DDEVINFOID_D3DTEXTUREMANAGER = 2
    D3DDEVINFOID_TEXTUREMANAGER = 1
    D3DDEVINFOID_TEXTURING = 3
End Enum
D3DDEVINFOID_D3DTEXTUREMANAGER
The type in the DevInfoType parameter of the GetInfo method is a D3DDEVINFO_TEXTUREMANAGER type that contains information about texture management that is performed by Direct3D.
D3DDEVINFOID_TEXTUREMANAGER
The type in the DevInfoType parameter of the GetInfo method is a D3DDEVINFO_TEXTUREMANAGER type that contains information about texture management being performed by the driver. If the driver does not manage textures, information about texture management performed by Direct3D is retrieved.
D3DDEVINFOID_TEXTURING
The type in the DevInfoType parameter of the GetInfo method is a D3DDEVINFO_TEXTURING type that contains information about texturing activity of the application.

See Also

Direct3DDevice7.GetInfo


CONST_D3DDPFLAGS

The CONST_D3DDPFLAGS enumeration defines flags that are used to determine the behavior of the Direct3D rendering methods. These flags are used with the Direct3DDevice7.DrawPrimitive, Direct3DDevice7.DrawIndexedPrimitive, Direct3DDevice7.DrawPrimitiveVB, and Direct3DDevice7.DrawIndexedPrimitiveVB.

Enum CONST_D3DDPFLAGS
    D3DDP_DEFAULT = 0
    D3DDP_WAIT = 1
End Enum
D3DDP_DEFAULT
Perform normal rendering. (Return as soon as the polygons are sent to the card.)
D3DDP_WAIT
Causes the method to wait until the polygons have been rendered before it returns, instead of returning as soon as the polygons have been sent to the card. (On scene-capture cards, the method returns as soon as the card responds.) This flag is typically used for debugging. Applications should not attempt to use this flag to ensure that a scene is up-to-date before continuing.


CONST_D3DFILLMODE

The CONST_D3DFILLMODE enumeration contains constants describing the fill mode. These values are used by the D3DRENDERSTATE_FILLMODE render state in the CONST_D3DRENDERSTATETYPE enumeration.

Enum CONST_D3DFILLMODE
    D3DFILL_POINT     = 1
    D3DFILL_WIREFRAME = 2
    D3DFILL_SOLID     = 3
End Enum
D3DFILL_POINT
Fill points.
D3DFILL_WIREFRAME
Fill wireframes. This fill mode currently does not work for clipped primitives when you are using the DrawPrimitive methods.
D3DFILL_SOLID
Fill solids.


CONST_D3DFOGMODE

The CONST_D3DFOGMODE enumeration contains constants describing the fog mode. These values are used by the D3DRENDERSTATE_FOGTABLEMODE and D3DRENDERSTATE_FOGVERTEXMODE render state in the CONST_D3DRENDERSTATETYPE enumeration.

Enum CONST_D3DFOGMODE
    D3DFOG_NONE   = 0
    D3DFOG_EXP    = 1
    D3DFOG_EXP2   = 2
    D3DFOG_LINEAR = 3
End Enum
D3DFOG_NONE
No fog effect.
D3DFOG_EXP
The fog effect intensifies exponentially, according to the following formula:

D3DFOG_EXP2
The fog effect intensifies exponentially with the square of the distance, according to the following formula:

D3DFOG_LINEAR
The fog effect intensifies linearly between the start and end points, according to the following formula:

This is the only fog mode currently supported.

Remarks

In monochromatic (ramp) lighting mode, fog works properly only when the fog color is black. (If there is no lighting, any fog color will work, since in this case any fog color is effectively black.)

For more information about fog, see Fog.

Note Fog can be considered a measure of visibility — the lower the fog value produced by one of the fog equations, the less visible an object is.


CONST_D3DFVFCAPSFLAGS

The CONST_D3DFVFCAPSFLAGS enumeration defines values present within or used with the lFVFCaps member of the D3DDEVICEDESC7 type.

Enum CONST_D3DFVFCAPSFLAGS
    D3DFVFCAPS_DONOTSTRIPELEMENTS = 524288
    D3DFVFCAPS_TEXCOORDCOUNTMASK = 65535
End Enum
D3DFVFCAPS_DONOTSTRIPELEMENTS
Device prefers that vertex elements not be stripped. That is, if the vertex format contains elements that will not be used with the current render states, there is no need to regenerate the vertices. If this capability flag is not present, stripping extraneous elements from the vertex format will provide better performance.
D3DFVFCAPS_TEXCOORDCOUNTMASK
Used to mask the low 16-bits of the lFVFCaps member of the D3DDEVICEDESC7 type. Set the result to a variable of type Integer to calculate the total number of texture coordinate sets that the device can simultaneously use for multiple texture blending. (You can use up to eight texture coordinate sets for any vertex, but the device can only blend using the specified number of texture coordinate sets.)

Remarks

The following Visual Basic code fragment masks the low 16-bits of the lFVFCaps member to determine the total number of texture coordinate sets that the device can simultaneously use for multiple texture blending:

Dim HALdesc As D3DDEVICEDESC7, HELdesc As D3DDEVICEDESC7
Dim iTexCoords As Integer

' The d3ddevice variable is assumed to be referece to
' a valid Direct3DDevice3 object.
Call d3ddevice.GetCaps(HALDesc, HELDesc)

' Mask the low 16-bits and set them to an integer variable.
iTexCoords = (HALDesc.lFVFCaps And D3DFVFCAPS_TEXCOORDCOUNTMASK)


CONST_D3DFVFFLAGS

The CONST_D3DFVFFLAGS enumeration defines flexible vertex format flags for use with the DrawPrimitive rendering methods. For details, see Flexible Vertex Format Flags.


CONST_D3DIMERR

The CONST_D3DIMERR enumeration defines error codes raised by the system, and are not otherwise useful. For descriptions of these error codes, see Error Codes.


CONST_D3DLIGHTCAPSFLAGS

The CONST_D3DLIGHTCAPSFLAGS enumeration defines lighting capability flags that are combined and present in the lCaps member of the D3DLIGHTINGCAPS type.

Enum CONST_D3DLIGHTCAPSFLAGS
    D3DLIGHTCAPS_DIRECTIONAL = 4
    D3DLIGHTCAPS_POINT = 1
    D3DLIGHTCAPS_SPOT = 2
End Enum
D3DLIGHTCAPS_DIRECTIONAL
Supports directional lights.
D3DLIGHTCAPS_POINT
Supports point lights.
D3DLIGHTCAPS_SPOT
Supports spotlights.


CONST_D3DLIGHTINGMODELFLAGS

The CONST_D3DLIGHTINGMODELFLAGS enumeration defines lighting model capability flags that are combined and present in the lLightingModel member of the D3DLIGHTINGCAPS type.

Enum CONST_D3DLIGHTINGMODELFLAGS
    D3DLIGHTINGMODEL_MONO = 2
    D3DLIGHTINGMODEL_RGB = 1
End Enum
D3DLIGHTINGMODEL_MONO
Monochromatic lighting model.
D3DLIGHTINGMODEL_RGB
RGB lighting model.


CONST_D3DLIGHTTYPE

The CONST_D3DLIGHTTYPE enumeration defines flags that identify light types. These flags are used in the lType member of the D3DLIGHT7 type.

Enum CONST_D3DLIGHTTYPE
    D3DLIGHT_DIRECTIONAL = 3
    D3DLIGHT_POINT = 1
    D3DLIGHT_SPOT = 2
End Enum
D3DLIGHT_DIRECTIONAL
Light is a directional source. This is equivalent to using a point light source at an infinite distance.
D3DLIGHT_POINT
Light is a point source. The light has a position in space and radiates light in all directions.
D3DLIGHT_SPOT
Light is a spotlight source. This light is something like a point light except that the illumination is limited to a cone. This light type has a direction and several other parameters which determine the shape of the cone it produces. For information about these parameters, see the D3DLIGHT7 type.


CONST_D3DMATERIALCOLORSOURCE

The CONST_D3DMATERIALCOLORSOURCE enumeration defines the location at which a color or color component should be accessed for lighting calculations.

Enum CONST_D3DMATERIALCOLORSOURCE
    D3DMCS_MATERIAL    = 0
    D3DMCS_COLOR1      = 1
    D3DMCS_COLOR2      = 2
End Enum
D3DMCS_MATERIAL
Use the color from the current material.
D3DMCS_COLOR1
Use the diffuse vertex color.
D3DMCS_COLOR2
Use the specular vertex color.

Remarks

The values defined by this enumeration are used with the D3DRENDERSTATE_DIFFUSEMATERIALSOURCE, D3DRENDERSTATE_SPECULARMATERIALSOURCE, D3DRENDERSTATE_AMBIENTMATERIALSOURCE, and D3DRENDERSTATE_EMISSIVEMATERIALSOURCE render states.


CONST_D3DPRIMITIVETYPE

The CONST_D3DPRIMITIVETYPE enumeration lists the primitives supported by DrawPrimitive methods.

Enum CONST_D3DPRIMITIVETYPE
    D3DPT_POINTLIST     = 1
    D3DPT_LINELIST      = 2
    D3DPT_LINESTRIP     = 3
    D3DPT_TRIANGLELIST  = 4
    D3DPT_TRIANGLESTRIP = 5
    D3DPT_TRIANGLEFAN   = 6
End Enum
D3DPT_POINTLIST
Renders the vertices as a collection of isolated points.
D3DPT_LINELIST
Renders the vertices as a list of isolated straight line segments. Calls using this primitive type will fail if the count is less than 2, or is odd.
D3DPT_LINESTRIP
Renders the vertices as a single polyline. Calls using this primitive type will fail if the count is less than 2.
D3DPT_TRIANGLELIST
Renders the specified vertices as a sequence of isolated triangles. Each group of 3 vertices defines a separate triangle. Calls using this primitive type will fail if the count is less than 3, or if not evenly divisible by 3.

Back-face culling is affected by the current winding order render state.

D3DPT_TRIANGLESTRIP
Renders the vertices as a triangle strip. Calls using this primitive type will fail if the count is less than 3. The back-face removal flag is automatically flipped on even numbered triangles.
D3DPT_TRIANGLEFAN
Renders the vertices as a triangle fan. Calls using this primitive type will fail if the count is less than 3.

Remarks

Using triangle strips or fans is often more efficient than using triangle lists, as fewer vertices are duplicated. For a conceptual overview and information about defining triangle strips and fans, see Triangle Strips and Triangle Fans.

See Also

Direct3DDevice7.DrawIndexedPrimitive, Direct3DDevice7.DrawPrimitive, Primitive Types


CONST_D3DPROCESSVERTICESFLAGS

The CONST_D3DPROCESSVERTICESFLAGS enumeration defines flags used with the Direct3DVertexBuffer7.ProcessVertices method.

Enum CONST_D3DPROCESSVERTICESFLAGS
    D3DPV_DEFAULT = 0
    D3DPV_DONOTCOPYDATA = 1
End Enum
D3DPV_DEFAULT
Perform standard vertex processing using the current vertex operation.
D3DPV_DONOTCOPYDATA
Process the vertices into the destination buffer, but do not copy vertex data not affected by the current vertex operation into the destination buffer.

See Also

Direct3DVertexBuffer7.ProcessVertices, Processing Vertices


CONST_D3DRENDERSTATESINGLE

The CONST_D3DRENDERSTATESINGLE enumeration defines device render states that are set and retrieved through the Direct3DDevice7.SetRenderStateSingle and Direct3DDevice7.GetRenderStateSingle methods.

Type CONST_D3DRENDERSTATESINGLE
    D3DRENDERSTATE_FOGDENSITY = 38
    D3DRENDERSTATE_FOGEND     = 37
    D3DRENDERSTATE_FOGSTART   = 36
End Type
D3DRENDERSTATE_FOGDENSITY
Fog density for pixel or vertex fog to be used in the exponential fog modes (D3DFOG_EXP and D3DFOG_EXP2). Valid density values range from 0.0 to 1.0, inclusive. The default value is 1.0. For more information, see Fog Parameters.
D3DRENDERSTATE_FOGEND and D3DRENDERSTATE_FOGSTART
Depth at which pixel or vertex fog effects begin and end for linear fog mode. Depth is specified in world space for vertex fog, and either device space [0.0, 1.0] or world space for pixel fog. For pixel fog, these values are in device space when the system uses z for fog calculations, and world-space when the system is using eye-relative fog ("w-fog"). For more information, see Fog Parameters and Eye-Relative vs. Z-Based Depth.

These render states enable you to exclude fog effects for positions close to the camera. When using z-based pixel fog, for example, you could set the starting depth to 0.3 to prevent fog effects for depths between 0.0 and 0.299, and the ending depth to 0.7 to prevent additional fog effects for depths between 0.701 and 1.0.

See Also

Direct3DDevice7.SetRenderStateSingle, Direct3DDevice7.GetRenderStateSingle


CONST_D3DRENDERSTATETYPE

The CONST_D3DRENDERSTATETYPE enumeration defines device render states that are set and retrieved through the Direct3DDevice7.SetRenderState and Direct3DDevice7.GetRenderState methods.

Enum CONST_D3DRENDERSTATETYPE
    D3DRENDERSTATE_ALPHABLENDENABLE      = 27
    D3DRENDERSTATE_ALPHAFUNC             = 25
    D3DRENDERSTATE_ALPHAREF              = 24
    D3DRENDERSTATE_ALPHATESTENABLE       = 15
    D3DRENDERSTATE_AMBIENT               = 139
    D3DRENDERSTATE_AMBIENTMATERIALSOURCE = 147
    D3DRENDERSTATE_ANTIALIAS             = 2
    D3DRENDERSTATE_CLIPPING              = 136
    D3DRENDERSTATE_CLIPPLANEENABLE       = 152
    D3DRENDERSTATE_COLORKEYBLENDENABLE   = 144
    D3DRENDERSTATE_COLORKEYENABLE        = 41
    D3DRENDERSTATE_COLORVERTEX           = 141
    D3DRENDERSTATE_CULLMODE              = 22
    D3DRENDERSTATE_DESTBLEND             = 20
    D3DRENDERSTATE_DIFFUSEMATERIALSOURCE = 145
    D3DRENDERSTATE_DITHERENABLE          = 26
    D3DRENDERSTATE_EDGEANTIALIAS         = 40
    D3DRENDERSTATE_EMISSIVEMATERIALSOURCE= 148
    D3DRENDERSTATE_EXTENTS            = 138
    D3DRENDERSTATE_FILLMODE           = 8
    D3DRENDERSTATE_FOGCOLOR           = 34
    D3DRENDERSTATE_FOGENABLE          = 28
    D3DRENDERSTATE_FOGTABLEMODE       = 35
    D3DRENDERSTATE_FOGVERTEXMODE      = 140
    D3DRENDERSTATE_LASTPIXEL          = 16
    D3DRENDERSTATE_LIGHTING           = 137
    D3DRENDERSTATE_LINEPATTERN        = 10
    D3DRENDERSTATE_LOCALVIEWER        = 142
    D3DRENDERSTATE_NORMALIZENORMALS   = 143
    D3DRENDERSTATE_RANGEFOGENABLE     = 48
    D3DRENDERSTATE_SHADEMODE          = 9
    D3DRENDERSTATE_SPECULARENABLE     = 29
    D3DRENDERSTATE_SPECULARMATERIALSOURCE = 146
    D3DRENDERSTATE_SRCBLEND           = 19
    D3DRENDERSTATE_STENCILENABLE      = 52
    D3DRENDERSTATE_STENCILFAIL        = 53
    D3DRENDERSTATE_STENCILFUNC        = 56
    D3DRENDERSTATE_STENCILMASK        = 58
    D3DRENDERSTATE_STENCILPASS        = 55
    D3DRENDERSTATE_STENCILREF         = 57
    D3DRENDERSTATE_STENCILWRITEMASK   = 59
    D3DRENDERSTATE_STENCILZFAIL       = 54
    D3DRENDERSTATE_STIPPLEDALPHA      = 33
    D3DRENDERSTATE_TEXTUREFACTOR      = 60
    D3DRENDERSTATE_TEXTUREPERSPECTIVE = 4
    D3DRENDERSTATE_VERTEXBLEND        = 151
    D3DRENDERSTATE_WRAP0              = 128
    ' Wrap render states 1 through 6 omitted here.
    D3DRENDERSTATE_WRAP7              = 135
    D3DRENDERSTATE_ZBIAS              = 47
    D3DRENDERSTATE_ZENABLE            = 7
    D3DRENDERSTATE_ZFUNC              = 23
    D3DRENDERSTATE_ZVISIBLE           = 30
    D3DRENDERSTATE_ZWRITEENABLE       = 14
End Type
D3DRENDERSTATE_ALPHABLENDENABLE
True to enable alpha-blended transparency. The default value is False. This member supersedes the legacy D3DRENDERSTATE_BLENDENABLE render state; see remarks for more information.

You can use the D3DRENDERSTATE_COLORKEYENABLE render state to toggle color keying. (Hardware rasterizers have always used the D3DRENDERSTATE_BLENDENABLE render state only for toggling alpha blending.)

The type of alpha blending is determined by the D3DRENDERSTATE_SRCBLEND and D3DRENDERSTATE_DESTBLEND render states. D3DRENDERSTATE_ALPHABLENDENABLE, with D3DRENDERSTATE_COLORKEYENABLE, allows fine blending control.

Applications should check the D3DDEVCAPS_DRAWPRIMTLVERTEX flag in the D3DDEVICEDESC7 type to find out whether this render state is supported.

D3DRENDERSTATE_ALPHAFUNC
One of the constants of the CONST_D3DCMPFUNC enumeration. The default value is D3DCMP_ALWAYS. This member enables an application to accept or reject a pixel based on its alpha value.
D3DRENDERSTATE_ALPHAREF
Value specifying a reference alpha value against which pixels are tested when alpha-testing is enabled. This can be a 16:16 fixed point value (D3DFIXED) ranging from 0 to 1, inclusive, where 1.0 is represented as 0x00010000. The default value is 0.0.
D3DRENDERSTATE_ALPHATESTENABLE
True to enable alpha tests. The default value is False. This member enables applications to turn off the tests that otherwise would accept or reject a pixel based on its alpha value.

The incoming alpha value is compared with the reference alpha value using the comparison function provided by the D3DRENDERSTATE_ALPHAFUNC render state. When this mode is enabled, alpha blending occurs only if the test succeeds.

D3DRENDERSTATE_AMBIENT
Ambient light color. The default value is 0. This render state is analogous to the legacy D3DLIGHTSTATE_AMBIENT lighting state.
D3DRENDERSTATE_AMBIENTMATERIALSOURCE
The ambient color source for lighting calculations. Valid values are members of the CONST_D3DMATERIALCOLORSOURCE enumeration. The default value is D3DMCS_COLOR2.
D3DRENDERSTATE_ANTIALIAS
One of the members of the CONST_D3DANTIALIASMODE enumeration specifying the desired type of full-scene antialiasing. The default value is D3DANTIALIAS_NONE. For more information, see Full-scene Antialiasing and Antialiasing States.

You can only enable full-scene antialiasing on devices that expose the D3DPRASTERCAPS_ANTIALIASSORTINDEPENDENT or D3DPRASTERCAPS_ANTIALIASSORTDEPENDENT capabilities.

D3DRENDERSTATE_CLIPPING
Nonzero to enable primitive clipping by Direct3D, or zero to disable it. The default value is nonzero.
D3DRENDERSTATE_CLIPPLANEENABLE
Enables or disables user-defined clipping planes. Valid values are combinations of values from the CONST_D3DCLIPPLANEFLAGS enumeration. If you include a value from the enumeration, the corresponding clipping plane is enabled; if a value isn't included, the clipping plane is disabled. The default value is D3DCPF_DISABLEALL.
D3DRENDERSTATE_COLORKEYBLENDENABLE
Nonzero to enable alpha-blended colorkeying, or zero to disable it. Alpha-blended colorkey mode sets the alpha and color of matching texture samples to zero. The application is required to set the alpha test and alpha blend modes to achieve the desired discard and/or alpha-blended result.
D3DRENDERSTATE_COLORKEYENABLE
True to enable color-keyed transparency. The default value is False. You can use this render state with D3DRENDERSTATE_ALPHABLENDENABLE to implement fine blending control.

Applications should check the D3DDEVCAPS_DRAWPRIMTLVERTEX flag in the D3DDEVICEDESC7 type to find out whether this render state is supported.

When color-keyed transparency is enabled, only texture surfaces that were created with the DDSD_CKSRCBLT flag will be affected. Surfaces that were created without the DDSD_CKSRCBLT flag will exhibit color-keyed transparency effects.

D3DRENDERSTATE_COLORVERTEX
Nonzero to enable per-vertex color, or zero to disable it. The default value is nonzero. Enabling per-vertex color allows the system to include the color defined for individual vertices in its lighting calculations.

See also: D3DRENDERSTATE_DIFFUSEMATERIALSOURCE, D3DRENDERSTATE_SPECULARMATERIALSOURCE, D3DRENDERSTATE_AMBIENTMATERIALSOURCE, and D3DRENDERSTATE_EMISSIVEMATERIALSOURCE.

D3DRENDERSTATE_CULLMODE
Specifies how back-facing triangles are to be culled, if at all. This can be set to one of the constants of the CONST_D3DCULL enumeration. The default value is D3DCULL_CCW.
D3DRENDERSTATE_DESTBLEND
One of the constants of the CONST_D3DBLEND enumeration. The default value is D3DBLEND_ZERO.
D3DRENDERSTATE_DIFFUSEMATERIALSOURCE
The diffuse color source for lighting calculations. Valid values are members of the CONST_D3DMATERIALCOLORSOURCE enumeration. The default value is D3DMCS_COLOR1. The value for this render state is used only if the D3DRENDERSTATE_COLORVERTEX render state is set to nonzero.
D3DRENDERSTATE_DITHERENABLE
True to enable dithering. The default value is False.
D3DRENDERSTATE_EDGEANTIALIAS
True to antialias lines forming the convex outline of objects. The default value is False. For more information, see Edge Antialiasing and Antialiasing States. When set to True, applications should only render lines, and only to the exterior edges of polygons in a scene. The behavior is undefined if triangles or points are drawn when this render state is set. Antialiasing is performed simply by averaging the values of neighboring pixels. Although this is not the best way to perform antialiasing, it can be very efficient; hardware that supports this kind of operation is becoming more common.

You can only enable edge antialiasing on devices that expose the D3DPRASTERCAPS_ANTIALIASEDGES capability.

D3DRENDERSTATE_EMISSIVEMATERIALSOURCE
The emissive color source for lighting calculations. Valid values are members of the CONST_D3DMATERIALCOLORSOURCE enumeration. The default value is D3DMCS_MATERIAL.
D3DRENDERSTATE_EXTENTS
Nonzero to cause the system to update the screen extents for each rendering call, or zero to disable screen extent updates. The default value is zero.
D3DRENDERSTATE_FILLMODE
One or more constants of the CONST_D3DFILLMODE enumeration. The default value is D3DFILL_SOLID.
D3DRENDERSTATE_FOGCOLOR
Value of type Long indicating RGB color, as returned by the DirectX7.CreateColorRGB method. The default value is 0. For more information, see Fog Color.
D3DRENDERSTATE_FOGENABLE
True to enable fog blending. The default value is False. For more information, see Fog Blending and Fog.

These render states enable you to exclude fog effects for positions close to the camera. For example, you could set the starting depth to 0.3 to prevent fog effects for depths between 0.0 and 0.299, and the ending depth to 0.7 to prevent additional fog effects for depths between 0.701 and 1.0.

D3DRENDERSTATE_FOGTABLEMODE
The fog formula to be used for pixel fog. Set to one of the constants of the CONST_D3DFOGMODE enumeration. The default value is D3DFOG_NONE. For more information, see Pixel Fog.
D3DRENDERSTATE_FOGVERTEXMODE
The fog formula to be used for vertex fog. Set to one of the members of the CONST_D3DFOGMODE enumeration. The default value is D3DFOG_NONE. For more information, see Vertex Fog.
D3DRENDERSTATE_LASTPIXEL
False to enable drawing the last pixel in a line or triangle. The default value is True.
D3DRENDERSTATE_LIGHTING
Nonzero to enable Direct3D lighting, or zero disable it. The default value is nonzero. Only vertices that include a vertex normal will be properly lit; vertices that do not contain a normal will employ a dot-product of 0 in all lighting calculations.
D3DRENDERSTATE_LINEPATTERN
Line pattern. The D3DLINEPATTERN type defines valid values. The default values for the members of D3DLINEPATTERN are 0 for repeatPattern and 0 for linePattern.
D3DRENDERSTATE_LOCALVIEWER
Nonzero to enable camera-relative specular highlights, or zero to use orthogonal specular highlights. The default value is nonzero to use camera-relative specular highlights. Applications that use orthogonal projection should specify zero.
D3DRENDERSTATE_NORMALIZENORMALS
Nonzero to enable automatic normalization of vertex normals, or zero to disable it. The default value it zero. Enabling this feature causes the system to normalize the vertex normals for vertices after transforming them to camera space, which can be computationally intensive.
D3DRENDERSTATE_RANGEFOGENABLE
True to enable range-based vertex fog. (The default value is False, in which case the system uses depth-based fog.) In range-based fog, the distance of an object from the viewer is used to compute fog effects, not the depth of the object (that is, the z-coordinate) in the scene. In range-based fog, all fog methods work as usual, except that they use range instead of depth in the computations.

Range is the correct factor to use for fog computations, but depth is commonly used instead because range is expensive to compute and depth is generally already available. Using depth to calculate fog has the undesirable effect of having the 'fogginess' of peripheral objects change as the eye is rotated — in this case, the depth changes while the range remains constant.

This render state works only with D3DVERTEX vertices. When you specify D3DLVERTEX or D3DTLVERTEX vertices, the F (fog) component of the RGBF fog value should already be corrected for range.

Since no hardware currently supports per-pixel range-based fog, range correction offered only for vertex fog. For more information, see Range-based Fog and Vertex Fog

D3DRENDERSTATE_SHADEMODE
One or more constants of the D3DSHADEMODE enumeration. The default value is D3DSHADE_GOURAUD.
D3DRENDERSTATE_SPECULARENABLE
True to enable specular highlights. The default value is True.

Specular highlights are calculated as though every vertex in the object being lit were at the object's origin. This gives the expected results as long as the object is modeled around the origin and the distance from the light to the object is relatively large.

D3DRENDERSTATE_SPECULARMATERIALSOURCE
The specular color source for lighting calculations. Valid values are members of the CONST_D3DMATERIALCOLORSOURCE enumeration. The default value is D3DMCS_COLOR2.
D3DRENDERSTATE_SRCBLEND
One of the constants of the CONST_D3DBLEND enumeration. The default value is D3DBLEND_ONE.
D3DRENDERSTATE_STENCILENABLE
True to enable stenciling, or False to disable stenciling. The default value is False. For more information, see Stencil Buffers.
D3DRENDERSTATE_STENCILFAIL
Stencil operation to perform if the stencil test fails. This can be one of the constants of the CONST_D3DSTENCILOP enumeration. The default value is D3DSTENCILOP_KEEP. For more information, see Stencil Buffers.
D3DRENDERSTATE_STENCILFUNC
Comparison function for the stencil test. This can be one of the constants of the CONST_D3DCMPFUNC enumeration. The default value is D3DCMP_ALWAYS.

The comparison function is used to compare the reference value to a stencil buffer entry. This comparison only applies to the bits in the reference value and stencil buffer entry that are set in the stencil mask (set by the D3DRENDERSTATE_STENCILMASK render state). If the comparison is true, the stencil test passes.

D3DRENDERSTATE_STENCILMASK
Mask applied to the reference value and each stencil buffer entry to determine the significant bits for the stencil test. The default mask is 0xFFFFFFFF.
D3DRENDERSTATE_STENCILPASS
Stencil operation to perform if both the stencil and depth (z) tests pass. This can be one of the constants of the CONST_D3DSTENCILOP enumeration. The default value is D3DSTENCILOP_KEEP. For more information, see Stencil Buffers.
D3DRENDERSTATE_STENCILREF
Integer reference value for the stencil test. The default value is 0.
D3DRENDERSTATE_STENCILWRITEMASK
Write mask applied to values written into the stencil buffer. The default mask is 0xFFFFFFFF.
D3DRENDERSTATE_STENCILZFAIL
Stencil operation to perform if the stencil test passes and depth test (z-test) fails. This can be one of the constants of the CONST_D3DSTENCILOP enumeration. The default value is D3DSTENCILOP_KEEP. For more information, see Stencil Buffers.
D3DRENDERSTATE_STIPPLEDALPHA
True to enable stippled alpha. The default value is False.

Current software rasterizers ignore this render state. You can use the D3DPSHADECAPS_ALPHAFLATSTIPPLED flag in the D3DPRIMCAPS type to discover whether the current hardware supports this render state.

D3DRENDERSTATE_TEXTUREFACTOR
Color used for multiple texture blending with the D3DTA_TFACTOR texture-blending argument or D3DTOP_BLENDFACTORALPHA texture-blending operation.
D3DRENDERSTATE_TEXTUREPERSPECTIVE
True to enable for perspective correct texture mapping. (See perspective correction.) The default value is True. For more information, see Texture Perspective State.
D3DRENDERSTATE_VERTEXBLEND
Number of matrices to be used to perform geometry blending, if any. Valid values are members of the CONST_D3DVERTEXBLENDFLAGS enumeration. The default value is D3DVBLEND_DISABLE. For more information see Geometry Blending.
D3DRENDERSTATE_WRAP0 through D3DRENDERSTATE_WRAP7
Texture wrapping behavior for multiple sets of texture coordinates. Valid values for these render states can be any combination of the D3DWRAPCOORD_0, D3DWRAPCOORD_1, D3DWRAPCOORD_2, and D3DWRAPCOORD_3 flags from the CONST_D3D enumeration. These cause the system to wrap in the direction of the first, second, third, and fourth dimensions (sometimes referred to at the "s, t, r, and q" directions) for a given texture. The default value for these render states is 0 (wrapping disabled in all directions). For more information, see Texture Wrapping.
D3DRENDERSTATE_ZBIAS
An integer value in the range 0 to 16 that causes polygons that are physically coplanar to appear separate. Polygons with a high z-bias value will appear in front of polygons with a low value, without requiring sorting for drawing order. Polygons with a value of 1 appear in front of polygons with a value of 0, and so on. The default value is zero. For more information, see Using Depth Buffers.
D3DRENDERSTATE_ZENABLE
The depth buffering state, as one of the constants of the CONST_D3DZBUFFERTYPE enumeration. Set this state to D3DZB_TRUE to enable z-buffering, D3DZB_USEW to enable w-buffering, or D3DZB_FALSE to disable depth buffering.

The default value for this render state is D3DZB_TRUE if a depth buffer is attached to the render-target surface, and D3DZB_FALSE otherwise.

D3DRENDERSTATE_ZFUNC
One of the constants of the CONST_D3DCMPFUNC enumeration. The default value is D3DCMP_LESSEQUAL. This member enables an application to accept or reject a pixel based on its distance from the camera.

The depth value of the pixel is compared with the depth buffer value. If the depth value of the pixel passes the comparison function, the pixel is written.

The depth value is written to the depth buffer only if the render state D3DRENDERSTATE_ZWRITEENABLE is True.

Software rasterizers and many hardware accelerators work faster if the depth test fails, since there is no need to filter and modulate the texture if the pixel is not going to be rendered.

D3DRENDERSTATE_ZVISIBLE
Not used.
D3DRENDERSTATE_ZWRITEENABLE
True to enable writes to the depth buffer. The default value is True. This member enables an application to prevent the system from updating the depth buffer with new depth values. If this state is False, depth comparisons are still made according to the render state D3DRENDERSTATE_ZFUNC (assuming depth buffering is taking place), but depth values are not written to the buffer.

Remarks

Direct3D defines the D3DRENDERSTATE_WRAPBIAS constant as a convenience for applications to enable or disable texture wrapping based on the zero-based integer of a texture coordinate set (rather than explicitly using one of the D3DRENDERSTATE_WRAPn state values). Add the D3DRENDERSTATE_WRAPBIAS value to the zero-based index of a texture coordinate set to calculate the D3DRENDERSTATE_WRAPn value that corresponds to that index, as shown in the following example:

    On Local Error Resume Next

    ' Enable U/V wrapping for textures that use the texture
    ' coordinate set at the index within the lIndex variable.
    Call d3dDevice.SetRenderState( _
            lIndex + D3DRENDERSTATE_WRAPBIAS, _
            D3DWRAPCOORD_0 Or D3DWRAPCOORD_1)

    ' If lIndex is 3, the value that results from
    ' the addition equates to D3DRENDERSTATE_WRAP3 (131).
    If Err.Number <> DD_OK Then
       ' Code to handle error goes here.
    End If


CONST_D3DSHADEMODE

The CONST_D3DSHADEMODE enumeration describes the supported shade mode for the D3DRENDERSTATE_SHADEMODE render state in the CONST_D3DRENDERSTATETYPE enumeration.

Enum CONST_D3DSHADEMODE
    D3DSHADE_FLAT         = 1
    D3DSHADE_GOURAUD      = 2
    D3DSHADE_PHONG        = 3
End Enum
D3DSHADE_FLAT
Flat shade mode. The color and specular component of the first vertex in the triangle are used to determine the color and specular component of the face. These colors remain constant across the triangle; that is, they aren't interpolated.
D3DSHADE_GOURAUD
Gouraud shade mode. The color and specular components of the face are determined by a linear interpolation between all three of the triangle's vertices.
D3DSHADE_PHONG
Phong shade mode is not currently supported.

See Also

CONST_D3DRENDERSTATETYPE


CONST_D3DSTATEBLOCKTYPE

The CONST_D3DSTATEBLOCK enumerated type defines logical groups of device states, for use with the Direct3DDevice7.CreateStateBlock method.

Type D3DSTATEBLOCKTYPE
    D3DSBT_ALL = 1
    D3DSBT_PIXELSTATE = 2
    D3DSBT_VERTEXSTATE = 3
End Type
D3DSBT_ALL
Capture all device states.
D3DSBT_PIXELSTATE
Capture only pixel-related device states.
D3DSBT_VERTEXSTATE
Capture only vertex-related device states.

Remarks

The D3DSBT_PIXELSTATE and D3DSBT_VERTEXSTATE values identify different logical groups of device states, though some states are common to both groups. For information about the states defined by each group, see Creating Predefined State Blocks.

See Also

Direct3DDevice7.CreateStateBlock


CONST_D3DSTENCILCAPSFLAGS

The CONST_D3DSTENCILCAPSFLAGS enumeration defines stencil buffer capability flags that are combined and present in the lStencilCaps member of the D3DDEVICEDESC7 type.

Enum CONST_D3DSTENCILCAPSFLAGS
    D3DSTENCILCAPS_DECR = 128
    D3DSTENCILCAPS_DECRSAT = 16
    D3DSTENCILCAPS_INCR = 64
    D3DSTENCILCAPS_INCRSAT = 8
    D3DSTENCILCAPS_INVERT = 32
    D3DSTENCILCAPS_KEEP = 1
    D3DSTENCILCAPS_REPLACE = 4
    D3DSTENCILCAPS_ZERO = 2
End Enum
D3DSTENCILCAPS_DECR
The D3DSTENCILOP_DECR stencil buffer operation is supported.
D3DSTENCILCAPS_DECRSAT
The D3DSTENCILOP_DECRSAT stencil buffer operation is supported.
D3DSTENCILCAPS_INCR
The D3DSTENCILOP_INCR stencil buffer operation is supported.
D3DSTENCILCAPS_INCRSAT
The D3DSTENCILOP_INCRSAT stencil buffer operation is supported.
D3DSTENCILCAPS_INVERT
The D3DSTENCILOP_INVERT stencil buffer operation is supported.
D3DSTENCILCAPS_KEEP
The D3DSTENCILOP_KEEP stencil buffer operation is supported.
D3DSTENCILCAPS_REPLACE
The D3DSTENCILOP_REPLACE stencil buffer operation is supported.
D3DSTENCILCAPS_ZERO
The D3DSTENCILOP_ZERO stencil buffer operation is supported.


CONST_D3DSTENCILOP

The CONST_D3DSTENCILOP enumeration describes the stencil operations for the D3DRENDERSTATE_STENCILFAIL, D3DRENDERSTATE_STENCILZFAIL, D3DRENDERSTATE_STENCILPASS render states.

Enum CONST_D3DSTENCILOP
    D3DSTENCILOP_DECR = 8
    D3DSTENCILOP_DECRSAT = 5
    D3DSTENCILOP_INCR = 7
    D3DSTENCILOP_INCRSAT = 4
    D3DSTENCILOP_INVERT = 6
    D3DSTENCILOP_KEEP = 1
    D3DSTENCILOP_REPLACE = 3
    D3DSTENCILOP_ZERO = 2
End Enum
D3DSTENCILOP_DECR
Decrement the stencil-buffer entry, wrapping to the maximum value if the new value is less than zero.
D3DSTENCILOP_DECRSAT
Decrement the stencil-buffer entry, clamping to zero.
D3DSTENCILOP_INCRSAT
Increment the stencil-buffer entry, clamping to the maximum value. See remarks for information on the maximum stencil-buffer values.
D3DSTENCILOP_INVERT
Invert the bits in the stencil-buffer entry.
D3DSTENCILOP_INCR
Increment the stencil-buffer entry, wrapping to zero if the new value exceeds the maximum value. See remarks for information on the maximum stencil-buffer values.
D3DSTENCILOP_KEEP
Do not update the entry in the stencil buffer. This is the default value.
D3DSTENCILOP_REPLACE
Replace the stencil-buffer entry with reference value.
D3DSTENCILOP_ZERO
Set the stencil-buffer entry to zero.

Remarks

Stencil-buffer entries are integer values ranging inclusively from 0 to 2n -1, where n is the bit depth of the stencil buffer.

See Also

CONST_D3DRENDERSTATETYPE, Stencil Buffers


CONST_D3DTAFLAGS

The CONST_D3DTAFLAGS enumeration defines texture argument flags used to define texture blending stages. For details, see Texture Argument Flags.


CONST_D3DTEXCOORDINDEXFLAGS

The CONST_D3DTEXCOORDINDEXFLAGS enumeration defines values used in combination with the index values set with the D3DTSS_TEXCOORDINDEX texture-stage state.

Type CONST_D3DTEXCOORDINDEXFLAGS
    D3DTSS_TCI_CAMERASPACENORMAL = 65536
    D3DTSS_TCI_CAMERASPACEPOSITION = 131072
    D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR = 196608
    D3DTSS_TCI_PASSTHRU = 0
End Type
D3DTSS_TCI_CAMERASPACENORMAL
Use the vertex normal, transformed to camera space, as the input texture coordinates for this stage's texture transformation.
D3DTSS_TCI_CAMERASPACEPOSITION
Use the vertex position, transformed to camera space, as the input texture coordinates for this stage's texture transformation.
D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR
Use the reflection vector, transformed to camera space, as the input texture coordinate for this stage's texture transformation. The reflection vector is computed from the input vertex position and normal vector.
D3DTSS_TCI_PASSTHRU
Use the specified texture coordinates contained within the vertex format.

Remarks

The values from this enumeration (except for D3DTSS_TCI_PASSTHRU, which resolves to zero) change how the system uses the index value being set in D3DTSS_TEXCOORDINDEX. Normally, the value set in D3DTSS_TEXCOORDINDEX controls the texture coordinate set used to address the texture. However, when you include the D3DTSS_TCI_CAMERASPACENORMAL, D3DTSS_TCI_CAMERASPACEPOSITION, or D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR values (as a logical Or operation with the index being set), the system uses the index strictly to determine the texture wrapping mode.

Values within this enumeration are useful to applications that benefit from automatic generation of texture coordinates for environment mapping.

See Also

Configuring Automatically Generated Texture Coordinates


CONST_D3DTEXOPCAPSFLAGS

The CONST_D3DTEXOPCAPSFLAGS enumeration defines texture-blending operation capabilities that are combined and present in the lTextureOpCaps member of the D3DDEVICEDESC7 type.

Enum CONST_D3DTEXOPCAPSFLAGS
    D3DTEXOPCAPS_ADD = 64
    D3DTEXOPCAPS_ADDSIGNED = 128
    D3DTEXOPCAPS_ADDSIGNED2X = 256
    D3DTEXOPCAPS_ADDSMOOTH = 1024
    D3DTEXOPCAPS_BLENDCURRENTALPHA = 32768
    D3DTEXOPCAPS_BLENDDIFFUSEALPHA = 2048
    D3DTEXOPCAPS_BLENDFACTORALPHA = 8192
    D3DTEXOPCAPS_BLENDTEXTUREALPHA = 4096
    D3DTEXOPCAPS_BLENDTEXTUREALPHAPM = 16384
    D3DTEXOPCAPS_BUMPENVMAP = 2097152
    D3DTEXOPCAPS_BUMPENVMAPLUMINANCE = 4194304
    D3DTEXOPCAPS_DISABLE = 1
    D3DTEXOPCAPS_DOTPRODUCT3 = 8388608
    D3DTEXOPCAPS_MODULATE = 8
    D3DTEXOPCAPS_MODULATE2X = 16
    D3DTEXOPCAPS_MODULATE4X = 32
    D3DTEXOPCAPS_MODULATEALPHA_ADDCOLOR = 131072
    D3DTEXOPCAPS_MODULATECOLOR_ADDALPHA = 262144
    D3DTEXOPCAPS_MODULATEINVALPHA_ADDCOLOR = 524288
    D3DTEXOPCAPS_MODULATEINVCOLOR_ADDALPHA = 1048576
    D3DTEXOPCAPS_PREMODULATE = 65536
    D3DTEXOPCAPS_SELECTARG1 = 2
    D3DTEXOPCAPS_SELECTARG2 = 4
    D3DTEXOPCAPS_SUBTRACT = 512
End Enum
D3DTEXOPCAPS_ADD
The D3DTOP_ADD texture blending operation is supported by this device.
D3DTEXOPCAPS_ADDSIGNED
The D3DTOP_ADDSIGNED texture blending operation is supported by this device.
D3DTEXOPCAPS_ADDSIGNED2X
The D3DTOP_ADDSIGNED2X texture blending operation is supported by this device.
D3DTEXOPCAPS_ADDSMOOTH
The D3DTOP_ADDSMOOTH texture blending operation is supported by this device.
D3DTEXOPCAPS_BLENDCURRENTALPHA
The D3DTOP_BLENDCURRENTALPHA texture blending operation is supported by this device.
D3DTEXOPCAPS_BLENDDIFFUSEALPHA
The D3DTOP_BLENDDIFFUSEALPHA texture blending operation is supported by this device.
D3DTEXOPCAPS_BLENDFACTORALPHA
The D3DTOP_BLENDFACTORALPHA texture blending operation is supported by this device.
D3DTEXOPCAPS_BLENDTEXTUREALPHA
The D3DTOP_BLENDTEXTUREALPHA texture blending operation is supported by this device.
D3DTEXOPCAPS_BLENDTEXTUREALPHAPM
The D3DTOP_BLENDTEXTUREALPHAPM texture blending operation is supported by this device.
D3DTEXOPCAPS_BUMPENVMAP
The D3DTOP_BUMPENVMAP texture blending operation is supported by this device.
D3DTEXOPCAPS_BUMPENVMAPLUMINANCE
The D3DTOP_BUMPENVMAPLUMINANCE texture blending operation is supported by this device.
D3DTEXOPCAPS_DISABLE
The D3DTOP_DISABLE texture blending operation is supported by this device.
D3DTEXOPCAPS_DOTPRODUCT3
The D3DTOP_DOTPRODUCT3 texture blending operation is supported by this device.
D3DTEXOPCAPS_MODULATE
The D3DTOP_MODULATE texture blending operation is supported by this device.
D3DTEXOPCAPS_MODULATE2X
The D3DTOP_MODULATE2X texture blending operation is supported by this device.
D3DTEXOPCAPS_MODULATE4X
The D3DTOP_MODULATE4X texture blending operation is supported by this device.
D3DTEXOPCAPS_MODULATEALPHA_ADDCOLOR
The D3DTOP_MODULATEALPHA_ADDCOLOR texture blending operation is supported by this device.
D3DTEXOPCAPS_MODULATECOLOR_ADDALPHA
The D3DTOP_MODULATEALPHA_ADDCOLOR texture blending operation is supported by this device.
D3DTEXOPCAPS_MODULATEINVALPHA_ADDCOLOR
The D3DTOP_MODULATEINVALPHA_ADDCOLOR texture blending operation is supported by this device.
D3DTEXOPCAPS_MODULATEINVCOLOR_ADDALPHA
The D3DTOP_MODULATEINVCOLOR_ADDALPHA texture blending operation is supported by this device.
D3DTEXOPCAPS_PREMODULATE
The D3DTOP_PREMODULATE texture blending operation is supported by this device.
D3DTEXOPCAPS_SELECTARG1
The D3DTOP_SELECTARG1 texture blending operation is supported by this device.
D3DTEXOPCAPS_SELECTARG2
The D3DTOP_SELECTARG2 texture blending operation is supported by this device.
D3DTEXOPCAPS_SUBTRACT
The D3DTOP_SUBTRACT texture blending operation is supported by this device.


CONST_D3DTEXTUREADDRESS

The CONST_D3DTEXTUREADDRESS enumeration describes the supported texture addressing modes when setting them with the D3DTSS_ADDRESS, D3DTSS_ADDRESSU, and D3DTSS_ADDRESSV texture stage states.

Enum CONST_D3DTEXTUREADDRESS
    D3DTADDRESS_WRAP         = 1
    D3DTADDRESS_MIRROR       = 2
    D3DTADDRESS_CLAMP        = 3
    D3DTADDRESS_BORDER       = 4
End Enum
D3DTADDRESS_WRAP
Tile the texture at every integer junction. For example, for u values between 0 and 3, the texture will be repeated three times; no mirroring is performed.
D3DTADDRESS_MIRROR
Similar to D3DTADDRESS_WRAP, except that the texture is flipped at every integer junction. For u values between 0 and 1, for example, the texture is addressed normally, between 1 and 2 the texture is flipped (mirrored), between 2 and 3 the texture is normal again, and so on.
D3DTADDRESS_CLAMP
Texture coordinates outside the range [0.0, 1.0] are set to the texture color at 0.0 or 1.0, respectively.
D3DTADDRESS_BORDER
Texture coordinates outside the range [0.0, 1.0] are drawn with the border color, set with the D3DTSS_BORDERCOLOR texture stage state in the CONST_D3DTEXTURESTAGESTATETYPE enumeration.

See Also

CONST_D3DTEXTURESTAGESTATETYPE


CONST_D3DTEXTUREMAGFILTER

The CONST_D3DTEXTUREMAGFILTER enumeration defines texture magnification filtering modes for a texture stage.

Enum CONST_D3DTEXTUREMAGFILTER
    D3DTFG_POINT        = 1
    D3DTFG_LINEAR       = 2
    D3DTFG_FLATCUBIC    = 3
    D3DTFG_GAUSSIANCUBIC= 4
    D3DTFG_ANISOTROPIC  = 5
End Enum
D3DTFG_POINT
Point filtering. The texel with coordinates nearest to the desired pixel value is used.
D3DTFG_LINEAR
Bilinear interpolation filtering. A weighted average of a 2×2 area of texels surrounding the desired pixel is used.
D3DTFG_FLATCUBIC
Not currently supported; do not use.
D3DTFG_GAUSSIANCUBIC
Not currently supported; do not use.
D3DTFG_ANISOTROPIC
Anisotropic texture filtering. Compensates for distortion caused by the difference in angle between the texture polygon and the plane of the screen.

Remarks

You set a texture stage's magnification filter by calling the Direct3DDevice7.SetTextureStageState method with the D3DTSS_MAGFILTER value as the second parameter, and one of constants of this enumeration as the third parameter.

See Also

CONST_D3DTEXTUREMINFILTER, CONST_D3DTEXTUREMIPFILTER, Texture Filtering


CONST_D3DTEXTUREMINFILTER

The CONST_D3DTEXTUREMINFILTER enumeration defines texture minification filtering modes for a texture stage.

Enum CONST_D3DTEXTUREMINFILTER
    D3DTFN_POINT        = 1
    D3DTFN_LINEAR       = 2
    D3DTFN_ANISOTROPIC  = 3
End Enum
D3DTFN_POINT
Point filtering. The texel with coordinates nearest to the desired pixel value is used.
D3DTFN_LINEAR
Bilinear interpolation filtering. A weighted average of a 2×2 area of texels surrounding the desired pixel is used.
D3DTFN_ANISOTROPIC
Anisotropic texture filtering. Compensates for distortion caused by the difference in angle between the texture polygon and the plane of the screen.

Remarks

You set a texture stage's magnification filter by calling the Direct3DDevice7.SetTextureStageState method with the D3DTSS_MINFILTER value as the second parameter, and one of constants of this enumeration as the third parameter.

See Also

CONST_D3DTEXTUREMAGFILTER, CONST_D3DTEXTUREMIPFILTER, Texture Filtering


CONST_D3DTEXTUREMIPFILTER

The CONST_D3DTEXTUREMIPFILTER enumeration defines texture mipmap filtering modes for a texture stage.

Enum CONST_D3DTEXTUREMIPFILTER
    D3DTFP_NONE         = 1
    D3DTFP_POINT        = 2
    D3DTFP_LINEAR       = 3
End Enum
D3DTFP_NONE
Mipmapping disabled. The rasterizer should use the magnification filter instead.
D3DTFP_POINT
Nearest point mipmap filtering. The rasterizer uses the color from the texel of the nearest mipmap texture.
D3DTFP_LINEAR
Trilinear mipmap interpolation. The rasterizer linearly interpolates pixel color using the texels of the two nearest mipmap textures.

Remarks

You set a texture stage's magnification filter by calling the Direct3DDevice7.SetTextureStageState method with the D3DTSS_MIPFILTER value as the second parameter, and one of constants of this enumeration as the third parameter.

See Also

CONST_D3DTEXTUREMAGFILTER, CONST_D3DTEXTUREMIPFILTER, Texture Filtering


CONST_D3DTEXTUREOP

The CONST_D3DTEXTUREOP enumeration defines per-stage texture blending operations. The constants of this type are used when setting color or alpha operations by using the D3DTSS_COLOROP or D3DTSS_ALPHAOP values with the Direct3DDevice7.SetTextureStageState method.

Enum CONST_D3DTEXTUREOP
    D3DTOP_DISABLE    = 1
    D3DTOP_SELECTARG1 = 2
    D3DTOP_SELECTARG2 = 3
    D3DTOP_MODULATE   = 4
    D3DTOP_MODULATE2X = 5
    D3DTOP_MODULATE4X = 6
    D3DTOP_ADD        = 7
    D3DTOP_ADDSIGNED  = 8
    D3DTOP_ADDSIGNED2X  =  9
    D3DTOP_SUBTRACT     = 10
    D3DTOP_ADDSMOOTH    = 11
    D3DTOP_BLENDDIFFUSEALPHA    = 12
    D3DTOP_BLENDTEXTUREALPHA    = 13
    D3DTOP_BLENDFACTORALPHA     = 14
    D3DTOP_BLENDTEXTUREALPHAPM  = 15
    D3DTOP_BLENDCURRENTALPHA    = 16
    D3DTOP_PREMODULATE            = 17
    D3DTOP_MODULATEALPHA_ADDCOLOR = 18
    D3DTOP_MODULATECOLOR_ADDALPHA = 19
    D3DTOP_MODULATEINVALPHA_ADDCOLOR = 20
    D3DTOP_MODULATEINVCOLOR_ADDALPHA = 21
    D3DTOP_BUMPENVMAP           = 22
    D3DTOP_BUMPENVMAPLUMINANCE  = 23
    D3DTOP_DOTPRODUCT3          = 24
End Enum
Control constants
D3DTOP_DISABLE
Disables output from this texture stage and all stages with a higher index. To disable texture mapping, set this as the color operation for the first texture stage (stage 0). Alpha operations cannot be disabled when color operations are enabled. Setting the alpha operation to D3DTOP_DISABLE when color blending is enabled causes undefined behavior.
D3DTOP_SELECTARG1
Use this texture stage's first color or alpha argument, unmodified, as the output. This operation affects the color argument when used with the D3DTSS_COLOROP texture stage state, and the alpha argument when used with D3DTSS_ALPHAOP.

D3DTOP_SELECTARG2
Use this texture stage's second color or alpha argument, unmodified, as the output. This operation affects the color argument when used with the D3DTSS_COLOROP texture stage state, and the alpha argument when used with D3DTSS_ALPHAOP.

Modulation constants
D3DTOP_MODULATE
Multiply the components of the arguments together.

D3DTOP_MODULATE2X
Multiply the components of the arguments and shift the products to the left one bit (effectively multiplying them by two) for brightening.

D3DTOP_MODULATE4X
Multiply the components of the arguments and shift the products to the left two bits (effectively multiplying them by four) for brightening.

Addition and Subtraction constants
D3DTOP_ADD
Add the components of the arguments.

D3DTOP_ADDSIGNED
Add the components of the arguments with a -0.5 bias, making the effective range of values from -0.5 to 0.5.

D3DTOP_ADDSIGNED2X
Add the components of the arguments with a -0.5 bias, and shift the products to the left one bit.

D3DTOP_SUBTRACT
Subtract the components of the second argument from those of the first argument.

D3DTOP_ADDSMOOTH
Add the first and second arguments, then subtract their product from the sum.

Linear alpha blending constants
D3DTOP_BLENDDIFFUSEALPHA
D3DTOP_BLENDTEXTUREALPHA
D3DTOP_BLENDFACTORALPHA
D3DTOP_BLENDCURRENTALPHA
Linearly blend this texture stage using the interpolated alpha from each vertex (D3DTOP_BLENDDIFFUSEALPHA), alpha from this stage's texture (D3DTOP_BLENDTEXTUREALPHA), a scalar alpha (D3DTOP_BLENDFACTORALPHA) set with the D3DRENDERSTATE_TEXTUREFACTOR render state, or the alpha taken from the previous texture stage (D3DTOP_BLENDCURRENTALPHA).

D3DTOP_BLENDTEXTUREALPHAPM
Linearly blend a texture stage that uses premultiplied alpha.

Specular mapping constants
D3DTOP_PREMODULATE
Modulate this texture stage with the next texture stage.
D3DTOP_MODULATEALPHA_ADDCOLOR
Modulate the second argument's color using the first argument's alpha, then add the result to argument one. This operation is supported only for color operations (D3DTSS_COLOROP).

D3DTOP_MODULATECOLOR_ADDALPHA
Modulate the arguments, then add the first argument's alpha. This operation is supported only for color operations (D3DTSS_COLOROP).

D3DTOP_MODULATEINVALPHA_ADDCOLOR
Similar to D3DTOP_MODULATEALPHA_ADDCOLOR, but use the inverse of the first argument's alpha. This operation is supported only for color operations (D3DTSS_COLOROP).

D3DTOP_MODULATEINVCOLOR_ADDALPHA
Similar to D3DTOP_MODULATECOLOR_ADDALPHA, but use the inverse of the first argument's color. This operation is supported only for color operations (D3DTSS_COLOROP).

Bump mapping constants
D3DTOP_BUMPENVMAP
Perform per-pixel bump-mapping using the environment map in the next texture stage (without luminance).
D3DTOP_BUMPENVMAPLUMINANCE
Perform per-pixel bump-mapping using the environment map in the next texture stage (with luminance).
D3DTOP_DOTPRODUCT3
Modulate the components of each argument (as signed components), add their products, then replicate the sum to all color channels, including alpha. This operation is supported only for color operations (D3DTSS_COLOROP).

Remarks

In the preceding formulas, SRGBA is the RGBA color produced by a texture operation, and Arg1 and Arg2 represent the complete RGBA color of the texture arguments. Individual components of an argument are shown with subscripts. For example, the alpha component for argument one would be shown as Arg1A.

See Also

Direct3DDevice7.GetTextureStageState, Direct3DDevice7.SetTextureStageState, CONST_D3DTEXTURESTAGESTATETYPE


CONST_D3DTEXTURESTAGESINGLE

The CONST_D3DTEXTURESTAGESINGLE enumeration defines texture stage states that accepts values of type Single. Constants of this enumeration are used with the Direct3DDevice7.GetTextureStageStateSingle and Direct3DDevice7.SetTextureStageStateSingle methods to retrieve and set texture state values.

Enum CONST_D3DTEXTURESTAGESINGLE
    D3DTSS_BUMPENVLOFFSET = 23
    D3DTSS_BUMPENVLSCALE  = 22
    D3DTSS_BUMPENVMAT00   = 7
    D3DTSS_BUMPENVMAT01   = 8
    D3DTSS_BUMPENVMAT10   = 9
    D3DTSS_BUMPENVMAT11   = 10
    D3DTSS_MIPMAPLODBIAS  = 19
End Enum
D3DTSS_BUMPENVMAT00
The texture stage state is a value for the [0][0] coefficient in a bump mapping matrix. The default value is 0.
D3DTSS_BUMPENVMAT01
The texture stage state is a value for the [0][1] coefficient in a bump mapping matrix. The default value is 0.
D3DTSS_BUMPENVMAT10
The texture stage state is a value for the [1][0] coefficient in a bump mapping matrix. The default value is 0.
D3DTSS_BUMPENVMAT11
The texture stage state is a value for the [1][1] coefficient in a bump mapping matrix. The default value is 0.
D3DTSS_BUMPENVLSCALE
Scale for bump map luminance. The default value is 0.
D3DTSS_BUMPENVLOFFSET
Offset for bump map luminance. The default value is 0.
D3DTSS_MIPMAPLODBIAS
Level of detail bias for mipmaps. Can be used to make textures appear more chunky or more blurred. The default value is 0.

Remarks

The valid range of values for the D3DTSS_BUMPENVMAT00, D3DTSS_BUMPENVMAT01, D3DTSS_BUMPENVMAT10, and D3DTSS_BUMPENVMAT11 bump-mapping matrix coefficients is greater than or equal to -8.0, and less than 8.0. This range, expressed in mathematical notation is [-8.0,8.0).

See Also

Direct3DDevice7.GetTextureStageStateSingle, Direct3DDevice7.SetTextureStageStateSingle


CONST_D3DTEXTURESTAGESTATETYPE

The CONST_D3DTEXTURESTAGESTATETYPE enumeration defines texture stage states. Constants of this enumeration are used with the Direct3DDevice7.GetTextureStageState and Direct3DDevice7.SetTextureStageState methods to retrieve and set texture state values.

Enum CONST_D3DTEXTURESTAGESTATETYPE
    D3DTSS_ADDRESS        = 12
    D3DTSS_ADDRESSU       = 13
    D3DTSS_ADDRESSV       = 14
    D3DTSS_ALPHAARG1      = 5
    D3DTSS_ALPHAARG2      = 6
    D3DTSS_ALPHAOP        = 4
    D3DTSS_BORDERCOLOR    = 15
    D3DTSS_COLORARG1      = 2
    D3DTSS_COLORARG2      = 3
    D3DTSS_COLOROP        = 1
    D3DTSS_MAGFILTER      = 16
    D3DTSS_MAXANISOTROPY  = 21
    D3DTSS_MAXMIPLEVEL    = 20
    D3DTSS_MINFILTER      = 17
    D3DTSS_MIPFILTER      = 18
    D3DTSS_TEXCOORDINDEX  = 11
    D3DTSS_TEXTURETRANSFORMFLAGS = 24
End Enum
D3DTSS_ADDRESS
Member of the CONST_D3DTEXTUREADDRESS enumeration. Selects the texture addressing method for both the u and v coordinates. The default is D3DTADDRESS_WRAP.
D3DTSS_ADDRESSU
Member of the CONST_D3DTEXTUREADDRESS enumeration. Selects the texture addressing method for the u coordinate. The default is D3DTADDRESS_WRAP.
D3DTSS_ADDRESSV
Member of the CONST_D3DTEXTUREADDRESS enumeration. Selects the texture addressing method for the v coordinate. The default value is D3DTADDRESS_WRAP.
D3DTSS_ALPHAARG1
The texture stage state is the first alpha argument for the stage, identified by a texture argument flag. The default argument is D3DTA_TEXTURE. If no texture is set for this stage, the default argument is D3DTA_DIFFUSE.
D3DTSS_ALPHAARG2
The texture stage state is the second alpha argument for the stage, identified by a texture argument flag. The default argument is D3DTA_CURRENT.
D3DTSS_ALPHAOP
The texture stage state is texture alpha blending operation identified by one of the constants of the CONST_D3DTEXTUREOP enumeration. The default value for the first texture stage (stage 0) is D3DTOP_SELECTARG1, and for all other stages the default is D3DTOP_DISABLE.
D3DTSS_BORDERCOLOR
Value that describes the color to be used for rasterizing texture coordinates outside the [0.0,1.0] range. The default color is 0x00000000.
D3DTSS_COLORARG1
The texture stage state is the first color argument for the stage, identified by a texture argument flag. The default argument is D3DTA_TEXTURE.
D3DTSS_COLORARG2
The texture stage state is the second color argument for the stage, identified by a texture argument flag. The default argument is D3DTA_CURRENT.
D3DTSS_COLOROP
The texture stage state is a texture color blending operation identified by one of the constants of the CONST_D3DTEXTUREOP enumeration. The default value for the first texture stage (stage 0) is D3DTOP_MODULATE, and for all other stages the default is D3DTOP_DISABLE.
D3DTSS_MAGFILTER
Member of the CONST_D3DTEXTUREMAGFILTER enumeration that indicates the texture magnification filter to be used when rendering the texture onto primitives. The default value is D3DTFG_POINT.
D3DTSS_MAXANISOTROPY
Maximum level of anisotropy. The default value is 1.
D3DTSS_MAXMIPLEVEL
Maximum level-of-detail mipmap that the application will allow. Zero, which is the default, indicates that all levels can be used.
D3DTSS_MINFILTER
Member of the CONST_D3DTEXTUREMINFILTER enumeration that indicates the texture magnification filter to be used when rendering the texture onto primitives. The default value is D3DTFN_POINT.
D3DTSS_MIPFILTER
Member of the CONST_D3DTEXTUREMIPFILTER enumeration that indicates the texture magnification filter to be used when rendering the texture onto primitives. The default value is D3DTFP_NONE.
D3DTSS_TEXCOORDINDEX
Index of the texture coordinate set to use with this texture stage. The default index is 0. Set this state to the zero-based index of the texture set at for each vertex that this texture stage will use. (You can specify up to eight sets of texture coordinates per vertex.) If a vertex does not include a set of texture coordinates at the specified index, the system defaults to using the u, v coordinates (0,0).

You can include flags from the CONST_D3DTEXCOORDINDEXFLAGS enumeration with the index you specify for this state to modify how the system interprets the index value. For more information, see Configuring Automatically Generated Texture Coordinates.

D3DTSS_TEXTURETRANSFORMFLAGS
Member of the CONST_D3DTEXTURETRANSFORMFLAGS enumeration that controls the transformation of texture coordinates for this texture stage. The default value is D3DTTFF_DISABLE.


CONST_D3DTEXTURETRANSFORMFLAGS

The CONST_D3DTEXTURETRANSFORMFLAGS enumeration is used with the D3DTSS_TEXTURETRANSFORMFLAGS texture stage state.

Type CONST_D3DTEXTURETRANSFORMFLAGS
    D3DTTFF_COUNT1          = 1
    D3DTTFF_COUNT2          = 2
    D3DTTFF_COUNT3          = 3
    D3DTTFF_COUNT4          = 4
    D3DTTFF_DISABLE         = 0
    D3DTTFF_PROJECTED       = 256
End Type
D3DTTFF_COUNT1
The rasterizer should expect 1-D texture coordinates.
D3DTTFF_COUNT2
The rasterizer should expect 2-D texture coordinates.
D3DTTFF_COUNT3
The rasterizer should expect 3-D texture coordinates.
D3DTTFF_COUNT4
The rasterizer should expect 4-D texture coordinates.
D3DTTFF_DISABLE
Texture coordinates are to be passed directly to the rasterizer.
D3DTTFF_PROJECTED
The texture coordinates should all be divided by the last element before being passed to the rasterizer. For example, if this flag is specified with the D3DTTFF_COUNT3 flag, the first and second texture coordinates will be divided by the third coordinate before being passed to the rasterizer.

See Also

D3DTSS_TEXTURETRANSFORMFLAGS


CONST_D3DTRANSFORMSTATETYPE

The CONST_D3DTRANSFORMSTATETYPE enumeration defines values that describe the transformation state.

Enum CONST_D3DTRANSFORMSTATETYPE
    D3DTRANSFORMSTATE_WORLD        = 1
    D3DTRANSFORMSTATE_WORLD1       = 4,
    D3DTRANSFORMSTATE_WORLD2       = 5,
    D3DTRANSFORMSTATE_WORLD3       = 6,
    D3DTRANSFORMSTATE_VIEW         = 2
    D3DTRANSFORMSTATE_PROJECTION   = 3
    D3DTRANSFORMSTATE_TEXTURE0     = 16
    D3DTRANSFORMSTATE_TEXTURE1     = 17
    D3DTRANSFORMSTATE_TEXTURE2     = 18
    D3DTRANSFORMSTATE_TEXTURE3     = 19
    D3DTRANSFORMSTATE_TEXTURE4     = 20
    D3DTRANSFORMSTATE_TEXTURE5     = 21
    D3DTRANSFORMSTATE_TEXTURE6     = 22
    D3DTRANSFORMSTATE_TEXTURE7     = 23
End Enum
D3DTRANSFORMSTATE_WORLD, D3DTRANSFORMSTATE_VIEW, and D3DTRANSFORMSTATE_PROJECTION
Define the matrices for the world, view, and projection transformations. The default values are Nothing (the identity matrices).
D3DTRANSFORMSTATE_WORLD1, D3DTRANSFORMSTATE_WORLD2, D3DTRANSFORMSTATE_WORLD3
Identifiy subsequent transformation matrices that can be used to blend vertices by using the corresponding matrix and a blending (beta) weight value specified in the vertex format.
D3DTRANSFORMSTATE_TEXTURE0 through D3DTRANSFORMSTATE_TEXTURE7
Identifies the transformation matrix being set for the specified texture stage.

See Also

CONST_D3DRENDERSTATETYPE, Geometry Blending


CONST_D3DVBCAPSFLAGS

The CONST_D3DVBCAPSFLAGS enumeration defines vertex buffer capability flags that are used in the lCaps member of the D3DVERTEXBUFFERDESC type.

Enum CONST_D3DVBCAPSFLAGS
    D3DVBCAPS_DEFAULT = 0
    D3DVBCAPS_DONOTCLIP = 1
    D3DVBCAPS_OPTIMIZED = 2147483648
    D3DVBCAPS_SYSTEMMEMORY = 2048
    D3DVBCAPS_WRITEONLY = 65536
End Enum
D3DVBCAPS_DEFAULT
The vertex buffer should be created in whatever memory the driver chooses to allow efficient read operations.
D3DVBCAPS_DONOTCLIP
The vertex buffer cannot contain clipping information.
D3DVBCAPS_OPTIMIZED
The vertex buffer contains optimized vertex data. (This flag is not used when creating a new vertex buffer.)
D3DVBCAPS_SYSTEMMEMORY
The vertex buffer should be created in system memory. Use this capability for vertex buffers that will be rendered by using software devices (MMX and RGB devices).
D3DVBCAPS_WRITEONLY
Hints to the system that the application will only write to the vertex buffer. Using this flag enables the driver to choose the best memory location for efficient write operations and rendering. Attempts to read from a vertex buffer that is created with this capability can result in degraded performance.


CONST_D3DVERTEXBLENDFLAGS

The CONST_D3DVERTEXBLENDFLAGS enumeration defines flags used to control the number or matrices that the system applies when performing geometry blending. Members of this enumeration are used with the D3DRENDERSTATE_VERTEXBLEND render state.

Enum CONST_D3DVERTEXBLENDFLAGS
    D3DVBLEND_1WEIGHT = 1
    D3DVBLEND_2WEIGHTS = 2
    D3DVBLEND_3WEIGHTS = 3
    D3DVBLEND_DISABLE = 0
End Enum
D3DVBLEND_1WEIGHT
Enable vertex blending between the two matrices set by the D3DTRANSFORMSTATE_WORLD and D3DTRANSFORMSTATE_WORLD1 transformation states.
D3DVBLEND_2WEIGHTS
Enable vertex blending between the three matrices set by the D3DTRANSFORMSTATE_WORLD, D3DTRANSFORMSTATE_WORLD1, and D3DTRANSFORMSTATE_WORLD2 transformation states.
D3DVBLEND_3WEIGHTS
Enable vertex blending between the four matrices set by the D3DTRANSFORMSTATE_WORLD, D3DTRANSFORMSTATE_WORLD1, D3DTRANSFORMSTATE_WORLD2, and D3DTRANSFORMSTATE_WORLD3 transformation states.
D3DVBLEND_DISABLE
Disable vertex blending; only apply the world matrix specified by the D3DTRANSFORMSTATE_WORLD transformation state.

Remarks

Geometry blending (multi-matrix vertex blending) requires that your application use a vertex format that has blending (beta) weights for each vertex.

See Also

CONST_D3DRENDERSTATETYPE, CONST_D3DTRANSFORMSTATETYPE, Direct3DDevice7.SetTransform, Geometry Blending


CONST_D3DVOPFLAGS

The CONST_D3DVOPFLAGS enumeration devices vertex operation flags used in the vertexOp parameter of the Direct3DVertexBuffer7.ProcessVertices method.

Enum CONST_D3DVOPFLAGS
    D3DVOP_CLIP      = 2
    D3DVOP_EXTENTS   = 4
    D3DVOP_LIGHT     = 1024
    D3DVOP_TRANSFORM = 1
End Enum
D3DVOP_CLIP
Transform the vertices and clip any vertices that exist outside the viewing frustum. This flag cannot be used with vertex buffers that do not contain clipping information (for example, created with the D3DDP_DONOTCLIP flag).
D3DVOP_EXTENTS
Transform the vertices, then update the extents of the screen rectangle when the vertices are rendered. Using this flag can potentially help performance, but the extents returned by Direct3DDevice7.GetClipStatus will not have been updated to account for the vertices when they are rendered.
D3DVOP_LIGHT
Light the vertices.
D3DVOP_TRANSFORM
Transform the vertices using the world, view, and projection matrices. This flag must always be set.


CONST_D3DVTXPCAPS

The CONST_D3DVTXPCAPS enumeration defines flags that describe the vertex processing capabilities that the device exposes in the lVertexProcessingCaps member of the D3DDEVICEDESC7 type.

Type CONST_D3DVTXPCAPS
    D3DVTXPCAPS_DIRECTIONALLIGHTS = 8
    D3DVTXPCAPS_MATERIALSOURCE7 = 2
    D3DVTXPCAPS_NONLOCALVIEWER = 32
    D3DVTXPCAPS_POSITIONALLIGHTS = 16
    D3DVTXPCAPS_TEXGEN = 1
    D3DVTXPCAPS_VERTEXFOG = 4
End Type
D3DVTXPCAPS_DIRECTIONALLIGHTS
Device supports directional lights.
D3DVTXPCAPS_MATERIALSOURCE7
Device supports selectable vertex color sources. For more information, see Light Color Types and Sources.
D3DVTXPCAPS_NONLOCALVIEWER
Device supports orthogonal specular highlights, enabled by setting the D3DRENDERSTATE_LOCALVIEWER render state to False.
D3DVTXPCAPS_POSITIONALLIGHTS
Device supports positional lights (including point lights and spotlights).
D3DVTXPCAPS_TEXGEN
Device can generate texture coordinates.
D3DVTXPCAPS_VERTEXFOG
Device supports vertex fog.

See Also

D3DDEVICEDESC7


CONST_D3DZBUFFERTYPE

The CONST_D3DZBUFFERTYPE enumeration describes depth-buffer formats for use with the D3DRENDERSTATE_ZENABLE render state.

Enum CONST_D3DZBUFFERTYPE
    D3DZB_FALSE        = 0
    D3DZB_TRUE         = 1
    D3DZB_USEW         = 2
End Enum
D3DZB_FALSE
Disable depth-buffering.
D3DZB_TRUE
Enable z-buffering.
D3DZB_USEW
Enable w-buffering.

Remarks

The D3DZB_FALSE and D3DZB_TRUE values are interchangeable with the True and False macro values previously used with D3DRENDERSTATE_ZENABLE.

See Also

Direct3DDevice7.SetRenderState, Depth Buffers


Flexible Vertex Format Flags

Direct3D Immediate Mode uses flag values to describe vertex formats used for DrawPrimitive-based rendering. The CONST_D3DFVFFLAGS enumeration defines the following flags to explicitly describe a vertex format, and provides helper macros that act as common combinations of such flags. For more information, see About Vertex Formats.

Flexible vertex format (FVF) flags
D3DFVF_DIFFUSE
Vertex format includes a diffuse color component.
D3DFVF_LVERTEX
Vertex format is equivalent to the D3DLVERTEX vertex type.
D3DFVF_NORMAL
Vertex format includes a vertex normal vector. This flag cannot be used with the D3DFVF_XYZRHW flag.
D3DFVF_SPECULAR
Vertex format includes a specular color component.
D3DFVF_TLVERTEX
Vertex format is equivalent to the D3DTLVERTEX vertex type.
D3DFVF_VERTEX
Vertex format is equivalent to the D3DVERTEX vertex type.
D3DFVF_XYZ
Vertex format includes the position of an untransformed vertex. This flag cannot be used with the D3DFVF_XYZRHW flag. If you use this flag, you must also specify a vertex normal, a vertex color component (D3DFVF_DIFFUSE or D3DFVF_SPECULAR), or include at least one set of texture coordinates (D3DFVF_TEX1 through D3DFVF_TEX8).
D3DFVF_XYZRHW
Vertex format includes the position of a transformed vertex. This flag cannot be used with the D3DFVF_XYZ or D3DFVF_NORMAL flags. If you use this flag, you must also specify a vertex color component (D3DFVF_DIFFUSE or D3DFVF_SPECULAR) or include at least one set of texture coordinates (D3DFVF_TEX1 through D3DFVF_TEX8).
D3DFVF_XYZB1 through D3DFVF_XYZB5
Vertex format contains position data, and a corresponding number of weighting (beta) values to be used for multimatrix vertex blending operations. Currently, Direct3D can blend with up to three weighting values (and four blending matrices).
Texture-related FVF flags
D3DFVF_TEX0 through D3DFVF_TEX8
Number of texture coordinate sets for this vertex. The actual values for these flags are not sequential.

See Also

About Vertex Formats, Geometry Blending


Texture Argument Flags

Each texture stage for a device can have two texture arguments that affect the color or alpha channel of the texture. You set and retrieve texture arguments by calling the Direct3DDevice7.SetTextureStageState and Direct3DDevice7.GetTextureStageState, specifying the D3DTSS_COLORARG1, D3DTSS_COLORARG2, D3DTSS_ALPHAARG1 or D3DTSS_ALPHAARG2 constants of the CONST_D3DTEXTURESTAGESTATETYPE enumeration.

The following flags, organized as arguments and modifiers, can be used with color and alpha arguments for a texture stage. You can combine an argument flag with a modifier, but you cannot combine two argument flags.

Argument flags
D3DTA_CURRENT
The texture argument is the result of the previous blending stage. In the first texture stage (stage 0), this argument is equivalent to D3DTA_DIFFUSE. If the previous blending stage uses a bump-map texture (the D3DTOP_BUMPENVMAP operation), the system chooses the texture from the stage before the bump-map texture. (If s represents the current texture stage, and s – 1 contains a bump-map texture, this argument becomes the result output by texture stage s – 2.)
D3DTA_DIFFUSE
The texture argument is the diffuse color interpolated from vertex components during Gouraud shading. If the vertex does not contain a diffuse color, the default color is 0xFFFFFFFF.
D3DTA_SELECTMASK
Mask value for all arguments; not used when setting texture arguments.
D3DTA_SPECULAR
The texture argument is the specular color interpolated from vertex components during Gouraud shading. If the vertex does not contain a diffuse color, the default color is 0xFFFFFFFF.
D3DTA_TEXTURE
The texture argument is the texture color for this texture stage. This is valid only for the first color and alpha arguments in a stage (the D3DTSS_COLORARG1 and D3DTSS_ALPHAARG1 constants of CONST_D3DTEXTURESTAGESTATETYPE). If no texture is set for a stage that uses this blending argument, the system defaults to a color value of R: 1.0, G: 1.0, B: 1.0 for color, and 1.0 for alpha.
D3DTA_TFACTOR
The texture argument is the texture factor set in a previous call to the Direct3DDevice7.SetRenderState with the D3DRENDERSTATE_TEXTUREFACTOR render state value.
Modifier flags
D3DTA_ALPHAREPLICATE
Replicate the alpha information to all color channels before the operation completes.
D3DTA_COMPLEMENT
Invert the argument such that, if the result of the argument were referred to by the variable x, the value would be 1.0 - x.


Error Codes

Errors, defined by the CONST_D3DIMERR enumeration, are represented by negative values and cannot be combined. This table lists the error codes that can be generated by all Direct3D Immediate Mode methods. See the individual method descriptions for lists of the values each can return.

D3D_OK
No error occurred.
D3DERR_BADMAJORVERSION
The service you requested is unavailable in this major version of DirectX. (A "major version" denotes a primary release, such as DirectX 6.0.)
D3DERR_BADMINORVERSION
The service you requested is available in this major version of DirectX, but not in this minor version. Get the latest version of the component runtime from Microsoft. (A "minor version" denotes a secondary release, such as DirectX 6.1.)
D3DERR_COLORKEYATTACHED
The application attempted to create a texture with a surface that uses a color key for transparency.
D3DERR_CONFLICTINGTEXTUREFILTER
The current texture filters cannot be used together.
D3DERR_CONFLICTINGTEXTUREPALETTE
The current textures cannot be used simultaneously. This generally occurs when a multitexture device requires that all palettized textures simultaneously enabled also share the same palette.
D3DERR_CONFLICTINGRENDERSTATE
The currently set render states cannot be used together.
D3DERR_DEVICEAGGREGATED
The Direct3DDevice7.SetRenderTarget method was called on a device that was retrieved from the render target surface.
D3DERR_INITFAILED
A rendering device could not be created because the new device could not be initialized.
D3DERR_INBEGIN
The requested operation cannot be completed while scene rendering is taking place. Try again after the scene is completed and the Direct3DDevice7.EndScene method (or equivalent method) is called.
D3DERR_INBEGINSTATEBLOCK
The operation cannot be completed while recording states for a state block. Complete recording by calling the Direct3DDevice7.EndStateBlock method and try again.
D3DERR_INOVERLAYSTATEBLOCK
The operation cannot be completed while overlaying a state block. Remove the state block overlay and try again.
D3DERR_INVALID_DEVICE
The requested device type is not valid.
D3DERR_INVALIDCURRENTVIEWPORT
The currently selected viewport is not valid.
D3DERR_INVALIDMATRIX
The requested operation could not be completed because the combination of the currently set world, view, and projection matrices is invalid (the determinant of the combined matrix is zero).
D3DERR_INVALIDPALETTE
The palette associated with a surface is invalid.
D3DERR_INVALIDPRIMITIVETYPE
The primitive type specified by the application is invalid.
D3DERR_INVALIDRAMPTEXTURE
Ramp mode is being used and the texture handle in the current material does not match the current texture handle that is set as a render state.
D3DERR_INVALIDSTATEBLOCK
The state block handle is invalid.
D3DERR_INVALIDVERTEXFORMAT
The combination of flexible vertex format flags specified by the application is not valid.
D3DERR_INVALIDVERTEXTYPE
The vertex type specified by the application is invalid.
D3DERR_LIGHT_SET_FAILED
The attempt to set lighting parameters for a light object failed.
D3DERR_LIGHTHASVIEWPORT
The requested operation failed because the light object is associated with another viewport.
D3DERR_LIGHTNOTINTHISVIEWPORT
The requested operation failed because the light object has not been associated with this viewport.
D3DERR_MATERIAL_CREATE_FAILED
The material could not be created. This typically occurs when no memory is available to allocate for the material.
D3DERR_MATERIAL_DESTROY_FAILED
The memory for the material could not be deallocated.
D3DERR_MATERIAL_GETDATA_FAILED
The material parameters could not be retrieved.
D3DERR_MATERIAL_SETDATA_FAILED
The material parameters could not be set.
D3DERR_MATRIX_CREATE_FAILED
The matrix could not be created. This can occur when no memory is available to allocate for the matrix.
D3DERR_MATRIX_DESTROY_FAILED
The memory for the matrix could not be deallocated.
D3DERR_MATRIX_GETDATA_FAILED
The matrix data could not be retrieved. This can occur when the matrix was not created by the current device.
D3DERR_MATRIX_SETDATA_FAILED
The matrix data could not be set. This can occur when the matrix was not created by the current device.
D3DERR_NOCURRENTVIEWPORT
The viewport parameters could not be retrieved because none have been set.
D3DERR_NOTINBEGIN
The requested rendering operation could not be completed because scene rendering has not begun. Call Direct3DDevice7.BeginScene to begin rendering then try again.
D3DERR_NOTINBEGINSTATEBLOCK
The requested operation could not be completed because it is only valid while recording a state block. Call the Direct3DDevice7.BeginStateBlock method and try again.
D3DERR_NOVIEWPORTS
The requested operation failed because the device currently has no viewports associated with it.
D3DERR_SCENE_BEGIN_FAILED
Scene rendering could not begin.
D3DERR_SCENE_END_FAILED
Scene rendering could not be completed.
D3DERR_SCENE_IN_SCENE
Scene rendering could not begin because a previous scene was not completed by a call to the Direct3DDevice7.EndScene method.
D3DERR_SCENE_NOT_IN_SCENE
Scene rendering could not be completed because a scene was not started by a previous call to the Direct3DDevice7.BeginScene method.
D3DERR_SETVIEWPORTDATA_FAILED
The viewport parameters could not be set.
D3DERR_STENCILBUFFER_NOTPRESENT
The requested stencil buffer operation could not be completed because there is no stencil buffer attached to the render target surface.
D3DERR_SURFACENOTINVIDMEM
The device could not be created because the render target surface is not located in video-memory. (Hardware-accelerated devices require video-memory render target surfaces.)
D3DERR_TEXTURE_BADSIZE
The dimensions of a current texture are invalid. This can occur when an application attempts to use a texture that has non-power-of-two dimensions with a device that requires them.
D3DERR_TEXTURE_CREATE_FAILED
The texture handle for the texture could not be retrieved from the driver.
D3DERR_TEXTURE_DESTROY_FAILED
The device was unable to deallocate the texture memory.
D3DERR_TEXTURE_GETSURF_FAILED
The DirectDraw surface used to create the texture could not be retrieved.
D3DERR_TEXTURE_LOAD_FAILED
The texture could not be loaded.
D3DERR_TEXTURE_LOCK_FAILED
The texture could not be locked.
D3DERR_TEXTURE_LOCKED
The requested operation could not be completed because the texture surface is currently locked.
D3DERR_TEXTURE_NO_SUPPORT
The device does not support texture mapping.
D3DERR_TEXTURE_NOT_LOCKED
The requested operation could not be completed because the texture surface is not locked.
D3DERR_TEXTURE_SWAP_FAILED
The texture handles could not be swapped.
D3DERR_TEXTURE_UNLOCK_FAILED
The texture surface could not be unlocked.
D3DERR_TOOMANYOPERATIONS
The application is requesting more texture filtering operations than the device supports.
D3DERR_TOOMANYPRIMITIVES
The device is unable to render the provided quantity of primitives in a single pass.
D3DERR_UNSUPPORTEDALPHAARG
The device does not support one of the specified texture blending arguments for the alpha channel.
D3DERR_UNSUPPORTEDALPHAOPERATION
The device does not support one of the specified texture blending operations for the alpha channel.
D3DERR_UNSUPPORTEDCOLORARG
The device does not support the one of the specified texture blending arguments for color values.
D3DERR_UNSUPPORTEDCOLOROPERATION
The device does not support the one of the specified texture blending operations for color values.
D3DERR_UNSUPPORTEDFACTORVALUE
The specified texture factor value is not supported by the device.
D3DERR_UNSUPPORTEDTEXTUREFILTER
The specified texture filter is not supported by the device.
D3DERR_VBUF_CREATE_FAILED
The vertex buffer could not be created. This can happen when there is insufficient memory to allocate a vertex buffer.
D3DERR_VERTEXBUFFERLOCKED
The requested operation could not be completed because the vertex buffer is locked.
D3DERR_VERTEXBUFFEROPTIMIZED
The requested operation could not be completed because the vertex buffer is optimized. (The contents of optimized vertex buffers are driver specific, and considered private.)
D3DERR_VERTEXBUFFERUNLOCKFAILED
The vertex buffer could not be unlocked because the vertex buffer memory was overrun. Make sure that your application does not write beyond the size of the vertex buffer.
D3DERR_VIEWPORTDATANOTSET
The requested operation could not be completed because viewport parameters have not yet been set. Set the viewport parameters by calling Direct3DDevice7.SetViewport method and try again.
D3DERR_VIEWPORTHASNODEVICE
The requested operation could not be completed because the viewport has not yet been associated with a device.
D3DERR_WRONGTEXTUREFORMAT
The pixel format of the texture surface is not valid.
D3DERR_ZBUFF_NEEDS_SYSTEMMEMORY
The requested operation could not be completed because the specified device requires system-memory depth-buffer surfaces. (Software rendering devices require system-memory depth buffers.)
D3DERR_ZBUFF_NEEDS_VIDEOMEMORY
The requested operation could not be completed because the specified device requires video-memory depth-buffer surfaces. (Hardware-accelerated devices require video-memory depth buffers.)
D3DERR_ZBUFFER_NOTPRESENT
The requested operation could not be completed because the render target surface does not have an attached depth buffer.


Direct3D Immediate Mode Tools and Samples

This section describes sample applications included with the Microsoft® DirectX® SDK that demonstrate the use of Microsoft® Direct3D® Immediate Mode. Descriptions are organized as follows:

  • Direct3D Immediate Mode Tools
  • Direct3D Immediate Mode C++ Samples
  • Direct3D Immediate Mode Visual Basic Samples


Direct3D Immediate Mode Tools

This section describes the following tool supplied with the DirectX Software Development Kit (SDK):

  • MFCTex Tool


MFCTex Tool

Description

MFCTex is an interactive tool that lets you experiment with multiple texture blending and see the results instantly. The tool also generates the necessary code for achieving the desired effect.

Path

Source: (SDK root)\Samples\Multimedia\D3dim\Src\Mfctex

Executable: (SDK root)\Samples\Multimedia\D3dim\Bin\Mfctex.exe

User's Guide

Select up to three bitmaps, and change the parameters by using the text boxes and drop-down lists. To use fewer than three states, leave one of the Texture File text boxes blank.

When you have achieved an effect that you want to use in your application, click View Code, and copy all the text from the Direct3D Texture Stage Code dialog box.

For information on the parameters that you can change, see Multiple Texture Blending.


Direct3D Immediate Mode C++ Samples

[Visual Basic]

This section pertains only to application development in C++. See Direct3D Immediate Mode Visual Basic Samples.

[C++]

This section provides descriptions of sample applications provided with the DirectX SDK that are primarily intended to demonstrate how to use Direct3D Immediate Mode. The following samples are described:

  • Bend Sample
  • Billboard Sample
  • Boids Sample
  • BumpEarth Sample
  • BumpWaves Sample
  • ClipMirror Sample
  • Compress Sample
  • D3DFrame Library
  • Dolphin Sample
  • EnumTex Sample
  • EnvCube Sample
  • Filter Sample
  • Fireworks Sample
  • Flare Sample
  • LightMap Sample
  • Lights Sample
  • MFCFog Sample
  • MipMap Sample
  • MTexture Sample
  • ScreenSaver Sample
  • ShadowVol Sample
  • ShadowVol2 Sample
  • Spheremap Sample
  • StencilDepth Sample
  • StencilMirror Sample
  • VBuffer Sample
  • VideoTex Sample
  • WBuffer Sample
  • XFile Sample

Note Most of the sample applications have a common interface (found in the D3DFrame Library) that has no menu bar. In addition to normal Microsoft® Windows® functions (minimize, maximize, restore, resize, and close), the interface supports the following commands:

Key/input | Command
ESC | Quit
F1 | Help/About dialog box (lists these keystrokes)
F2 | Device options
ALT+ENTER | Toggle between full-screen and windowed mode
Right mouse button | Display options popup menu.

The device options dialog box allows the user to change the driver, Direct3D device, or display mode (full-screen only) at run time. Not all devices can support rendering in a window at all display depths. Three-dimensional (3-D) hardware has finite video memory that may be exceeded for certain display modes and window sizes. In either case, the samples display a message and default to a software rasterizer.

Although DirectX samples include Microsoft® Visual C++® project workspace files, you might need to verify other settings in your development environment to ensure that the samples compile properly. For more information, see Compiling DirectX Samples and Other DirectX Applications.

See Also

Direct3D Immediate Mode C/C++ Tutorials


Bend Sample

[Visual Basic]

This topic pertains only to application development in C++. See Direct3D Immediate Mode Visual Basic Samples.

[C++]

Description

The Bend sample demonstrates a technique called surface skinning. It displays a 3-D object, which rotates about the y-axis and appears to bend.

Path

Source: (SDK root)\Samples\Multimedia\D3dim\Src\Bend

Executable: (SDK root)\Samples\Multimedia\D3dim\Bin\Bend.exe

User's Guide

Press F1 to see available commands, or choose from the menu.

Programming Notes

The sample achieves the surface-skinning effect by using two static copies of the object, one of which is oscillating along an axis. At each frame, the vertices of the two objects are merged and blended into a third object. The sample displays the object derived from the third set of vertices.

This sample was built using the Direct3D sample framework.


Billboard Sample

[Visual Basic]

This topic pertains only to application development in C++. See Direct3D Immediate Mode Visual Basic Samples.

[C++]

Description

The Billboard sample demonstrates the billboarding technique. Billboarding is a way of making two-dimensional (2-D) sprites appear to be 3-D. It can also be used for smoke, clouds, vapor trails, energy blasts, and so on. For more information, see Common Techniques and Special Effects.

Path

Source: (SDK root)\Samples\Multimedia\D3dim\Src\Billboard

Executable: (SDK root)\Samples\Multimedia\D3dim\Bin\Billboard.exe

User's Guide

Press F1 to see available commands, or choose from the menu.

Programming Notes

The sample displays a grassy field with trees in it. The trees look like 3-D objects. However, they are actually 2-D texture bitmaps that are blended onto invisible rectangular polygons.

As the sample runs, the viewpoint changes. Each time it does, all the billboard polygons that the trees are painted onto are rotated so that they face the viewer. The sample then blends the images of the trees onto the billboard polygons. The trees appear to be 3-D because they can be viewed from all angles. However, close inspection reveals that the trees have exactly the same appearance from all angles. For many applications, this minor drawback is not noticeable.

The shadows are also 2-D textures.

This sample was built using the Direct3D sample framework.


Boids Sample

[Visual Basic]

This topic pertains only to application development in C++. See Direct3D Immediate Mode Visual Basic Samples.

[C++]

Description

The Boids sample shows how to write a Direct3D application. Using a flocking algorithm, the sample moves a group of 3-D objects over a simple landscape.

Path

Source: (SDK root)\Samples\Multimedia\D3dim\Src\Boids

Executable: (SDK root)\Samples\Multimedia\D3dim\Bin\Boids.exe

User's Guide

Press F1 to see available commands, or choose from the menu.

Programming Notes

The Boids sample demonstrates the fundamentals of creating a 3-D environment and animating a group of objects in it.


BumpEarth Sample

[Visual Basic]

This topic pertains only to application development in C++. See Direct3D Immediate Mode Visual Basic Samples.

[C++]

Description

The BumpEarth sample demonstrates the bump-mapping capabilities of Direct3D. Bump mapping is a texture-blending technique used to render the appearance of rough surfaces.

Path

Source: (SDK root)\Samples\Multimedia\D3dim\Src\BumpEarth

Executable: (SDK root)\Samples\Multimedia\D3dim\Bin\BumpEarth.exe

User's Guide

Press F1 to see available keystroke commands, or choose from the menu.

Your graphics hardware might not support bump mapping; if not, Direct3D displays a message to that effect when you attempt to run this sample. The solution is to enable the reference rasterizer by running (SDK root))\Samples\Multimedia\D3dim\Bin\Enablerefrast.reg.

Programming Notes

Bump mapping is an advanced multitexture blending technique that can be used to render the appearance of rough surfaces. The bump map itself is a texture that stores the perturbation data.

In this sample, the map of the world is a texture. The sample blends both the map texture and the bump-map texture onto the sphere to give the appearance of a high-resolution topographical map.

For more information, see Bump Mapping and the BumpWaves Sample.

This sample was built using the Direct3D sample framework.


BumpWaves Sample

[Visual Basic]

This topic pertains only to application development in C++. See Direct3D Immediate Mode Visual Basic Samples.

[C++]

Description

The BumpWaves sample simulates reflections off waves, using bump mapping.

Path

Source: (SDK root)\Samples\Multimedia\D3dim\Src\BumpWaves

Executable: (SDK root)\Samples\Multimedia\D3dim\Bin\BumpWaves.exe

User's Guide

Press F1 to see available keystroke commands, or choose from the menu.

Your graphics hardware might not support bump mapping; if not, Direct3D displays a message to that effect when you attempt to run this sample. The solution is to enable the reference rasterizer. You can do so by running (SDK root)\Samples\Multimedia\D3dim\Bin\Enablerefrast.reg.

Programming Notes

For more information, see Bump Mapping and the BumpEarth Sample.

The sample was built using the Direct3D sample framework.


ClipMirror Sample

[Visual Basic]

This topic pertains only to application development in C++. See Direct3D Immediate Mode Visual Basic Samples.

[C++]

Description

The ClipMirror sample shows how to use clip planes to implement a planar mirror.

Path

Source: (SDK root)\Samples\Multimedia\D3dim\Src\ClipMirror

Executable: (SDK root)\Samples\Multimedia\D3dim\Bin\ClipMirror.exe

User's Guide

Press F1 to see available commands, or choose from the menu.

Programming Notes

The scene is reflected in a mirror and rendered in a second pass. The corners of the mirrors, together with the camera eye point, are used to define a custom set of clip planes so that the reflected geometry appears only within the mirror's boundaries.


Compress Sample

[Visual Basic]

This topic pertains only to application development in C++. See Direct3D Immediate Mode Visual Basic Samples.

[C++]

Description

The Compress sample shows how to load the DDS file format into a compressed texture surface. DDS textures can be created using DxTex included with the DirectDraw tools in the DirectX SDK.

Path

Source: (SDK root)\Samples\Multimedia\D3dim\Src\Compress

Executable: (SDK root)\Samples\Multimedia\D3dim\Bin\Compress.exe

User's Guide

Press F1 to see available commands, or choose from the menu.

Programming Notes

The file format is called DDS because it encapsulates the information in a DirectDrawSurface. The data can be read directly into a surface of a matching format.

The ReadDDSTexture function demonstrations how a DDS surface is read from a file.

A DDS file has the following format:

DWORD dwMagic | (0x20534444, or "DDS ")
DDSURFACEDESC2 ddsd | Information about the surface format
BYTE bData1[] | Data for the main surface
[BYTE bData2[]] | Data for attached surfaces, if any, follows.

This format is easy to read and write, and it supports features such as alpha and multiple MIP levels, as well as DXTn compression. If it uses DXTn compression, it can be one of five compressed types. See Compressed Texture Surfaces.

After the texture is read in, a pixel format must be chosen that is supported by the renderer. In the sample, the supported pixel formats are enumerated and stored in a linked list. After the pixel formats are collected, the list is searched for a best match, using the FindBestPixelFormatMatch function.

Some Direct3D devices, such as the reference rasterizer and some hardware devices, can render compressed textures directly. For renderers that do not directly support this, the compressed surface must be blitted to a noncompressed surface. The BltToUncompressedSurface function shows how this is done.


D3DFrame Library

[Visual Basic]

This topic pertains only to application development in C++. See Direct3D Immediate Mode Visual Basic Samples.

[C++]

Description

The D3D framework is a set of C++ classes used to create the Direct3D Immediate Mode samples. It is not a part of the Direct3D API. The framework was created and used to provide consistency and clarity of presentation for the Direct3D samples. The framework classes may or may not be appropriate for use in your applications.

Path

Source: (SDK root)\Samples\Multimedia\D3dim\Src\D3DFrame

Executable: None.

User's Guide

D3DFrame compiles as a static library, which is used to build the remainder of the Direct3D Immediate Mode samples.

Programming Notes

The framework consists of classes that enumerate the DirectDraw drivers, Direct3D devices, and display modes available to each device. The samples use them to initialize and run Direct3D. The classes also help provide a consistent user interface for the set of samples. In addition, the framework includes a set of classes for loading and managing textures.

The Direct3D framework also contains numerous macros and functions for debugging, for manipulating Direct3D objects, and for doing math operations common in Direct3D programming.


Dolphin Sample

[Visual Basic]

This topic pertains only to application development in C++. See Direct3D Immediate Mode Visual Basic Samples.

[C++]

Description

The Dolphin sample is a simple 3-D application that uses an animated model and textures.

Path

Source: (SDK root)\Samples\Multimedia\D3dim\Src\Dolphin

Executable: (SDK root)\Samples\Multimedia\D3dim\Bin\Dophin.exe

User's Guide

Press F1 to see available commands, or choose from the menu.

Programming Notes

The dolphin is loaded as three separate meshes, which are linearly interpolated to produce the final mesh.


EnumTex Sample

[Visual Basic]

This topic pertains only to application development in C++. See Direct3D Immediate Mode Visual Basic Samples.

[C++]

Description

The EnumTex sample demonstrates the recommended way of enumerating texture formats.

Path

Source: (SDK root)\Samples\Multimedia\D3dim\Src\Dolphin

Executable: None.

User's Guide

No executable is included with the SDK because this sample does nothing visible.

Programming Notes

It is important to enumerate textures correctly so that applications remain compatible as new texture formats become available. The sample code shows how to do this.


EnvCube Sample

[Visual Basic]

This topic pertains only to application development in C++. See Direct3D Immediate Mode Visual Basic Samples.

[C++]

Description

This sample shows how to implement cube mapping, which is a new environment-mapping technique implemented in DirectX 7.0.

Path

Source: (SDK root)\Samples\Multimedia\D3dim\Src\EnvCube

Executable: (SDK root)\Samples\Multimedia\D3dim\Bin\EnvCube.exe

User's Guide

Press F1 to see available commands, or choose from the menu.

Programming Notes

A cube map is a special texture surface created by rendering a scene in six orthogonal directions. It is then used for traditional environment-mapping effects.


Filter Sample

[Visual Basic]

This topic pertains only to application development in C++. See Direct3D Immediate Mode Visual Basic Samples.

[C++]

Description

The Filter sample demonstrates the texture-filtering techniques that Direct3D supports. Direct3D texture-filtering techniques enable applications to achieve greater realism in the appearance of rendered primitives. For more information, see Texture Filtering.

Path

Source: (SDK root)\Samples\Multimedia\D3dim\Src\Filter

Executable: (SDK root)\Samples\Multimedia\D3dim\Bin\Filter.exe

User's Guide

When the sample begins, it displays two rectangular primitives with textures on them.

In addition to the usual commands listed in the About dialog box when you press F1, this sample has a main menu.

The File menu contains choices for pausing and resuming the sample, changing the Direct3D device, and exiting. You can also pause and resume the sample by pressing the ENTER key.

The Left Pane menu controls the texture-filtering methods that the sample uses for magnification and reduction of the 3-D primitive on the left side of the screen. It also has options for edge antialiasing and anisotropic texture filtering. You might have to enable the software reference rasterizer to view the effects of these options. To enable the reference rasterizer, run (SDK root)\Samples\Multimedia\D3dim\Bin\Enablerefrast.reg.

The Right Pane menu allows you to set the filtering methods that the sample uses to perform magnification and reduction when it renders the primitive on the right side of the screen.

Programming Notes

This sample demonstrates nearest-point sampling, linear filtering, and anisotropic texture filtering. It shows how to enable and disable anisotropy. In addition, this sample shows how to enable edge antialiasing.


Fireworks Sample

[Visual Basic]

This topic pertains only to application development in C++. See Direct3D Immediate Mode Visual Basic Samples.

[C++]

Description

The Fireworks sample implements a system of particles simulating a fireworks explosion. Particles are popular in games to show effects like smoke, sparks, and explosions.

Path

Source: (SDK root)\Samples\Multimedia\D3dim\Src\Fireworks

Executable: (SDK root)\Samples\Multimedia\D3dim\Bin\Fireworks.exe

User's Guide

Press F1 to see available commands, or choose from the menu.

Programming Notes

The fireworks explosion is simulated by using a system of particles; each particle is rendered with a partially transparent texture map of a sphere. The position and color of each particle are governed by parameterized equations and are updated in each frame.


Flare Sample

[Visual Basic]

This topic pertains only to application development in C++. See Direct3D Immediate Mode Visual Basic Samples.

[C++]

Description

The Flare sample shows how to create a lens flare effect, using alpha blending.

Path

Source: (SDK root)\Samples\Multimedia\D3dim\Src\Flare

Executable: (SDK root)\Samples\Multimedia\D3dim\Bin\Flare.exe

User's Guide

Press F1 to see available commands, or choose from the menu.

Programming Notes

In this sample, lens flare is simulated with mathematical functions that govern the position of each flare. The flares are rendered using additive alpha blending and animated to give a sparkle effect.


LightMap Sample

[Visual Basic]

This topic pertains only to application development in C++. See Direct3D Immediate Mode Visual Basic Samples.

[C++]

Description

This sample shows how to use multitexturing and multipass techniques to create some complex lighting effects. It shows a light swinging in a room, which dynamically lights up the walls and ceiling as the light moves.

Path

Source: (SDK root)\Samples\Multimedia\D3dim\Src\LightMap

Executable: (SDK root)\Samples\Multimedia\D3dim\Bin\Lightmap.exe

User's Guide

On the Options menu, choose between multipass and multiple-texture blending. The latter is not available if your hardware does not support it.

Press F1 to see other available commands, or choose from the menu.

Programming Notes

There is no true lighting in this sample—everything is done with light maps. Light maps are extremely useful in games because they are much faster than real lighting. In addition, real lighting is calculated only at the vertices, so highly tessellated meshes are required.


Lights Sample

[Visual Basic]

This topic pertains only to application development in C++. See Direct3D Immediate Mode Visual Basic Samples.

[C++]

Description

The Lights sample shows how to turn on and move the various types of Direct3D lights. The lights fly around, illuminating the scene, and switch every few seconds to a new type of light.

Path

Source: (SDK root)\Samples\Multimedia\D3dim\Src\Lights

Executable: (SDK root)\Samples\Multimedia\D3dim\Bin\Lights.exe

User's Guide

Press F1 to see available commands, or choose from the menu.

Programming Notes

This sample shows how to set up the light properties for each of the types of lights available. It also shows how to dynamically orient the lights on each frame.


MFCFog Sample

[Visual Basic]

This topic pertains only to application development in C++. See Direct3D Immediate Mode Visual Basic Samples.

[C++]

Description

The MFCFog sample does a fly-by over some terrain and allows you to see the effects of various fog parameters.

Path

Source: (SDK root)\Samples\Multimedia\D3dim\Src\MFCFog

Executable: (SDK root)\Samples\Multimedia\D3dim\Bin\Mfcfog.exe

User's Guide

Change parameters by using the controls. For information on the parameters, see Fog. The effects are most striking in full-screen mode.

Programming Notes

Games that use terrain typically turn on fog so that they can prevent the rendering of objects in the far distance.


MipMap Sample

[Visual Basic]

This topic pertains only to application development in C++. See Direct3D Immediate Mode Visual Basic Samples.

[C++]

Description

This sample shows two brick walls moving back and forth along the z-axis. One uses mipmapping, and the other does not, giving a side-by-side comparison of the benefits of mipmapping.

Path

Source: (SDK root)\Samples\Multimedia\D3dim\Src\MipMap

Executable: (SDK root)\Samples\Multimedia\D3dim\Bin\Mipmap.exe

User's Guide

Press F1 to see available commands, or choose from the menu.

Programming Notes

This sample does not use the texture code of D3DFrame, but shows the full implementation needed to load and build mipmapped textures.


MTexture Sample

[Visual Basic]

This topic pertains only to application development in C++. See Direct3D Immediate Mode Visual Basic Samples.

[C++]

Description

The MTexture sample shows how to use multitexturing. The scene consists of a room with walls that have a base texture and a spotlight texture, each using a different set of texture coordinates.

Path

Source: (SDK root)\Samples\Multimedia\D3dim\Src\MTexture

Executable: (SDK root)\Samples\Multimedia\D3dim\Bin\Mtexture.exe

User's Guide

Press F1 to see available commands, or choose from the menu.

Programming Notes

This sample shows how to program the multitexture stages, using the IDirect3DDevice7::SetTextureStageState method. Dozens of different effects are possible with this method. The sample shows one, monochrome light mapping, which is very popular in current game titles.


ScreenSaver Sample

[Visual Basic]

This topic pertains only to application development in C++. See Direct3D Immediate Mode Visual Basic Samples.

[C++]

Description

The ScreenSaver sample shows how to create a Direct3D screen saver.

Path

Source: (SDK root)\Samples\Multimedia\D3dim\Src\ScreenSaver

Executable: None

User's Guide

When you compile the code, the output file is D3DBend.scr. You can view the screen saver by double-clicking on this file. To make it available in the Windows Display Properties dialog box, copy it to the \Windows\System directory.

Programming Notes

The startup code is in Scrnsave.lib.

For more information about compiling screen savers, see the Screen Saver Library topic in the Platform SDK User Interface Services documentation.


ShadowVol Sample

[Visual Basic]

This topic pertains only to application development in C++. See Direct3D Immediate Mode Visual Basic Samples.

[C++]

Description

The ShadowVol sample shows how to create and use stencil buffers to implement shadow volumes. With shadow volumes, an object of any shape can cast a shadow onto another object of any shape.

Path

Source: (SDK root)\Samples\Multimedia\D3dim\Src\ShadowVol

Executable: (SDK root)\Samples\Multimedia\D3dim\Shadowvol.exe

User's Guide

This sample runs only on devices that support stencil buffers.

Press F1 to see available commands, or choose from the menu.

Programming Notes

Shadow volumes are a fairly advanced technique.

To create shadow volumes

  1. Build a set of polygonal faces that encompass the volume of the shadow.
  2. Use the stencil buffer to render the front-facing planes of the shadow volume.
  3. Set up the stencil buffer to render the back-facing planes, this time subtracting values from the stencil buffer. The stencil buffer then contains a mask of the cast shadow.
  4. Draw a large gray or black rectangle, using the stencil buffer as a mask, and the frame buffer will be updated with the shadow.


ShadowVol2 Sample

[Visual Basic]

This topic pertains only to application development in C++. See Direct3D Immediate Mode Visual Basic Samples.

[C++]

Description

The ShadowVol2 sample shows how to create and use stencil buffers to implement shadow volumes, which are used to cast shadows on objects of any complexity. It is an extension of the ShadowVol Sample.

Path

Source: (SDK root)\Samples\Multimedia\D3dim\Src\ShadowVol2

Executable: (SDK root)\Samples\Multimedia\D3dim\Bin\Shadowvol2.exe

User's Guide

This sample runs only on devices that support stencil buffers.

Press F1 to see available commands, or choose from the menu.

The following options are available on the Shadow Modes menu:

  • Draw Shadows: Check this option to enable shadow rendering.
  • Show Shadow Volumes: Instead of shadows, draw the shadow volumes used to compute them.
  • Draw Shadow Volume Caps: If this is turned on, the end surfaces of the shadow volumes are drawn.
  • 1-Bit Stencil Mode: Use a different algorithm that uses only a 1-bit stencil buffer and in which overlapping shadows are not allowed. If the device supports only a 1-bit stencil, you cannot switch out of this mode.
  • Z-Order Shadow Vols: In 1-bit mode, shadow volumes must be rendered front to back, so rendering might be incorrect unless this option is checked.

Programming Notes

Shadow volumes are a technique for casting shadows onto arbitrary nonplanar surfaces. The effect is achieved by constructing a shadow volume with respect to the light source and the object that casts the shadow. In this sample, the light source is a directional light whose direction circles about points on the plane, and the shadow volume is computed by projecting the vertices of the object that casts the shadow onto a plane perpendicular to the light, finding the 2-D convex hull of these points in the plane and extruding the 2-D hull in the light direction to form the 3-D shadow volume. The shadow volume must extend far enough that it covers any geometry that is in shadow. This particular shadow-volume computation requires that the shadow caster be a convex object.

The rendering proceeds as follows:

  1. The geometry is rendered as normal.
  2. The shadow volume is rendered without writing to the z or color buffer.

    Alpha blending is used here to avoid writing to the color buffer. Every place the shadow volume appears is marked in the stencil buffer.

  3. The culling order is reversed, and the back faces of the shadow volume are rendered, this time unmarking all the pixels that are covered in the stencil buffer.

    These have passed the z-test, and thus are visible behind the back of the shadow volume; they are not in shadow. The pixels still marked are those that lie inside the front and back bounds of the shadow volume and are thus in shadow.

  4. The pixels that are still marked are blended with a large black rectangle that covers the viewport, generating the shadow.


Spheremap Sample

[Visual Basic]

This topic pertains only to application development in C++. See Direct3D Immediate Mode Visual Basic Samples.

[C++]

Description

This sample loads a 3-D object and renders it, using a sphere map.

Path

Source: (SDK root)\Samples\Multimedia\D3dim\Src\Spheremap

Executable: (SDK root)\Samples\Multimedia\D3dim\Bin\Spheremap.exe

User's Guide

Press F1 to see available commands, or choose from the menu.

Programming Notes

The sphere map itself is a special, preconstructed texture map containing a 180-degree view of an environment. Before a frame is rendered, the object's normals are used to compute the texture coordinates for each vertex of the object. When rendered, the object looks as if it reflects the environment.


StencilDepth Sample

[Visual Basic]

This topic pertains only to application development in C++. See Direct3D Immediate Mode Visual Basic Samples.

[C++]

Description

The StencilDepth sample shows how to use a stencil buffer to visualize the depth complexity of a scene.

Path

Source: (SDK root)\Samples\Multimedia\D3dim\Src\StencilDepth

Executable: (SDK root)\Samples\Multimedia\D3dim\Bin\StencilDepth.exe

User's Guide

Press F1 to see available commands, or choose from the menu.


StencilMirror Sample

[Visual Basic]

This topic pertains only to application development in C++. See Direct3D Immediate Mode Visual Basic Samples.

[C++]

Description

The StencilMirror sample shows how to use a stencil buffer to implement planar mirrors of any shape in a scene.

Path

Source: (SDK root)\Samples\Multimedia\D3dim\Src\StencilMirror

Executable: (SDK root)\Samples\Multimedia\D3dim\Bin\StencilMirror.exe

User's Guide

Press F1 to see available commands, or choose from the menu.


VBuffer Sample

[Visual Basic]

This topic pertains only to application development in C++. See Direct3D Immediate Mode Visual Basic Samples.

[C++]

Description

This sample shows how to use vertex buffers.

Path

Source: (SDK root)\Samples\Multimedia\D3dim\Src\VBuffer

Executable: (SDK root)\Samples\Multimedia\D3dim\Bin\VBuffer.exe

User's Guide

Press F1 to see available commands, or choose from the menu.

Programming Notes

Before vertex buffers, geometry rendering was accomplished by using an array of vertices passed to the DrawPrimitive function. Vertex buffers are more useful, but need to be specifically created, locked, filled, and unlocked before being rendered with the new DrawPrimitiveVB function.


VideoTex Sample

[Visual Basic]

This topic pertains only to application development in C++. See Direct3D Immediate Mode Visual Basic Samples.

[C++]

Description

The VideoTex sample shows how to use an .avi file as a texture map.

Path

Source: (SDK root)\Samples\Multimedia\D3dim\Src\VideoTex

Executable: (SDK root)\Samples\Multimedia\D3dim\Bin\Videotex.exe

User's Guide

Press F1 to see a list of the usual commands, or choose from the menu.

Programming Notes

The sample draws a cube with an .avi texture mapped to each of its faces. The texture's surface must use the DDSCAPS2_HINTDYNAMIC flag.


WBuffer Sample

[Visual Basic]

This topic pertains only to application development in C++. See Direct3D Immediate Mode Visual Basic Samples.

[C++]

Description

The WBuffer sample shows how to use w-buffering.

Path

Source: (SDK root)\Samples\Multimedia\D3dim\Src\WBuffer

Executable: (SDK root)\Samples\Multimedia\D3dim\Bin\WBuffer.exe

User's Guide

Press F1 to see a list of the usual commands, or choose from the menu. In addition, you can change the buffering mechanism by pressing W (w-buffering, if supported), Z (z-buffering), or N (no buffering). Note the artifacts that appear when using z-buffering.

Programming Notes

W-buffering is a depth-buffering alternative to z-buffering and should be used in cases where z-buffering produces artifacts. W-buffering quantizes the depth buffer much better.


XFile Sample

[Visual Basic]

This topic pertains only to application development in C++. See Direct3D Immediate Mode Visual Basic Samples.

[C++]

Description

This sample shows how to load and render .x files.

Path

Source: (SDK root)\Samples\Multimedia\D3dim\Src\XFile

Executable: (SDK root)\Samples\Multimedia\D3dim\Bin\XFile.exe

User's Guide

When you run the sample, an Open File dialog box appears. You can find some .x files in the media folder of the D3DIM samples directory. If there is a .bmp file of the same name in the directory, it is automatically used as a texture for the object.

Press F1 to see available commands. In addition, you can load a different file from the File menu.

Programming Notes

If a texture appears upside-down on an object that you have loaded, it is because of the way the object loads the texture. An earlier version of Direct3D loaded bitmaps upside-down, so the creators of some .x files compensated by reversing the coordinates.


Direct3D Immediate Mode Visual Basic Samples

[C++]

This section pertains only to application development in Visual Basic. See Direct3D Immediate Mode C++ Samples.

[Visual Basic]

This section provides descriptions of sample applications provided with the DirectX® SDK that are primarily intended to demonstrate how to use the Direct3D® component in Immediate Mode. The following sample programs are described:

  • Billboard Sample
  • Fireworks Sample
  • IMControl Sample
  • MipMap Sample
  • PPlane Sample
  • Tunnel Sample
  • VBuffer Sample
  • XFile Sample

Most of the sample programs use the IMControl custom control as a common rendering canvas. This control implements the F5 key for bringing up a device options dialog box. This dialog box allows the user to change the driver, Direct3D device, or display mode (full-screen only) at run time.

See Also

Direct3D Immediate Mode Visual Basic Tutorials


Billboard Sample

[C++]

This topic pertains only to application development in Visual Basic. See Direct3D Immediate Mode C++ Samples.

[Visual Basic]

Description

This sample illustrates the billboarding technique. Billboarding is a way of making 2-D sprites appear to be 3-D. It can also be used for smoke, clouds, vapor trails, energy blasts, and other effects. For more information, see Common Techniques and Special Effects.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\D3dim\Src\Billboard

Executable: (SDK root)\Samples\Multimedia\VBSamples\D3dim\Bin\VB_Billboard.exe

User's Guide

Press F5 to change the device or display mode.

Programming Notes

The sample displays a grassy field with trees in it. The trees look like 3-D objects. However, they are actually 2-D texture bitmaps that are blended onto invisible rectangular polygons.

As the sample program executes, the viewpoint changes. Each time it does, all of the billboard polygons that the trees are painted onto are rotated so they face the viewer. The program then blends the images of the trees onto the billboard polygons. The trees appear to be 3-D because they can be viewed from all angles. However, close inspection reveals that the trees have exactly the same appearance from all angles. For many applications, users will not notice this minor drawback.

The shadows are also 2-D textures.


Fireworks Sample

[C++]

This topic pertains only to application development in Visual Basic. See Direct3D Immediate Mode C++ Samples.

[Visual Basic]

Description

This sample uses 3-D particles to simulate a fireworks explosion.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\D3dim\Src\Fireworks

Executable: (SDK root)\Samples\Multimedia\VBSamples\D3dim\Bin\VB_Fireworks.exe

User's Guide

Press F5 to change the device or display mode.

Programming Notes

The Fireworks sample demonstrates simple particle systems using Direct3D Immediate Mode textures and alpha blending. Each particle is rendered as a partially transparent texture map of a sphere.


IMControl Sample

[C++]

This topic pertains only to application development in Visual Basic. See Direct3D Immediate Mode C++ Samples.

[Visual Basic]

Description

This sample is a control that can be used in an application to render a 3-D scene. It is used in most of the other Visual Basic Direct3D samples.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\D3dim\Src\Imcontrol

Executable: (SDK root)\Samples\Multimedia\VBSamples\D3dim\Bin\Imcontrol.exe

User's Guide

For an example of how Imcontrol.ocx can be integrated into a 3-D application, see the Billboard sample. Most of the other samples also use this control.

Programming Notes

The control handles the initialization of DirectDraw and Direct3D in full-screen and windowed modes, as well as implementing the F5 key for displaying a dialog box that allows the user to change the device and configuration.


MipMap Sample

[C++]

This topic pertains only to application development in Visual Basic. See Direct3D Immediate Mode C++ Samples.

[Visual Basic]

Description

The MipMap sample demonstrates mip-mapped textures.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\D3dim\Src\Mipmap

Executable: (SDK root)\Samples\Multimedia\VBSamples\D3dim\Bin\VB_MipMap.exe

User's Guide

Press F5 to change the device or display mode.

Programming Notes

The sample presents a comparison between two sets of polygons: one with a constant single texture applied, and a second that uses a set of mipmapped textures.


PPlane Sample

[C++]

This topic pertains only to application development in Visual Basic. See Direct3D Immediate Mode C++ Samples.

[Visual Basic]

Description

The PPlane sample animates paper airplanes over a flat surface.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\D3dim\Src\PPlane

Executable: (SDK root)\Samples\Multimedia\VBSamples\D3dim\Bin\VB_pplanes.exe

User's Guide

Press F5 to change the device or display mode.


Tunnel Sample

[C++]

This topic pertains only to application development in Visual Basic. See Direct3D Immediate Mode C++ Samples.

[Visual Basic]

Description

The Tunnel sample simulates a voyage down a tunnel.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\D3dim\Src\Tunnel

Executable: (SDK root)\Samples\Multimedia\VBSamples\D3dim\Bin\VB_tunnel.exe

User's Guide

Press F5 to change the device or display mode.


VBuffer Sample

[C++]

This topic pertains only to application development in Visual Basic. See Direct3D Immediate Mode C++ Samples.

[Visual Basic]

Description

This sample shows how to use vertex buffers.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\D3dim\Src\VBuffer

Executable: (SDK root)\Samples\Multimedia\VBSamples\D3dim\Bin\VB_vertexBuffer.exe

User's Guide

Press F5 to change the device or display mode.

Programming Notes

Before vertex buffers, geometry rendering was accomplished by using an array of vertices passed to DrawPrimitive calls. Vertex buffers are more useful, but need to be specifically created, locked, filled, and unlocked before being rendered with the new DrawPrimitiveVB calls.


XFile Sample

[C++]

This topic pertains only to application development in Visual Basic. See Direct3D Immediate Mode C++ Samples.

[Visual Basic]

Description

The XFile sample is a viewer for 3-D image files in DirectX format.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\D3dim\Src\XFile

Executable: (SDK root)\Samples\Multimedia\VBSamples\D3dim\Bin\VB_XFile.exe

User's Guide

Load a file by selecting Open from the File menu. There are some sample .x files in the (SDK root)\Samples\Multimedia\VBSamples\D3DRM\media folder. Rotate the image by dragging the mouse anywhere in the window. Spin the image by releasing the mouse button while dragging, or by pressing an arrow key. Move the image closer or farther by using the plus and minus keys. Change the appearance of the object by selecting from the Fill Options and Shade Options menus.

Programming Notes

The core functionality for loading files is provided by XFileClass, which uses Direct3D Retained Mode.


Direct3DX Utility Library [C++]

The Direct3DX utility library is part of the three-dimensional (3-D) graphics component of DirectX®. Information on the Direct3DX utility library is organized into the following topics:

  • About the Direct3DX Utility Library
  • Why Use the Direct3DX Utility Library?
  • Direct3DX Utility Library Architecture
  • Direct3DX Utility Library Essentials
  • Direct3DX Utility Library Reference
  • Direct3DX Utility Library Samples


About the Direct3DX Utility Library

The Direct3DX Utility Library application programming interface (API), based on COM, is a helper layer that sits on top of the Direct3D® and DirectDraw® components of DirectX 7.0. It is designed as a set of header files and a library (d3dx.lib or d3dxd.lib) that applications can link to statically.

Applications that take advantage of the functionality provided by Direct3DX utility library should link to d3dx.lib. However, for debug applications, it is best to link to the debug version of the library, d3dxd.lib. This version of the library provides parameter and data structure validation, and output debug error messages. When an error occurs, the debug output gives you a more detailed description of the problem. The debug library executes more slowly than the retail version of the library (d3dx.lib), but it is much more useful for debugging an application.

The Direct3DX utility library provides helper functions to simplify the common tasks encountered by 3-D graphics developers. The utility library is an adjunct to Direct3D Immediate Mode, and requires familiarity with the essential aspects of Direct3D Immediate Mode.

The utility library is designed for developers who want a quick and efficient way to use Direct3D Immediate Mode. By eliminating some of the more tedious tasks, the utility library provides a tool-kit of short-cuts, allowing developers to immediately focus on the core application or game development.

The Direct3DX utility library provides helper functionality for enumerating device configurations, setting up a device, running full-screen or windowed mode uniformly, running resizing operations, calculating vector and matrix operations, and simplifying image file loading and texture creation. In addition, it provides functions for drawing simple shapes, sprites, and cube maps. However, Direct3DX does not provide a scene hierarchy or support X Files.

Note that the utility library requires that at least DirectX 7.0 is installed on your system. The Direct3DX utility library supports multiple monitor configurations. Note that none of the Direct3DX objects are multithread-safe. A multithreaded application must add its own locks and synchronization primitives to access Direct3DX objects.

D3DX_DEFAULT is a predefined value that can be used for any parameter of the Direct3DX application programming interfaces (APIs) or member functions that is an enumerant or a handle. The reference section indicates wherever D3DX_DEFAULT may be used, and how it will be interpreted in each situation.

D3DX_DEFAULT_FLOAT is similar to D3DX_DEFAULT, but it is used for floating point parameters.


Why Use the Direct3DX Utility Library?

If you want to use Direct3D Immediate Mode for high-performance 3-D rendering, the Direct3DX utility library will get you started quickly. Developers who want to focus on the performance-critical and application-specific aspects of their work can take advantage of the utility library to increase productivity. The Direct3DX utility library simplifies the following tasks:

  • Setting up a DirectDraw object and Direct3D devices.
  • Drawing simple geometric shapes.
  • Providing hardware independence for textures.
  • Providing color conversions for several surface formats.
  • Loading texture files (BMP, TGA, and DDS).
  • Creating cube-map textures for environmental mapping.
  • Providing sprite support (rotation, alpha, scaling, and warping).
  • Performing common 3-D mathematical operations.

Therefore, if you already have a working engine based on Direct3D Immediate Mode and you need to add some helper functionality, the Direct3DX utility library may be a viable option.

In general, each of the components of the utility library are designed to be reusable and interchangeable. For example, you can use sprites with any Direct3DDevice and DirectDrawSurface object, not just those created with the Direct3DX utility library. Similarly, you can use the math functions or shape creation application programming interface (API) without using any of the other features provided by the Direct3DX utility library.

Finally, if you are porting an application or a game that was based on a non-Direct3D graphics API, you may find that the functionality provided by the Direct3DX utility library will simplify the transition.


Direct3DX Utility Library Architecture

This section provides high-level information about the structure of the Direct3DX utility library. Information is divided into the following topics:

  • Architectural Overview of the Direct3DX Utility Library
  • Direct3DX Utility Library Interfaces and Object Types


Architectural Overview of the Direct3DX Utility Library

The Direct3DX utility library is a helper layer on top of the Direct3D and DirectDraw components of DirectX 7.0. It is comprised of features such as initialization support, texturing support, and sprite support, each of which are largely independent of each other.

The only application programming interface (API) elements that tie the utility library's functionality together are the D3DXInitialize and D3DXUninitialize functions, which are initialization functions.

The following graphic illustrates how the Direct3DX utility library is related to Direct3D and DirectDraw:

Note D3DXInitialize must be called before using the Direct3DX utility library APIs; D3DXUninitialize must be called before the application terminates, freeing the resources allocated by Direct3DX.


Direct3DX Utility Library Interfaces and Object Types

The Direct3DX utility library defines the following COM interfaces:

ID3DXContext | The root interface which is used for state configuration, texture creation, and display updating.
ID3DXMatrixStack | A helper interface that is used for implementing a scene hierarchy.
ID3DXSimpleShape | A vertex-buffer interface that is used for draw primitive-based rendering.

The most fundamental object in the Direct3DX utility library is the D3DXDevice object. This object cannot be created (unlike the D3DXContext and D3DXMatrixStack objects) and does not expose any interfaces. It is simply referred to as an index into the list of Direct3DX Devices that are available on the system. The D3DXDevice object represents the driver that does the rendering and the capabilities of that driver.

For more information, see Direct3DX Devices.

The ID3DXContext interface represents the D3DXContext object. You can create multiple D3DXContext objects for each D3DXDevice object.

The D3DXDevice object encapsulates the following objects:

  • DirectDraw object
  • Direct3D object
  • Direct3DDevice object
  • Various Direct3D and DirectDraw objects, such as clippers and surfaces that are required for rendering.

Creating the D3DXContext object creates all of the preceding objects for your game or application. A pointer to the interface that implements each of these encapsulated objects can be obtained from the context object by calling the following methods:

  • ID3DXContext::GetDD
  • ID3DXContext::GetD3D
  • ID3DXContext::GetD3DDevice

You can think of a D3DXContext object as a rendering context on a particular D3DXDevice object.

The ID3DXMatrixStack interface represents the D3DXMatrixStack object. D3DXMatrixStack is a matrix stack object that implements the matrix stack to enable the manipulation of transformation hierarchies. The ID3DXMatrixStack interface completely defines this object.

The ID3DXSimpleShape interface is exposed through all of the shape objects:

  • D3DXBox
  • D3DXCylinder
  • D3DXPolygon
  • D3DXSphere
  • D3DXTeapot
  • D3DXTorus

For information on the shape objects provided by Direct3DX, see the following topics:

  • Shape Drawing Functions
  • Simple Geometric Shapes

A shape object contains the shape data (the vertex and the index information) that defines the shape. By using the ID3DXSimpleShape interface, you can either draw the shape, or obtain vertex and index information directly from the shape object.


Direct3DX Utility Library Essentials

The Direct3DX utility library consists of application programming interface (API) elements that create objects, encapsulate objects, and manipulate objects.

This section provides technical information about the myriad components of the Direct3DX utility library. Information is divided into the following topics.

  • Direct3DX and Direct3D
  • Direct3DX Context
  • Direct3DX Devices
  • Direct3DX Matrix Stack
  • Hardware Acceleration Levels
  • Sprite Support
  • Texturing Support
  • Simple Geometric Shapes
  • 3-D Math Support

In general, the helper components (sprite support, texturing support, simple geometric shapes, and 3-D math support) that comprise the Direct3DX utility library are independent of each other. This makes it easy for you to take advantage of only the functionality that you want before moving on to implementing your own custom versions of particular sub-components.


Direct3DX and Direct3D

There is a close relationship between Direct3DX and the underlying Direct3D interfaces.

This section is divided into the following topics:

  • Using Direct3DX to Initialize Direct3D and DirectDraw
  • Using Direct3DX to Access Direct3D and DirectDraw

For background information on the close relationship between DirectDraw and Direct3D, see Direct3D and DirectDraw.


Using Direct3DX to Initialize Direct3D and DirectDraw

The Direct3DX utility library provides initialization support for Direct3D and DirectDraw.

Direct3D is implemented through COM objects and interfaces. The Direct3D interfaces are interfaces to the DirectDraw object which represents the display device. Direct3DX creates the DirectDraw object and the Direct3DDevice object for your application in a single step by creating a context object.

    if(FAILED(hr = D3DXCreateContextEx(D3DX_DEFAULT, 0, g_hwnd, NULL, D3DX_DEFAULT, 0,
        D3DX_DEFAULT, 0, 1, D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, &g_pd3dx)))
    {
        return hr;
    }

As the code sample shows, the D3DXCreateContextEx function will return the address of a pointer to an ID3DXContext interface. Note that the D3DXCreateContext function will also return the address of a pointer to an ID3DXContext interface. See the reference pages for the differences between the D3DXCreateContext and D3DXCreateContextEx functions.

For information on contexts and how contexts wrap Direct3D and DirectDraw objects, see Direct3DX Context.

Direct3DX provides another useful, time-saving initialization feature: a mechanism to enumerate the capabilities of the various devices in the system. For information on devices and device enumeration specific to Direct3DX, see Direct3DX Devices.


Using Direct3DX to Access Direct3D and DirectDraw

After you have obtained a context object, you can access the encapsulated objects.

To obtain a pointer to an IDirect3DDevice7 interface, use the ID3DXContext::GetD3DDevice method:

    m_pd3dDevice = g_pd3dx->GetD3DDevice();
    if (m_pd3dDevice == NULL)
        return E_FAIL;

To obtain a pointer to an IDirect3D7 interface, use the ID3DXContext::GetD3D method:

    m_pd3d = g_pd3dx->GetD3D();
    if (m_pd3d == NULL)
        return E_FAIL;

To obtain a pointer to an IDirectDraw7 interface, use the ID3DXContext::GetDD method:

    m_pdd = g_pd3dx->GetDD();
    if (m_pdd == NULL)
        return E_FAIL;

These retrieved interfaces can then be used by your application. For example, the following code uses the retrieved pointer to an IDirect3DDevice7 interface, m_pd3dDevice, to enable dithering, specular effects, lighting, and z-buffer usage.

    hr = m_pd3dDevice->SetRenderState(D3DRENDERSTATE_DITHERENABLE, TRUE);

    hr = m_pd3dDevice->SetRenderState(D3DRENDERSTATE_SPECULARENABLE, TRUE);

    hr = m_pd3dDevice->SetRenderState(D3DRENDERSTATE_LIGHTING, TRUE);

    hr = m_pd3dDevice->SetRenderState(D3DRENDERSTATE_ZENABLE, TRUE);


Direct3DX Context

For information on the Direct3DX context object and its usage, see the following sections:

  • What Is a Direct3DX Context Object?
  • Using Direct3DX to Clear Surfaces
  • Using Direct3DX to Update the Scene


What Is a Direct3DX Context Object?

The Direct3DX context object is a COM object that is the encapsulation of all the various Direct3D and DirectDraw objects that are needed for rendering on the display device. It is created with one of the following methods:

  • D3DXCreateContext
  • D3DXCreateContextEx

The creation of a context object reduces the amount of work that a DirectX application has to do to initialize Direct3D and DirectDraw, Once created, various Direct3D and DirectDraw objects such as the Direct3DDevice and DirectDrawSurface objects can be indirectly obtained from the context object.

The context object also supports flipping (or blitting) its encapsulated buffers to support multi-buffered rendering through the ID3DXContext::UpdateFrame method.

The ID3DXContext::DrawDebugText and ID3DXContext::Resize methods also simplify tasks common to DirectX applications.

In addition, the ID3DXContext interface supplies a method to clear the various rendering related buffers. For more information on specific methods, see the ID3DXContext reference topic.


Using Direct3DX to Clear Surfaces

Many C++ applications clear the depth buffer prior to rendering each new frame. You can explicitly clear the depth buffer with the Direct3DX utility library by using the ID3DXContext::Clear method.

    hr = g_pD3DX->Clear(D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER);
    if (FAILED(hr))
        return hr;

The Clear method allows you to specify which surfaces should be cleared. The preceding code fragment clears both the rendering target and the depth-buffer.


Using Direct3DX to Update the Scene

The Direct3DX utility library can update the frame of a scene by using either page flipping or blitting.

    hr = g_pD3DX->UpdateFrame(D3DX_UPDATE_NOVSYNC);

The preceding code uses the ID3DXContext::UpdateFrame method to update the frame by setting the D3DX_UPDATE_NOVSYNC flag. As a result, this call specifies that a blit should be used if the driver cannot flip without waiting for vertical synchronization (vsync) in full-screen mode.


Direct3DX Devices

This section contains the following topics about Direct3DX devices:

  • What are Direct3DX Devices?
  • Enumerating Direct3DX Devices
  • Querying Direct3DX Devices


What Are Direct3DX Devices?

A Direct3DX device expands upon the functionality offered by a Direct3D device. The Direct3DX utility library defines and implements a device construct, a D3DXDevice object, that encapsulates the functionality of a DirectDraw object and a Direct3DDevice object together. This design provides both convenience and flexibility for developers.

For example, if your system has one Direct3D capable graphics adapter, then there may be up to four D3DXDevice objects on your system:

  • DirectDraw on the primary display device + Direct3DRGBDevice
  • DirectDraw on the primary display device + Direct3DHALDevice
  • DirectDraw on the primary display device + Direct3DTnLHALDevice (if your adapter supports TnL Hal)
  • DirectDraw on the primary display device + Direct3DreferenceDevice

In addition, if your system has a 3-D accelerator card, then up to five D3DXDevice objects may be present on your system.

Direct3DX also supports multiple monitor configurations. So, if your system has two graphics adapters, you may have up to eight D3DXDevice objects on your system:

  • DirectDraw on the primary display device + Direct3DRGBDevice
  • DirectDraw on the primary display device + Direct3DHALDevice
  • DirectDraw on the primary display device + Direct3DTnLHALDevice (if your adapter supports TnL Hal)
  • DirectDraw on the primary display device + Direct3DReferenceDevice
  • DirectDraw on the secondary display device + Direct3DRGBDevice
  • DirectDraw on the secondary display device + Direct3DRGBDevice
  • DirectDraw on the secondary display device + Direct3DTnLHALDevice (if your adapter supports TnL Hal)
  • DirectDraw on the secondary display device + Direct3DReferenceDevice

For general information on Direct3D devices, see Direct3D Devices.


Enumerating Direct3DX Devices

This section details the components that comprise a particular display device and the functionality that the Direct3DX utility library provides for enumerating devices on a system.

A graphics configuration (display device) for a Direct3D application using the Direct3DX utility library may consist of the following components:

  • Display monitor
  • 2-D graphics device
  • 3-D graphics device

Given the preceding components, it is possible for a wide range of display options to be available on a particular system. For example, there may be several monitors on a system; the 2-D graphics device may or may not be using video acceleration; and the 3-D graphics device could be using any number of devices: RAMP, RGB, REFERENCE, HW, or TL HW.

For more information on device types, see the Direct3D Device Types topic in the Direct3D Immediate Mode documentation.

In most cases, not all of the display option combinations will be supported by the system. Typically, a 3-D card will be connected to a particular monitor. Also, choosing emulation for the 2-D engine may eliminate hardware choices for the 3-D engine. In order to resolve these conflicts and determine valid hardware configurations, your application should go through the process of enumerating the devices on the system.

As an example, the following code determines how many DirectDraw devices there are on the system, and for each DirectDraw device selects its highest level of hardware acceleration. The result is a list of indices into the device list that corresponds to the chosen device.

    dwNumDevices = D3DXGetDeviceCount();

    hr = D3DXGetDeviceDescription( 0, &pDeviceList[0] );

    GUID guidLastUniqueDeviceId = pDeviceList[0].ddDeviceID;
    cNumDDObjs = 1;
    indexOfChosenD3DXDevices[0] = 0; // start by picking the first device

    for( i = 1; i < dwNumDevices; i++ )
    {
        hr = D3DXGetDeviceDescription( i, &pDeviceList[i] );

        if( pDeviceList[i].ddDeviceID != guidLastUniqueDeviceId )
        {
            guidLastUniqueDeviceId = pDeviceList[i].ddDeviceID;
            cNumDDObjs++;
            indexOfChosenD3DXDevices[cNumDDObjs-1] = i;
        }
        else
        {
            int currIndex = indexOfChosenD3DXDevices[cNumDDObjs-1];
            if( pDeviceList[i].hwLevel > pDeviceList[currIndex].hwLevel )
            {
                indexOfChosenD3DXDevices[cNumDDObjs-1] = i;
            }
        }
    }

In the preceding example, the D3DXGetDeviceCount function is used to obtain the number of devices available for enumeration on the system. The D3DXGetDeviceDescription function is used to obtain a description of an enumerated device, identifying the device by its index value.

Note When you use the Direct3DX utility library your application does not have to manually enumerate devices; since reasonable defaults are built-into the Direct3DX context object.

Both the D3DXCreateContext and D3DXCreateContextEx functions supply parameters to allow for default device creation. However, sophisticated games and applications may want to expose the full device enumeration, so that users will be able to customize their own graphics experience.


Querying Direct3DX Devices

This section describes the video mode and surface format queries that can be performed on devices using the Direct3DX utility library functions.

You can query the various video modes supported by a particular device by using the following methods:

  • D3DXGetCurrentVideoMode
  • D3DXGetMaxNumVideoModes
  • D3DXGetVideoMode

The following code cycles through the video modes supported by a device:

    dwNumVidModes = D3DXGetMaxNumVideoModes( D3DX_DEFAULT,
                                             D3DX_GVM_REFRESHRATE );
    D3DX_VIDMODEDESC VidMode;

    for( i = 0; i<dwNumVidModes; i++ )
    {
        hr = D3DXGetVideoMode( D3DX_DEFAULT, D3DX_GVM_REFRESHRATE, i,
                               &VidMode );
    }

The preceding example uses the D3DX_GVM_REFRESHRATE flag to retrieve the refresh rates provided by the display device.

If you want to retrieve the current video mode setting, you can use the following code:

    D3DX_VIDMODEDESC CurrVidMode;
    D3DXGetCurrentVideoMode( D3DX_DEFAULT, &CurrVidMode );

You can query the capabilities of a Direct3DX device by using the D3DXGetDeviceCaps function. The D3DXGetDeviceCaps function returns the Direct3D device capabilities as well as the DirectDraw surface capabilities. Also, the D3DXGetDeviceCaps function takes a D3DX_VIDMODEDESC structure as an input parameter, since many video cards have varying capabilities based on the video mode.

The following code retrieves the device capabilities:

    DDCAPS DDHELCaps;
    DDCAPS DDHALCaps;
    D3DDEVICEDESC7 D3DCaps;
    hr = D3DXGetDeviceCaps( D3DX_DEFAULT,
                            NULL,
                            &D3DCaps,
                            &DDHALCaps,
                            &DDHELCaps );

In addition, you can request information about the known surface formats supported by a Direct3DX device for the various surface classes.

  • See the D3DX_SURFACECLASS enumerated type for the known surface formats.
  • See the D3DX_SURFACEFORMAT enumerated type for the various surface formats supported by Direct3DX.

The following methods can be used to query the supported surface formats of a Direct3DX device:

  • D3DXGetMaxSurfaceFormats
  • D3DXGetSurfaceFormat

The following code cycles through the surface formats supported by a device:

    DWORD dwNumSurfaceFormats =
    D3DXGetMaxSurfaceFormats( D3DX_DEFAULT, NULL, D3DX_SC_COLORTEXTURE);

    D3DX_SURFACEFORMAT SurfaceFormat;
    for( i=0; i<dwNumSurfaceFormats; i++ )
    {
        hr = D3DXGetSurfaceFormat( D3DX_DEFAULT, NULL, D3DX_SC_COLORTEXTURE,
                                   i, &SurfaceFormat );
    }

The preceding example uses the D3DX_SC_COLORTEXTURE flag to specify all the surfaces that have color information in them and can be used for texturing.


Direct3DX Matrix Stack

The Direct3DX utility library provides a matrix stack through a COM object.

This section provides information on the following topics:

  • What Is a Matrix Stack?
  • Implementing a Scene Hierarchy


What Is a Matrix Stack?

The Direct3DX utility library provides the ID3DXMatrixStack interface. It supplies a mechanism to allow matrices to be pushed onto and popped off of a matrix stack. Implementing a matrix stack is an efficient way to keep track of matrices while traversing a transform hierarchy.

The Direct3DX utility library uses a matrix stack to store transformations as matrices. The various methods of the ID3DXMatrixStack interface deal with the current matrix, or the matrix located on top of the stack. You can clear the current matrix with the ID3DXMatrixStack::LoadIdentity method. If you need to explicitly specify a certain matrix to be loaded as the current transformation matrix, use the ID3DXMatrixStack::LoadMatrix method. Then, you can call either the ID3DXMatrixStack::MultMatrix method or the ID3DXMatrixStack::MultMatrixLocal method to multiply the current matrix by the specified matrix.

The ID3DXMatrixStack::Pop method allows you to return to the previous transformation matrix and the ID3DXMatrixStack::Push method adds a transformation matrix to the stack.

The individual matrices on the matrix stack are represented as 4×4 homogenous matrices, defined by the Direct3DX utility library D3DXMATRIX structure.


Implementing a Scene Hierarchy

A matrix stack simplifies the construction of hierarchical models, in which complicated objects are constructed from a series of simpler objects.

A scene, or transform, hierarchy is usually represented by a tree data structure. Each node in the tree data structure contains a matrix. A particular matrix represents the change in coordinate systems from the node's parent to the node. For example, if you were modeling a human arm, you might implement the following hierarchy.

In the preceding hierarchy, the Body matrix places the body in the world. The UpperArm matrix contains the rotation of the shoulder, the LowerArm matrix contains the rotation of the elbow, and the Hand matrix contains the rotation of the wrist. To determine where the hand is relative to the world, you would simply multiply all the matrices from Body down through Hand together.

The previous hierarchy is overly simplistic, since each node has only one child. However, if you begin to model the hand in more detail, you will probably want to add fingers and a thumb. Each digit could be added to the hierarchy as children of Hand.

Now, if you traverse the complete graph of the arm in depth-first order (traversing as far down a single path as possible before moving on to the next alternative path) to draw the scene, you would perform a sequence of segmented rendering. For example, in order to render the hand and fingers you would implement the following pattern.

  1. Push the Hand matrix onto the matrix stack.
  2. Draw the hand.
  3. Push the Finger 1 matrix onto the matrix stack.
  4. Draw the first finger.
  5. Pop the Finger 1 matrix off of the stack.
  6. Push the Finger 2 matrix onto the matrix stack.
  7. Draw the second finger.
  8. Pop the Finger 2 matrix off of the stack.
  9. Push the Finger 3 matrix onto the matrix stack. You would continue in this manner until all of the fingers and thumb have been rendered.

After you have completed rendering the fingers, you would pop the Hand matrix off of the stack.

You can follow this basic process in code with the following examples. When you encounter a node during the depth-first search of the tree data structure, push the matrix onto the top of the matrix stack.

MatrixStack->Push();
MatrixStack->MultMatrix(pNode->matrix);

When you are finished with a node, pop the matrix off of the top of the matrix stack.

MatrixStack->Pop();

In this way, the matrix on the top of the stack will always represent the world-transform of the current node. Therefore, before drawing each node, you should set the Direct3D matrix.

pD3DDevice->SetTransform(D3DTRANSFORMSTATE_WORLD, *MatrixStack->GetTop());

For more information on the specific methods that you can perform on a Direct3DX matrix stack, see the ID3DXMatrixStack reference topic.


Hardware Acceleration Levels

This section about the Direct3DX utility library introduces the concept of hardware acceleration levels and describes some common usage situations:

  • About Hardware Acceleration Levels
  • Testing Hardware Acceleration Levels

For a reference list of the hardware acceleration levels, see Hardware Acceleration Level Constants.


About Hardware Acceleration Levels

The Direct3DX hardware acceleration level constants are pre-defined indices that can be used wherever the actual device index is required. For example, hardware acceleration level constants can be used in the ID3DXContext::GetDeviceIndex method. Each constant indicates a different level of hardware acceleration.

The hardware acceleration level constants are an alternative to using the explicit device indexes retrieved by the global D3DXGetDeviceDescription function.

If one of the Direct3DX devices on the primary DirectDraw device supports a requested hardware acceleration level, it will be used. Otherwise, the first matching device found by Direct3DX will be used. Of course, it is possible for no match to exist for any of the hardware acceleration level constants on a particular system. Passing such a value into the Direct3DX APIs will simply cause them to fail, reporting that no match is available.

The hardware acceleration level constants should only be used as device indices under the following circumstance: a particular level of hardware acceleration is required by the application and, given more that one compatible device on the computer, it is not critical which one is used.


Testing Hardware Acceleration Levels

Some applications may need to test a particular device for different hardware acceleration levels.

DescribeDevice( DWORD index )
{
    D3DX_DEVICEDESC devDesc;

    hr = D3DXGetDeviceDescription( index, &devDesc );

    if (D3DX_HWLEVEL_2D == devDesc.hwLevel)
    {
        // do something
    }
    else if (D3DX_HWLEVEL_RASTER == devDesc.hwLevel)
    {
        // do something
    }
    else if (D3DX_HWLEVEL_REFERENCE == devDesc.hwLevel)
    {
        // do something
    }
    else if (D3DX_HWLEVEL_TL == devDesc.hwLevel)
    {
        // do something
    }
    else    // D3DX_DEFAULT == devDesc.hwLevel
        // do something

The preceding code fragment uses the index of a device to look for the hardware acceleration flag that describes that device.


Sprite Support

The sprite helper application programming interface (API) provided by the Direct3DX utility library allows you to render 2-D style sprites using 3-D hardware. Sprite rendering is designed for 3-D hardware, and, for performance reasons, is not recommended for software emulation.

A sprite is an object that can be manipulated without disturbing the background image underneath it. In terms of the Direct3DX utility library, a sprite is loosely defined as a 2-D image that you can transfer to the rendering target.

This section discusses common tasks that applications will perform when using the Direct3DX utility library to work with sprites.

  • Preparing to Draw a Sprite
  • Drawing a Simple Sprite
  • Drawing a Transformed Sprite

For more information on the sprite functionality offered by the Direct3DX utility library, see the Sprite Helper Functions reference topic.


Preparing to Draw a Sprite

This section details the preparatory steps required before drawing a sprite using the Direct3DX utility library.

Before transferring the sprite to the rendering target, call the appropriate methods to begin the scene and clear the render target.

    hr = m_pd3dDevice->BeginScene();

    hr = m_pd3dx->Clear(D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER);

Initialize the rasterizer for rendering sprites by calling the D3DXPrepareDeviceForSprite function. Typically, this function only needs to be called once for all of the sprites that are rendered. However, D3DXPrepareDeviceForSprite does need to be called again if any render state changes are made outside of a D3DXDrawSpriteSimple call.

    ::D3DXPrepareDeviceForSprite(m_pd3dDevice);

You can set up a RECT structure that will define where the sprite should appear on the source texture.

    RECT srcRect;

Often, when using sprites your images will be comprised from a grid of pictures. In this case, your source RECT structure will be a different sub-rectangle for every frame. For example, your grid of pictures may have 10 columns and 6 rows. To determine the x-position, you would compute m_currentFrame % 10 (where m_currentFrame is the current frame). To determine the y-position, you would compute m_currentFrame / 10.

    int iX = (m_currentFrame % 10);
    int iY = (m_currentFrame / 10);

Each frame is spaced into 64 pixels by 64 pixels cells.

    srcRect.left = iX * 64;
    srcRect.top  = iY * 64;

Each sub-frame of the source RECT structure is 64 pixels wide and 48 pixels tall.

    srcRect.right  = srcRect.left + 64;
    srcRect.bottom = srcRect.top  + 48;

Now, you should retrieve the current viewport.

    D3DVIEWPORT7 viewport;
    hr = m_pd3dDevice->GetViewport(&viewport);

Then, you can convert the viewport into a RECT structure.

    RECT rectViewport;
    rectViewport.left   = viewport.dwX;
    rectViewport.top    = viewport.dwY;
    rectViewport.right  = viewport.dwX + viewport.dwWidth;
    rectViewport.bottom = viewport.dwY + viewport.dwHeight;

The non-rotated render target should be centered in the viewport.

    D3DXVECTOR3 pointDest;
    pointDest.x = (float)viewport.dwX + (float)viewport.dwWidth  / 2.0f;
    pointDest.y = (float)viewport.dwY + (float)viewport.dwHeight / 2.0f;

At this point you can draw the sprite by calling one of the sprite drawing functions provided by the Direct3DX utility library.

  • D3DXDrawSpriteSimple
  • D3DXDrawSpriteTransform
  • D3DXDrawSprite3D

For information on how to draw a sprite, see Drawing a Simple Sprite and Drawing a Transformed Sprite.

After you have drawn the sprite, you should call the appropriate methods to end the scene and update the frame.

    hr = m_pd3dDevice->EndScene();

    hr = m_pd3dx->UpdateFrame(D3DX_DEFAULT);


Drawing a Simple Sprite

This section demonstrates how the Direct3DX utility library can help you to draw a simple sprite

The following code fragment draws a simple sprite:

    hr = ::D3DXDrawSpriteSimple(
            m_ptex,                     // texture
            m_pd3dDevice,               // 3-D device
            &pointDest,                 // destination point (center)
            (float)m_dwAlpha/255.0f,    // alpha
            m_fScaleCurrent,            // scale
            m_fRotationCurrent,         // rotation
            NULL,                       // offset
            &srcRect                    // src sub rect
            );

The preceding code fragment shows how to draw a sprite with the D3DXDrawSpriteSimple function. This function supports scaling, rotation, alpha blending, mirroring, and placement. For a broader range of effects such as shearing and perspective, use the D3DXDrawSpriteTransform function.


Drawing a Transformed Sprite

This section details how to draw a transformed sprite by using the Direct3DX utility library.

The following code example builds and draw a sprite that had been transformed using scaling:

    D3DXMATRIX matScale;
    D3DXMatrixScaling(&matScale, m_fScaleCurrent, m_fScaleCurrent, 1);

    D3DXMATRIX matTransform;
    D3DXBuildSpriteTransform(&matTransform, &rectViewport, m_fRotationCurrent);

    D3DXMATRIX mat;
    mat = matScale * matTransform;

    hr = ::D3DXDrawSpriteTransform(
            m_ptex,         // texture
            m_pd3dDevice,   // 3-D device
            &mat,           // matrix
            (BYTE)m_dwAlpha,// alpha
            &srcRect        // source sub-rect
            );

The following code example builds and draws a sprite that has been transformed using rotation, translation, and scaling:

    D3DXMATRIX matScaleToSize;
    D3DXMatrixScaling(&matScaleToSize, 64, 48, 1);

    D3DXMATRIX matRotate;
    D3DXMatrixRotationZ(&matRotate, m_fRotationCurrent);

    D3DXMATRIX matTranslate;
    D3DXMatrixTranslation(&matTranslate, (float)pointDest.x, (float)pointDest.y, 0);

    D3DXMATRIX matScale;
    D3DXMatrixScaling(&matScale, m_fScaleCurrent, m_fScaleCurrent, 1);

    D3DXMATRIX mat;
    mat = matScaleToSize * matRotate * matScale * matTranslate;

    hr = ::D3DXDrawSpriteTransform(
           m_ptex,         // texture
           m_pd3dDevice,   // 3-D device
           &mat,           // matrix
           (BYTE)m_dwAlpha,// alpha
           &srcRect        // source sub-rect
           );


Texturing Support

This section describes the texturing support provided by the Direct3DX utility library.

  • Understanding Direct3DX Textures
  • Understanding Texture Files
  • Creating Textures
  • Loading Textures
  • Creating Cube-Map Textures
  • Generating Mipmaps
  • Understanding Filtering Options

For more information on the texturing functionality offered by the Direct3DX utility library, see the Texturing Functions reference topic.


Understanding Direct3DX Textures

The Direct3DX utility library provides extensive texturing facilities to provide hardware independence to as great a degree as possible. Direct3DX will automatically search the capabilities of the chosen device to build a texture that is compatible with that device.

A texture is a DirectDrawSurface object that has been specially created to be used with the 3-D hardware on the system. Creating a texture using the Direct3DX utility library will ensure that the texture will be supported by the hardware.

The texturing functions in the Direct3DX utility library allow you to perform the following operations:

  • Convert texture formats.
  • Create cube-map textures.
  • Create and load textures from files.
  • Create textures.
  • Generate mipmaps.
  • Filter.
  • Load textures from surfaces.

If you have authored your textures in one of the D3DX_SURFACEFORMAT standard texture types, the Direct3DX utility library will provide conversion to any of the other standard texture types; these types include 16-bit and 32-bit ARGB, a full set of RGB types, some compression formats and more.


Understanding Texture Files

The Direct3DX utility library supports loading textures from the following file formats: BMP, DIB, TGA, and DDS. The texture is loaded and then converted into a size and format commensurate with the current rasterizer restrictions. In this way, the Direct3DX utility library provides a simple way to create and manipulate textures.

The pointer to the IDirectDrawSurface7 interface that is returned by the texture creation functions can be used directly with the IDirect3DDevice7::SetTexture method.

In the case that the image needs to be resized, the image is stretched using a bilinear filter to fill the entire surface.

It is recommended that you use 256×256 (or smaller) square power-of two textures to avoid possible resizing errors. You can use the D3DXCheckTextureRequirements function to determine if Direct3DX will need to resize a particular texture to make it work with the current hardware.

There may be a performance degradation if a resizing or format change is necessary. For maximum image quality on a wide range of hardware platforms, use a 24-bit RGB or 32-bit ARGB format.


Creating Textures

When using the Direct3DX utility library, textures can be created as "blank" textures (each pixel is initialized with a value of zero) with the D3DXCreateTexture function.

Also, textures can be loaded and created in a single call using the D3DXCreateTextureFromFile function which supports the loading of BMP, DIB, TGA, and DDS file formats.

For example, the following call loads a bitmap file (texture.bmp):

    IDirectDrawSurface7 *m_ptex;
    m_pd3dDevice = m_pd3dx->GetD3DDevice();

    hr = D3DXCreateTextureFromFile(
            m_pd3dDevice,
            NULL,                   // dwFlags
            NULL,                   // auto-width
            NULL,                   // auto-height
            NULL,                   // auto-surface type
            NULL,                   // pointer to Palette
            &m_ptex,                // returned pointer to texture
            NULL,                   // returned number of mipmaps
            "texture.bmp",          // file name for texture
            D3DX_FT_DEFAULT);       // default scaling

However, surfaces created with the D3DXCreateTextureFromFile function may have been resized, or had their surface format changed because of the requirements of the rasterization device. As a result, calling IDirectDrawSurface7::Lock on surfaces created in this manner is not recommended; since the height, width, number of mipmap levels, and even the pixel format of the surface may vary on different devices.

To transfer pixels to surfaces created with the D3DXCreateTexture or D3DXCreateTextureFromFile functions, it is recommended that you use the D3DXLoadTextureFromSurface and D3DXLoadTextureFromFile functions, which are designed to handle all of the various possible formats and perform the appropriate resampling operations.


Loading Textures

The D3DXLoadTextureFromSurface and D3DXLoadTextureFromFile functions provide parameters to update existing textures with new data. For example, the following code fragment loads a texture with a D3DXLoadTextureFromFile function call:

    hr = D3DXLoadTextureFromFile(
        m_pD3DDev,
        pFace,                      // destination
        D3DX_DEFAULT,               // all mip levels
        pszTex,                     // source
        NULL,                       // entire source
        NULL,                       // entire destination
        D3DX_FT_DEFAULT);

If you are using the RECT structure parameter (for example, if you are only intending to update a portion of the destination rectangle or a portion of the source rectangle), then the Direct3DX utility library provides helper functionality for scenarios where the source or destination rectangle was not resized due to rasterizer constraints.

The application should setup the RECT structures as if the textures were not resized because Direct3DX will automatically interpret the RECT structures to account for any resizing. This provides a simple mechanism for applications to ignore resizing operations done by Direct3DX. However, if you created the surface outside of Direct3DX, then the RECT structures must correspond to the actual pixel size of that surface.


Creating Cube-Map Textures

The creation of cube-map textures is similar to regular texture creation. However, in addition to the regular texture attributes, you can specify which faces of the cube map you wish to have created.

The following code uses the D3DXCreateCubeMapTexture function to create a cube-map texture:

    DWORD w = 256, h = 256;
    D3DX_SURFACEFORMAT sf = D3DX_SF_A8R8G8B8;

    hr = D3DXCreateCubeMapTexture(
                    m_pD3DDev,
                    0,                              // flags
                    DDSCAPS2_CUBEMAP_ALLFACES,      // faces
                    0,                              // colors for empty faces
                    &w,                             // width
                    &h,                             // height
                    &sf,                            // surface format
                    NULL,                           // palette
                    &m_pEnvTex,                     // resulting surface
                    NULL);                          // number of mipmap levels

Now, you should load the faces of the cube map.

    DDSCAPS2 ddsCaps;
    ZeroMemory(&ddsCaps, sizeof(ddsCaps));
    for (i = 0; i < 6; i++)
    {
        DWORD FacesArray[] =
        {
            DDSCAPS2_CUBEMAP_POSITIVEX,
            DDSCAPS2_CUBEMAP_NEGATIVEX,
            DDSCAPS2_CUBEMAP_POSITIVEY,
            DDSCAPS2_CUBEMAP_NEGATIVEY,
            DDSCAPS2_CUBEMAP_POSITIVEZ,
            DDSCAPS2_CUBEMAP_NEGATIVEZ
        };

Map the file indexes to the various faces of the cube map.

        DWORD FileIndex[] =
        {
            2, 0, 5, 4, 1, 3
        };

You can use the following code to locate the correct face.

        LPDIRECTDRAWSURFACE7 pFace;
        if (i != 0)
        {
            ddsCaps.dwCaps2 = FacesArray[i];
            if (FAILED(hr = m_pEnvTex->GetAttachedSurface(&ddsCaps, &pFace)))
                return hr;
        }

Lastly, you need to compensate for a special case: the zero face. The zero face is the same as the top-level environment map.

        else
        {
            pFace = m_pEnvTex;
            pFace->AddRef();
        }

By default, all six faces of a cube map are created. Also, you can specify a color to use for the empty faces. This can help save memory when some of the faces of the cube map can be adequately represented with a single color. For example, if you are using a set of cube maps to simulate reflections on a car's hood from the overhead lights of a highway, you only need the POSITIVE_Y faces, while the rest of the faces can be approximated with black.


Generating Mipmaps

By default, the texture creation methods provided by the Direct3DX utility library will generate mipmaps for textures as long as the rasterizer supports mipmaps. However, mipmap generation can be disabled with the D3DX_TEXTURE_NOMIPMAP flag.

The following code fragment sets the D3DX_TEXTURE_NOMIPMAP flag to create a texture that does not support mipmaps:

    DWORD flags = D3DX_TEXTURE_NOMIPMAP;
    pFlags = &flags;

    hr = D3DXCreateTexture(
            pd3dDevice,         // d3ddevice passed in
            pFlags,             // loading options
            pWidth,             // width
            pHeight,            // height
            pTmpPixelFormat,    // desired pixel format
            NULL,               // palette
            &pSurf,             // return surface
            pNumMipMaps);       // number of mipmap levels

The following code example then queries the created texture for mipmap support:

    DDCAPS ddcaps;
    ZeroMemory(&ddcaps, sizeof(ddcaps));
    ddcaps.dwSize = sizeof(ddcaps);

    hr = pDD->GetCaps(&ddcaps, NULL);
    if (SUCCEEDED(hr))
    {
    // Check for mipmapping
        if (!(*pFlags & D3DX_TEXTURE_NOMIPMAP))
        {
            if (!(ddcaps.ddsCaps.dwCaps & DDSCAPS_MIPMAP))
            {
                // Disable mipmapping
                *pFlags |= D3DX_TEXTURE_NOMIPMAP;
            }
        }
    }

The D3DXLoadTextureFromSurface and D3DXLoadTextureFromFile functions allow the specification of the particular mipmap level that you want to update. If you specify D3DX_DEFAULT as the mipmap level, then the top-most level is updated and the other mipmap levels are automatically updated to match.

Applications that need to carefully update the individual levels of a mipmap should pass explicit mipmap levels to the Direct3DX texture loading methods. Also, applications that directly use the IDirectDrawSurface7::Blt and IDirectDrawSurface7::Lock methods to modify surfaces should update mipmap levels as necessary.


Understanding Filtering Options

The Direct3DX utility library supports two type of filtering: bilinear (D3DX_FT_LINEAR) and point-sampling (D3DX_FT_POINT). For higher quality resizing and mipmap generation, choose bilinear filtering. For faster operation, choose D3DX_FT_POINT.

Note To avoid blurring in images that have text in them, using point-sampling and disabling mipmapping may work better in some specific cases.


Simple Geometric Shapes

When a shape is created using one of the shape drawing functions, an address of a pointer to a ID3DXSimpleShape COM interface is returned in the parameter list. Using this interface, you can obtain the vertex information (stored in a vertex buffer) and the index information.

  • ID3DXSimpleShape::GetIndices
  • ID3DXSimpleShape::GetVB

Drawing the shape is done by a call to the ID3DXSimpleShape::Draw method on the ID3DXSimpleShape interface.

The 3-D shape drawing application programming interface (API) provided by the Direct3DX utility library allows you to draw the following simple geometric shapes:

  • Cube
  • Cylinder/cone
  • Donut
  • N-sided polygon
  • Sphere
  • Teapot

Before creating the shape, you can specify the number of texture coordinates. Direct3DX will then allocate the appropriate amount of space in the vertex buffer.

For more information, see the Shape Drawing Functions reference topic.


3-D Math Support

The math functions in the Direct3DX utility library provide exhaustive support for commonly used mathematical operations in 3-D graphics. C++ programmers can make use of more extensible and flexible template classes for the common 3-D data-types.

The following classes are implemented:

  • D3DXCOLOR
  • D3DXMATRIX
  • D3DXPLANE
  • D3DXQUATERNION
  • D3DXVECTOR2
  • D3DXVECTOR3
  • D3DXVECTOR4

Note The preceding data-types are classes in C++ and structures in C.

For more information, see the Math Functions and C++ Specific Features reference topics.


Direct3DX Utility Library Reference

This section contains reference information for the application programming interface (API) elements provided by the Direct3DX utility library. Reference material is divided into the following categories:

  • Interfaces
  • Functions
  • Macros
  • Structures
  • C++ Specific Features
  • Enumerated Types
  • Hardware Acceleration Level Constants
  • Return Values


Interfaces

This section contains reference information for the COM interfaces provided by Direct3DX utility library. The interfaces exposed by Direct3DX are as follows:

  • ID3DXContext
  • ID3DXMatrixStack
  • ID3DXSimpleShape


ID3DXContext

Applications use the methods of the ID3DXContext interface to encapsulate all of the various Direct3D and DirectDraw objects required to render a scene This section is a reference to the methods of this interface.

The ID3DXContext interface is obtained by calling the D3DXCreateContext function or the D3DXCreateContextEx function.

The methods of the ID3DXContext interface can be organized into the following groups:

Buffer Management | GetBackBuffer
 | GetBufferSize
 | GetNumBackBuffers
 | GetPrimary
 | GetZBuffer
 | Resize
Information | GetDD
 | GetD3D
 | GetD3DDevice
Miscellaneous | GetCreationFlags
 | GetDeviceIndex
 | GetNumBits
 | GetRefreshRate
 | UpdateFrame
 | DrawDebugText
Surface Management | RestoreSurfaces
Viewports | Clear
 | SetClearColor
 | SetClearDepth
 | SetClearStencil
Window Management | GetFocusWindow
 | GetWindow

The ID3DXContext interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The PD3DXCONTEXT type is defined as a pointer to an ID3DXContext interface:

typedef struct ID3DXContext *PD3DXCONTEXT;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.


ID3DXContext::Clear

The ID3DXContext::Clear method clears specified surfaces from the current viewport.

HRESULT Clear(
  DWORD ClearFlags
);

Parameters

ClearFlags
Flags indicating which surfaces should be cleared. This parameter can be any combination of the following flags, but at least one flag must be used:
D3DCLEAR_TARGET
Clear the rendering target.
D3DCLEAR_STENCIL
Clear the stencil buffer.
D3DCLEAR_ZBUFFER
Clear the depth-buffer.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value may be one of the following values:

D3DERR_STENCILBUFFER_NOTPRESENT
D3DERR_VIEWPORTHASNODEVICE
D3DERR_ZBUFFER_NOTPRESENT
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

This method fails if you specify the D3DCLEAR_ZBUFFER or D3DCLEAR_STENCIL flags when the render target does not have an attached depth-buffer. Similarly, if you specify the D3DCLEAR_STENCIL flag when the depth-buffer format doesn't contain stencil buffer information, this method fails.

This method clears to the current viewport. Specify the color the viewport clears to with the ID3DXContext::SetClearColor method, the value the depth buffer clear to with the ID3DXContext::SetClearDepth method, and the value the stencil buffer clears to with ID3DXContext::SetClearStencil method.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

ID3DXContext::SetClearColor, ID3DXContext::SetClearDepth, ID3DXContext::SetClearStencil


ID3DXContext::DrawDebugText

The ID3DXContext::DrawDebugText method draws a null-terminated string to the render buffer.

HRESULT DrawDebugText(
  float topLeftX,
  float topLeftY,
  D3DCOLOR color,
  LPSTR pString
);

Parameters

topLeftX
The x-coordinate of the top left corner of the string to be drawn on the render target.
topLeftY
The y-coordinate of the top left corner of the string to be drawn on the render target.
color
A D3DCOLOR type specifying the color of the string to be drawn on the render target.
pString
A pointer to the null-terminated string to be drawn on the render target.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value may be one of the following values:

D3DXERR_NULLPOINTER
D3DXERR_FAILEDDRAWTEXT
DDERR_DCALREADYCREATED
DDERR_GENERIC
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDSURFACETYPE
DDERR_SURFACELOST
DDERR_UNSUPPORTED
DDERR_WASSTILLDRAWING

Remarks

This method is provided as a convenience for debugging and gathering information during development.

The coordinate and color parameters of this method each have a range of 0.0 to 1.0.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.


ID3DXContext::GetBackBuffer

The ID3DXContext::GetBackBuffer method retrieves a back buffer encapsulated by a context object.

LPDIRECTDRAWSURFACE7 GetBackBuffer(
  DWORD dwWhich
);

Parameters

dwWhich
Index of the back buffer object to return.

Return Values

If the method succeeds, the method returns a pointer to an IDirectDrawSurface7 interface.

If the method fails, NULL is returned.

Remarks

Note that reference counts are maintained for the buffers encapsulated by a context object. So, it is the application's responsibility to release buffers before the application exits or when it is resized.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

ID3DXContext::GetBufferSize, ID3DXContext::GetNumBackBuffers, ID3DXContext::Resize


ID3DXContext::GetBufferSize

The ID3DXContext::GetBufferSize method returns the current buffer size encapsulated by a context object.

HRESULT GetBufferSize(
  LPDWORD width,
  LPDWORD height
);

Parameters

width
After this method returns, the parameter points to a DWORD value containing the width of the buffer in pixels.
height
After this method returns, the parameter, points to a DWORD value containing the height of the buffer in pixels.

Return Values

This method returns S_OK.

Remarks

Note that reference counts are maintained for the buffers encapsulated by a context object. So, it is the application's responsibility to release buffers before the application exits or when it is resized.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

ID3DXContext::GetPrimary, ID3DXContext::Resize


ID3DXContext::GetCreationFlags

The ID3DXContext::GetCreationFlags method retrieves the flags used to create this context object.

DWORD GetCreationFlags();

Parameters

None.

Return Values

The method returns a DWORD value indicating the flags used to create the context object.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

D3DXCreateContext, D3DXCreateContextEx


ID3DXContext::GetD3D

The ID3DXContext::GetD3D method retrieves a pointer to an IDirect3D7 interface.

LPDIRECT3D7 GetD3D();

Parameters

None.

Return Values

If the method succeeds, the method returns a pointer to an IDirect3D7 interface.

If the method fails, NULL is returned.

Remarks

Applications use the returned IDirect3D7 interface to call Direct3D functions.

Note that a reference count is maintained for the Direct3D object encapsulated by a context object. So, it is the application's responsibility to release the IDirect3D7 interface when it is no longer needed by the application.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.


ID3DXContext::GetD3DDevice

The ID3DXContext::GetD3DDevice method retrieves a pointer to an IDirect3DDevice7 interface.

LPDIRECT3DDEVICE7 GetD3DDevice();

Parameters

None.

Return Values

If the method succeeds, the method returns a pointer to an IDirect3DDevice7 interface.

If the method fails, NULL is returned.

Remarks

Applications use the returned IDirect3DDevice7 interface to call Direct3DDevice methods.

Note that a reference count is maintained for the Direct3DDevice object encapsulated by a context object. So, it is the application's responsibility to release the IDirect3DDevice7 interface when it is no longer needed by the application.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.


ID3DXContext::GetDD

The ID3DXContext::GetDD method retrieves a pointer to an IDirectDraw7 interface.

LPDIRECTDRAW7 GetDD();

Parameters

None.

Return Values

If the method succeeds, the method returns a pointer to an IDirectDraw7 interface.

If the method fails, NULL is returned.

Remarks

Applications use the returned IDirectDraw7 interface to call DirectDraw methods.

Note that a reference count is maintained for the DirectDraw object encapsulated by a context object. So, it is the application's responsibility to release the IDirectDraw7 interface when it is no longer needed by the application.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.


ID3DXContext::GetDeviceIndex

The ID3DXContext::GetDeviceIndex method returns the index of the hardware level for the device.

HRESULT GetDeviceIndex(
  LPDWORD pIndex,
  LPDWORD hwLevel
);

Parameters

pIndex
After this method returns, the parameter points to a DWORD value matching the index of the specified device.
hwLevel
After this method returns, the parameter points to a DWORD value matching one of the pre-defined, hardware acceleration level constants. See Remarks.

Return Values

This method returns S_OK.

Remarks

The pre-defined, hardware acceleration level constants can be used where ever the actual device index is required. Direct3DX will resolve them to the actual index value. The defined hardware levels are convenient shortcuts to access various levels of acceleration. See the following table for a listing of these constants.

D3DX_HWLEVEL_REFERENCE
D3DX_HWLEVEL_2D
D3DX_HWLEVEL_RASTER
D3DX_HWLEVEL_TL
D3DX_DEFAULT

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

ID3DXContext::GetD3DDevice


ID3DXContext::GetFocusWindow

The ID3DXContext::GetFocusWindow method retrieves a handle to the associated focus window.

HWND GetFocusWindow();

Parameters

None.

Return Values

This method returns a handle (HWND) to the associated focus window.

Remarks

The focus window is the window that is currently receiving keyboard input. The focus window is always the active window, a descendent of the active window, or NULL..

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

ID3DXContext::GetWindow


ID3DXContext::GetNumBackBuffers

The ID3DXContext::GetNumBackBuffers method returns the number of back buffers encapsulated by a context object.

DWORD GetNumBackBuffers();

Parameters

None.

Return Values

This method returns a DWORD value indicating the number of back buffers.

Remarks

Note that reference counts are maintained for the buffers encapsulated by a context object. So, it is the application's responsibility to release the buffers before the application exits or when it is resized.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

ID3DXContext::GetBackBuffer, ID3DXContext::Resize


ID3DXContext::GetNumBits

The ID3DXContext::GetNumBits method returns values describing the pixel format of the DirectDrawSurface objects encapsulated by a context object.

HRESULT GetNumBits(
  LPDWORD colorBits,
  LPDWORD depthBits,
  LPDWORD alphaBits,
  LPDWORD stencilBits
);

Parameters

colorBits
A pointer to the color depth of the current display mode.
depthBits
A pointer to the bit depth of the z-buffer.
alphaBits
A pointer to the bit depth of the alpha buffer
stencilBits
A pointer to the bit depth of the stencil buffer.

Return Values

This method returns S_OK.

Remarks

The stencilBits parameter specifies how many bits are reserved with each pixel of the z-buffer for stencil information.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

ID3DXContext::GetZBuffer


ID3DXContext::GetPrimary

The ID3DXContext::GetPrimary method returns the front buffer encapsulated by a context object.

LPDIRECTDRAWSURFACE7 GetPrimary();

Parameters

None.

Return Values

If the method succeeds, the method returns a pointer to an IDirectDrawSurface7 interface.

If the method fails, NULL is returned.

Remarks

Note that reference counts are maintained for the buffers encapsulated by a context object. So, it is the application's responsibility to release the buffers before the application exits or when it is resized.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

ID3DXContext::GetBufferSize, ID3DXContext::Resize


ID3DXContext::GetRefreshRate

The ID3DXContext::GetRefreshRate method returns the refresh rate.

DWORD GetRefreshRate();

Parameters

None.

Return Values

The method returns a DWORD value indicating the refresh rate of the current display mode.

Remarks

A value of 0 for the refresh rate indicates an adapter fault.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.


ID3DXContext::GetWindow

The ID3DXContext::GetWindow method retrieves a handle to the associated window.

HWND GetWindow();

Parameters

None.

Return Values

This method returns a handle (HWND) to the associated window.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

ID3DXContext::GetFocusWindow


ID3DXContext::GetZBuffer

The ID3DXContext::GetZBuffer method returns the z-buffer encapsulated by a context object.

LPDIRECTDRAWSURFACE7 GetZBuffer();

Parameters

None.

Return Values

If the method succeeds, the method returns a pointer to an IDirectDrawSurface7 interface.

If the method fails, NULL is returned.

Remarks

Note that reference counts are maintained for the buffers encapsulated by a context object. So, it is the application's responsibility to release the buffers before the application exits or when it is resized.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

ID3DXContext::GetBufferSize, ID3DXContext::Resize


ID3DXContext::Resize

The ID3DXContext::Resize method changes the dimensions of buffers encapsulated by a context object.

HRESULT Resize(
  DWORD width,
  DWORD height
);

Parameters

width
The new width of the buffers.
height
The new height of the buffers.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value may be one of the following values:

D3DXERR_CANNOTRESIZEFULLSCREEN
D3DXERR_INVALIDPARAMETER
DDERR_GENERIC
DDERR_INCOMPATIBLEPRIMARY
DDERR_INVALIDCAPS
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDPIXELFORMAT
DDERR_INVALIDSURFACETYPE
DDERR_NOALPHAHW
DDERR_NOCOOPERATIVELEVELSET
DDERR_NODIRECTDRAWHW
DDERR_NOEMULATION
DDERR_NOEXCLUSIVEMODE
DDERR_NOFLIPHW
DDERR_NOMIPMAPHW
DDERR_NOOVERLAYHW
DDERR_NOPALETTEATTACHED
DDERR_NOPALETTEHW
DDERR_NOT8BITCOLOR
DDERR_NOZBUFFERHW
DDERR_OUTOFMEMORY
DDERR_OUTOFVIDEOMEMORY
DDERR_PRIMARYSURFACEALREADYEXISTS
DDERR_SURFACELOST
DDERR_UNSUPPORTED
DDERR_UNSUPPORTEDMODE

Remarks

Note that reference counts are maintained for the buffers encapsulated by a context object. So, it is the application's responsibility to release the buffers before the application exits or when it is resized.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

ID3DXContext::GetBufferSize


ID3DXContext::RestoreSurfaces

The ID3DXContext::RestoreSurfaces method restores surfaces in case data has been lost.

HRESULT RestoreSurfaces();

Parameters

None.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value may be one of the following values:

DDERR_GENERIC
DDERR_IMPLICITLYCREATED
DDERR_INCOMPATIBLEPRIMARY
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOEXCLUSIVEMODE
DDERR_OUTOFMEMORY
DDERR_UNSUPPORTED
DDERR_WRONGMODE

Remarks

This method restores the primary (front buffer) surface, the back buffer surface, and the z-buffer surface.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

IDirectDrawSurface7::Restore


ID3DXContext::SetClearColor

The ID3DXContext::SetClearColor method sets the color to which the render target surface will be cleared.

HRESULT SetClearColor(
  D3DCOLOR color
);

Parameters

color
A D3DCOLOR type representing the value to which the render target surface will be cleared. The default value is 0.

Return Values

This method returns S_OK.

Remarks

The D3DRGBA macro can be used to specify the color in this method:

    hr = m_pD3DX->SetClearColor(D3DRGBA(0.5f,0.0f,0.0f,0));

After setting the color of the render target surface with this method, you can call the ID3DXContext::Clear method to clear the viewport to this color.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

ID3DXContext::Clear, ID3DXContext::SetClearDepth, ID3DXContext::SetClearStencil


ID3DXContext::SetClearDepth

The ID3DXContext::SetClearDepth method sets the value to which the depth-buffer surface will be cleared.

HRESULT SetClearDepth(
  float z
);

Parameters

z
New z value stored in the depth buffer. This parameter can range from 0.0 to 1.0, inclusive (for z-based or w-based depth buffers). The value of 0.0 represents the nearest distance to the viewer, and 1.0 the farthest distance. The default value is 1.0f.

Return Values

This method returns S_OK.

Remarks

After setting the z value stored in the depth buffer with this method, you can call the ID3DXContext::Clear method to clear the depth-buffer surface to this value.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

ID3DXContext::Clear, ID3DXContext::SetClearColor, ID3DXContext::SetClearStencil


ID3DXContext::SetClearStencil

The ID3DXContext::SetClearStencil method sets the value to which the stencil-buffer surface will be cleared.

HRESULT SetClearStencil(
  DWORD dwClearValue
);

Parameters

dwClearValue
DWORD value to store in each stencil buffer entry. This parameter can range from 0 to 2n-1 inclusive, where n is the bit depth of the stencil buffer. The default value is 0.

Return Values

This method returns S_OK.

Remarks

After setting the stencil value with this method, you can call the ID3DXContext::Clear method to clear the stencil-buffer surface to this value.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

ID3DXContext::Clear, ID3DXContext::SetClearColor, ID3DXContext::SetClearDepth


ID3DXContext::UpdateFrame

The ID3DXContext::UpdateFrame method updates a frame using either page flipping or blitting.

HRESULT UpdateFrame(
  DWORD flags
);

Parameters

flags
A flag specifying frame update options. See Remarks.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value may be one of the following values:

DDERR_DCALREADYCREATED
DDERR_GENERIC
DDERR_IMPLICITLYCREATED
DDERR_INCOMPATIBLEPRIMARY
DDERR_INVALIDCLIPLIST
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDRECT
DDERR_INVALIDSURFACETYPE
DDERR_NOALPHAHW
DDERR_NOBLTHW
DDERR_NOCLIPLIST
DDERR_NODDROPSHW
DDERR_NOEXCLUSIVEMODE
DDERR_NOFLIPHW
DDERR_NOTFLIPPABLE
DDERR_NOMIRRORHW
DDERR_NORASTEROPHW
DDERR_NOROTATIONHW
DDERR_NOSTRETCHHW
DDERR_NOZBUFFERHW
DDERR_OUTOFMEMORY
DDERR_SURFACEBUSY
DDERR_SURFACELOST
DDERR_UNSUPPORTED
DDERR_WASSTILLDRAWING
DDERR_WRONGMODE

Remarks

If the D3DX_UPDATE_NOVSYNC flag is set in the flags parameter, a blit is used if the driver cannot flip without waiting for vertical synchronization (vsync) in full-screen mode.

For more information, see Flipping Surfaces.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

IDirectDrawSurface7::Blt, IDirectDrawSurface7::Flip


ID3DXMatrixStack

Applications use the methods of the ID3DXMatrixStack interface to manipulate a matrix stack. This section is a reference to the methods of this interface.

The ID3DXMatrixStack interface is obtained by calling the D3DXCreateMatrixStack function.

The methods of the ID3DXMatrixStack interface can be organized into the following groups:

Matrix Multiplication | MultMatrix
 | MultMatrixLocal
Miscellaneous | GetTop
 | LoadIdentity
 | LoadMatrix
 | Pop
 | Push
Rotation | RotateAxis
 | RotateAxisLocal
 | RotateYawPitchRoll
 | RotateYawPitchRollLocal
Scaling | Scale
 | ScaleLocal
Translation | Translate
 | TranslateLocal

The ID3DXMatrixStack interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.


ID3DXMatrixStack::GetTop

The ID3DXMatrixStack::GetTop method returns the current matrix at the top of the stack.

D3DXMATRIX* GetTop();

Parameters

None.

Return Values

This method returns a pointer to a D3DXMATRIX structure representing the current matrix.

Remarks

The D3DXMATRIX pointer returned by this method is not guaranteed to be valid after subsequent stack operations.

Note that this method does not remove the current matrix from the top of the stack; rather; it just returns the current matrix.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

ID3DXMatrixStack::Pop, ID3DXMatrixStack::Push


ID3DXMatrixStack::LoadIdentity

The ID3DXMatrixStack::LoadIdentity method loads identity in the current matrix.

HRESULT LoadIdentity();

Parameters

None.

Return Values

This method returns S_OK.

Remarks

The identity matrix is a matrix in which all coefficients are 0.0 except the [1,1][2,2][3,3][4,4] coefficients, which are set to 1.0. The identity matrix is special in that when it is applied to vertices, they are unchanged. The identity matrix is used as the starting point for matrices that will modify vertex values to create rotations, translations, and any other transformations that can be represented by a 4×4 matrix.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

ID3DXMatrixStack::LoadMatrix


ID3DXMatrixStack::LoadMatrix

The ID3DXMatrixStack::LoadMatrix method loads the given matrix into the current matrix.

HRESULT LoadMatrix(
  const D3DXMATRIX* pMat
);

Parameters

pMat
A pointer to the D3DXMATRIX structure loaded into the current matrix.

Return Values

If this method is successful, it returns S_OK; otherwise, it returns D3DXERR_NULLPOINTER.

Remarks

Note that this method does not add an item to the stack; rather; it replaces the current matrix with the supplied matrix.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

ID3DXMatrixStack::LoadIdentity


ID3DXMatrixStack::MultMatrix

The ID3DXMatrixStack::MultMatrix method determines the product of the current matrix and the given matrix.

HRESULT MultMatrix(
  const D3DXMATRIX* pMat
);

Parameters

pMat
A pointer to the D3DXMATRIX structure to be multiplied with the current matrix.

Return Values

If this method is successful, it returns S_OK; otherwise, it returns D3DXERR_NULLPOINTER.

Remarks

This method right-multiplies the given matrix to the current matrix (transformation is about the current world origin):

    m_stack[m_currentPos] = m_stack[m_currentPos] * *pMat;

Note that this method does not add an item to the stack; rather; it replaces the current matrix with the product of the current matrix and the given matrix.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

ID3DXMatrixStack::MultMatrixLocal


ID3DXMatrixStack::MultMatrixLocal

The ID3DXMatrixStack::MultMatrixLocal method determines the product of the given matrix and the current matrix.

HRESULT MultMatrixLocal(
  const D3DXMATRIX* pMat
);

Parameters

pMat
A pointer to the D3DXMATRIX structure to be multiplied with the current matrix.

Return Values

If this method is successful, it returns S_OK; otherwise, it returns D3DXERR_NULLPOINTER.

Remarks

This method left-multiplies the given matrix to the current matrix (transformation is about the local origin of the object):

    m_stack[m_currentPos] = *pMat * m_stack[m_currentPos];

Note that this method does not add an item to the stack; rather; it replaces the current matrix with the product of the given matrix and the current matrix.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

ID3DXMatrixStack::MultMatrix


ID3DXMatrixStack::Pop

The ID3DXMatrixStack::Pop method removes the current matrix from the top of the stack.

HRESULT Pop();

Parameters

None.

Return Values

This method returns S_OK.

Remarks

Note that this method decrements the count of items on the stack by 1, effectively removing the current matrix from the top of the stack and promoting a matrix to the top of the stack. If the current count of items on the stack is 0, then this method simply returns without performing any action. If the current count of items on the stack is 1, then this method empties the stack.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

ID3DXMatrixStack::GetTop, ID3DXMatrixStack::Push


ID3DXMatrixStack::Push

The ID3DXMatrixStack::Push method adds a matrix to the stack.

HRESULT Push();

Parameters

None.

Return Values

If this method is successful, it returns S_OK; otherwise, it returns D3DXERR_NOMEMORY.

Remarks

This method increments the count of items on the stack by 1, duplicating the current matrix. The stack will grow dynamically as more items are added.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

ID3DXMatrixStack::GetTop, ID3DXMatrixStack::Pop


ID3DXMatrixStack::RotateAxis

The ID3DXMatrixStack::RotateAxis method determines the product of the current matrix and the computed rotation matrix.

HRESULT RotateAxis(
  const D3DXVECTOR3* pV,
  float angle
);

Parameters

pV
A pointer to a D3DXVECTOR3 structure that identifies the axis angle.
angle
The angle of rotation in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Return Values

If this method is successful, it returns S_OK; otherwise, it returns D3DXERR_NULLPOINTER.

Remarks

This method right-multiplies the current matrix with the computed rotation matrix, counterclockwise about the given axis with the given angle (rotation is about the current world origin):

    D3DXMATRIX tmp;

    D3DXMatrixRotationAxis( &tmp, pV, angle );
    m_stack[m_currentPos] = m_stack[m_currentPos] * tmp;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

ID3DXMatrixStack::RotateAxisLocal, ID3DXMatrixStack::RotateYawPitchRoll, ID3DXMatrixStack::RotateYawPitchRollLocal


ID3DXMatrixStack::RotateAxisLocal

The ID3DXMatrixStack::RotateAxisLocal method determines the product of the computed rotation matrix and the current matrix.

HRESULT RotateAxisLocal(
  const D3DXVECTOR3* pV,
  float angle
);

Parameters

pV
A pointer to a D3DXVECTOR3 structure that identifies the axis angle.
angle
The angle of rotation in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Return Values

If this method is successful, it returns S_OK; otherwise, it returns D3DXERR_NULLPOINTER.

Remarks

This method left-multiplies the current matrix with the computed rotation matrix, counterclockwise about the given axis with the given angle (rotation is about the local origin of the object):

    D3DXMATRIX tmp;

    D3DXMatrixRotationAxis( &tmp, pV, angle );
    m_stack[m_currentPos] = tmp * m_stack[m_currentPos];

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

ID3DXMatrixStack::RotateAxis, ID3DXMatrixStack::RotateYawPitchRoll, ID3DXMatrixStack::RotateYawPitchRollLocal


ID3DXMatrixStack::RotateYawPitchRoll

The ID3DXMatrixStack::RotateYawPitchRoll method determines the product of the current matrix and the computed rotation matrix (composed of a given yaw, pitch, and roll).

HRESULT RotateYawPitchRoll(
  float yaw,
  float pitch,
  float roll
);

Parameters

yaw
The yaw around the y-axis in radians.
pitch
The pitch around the x-axis in radians.
roll
The roll around the z-axis in radians.

Return Values

This method returns S_OK.

Remarks

This method right-multiplies the current matrix with the computed rotation matrix. All angles are counterclockwise and rotation is about the current world origin:

    D3DXMATRIX tmp;

    D3DXMatrixRotationYawPitchRoll( &tmp, yaw, pitch, roll );
    m_stack[m_currentPos] = m_stack[m_currentPos] * tmp;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

ID3DXMatrixStack::RotateAxis, ID3DXMatrixStack::RotateAxisLocal, ID3DXMatrixStack::RotateYawPitchRollLocal


ID3DXMatrixStack::RotateYawPitchRollLocal

The ID3DXMatrixStack::RotateYawPitchRollLocal method determines the product of the computed rotation matrix (composed of a given yaw, pitch, and roll) and the current matrix.

HRESULT RotateYawPitchRollLocal(
  float yaw,
  float pitch,
  float roll
);

Parameters

yaw
The yaw around the y-axis in radians.
pitch
The pitch around the x-axis in radians.
roll
The roll around the z-axis in radians.

Return Values

This method returns S_OK.

Remarks

This method left-multiplies the current matrix with the computed rotation matrix. All angles are counterclockwise and rotation is about the local origin of the object:

    D3DXMATRIX tmp;

    D3DXMatrixRotationYawPitchRoll( &tmp, yaw, pitch, roll );
    m_stack[m_currentPos] = tmp * m_stack[m_currentPos];

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

ID3DXMatrixStack::RotateAxis, ID3DXMatrixStack::RotateAxisLocal, ID3DXMatrixStack::RotateYawPitchRoll


ID3DXMatrixStack::Scale

The ID3DXMatrixStack::Scale method determines the product of the current matrix and the computed scale matrix composed from the given point (x, y, and z).

HRESULT Scale(
  float x,
  float y,
  float z
);

Parameters

x
The scaling component in the x-direction.
y
The scaling component in the y-direction.
z
The scaling component in the z-direction.

Return Values

This method returns S_OK.

Remarks

This method right-multiplies the current matrix with the computed scale matrix (transformation is about the current world origin):

    D3DXMATRIX tmp;

    D3DXMatrixScaling( &tmp, x, y, z );
    m_stack[m_currentPos] = m_stack[m_currentPos] * tmp;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

ID3DXMatrixStack::ScaleLocal


ID3DXMatrixStack::ScaleLocal

The ID3DXMatrixStack::ScaleLocal method determines the product of the computed scale matrix composed from the given point (x, y, and z) and the current matrix.

HRESULT Scale(
  float x,
  float y,
  float z
);

Parameters

x
The scaling component in the x-direction.
y
The scaling component in the y-direction.
z
The scaling component in the z-direction.

Return Values

This method returns S_OK.

Remarks

This method left-multiplies the current matrix with the computed scale matrix (transformation is about the local origin of the object):

    D3DXMATRIX tmp;

    D3DXMatrixScaling( &tmp, x, y, z );
    m_stack[m_currentPos] = tmp * m_stack[m_currentPos];

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

ID3DXMatrixStack::Scale


ID3DXMatrixStack::Translate

The ID3DXMatrixStack::Translate method determines the product of the current matrix and the computed translation matrix determined by the given factors (x, y, and z).

HRESULT Translate(
  float x,
  float y,
  float z
);

Parameters

x
The translation factor in the x-direction.
y
The translation factor in the y-direction.
z
The translation factor in the z-direction.

Return Values

This method returns S_OK.

Remarks

This method right-multiplies the current matrix with the computed translation matrix (transformation is about the current world origin):

    D3DXMATRIX tmp;

    D3DXMatrixTranslation( &tmp, x, y, z );
    m_stack[m_currentPos] = m_stack[m_currentPos] * tmp;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

ID3DXMatrixStack::TranslateLocal


ID3DXMatrixStack::TranslateLocal

The ID3DXMatrixStack::TranslateLocal method determines the product of the computed translation matrix determined by the given factors (x, y, and z) and the current matrix.

HRESULT TranslateLocal(
  float x,
  float y,
  float z
);

Parameters

x
The translation factor in the x-direction.
y
The translation factor in the y-direction.
z
The translation factor in the z-direction.

Return Values

This method returns S_OK.

Remarks

This method left-multiplies the current matrix with the computed translation matrix (transformation is about the local origin of the object):

    D3DXMATRIX tmp;

    D3DXMatrixTranslation( &tmp, x, y, z );
    m_stack[m_currentPos] = tmp * m_stack[m_currentPos];

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

ID3DXMatrixStack::Translate


ID3DXSimpleShape

The ID3DXSimpleShape interface is obtained by drawing a shape with one of the following global functions:

  • D3DXCreateBox
  • D3DXCreateCylinder
  • D3DXCreatePolygon
  • D3DXCreateSphere
  • D3DXCreateTeapot
  • D3DXCreateTorus

The methods of the ID3DXSimpleShape interface can be organized into the following groups:

Information | GetIndices
 | GetVB
Rendering | Draw

The ID3DXSimpleShape interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxshapes.h.
Library: Use d3dx.lib.


ID3DXSimpleShape ::Draw

DirectX SDK

ID3DXSimpleShape::Draw

The ID3DXSimpleShape::Draw method is used to draw a shape object.

HRESULT Draw();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value may be one of the following values:

D3DXERR_NULLPOINTER
D3DERR_INVALIDRAMPTEXTURE
D3DERR_INVALIDPRIMITIVETYPE
D3DERR_INVALIDVERTEXTYPE
D3DERR_VERTEXBUFFERLOCKED
DDERR_INVALIDPARAMS
DDERR_WASSTILLDRAWING

Remarks

This function is used to draw the vertex-buffer generated by one of the shape drawing functions.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxshapes.h.
Library: Use d3dx.lib.

See Also

IDirect3DDevice7::DrawIndexedPrimitive, IDirect3DDevice7::DrawPrimitive


ID3DXSimpleShape ::GetIndices

DirectX SDK

ID3DXSimpleShape::GetIndices

The ID3DXSimpleShape::GetIndices method is used to obtain index information from shape objects.

DWORD GetIndices(
  LPWORD* ppIndices
);

Parameters

ppIndices
After the method returns, this parameter holds the address of a pointer to the index list.

Return Values

This method returns the number of indices in the index list.

Remarks

The values in the index list are used to index into a vertex list when creating geometry to render.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxshapes.h.
Library: Use d3dx.lib.

See Also

IDirect3DDevice7::DrawIndexedPrimitive


ID3DXSimpleShape ::GetVB

DirectX SDK

ID3DXSimpleShape::GetVB

The ID3DXSimpleShape::GetVB method is used to obtain vertex information from shape objects.

LPDIRECT3DVERTEXBUFFER7 GetVB();

Parameters

None.

Return Values

This method returns a pointer to an IDirect3DVertexBuffer7 interface.

Remarks

This method will increase the reference count of the vertex buffer, so you should call Release on the returned vertex buffer when finished with it.

When you use one of the shape drawing methods to draw a shape, you can specify the number of texture coordinates. Direct3DX will then allocate the appropriate amount of space in the vertex buffer.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxshapes.h.
Library: Use d3dx.lib.

See Also

Vertex Buffers


Functions

This section contains links to the functions used by the Direct3DX utility library:

  • General Purpose Functions
  • Math Functions
  • Shape Drawing Functions
  • Sprite Helper Functions
  • Texturing Functions


General Purpose Functions

The general purpose functions provided by the Direct3DX utility library allow you to perform many basic tasks including querying devices, video modes and surface formats; setting up and shutting down Direct3DX; and creating contexts and making surface and pixel formats.

The general purpose functions can be organized into the following groups:

Creation | D3DXCreateContext
 | D3DXCreateContextEx
Devices | D3DXGetDeviceCaps
 | D3DXGetDeviceCount
 | D3DXGetDeviceDescription
Initialization | D3DXInitialize
 | D3DXUninitialize
Miscellaneous | D3DXGetErrorString
Modes | D3DXGetCurrentVideoMode
 | D3DXGetMaxNumVideoModes
 | D3DXGetVideoMode
Surfaces | D3DXGetMaxSurfaceFormats
 | D3DXGetSurfaceFormat
 | D3DXMakeDDPixelFormat
 | D3DXMakeSurfaceFormat


D3DXCreateContext

The D3DXCreateContext function initializes the specified device.

HRESULT D3DXCreateContext(
  DWORD deviceIndex,
  DWORD flags,
  HWND hwnd,
  DWORD width,
  DWORD height,
  LPD3DXCONTEXT* ppCtx
);

Parameters

deviceIndex
An index value specifying the device. Specifying D3DX_DEFAULT for this parameter will initialize the device with the highest acceleration level afforded on the primary surface. For a complete list of possible values see the Hardware Acceleration Level Constants reference topic.
flags
The valid flags are D3DX_CONTEXT_FULLSCREEN, and D3DX_CONTEXT_OFFSCREEN. These flags cannot both be specified. If no flags are specified, the context defaults to windowed mode.
hwnd
The device window. See remarks.
width
The width of the window, in pixels, or D3DX_DEFAULT. See remarks.
height
The height of the window, in pixels, or D3DX_DEFAULT. See remarks.
ppCtx
The address of a pointer to the context object that is used for rendering on the chosen device.

Return Values

If the function succeeds, the return value is S_OK.

If the function fails, the return value may be one of the following values:

D3DXERR_D3DXNOTSTARTEDYET
D3DXERR_INITFAILED
D3DXERR_INVALIDPARAMETER
D3DXERR_NOMEMORY
D3DXERR_NOZBUFFER
D3DXERR_NOZBUFFERAVAILABLE
D3DXERR_NULLPOINTER
DDERR_CANNOTATTACHSURFACE
DDERR_GENERIC
DDERR_INCOMPATIBLEPRIMARY
DDERR_INVALIDCAPS
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDPIXELFORMAT
DDERR_INVALIDSURFACETYPE
DDERR_NOALPHAHW
DDERR_NOCLIPPERATTACHED
DDERR_NOCOOPERATIVELEVELSET
DDERR_NODIRECTDRAWHW
DDERR_NOEMULATION
DDERR_NOEXCLUSIVEMODE
DDERR_NOFLIPHW
DDERR_NOMIPMAPHW
DDERR_NOOVERLAYHW
DDERR_NOPALETTEATTACHED
DDERR_NOPALETTEHW
DDERR_NOT8BITCOLOR
DDERR_NOZBUFFERHW
DDERR_OUTOFMEMORY
DDERR_OUTOFVIDEOMEMORY
DDERR_PRIMARYSURFACEALREADYEXISTS
DDERR_SURFACEALREADYATTACHED
DDERR_SURFACELOST
DDERR_UNSUPPORTED
DDERR_UNSUPPORTEDMODE
DDERR_WASSTILLDRAWING

Remarks

If your application is operating in windowed mode, hwnd must be a valid window (it cannot be NULL or D3DX_DEFAULT). Also, if either width or height is D3DX_DEFAULT, both values default to the dimensions of the client area of hwnd.

If your application is operating in full-screen mode, hwnd must be a valid window (it cannot be NULL or D3DX_DEFAULT). Also, if either width or height is D3DX_DEFAULT, width defaults to 640 pixels, and height defaults to 480 pixels.

If your application is operating in off-screen mode: hwnd must be NULL or D3DX_DEFAULT. An error is returned if either width or height is D3DX_DEFAULT.

The D3DXCreateContext function is the simplest Direct3DX initialization function available. Parameters are treated the same as the matching subset of parameters in the D3DXCreateContextEx function. The D3DXCreateContextEx parameters not present in the D3DXCreateContext function are treated as D3DX_DEFAULT.

Note Multiple monitor systems are not supported by contexts created with the D3DXCreateContext function. For multiple monitor support, see the D3DXCreateContextEx function.

As with any function, you should not expect D3DXCreateContext to be fail-safe. Supported device capabilities should be used as a guide for choosing parameter values. Inevitably, there will be some combinations of parameters that do not work.

The default projection matrix setup by the D3DXCreateContext function is a left-handed perspective projection with a field-of-view (fov) of pi/2 radians.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

D3DXCreateContextEx


D3DXCreateContextEx

The D3DXCreateContextEx function initializes the specified device. Note that this is a more advanced initialization function than D3DXCreateContext.

HRESULT D3DXCreateContextEx(
  DWORD deviceIndex,
  DWORD flags,
  HWND hwnd,
  HWND hwndFocus,
  DWORD numColorBits,
  DWORD numAlphaBits,
  DWORD numDepthbits,
  DWORD numStencilBits,
  DWORD numBackBuffers,
  DWORD width,
  DWORD height,
  DWORD refreshRate,
  LPD3DXCONTEXT* ppCtx
);

Parameters

deviceIndex
An index value specifying the device. Specifying D3DX_DEFAULT for this parameter will initialize the device with the highest acceleration level afforded on the primary surface. For a complete list of possible values see the Hardware Acceleration Level Constants reference topic.
flags
The valid flags are D3DX_CONTEXT_FULLSCREEN, and D3DX_CONTEXT_OFFSCREEN. These flags cannot both be specified. If no flags are specified, the context defaults to windowed mode.
hwnd
The device window. See remarks.
hwndFocus
The window that receives the keyboard messages from the device window. The device window should be a child of the focus window. This parameter is useful for multiple monitor applications. See remarks.
numColorBits
The number of color bits. If D3DX_DEFAULT is passed for windowed mode, the current desktop's color depth is chosen. For full screen mode, D3DX_DEFAULT causes 16 bit color to be used.
numAlphaBits
The number of bits reserved for the alpha channel. If D3DX_DEFAULT is passed, 0 is chosen.
numDepthbits
The number of bits reserved for the depth buffer. If D3DX_DEFAULT is passed, the highest available number of depth bits is chosen. See remarks.
numStencilBits
The number of bits reserved for the stencil buffer. If D3DX_DEFAULT is passed, the highest available number of stencil bits is chosen. See remarks.
numBackBuffers
The number of back buffers, or D3DX_DEFAULT. See remarks.
width
The width of the window, in pixels, or D3DX_DEFAULT. See remarks.
height
The height of the window, in pixels, or D3DX_DEFAULT. See remarks.
refreshRate
The refresh rate. This parameter is ignored for windowed and off-screen modes. D3DX_DEFAULT means to let DirectDraw choose for your application.
ppCtx
The address of a pointer to the context object that is used for rendering on the chosen device.

Return Values

If the function succeeds, the return value is S_OK.

If the function fails, the return value may be one of the following values:

D3DXERR_D3DXNOTSTARTEDYET
D3DXERR_INITFAILED
D3DXERR_INVALIDPARAMETER
D3DXERR_NOMEMORY
D3DXERR_NOZBUFFER
D3DXERR_NOZBUFFERAVAILABLE
D3DXERR_NULLPOINTER
DDERR_CANNOTATTACHSURFACE
DDERR_GENERIC
DDERR_INCOMPATIBLEPRIMARY
DDERR_INVALIDCAPS
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDPIXELFORMAT
DDERR_INVALIDSURFACETYPE
DDERR_NOALPHAHW
DDERR_NOCLIPPERATTACHED
DDERR_NOCOOPERATIVELEVELSET
DDERR_NODIRECTDRAWHW
DDERR_NOEMULATION
DDERR_NOEXCLUSIVEMODE
DDERR_NOFLIPHW
DDERR_NOMIPMAPHW
DDERR_NOOVERLAYHW
DDERR_NOPALETTEATTACHED
DDERR_NOPALETTEHW
DDERR_NOT8BITCOLOR
DDERR_NOZBUFFERHW
DDERR_OUTOFMEMORY
DDERR_OUTOFVIDEOMEMORY
DDERR_PRIMARYSURFACEALREADYEXISTS
DDERR_SURFACEALREADYATTACHED
DDERR_SURFACELOST
DDERR_UNSUPPORTED
DDERR_UNSUPPORTEDMODE
DDERR_WASSTILLDRAWING

Remarks

If your application is operating in windowed mode, the hwnd parameter must be a valid window. The hwndFocus parameter must be NULL or D3DX_DEFAULT. Also, if either the width or the height parameter is D3DX_DEFAULT, both values default to the dimensions of the client area of hwnd. Specifying D3DX_DEFAULT for numBackBuffers means 1. You must specify one back buffer.

If your application is operating in full-screen mode, either hwnd or hwndFocus must be a valid window (both cannot be NULL or D3DX_DEFAULT). If hwnd is NULL or D3DX_DEFAULT, a default device window will be created as a child of hwndFocus. If either width or height is D3DX_DEFAULT, width defaults to 640 pixels, and height defaults to 480 pixels. Specifying D3DX_DEFAULT for numBackBuffers means 1. Any number of back buffers can be specified.

If your application is operating in off-screen mode, both hwnd and hwndFocus must be NULL or D3DX_DEFAULT. An error is returned if either width or height is D3DX_DEFAULT. Specifying D3DX_DEFAULT for numBackBuffers means 0. You cannot specify additional back buffers.

If both the numDepthBits and numStencilBits parameters are D3DX_DEFAULT, Direct3DX first picks the highest available number of stencil bits. Then, for the chosen number of stencil bits, the highest available number of depth bits are chosen. If only one of the numStencilBits or numDepthBits parameters is D3DX_DEFAULT, the highest number of bits available for that default parameter is chosen out of the formats that support the number of bits requested for the fixed parameter.

As with any function, you should not expect D3DXCreateContextEx to be fail-safe. Supported device capabilities should be used as a guide for choosing parameter values. Inevitably, there will be some combinations of parameters that do not work.

The default projection matrix setup by the D3DXCreateContextEx function is a left-handed perspective projection with a field-of-view (fov) of pi/2 radians.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

D3DXCreateContext


D3DXGetCurrentVideoMode

The D3DXGetCurrentVideoMode function retrieves the current video mode for the specified device.

HRESULT D3DXGetCurrentVideoMode(
  DWORD deviceIndex,
  D3DX_VIDMODEDESC* pVidMode
);

Parameters

deviceIndex
An index value specifying the device. Using D3DX_DEFAULT for this parameter specifies the device with the highest acceleration level afforded on the primary surface.
pVidMode
A pointer to a D3DX_VIDMODEDESC structure that returns with a description of the current display mode.

Return Values

If the function succeeds, the return value is S_OK.

If the function fails, the return value may be one of the following values:

D3DXERR_D3DXNOTSTARTEDYET
D3DXERR_INITFAILED
D3DXERR_INVALIDD3DXDEVICEINDEX
D3DXERR_NULLPOINTER

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

D3DXGetMaxNumVideoModes, D3DXGetVideoMode


D3DXGetDeviceCaps

The D3DXGetDeviceCaps function lists all the capabilities of a device at a display mode.

HRESULT D3DXGetDeviceCaps(
  DWORD deviceIndex,
  D3DX_VIDMODEDESC* pVidMode,
  D3DDEVICEDESC7* pD3DCaps,
  DDCAPS* pDDHALCaps,
  DDCAPS* pDDHELCaps
);

Parameters

deviceIndex
An index value specifying the device. Using D3DX_DEFAULT for this parameter specifies the device with the highest acceleration level afforded on the primary surface.
pVidMode
A pointer to a D3DX_VIDMODEDESC structure describing the display mode. If this parameter is NULL, Direct3DX will return the capabilities for the current display mode of the device.
pD3DCaps
A pointer to a D3DDEVICEDESC7 structure, describing the Direct3D capabilities of the chosen device. Specify NULL to ignore this parameter.
pDDHALCaps
A pointer to a DDCAPS structure, describing the DirectDraw hardware abstraction layer (HAL) capabilities. Specify NULL to ignore this parameter.
pDDHELCaps
A pointer to a DDCAPS structure, describing the DirectDraw hardware emulation layer (HEL) capabilities. Specify NULL to ignore this parameter

Return Values

If the function succeeds, the return value is S_OK.

If the function fails, the return value may be one of the following values:

D3DXERR_CAPSNOTSUPPORTED
D3DXERR_D3DXNOTSTARTEDYET
D3DXERR_FAILEDGETCAPS
D3DXERR_INITFAILED
D3DXERR_INVALIDD3DXDEVICEINDEX

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

D3DXGetDeviceCount, D3DXGetDeviceDescription


D3DXGetDeviceCount

The D3DXGetDeviceCount function returns the maximum number of Direct3DX devices available.

DWORD D3DXGetDeviceCount();

Parameters

None.

Return Values

The maximum number of Direct3DX devices available.

Remarks

If there is an error, this function will return 0.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

D3DXGetDeviceCaps, D3DXGetDeviceDescription


D3DXGetDeviceDescription

The D3DXGetDeviceDescription function retrieves a description of the specified device.

HRESULT D3DXGetDeviceDescription(
  DWORD deviceIndex,
  D3DX_DEVICEDESC* pd3dxDeviceDesc
);

Parameters

deviceIndex
An index value specifying the device. Device indexing begins at zero. Using D3DX_DEFAULT for this parameter specifies the device with the highest acceleration level afforded by the primary surface.
pd3dxDeviceDesc
A pointer to the D3DX_DEVICEDESC structure to be filled with the capabilities of the specified device.

Return Values

If the function succeeds, the return value is S_OK.

If the function fails, the return value may be one of the following values:

D3DXERR_D3DXNOTSTARTEDYET
D3DXERR_INITFAILED
D3DXERR_INVALIDD3DXDEVICEINDEX
D3DXERR_NULLPOINTER

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

D3DXGetDeviceCaps, D3DXGetDeviceCount


D3DXGetErrorString

The D3DXGetErrorString function prints out an error string given an HRESULT.

void D3DXGetErrorString(
  HRESULT hr,
  DWORD strLength,
  LPSTR pStr
);

Parameters

hr
The HRESULT error code to be deciphered.
strLength
The length of the string passed in.
pStr
The string output. Note that a string of appropriate size, specified in the strLength parameter, needs to be passed in.

Return Values

None.

Remarks

The D3DXGetErrorString function prints Win32, DirectX 6.0, and Direct3DX error messages.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.


D3DXGetMaxNumVideoModes

The D3DXGetMaxNumVideoModes function returns the maximum number of video modes.

DWORD D3DXGetMaxNumVideoModes(
  DWORD deviceIndex,
  DWORD flags
);

Parameters

deviceIndex
An index value specifying the device. Using D3DX_DEFAULT for this parameter specifies the device with the highest acceleration level afforded on the primary surface.
flags
Refresh rates will be ignored unless the D3DX_GVM_REFRESHRATE flag is set by this parameter. If you want refresh rates to be ignored, set this parameter to 0.

Return Values

If the function succeeds, the return value is the maximum number of video modes.

If the function fails, zero is returned.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

D3DXGetCurrentVideoMode, D3DXGetVideoMode


D3DXGetMaxSurfaceFormats

The D3DXGetMaxSurfaceFormats function returns the maximum number of surface formats supported by the device at the specified video mode.

DWORD D3DXGetMaxSurfaceFormats(
  DWORD deviceIndex,
  D3DX_VIDMODEDESC* pDesc,
  DWORD surfClassFlags
);

Parameters

deviceIndex
An index value specifying the device. Using D3DX_DEFAULT for this parameter specifies the device with the highest acceleration level afforded on the primary surface.
pDesc
A pointer to a D3DX_VIDMODEDESC structure describing the display mode at which the supported surface formats are requested. If this parameter is NULL, the current display mode is assumed.
surfClassFlags
A member of the D3DX_SURFACECLASS enumerated type, indicating the surface classes whose supported formats are requested.

Return Values

If the function succeeds, the return value is the maximum number of surface formats supported by the device at the specified video mode.

If the function fails, the return value may be one of the following values:

D3DXERR_D3DXNOTSTARTEDYET
D3DXERR_INITFAILED
D3DXERR_INVALIDD3DXDEVICEINDEX

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

D3DXGetSurfaceFormat


D3DXGetSurfaceFormat

The D3DXGetSurfaceFormat function describes one of the supported surface formats for this device.

HRESULT D3DXGetSurfaceFormat(
  DWORD deviceIndex,
  D3DX_VIDMODEDESC* pDesc,
  DWORD surfClassFlags,
  DWORD surfaceIndex,
  D3DX_SURFACEFORMAT* pFormat
);

Parameters

deviceIndex
An index value specifying the device. Using D3DX_DEFAULT for this parameter specifies the device with the highest acceleration level afforded on the primary surface.
pDesc
A pointer to a D3DX_VIDMODEDESC structure describing the display mode at which the supported surface formats are requested. If this parameter is NULL, the current display mode is assumed.
surfClassFlags
A member of the D3DX_SURFACECLASS enumerated type, indicating the surface classes whose supported formats are requested.
surfaceIndex
A DWORD value, indicating which surface formats to retrieve. Indexing begins at zero.
pFormat
A pointer to a member of the D3DX_SURFACEFORMAT enumerated type; the returned surface format.

Return Values

If the function succeeds, the return value is S_OK.

If the function fails, the return value may be one of the following values:

D3DXERR_D3DXNOTSTARTEDYET
D3DXERR_INITFAILED
D3DXERR_INVALIDD3DXDEVICEINDEX
D3DXERR_INVALIDPARAMETER
D3DXERR_NULLPOINTER

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

D3DXGetMaxSurfaceFormats


D3DXGetVideoMode

The D3DXGetVideoMode function describes a particular video mode for this device.

HRESULT D3DXGetVideoMode(
  DWORD deviceIndex,
  DWORD flags,
  DWORD modeIndex,
  D3DX_VIDMODEDESC* pModeList
);

Parameters

deviceIndex
An index value specifying the device. Using D3DX_DEFAULT for this parameter specifies the device with the highest acceleration level afforded on the primary surface.
flags
Refresh rates will be ignored unless the D3DX_GVM_REFRESHRATE flag is set by this parameter. If you want refresh rates to be ignored, set this parameter to 0.
modeIndex
A DWORD value specifying the device. Indexing begins at zero.
pModeList
A pointer to a D3DX_VIDMODEDESC structure that returns with a description of the display mode for the device.

Return Values

If the function succeeds, the return value is S_OK.

If the function fails, the return value may be one of the following values:

D3DXERR_D3DXNOTSTARTEDYET
D3DXERR_INITFAILED
D3DXERR_INVALIDD3DXDEVICEINDEX
D3DXERR_INVALIDPARAMETER
D3DXERR_NULLPOINTER

Remarks

Queries performed with the D3DXGetVideoMode function will simply give you a list of modes that the display adapter tells DirectX that it supports. There is no guarantee that the D3DXCreateContext or D3DXCreateContextEx functions will succeed with all of the listed video modes.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

D3DXGetMaxNumVideoModes, D3DXGetMaxNumVideoModes


D3DXInitialize

The D3DXInitialize function initializes Direct3DX.

HRESULT D3DXInitialize();

Parameters

None.

Return Values

If the function succeeds, the return value is S_OK.

If the function fails, the return value may be one of the following values:

D3DXERR_NOMEMORY
D3DXERR_STARTUPFAILED

Remarks

The D3DXInitialize function is the first call made by a Direct3DX application.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

D3DXUninitialize


D3DXMakeDDPixelFormat

The D3DXMakeDDPixelFormat function returns a DDPIXELFORMAT structure based on the Direct3DX surface format requested.

HRESULT D3DXMakeDDPixelFormat(
  D3DX_SURFACEFORMAT d3dxFormat,
  DDPIXELFORMAT* pddpf
);

Parameters

d3dxFormat
A pointer to a member of the D3DX_SURFACEFORMAT enumerated type; the surface format.
pddpf
A pointer to a DDPIXELFORMAT structure which returns describing a pixel format matching the given surface format.

Return Values

If the function succeeds, the return value is S_OK.

If the function fails, the return value may be one of the following values:

D3DXERR_NULLPOINTER
D3DXERR_INVALIDPARAMETER

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

D3DXMakeSurfaceFormat


D3DXMakeSurfaceFormat

The D3DXMakeSurfaceFormat function determines the surface format corresponding to a given DDPIXELFORMAT structure.

D3DX_SURFACEFORMAT D3DXMakeSurfaceFormat(
  DDPIXELFORMAT* pddpf
);

Parameters

pddpf
A pointer to a DDPIXELFORMAT structure.

Return Values

A member of the D3DX_SURFACEFORMAT enumerated type corresponding to the pddpf parameter.

Remarks

The D3DXMakeSurfaceFormat function will return D3DX_SF_UNKNOWN if the pddpf parameter is NULL or is an unrecognized pixel format.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

D3DXMakeDDPixelFormat


D3DXUninitialize

The D3DXUninitialize function frees the resources used by Direct3DX.

HRESULT D3DXUninitialize();

Parameters

None.

Return Values

If this function is successful, it returns S_OK; otherwise it returns D3DXERR_D3DXNOTSTARTEDYET.

Remarks

The D3DXUninitialize function is the final call made by a Direct3DX application.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

D3DXInitialize


Math Functions

The math library provided by the Direct3DX utility library supplies functions to compute both basic and complicated 3-D mathematical operations.

The 3-D math application functions can be organized into the following groups:

Color | D3DXColorAdd
 | D3DXColorAdjustContrast
 | D3DXColorAdjustSaturation
 | D3DXColorLerp
 | D3DXColorModulate
 | D3DXColorNegative
 | D3DXColorScale
 | D3DXColorSubtract
Creation | D3DXCreateMatrixStack
Plane | D3DXPlaneDot
 | D3DXPlaneDotCoord
 | D3DXPlaneDotNormal
 | D3DXPlaneIntersectLine
 | D3DXPlaneFromPointNormal
 | D3DXPlaneFromPoints
 | D3DXPlaneTransform
Quaternion | D3DXQuaternionBaryCentric
 | D3DXQuaternionConjugate
 | D3DXQuaternionDot
 | D3DXQuaternionExp
 | D3DXQuaternionIdentity
 | D3DXQuaternionInverse
 | D3DXQuaternionIsIdentity
 | D3DXQuaternionLength
 | D3DXQuaternionLengthSq
 | D3DXQuaternionLn
 | D3DXQuaternionMultiply
 | D3DXQuaternionNormalize
 | D3DXQuaternionRotationAxis
 | D3DXQuaternionRotationMatrix
 | D3DXQuaternionRotationYawPitchRoll
 | D3DXQuaternionSlerp
 | D3DXQuaternionSquad
 | D3DXQuaternionToAxisAngle
2-D Vector | D3DXVec2Add
 | D3DXVec2BaryCentric
 | D3DXVec2CCW
 | D3DXVec2Dot
 | D3DXVec2Hermite
 | D3DXVec2Length
 | D3DXVec2LengthSq
 | D3DXVec2Lerp
 | D3DXVec2Maximize
 | D3DXVec2Minimize
 | D3DXVec2Normalize
 | D3DXVec2Scale
 | D3DXVec2Subtract
 | D3DXVec2Transform
 | D3DXVec2TransformCoord
 | D3DXVec2TransformNormal
3-D Vector | D3DXVec3Add
 | D3DXVec3BaryCentric
 | D3DXVec3Cross
 | D3DXVec3Dot
 | D3DXVec3Hermite
 | D3DXVec3Length
 | D3DXVec3LengthSq
 | D3DXVec3Lerp
 | D3DXVec3Maximize
 | D3DXVec3Minimize
 | D3DXVec3Normalize
 | D3DXVec3Scale
 | D3DXVec3Subtract
 | D3DXVec3Transform
 | D3DXVec3TransformCoord
 | D3DXVec3TransformNormal
4-D Matrix | D3DXMatrixAffineTransformation
 | D3DXMatrixfDeterminant
 | D3DXMatrixIdentity
 | D3DXMatrixInverse
 | D3DXMatrixIsIdentity
 | D3DXMatrixLookAt
 | D3DXMatrixLookAtLH
 | D3DXMatrixMultiply
 | D3DXMatrixOrtho
 | D3DXMatrixOrthoLH
 | D3DXMatrixOrthoOffCenter
 | D3DXMatrixOrthoOffCenterLH
 | D3DXMatrixPerspective
 | D3DXMatrixPerspectiveLH
 | D3DXMatrixPerspectiveFov
 | D3DXMatrixPerspectiveFovLH
 | D3DXMatrixPerspectiveOffCenter
 | D3DXMatrixPerspectiveOffCenterLH
 | D3DXMatrixReflect
 | D3DXMatrixRotationAxis
 | D3DXMatrixRotationQuaternion
 | D3DXMatrixRotationX
 | D3DXMatrixRotationY
 | D3DXMatrixRotationYawPitchRoll
 | D3DXMatrixRotationZ
 | D3DXMatrixScaling
 | D3DXMatrixShadow
 | D3DXMatrixTransformation
 | D3DXMatrixTranslation
 | D3DXMatrixTranspose
4-D Vector | D3DXVec4Add
 | D3DXVec4BaryCentric
 | D3DXVec4Cross
 | D3DXVec4Dot
 | D3DXVec4Hermite
 | D3DXVec4Length
 | D3DXVec4LengthSq
 | D3DXVec4Lerp
 | D3DXVec4Maximize
 | D3DXVec4Minimize
 | D3DXVec4Normalize
 | D3DXVec4Scale
 | D3DXVec4Subtract
 | D3DXVec4Transform

Note All of the math functions can take the same object as both the passed (in) and returned (out) parameters. Also, out parameters are typically returned as return values, so that the output of one math function may be used as a parameter for another math function.


D3DXColorAdd

The D3DXColorAdd function adds two color values together to create a new color value.

D3DXCOLOR* D3DXColorAdd(
  D3DXCOLOR* pOut,
  const D3DXCOLOR* pC1,
  const D3DXCOLOR* pC2
);

Parameters

pOut
A pointer to a D3DXCOLOR structure that is the result of the operation.
pC1
A pointer to a source D3DXCOLOR structure.
pC2
A pointer to a source D3DXCOLOR structure.

Return Values

This function returns a pointer to a D3DXCOLOR structure that is the sum of two color values.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXColorAdd function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXColorModulate, D3DXColorSubtract


D3DXColorAdjustContrast

The D3DXColorAdjustContrast function adjusts the contrast value of a given color.

D3DXCOLOR* D3DXColorAdjustContrast(
  D3DXCOLOR* pOut,
  D3DXCOLOR* pC,
  float c
);

Parameters

pOut
A pointer to a D3DXCOLOR structure that is the result of the operation.
pC
A pointer to a source D3DXCOLOR structure.
c
The contrast value. This parameter linearly interpolates between 50% gray and the given color, pC. There are not limits on the value of c. If this parameter is zero, then the returned color is 50% gray. If this parameter is 1, then the returned color is the original color.

Return Values

The function returns a pointer to a D3DXCOLOR structure that is the result of the contrast adjustment.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXColorAdjustContrast function can be used as a parameter for another function.

This function interpolates the red, green, and blue color components of a D3DXCOLOR structure between 50% gray and a specified contrast value:

    pOut->r = 0.5f + c * (pC->r - 0.5f);

If c is greater than zero and less than 1, then the contrast will be decreased. If c is greater than 1, then the contrast will be increased.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXColorAdjustSaturation


D3DXColorAdjustSaturation

The D3DXColorAdjustSaturation function adjusts the saturation value of a given color.

D3DXCOLOR* D3DXColorAdjustSaturation(
  D3DXCOLOR* pOut,
  D3DXCOLOR* pC,
  float s
);

Parameters

pOut
A pointer to a D3DXCOLOR structure that is the result of the operation.
pC
A pointer to a source D3DXCOLOR structure.
s
The saturation value. This parameter linearly interpolates between the color converted to gray-scale and the original color, pC. There are no limits on the value of s. If s is zero, then the returned color is the gray-scale color. If s is 1, then the returned color is the original color.

Return Values

The function returns a pointer to a D3DXCOLOR structure that is the result of the saturation adjustment.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXColorAdjustSaturation function can be used as a parameter for another function.

This function interpolates the red, green, and blue color components of a D3DXCOLOR structure between an unsaturated color and a given color:

    // Approximate values for each component's contribution to luminance.
    // Based upon the NTSC standard described in ITU-R Recommendation BT.709.
    float grey = pC->r * 0.2125f + pC->g * 0.7154f + pC->b * 0.0721f;

    pOut->r = grey + s * (pC->r - grey);

If s is greater than zero and less than 1, then the saturation will be decreased. If s is greater than 1, then the saturation will be increased.

The gray-scale color is computed as: r = g = b = 0.2125*r + 0.7154*g + 0.0721*b.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXColorAdjustContrast


D3DXColorLerp

The D3DXColorLerp function uses linear interpolation to create a color value.

D3DXCOLOR* D3DXColorLerp(
  D3DXCOLOR* pOut,
  const D3DXCOLOR* pC1,
  const D3DXCOLOR* pC2,
  float s
);

Parameters

pOut
A pointer to a D3DXCOLOR structure that is the result of the operation.
pC1
A pointer to a source D3DXCOLOR structure.
pC2
A pointer to a source D3DXCOLOR structure.
s
This parameter linearly interpolates between the two colors, pC1 and pC2, treating them both as 4-D vectors. There are no limits on the value of s.

Return Values

The function returns a pointer to a D3DXCOLOR structure that is the result of the linear interpolation.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXColorLerp function can be used as a parameter for another function.

This function interpolates the red, green, blue, and alpha components of a D3DXCOLOR structure between two given colors:

    pOut->r = pC1->r + s * (pC2->r - pC1->r);

If you are linearly interpolating between the colors A and B, and s is zero, then the resulting color is A. If s is 1, then the resulting color is color B.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXColorModulate, D3DXColorNegative, D3DXColorScale


D3DXColorModulate

The D3DXColorModulate function blends two given colors.

D3DXCOLOR* D3DXColorModulate(
  D3DXCOLOR* pOut,
  const D3DXCOLOR* pC1,
  const D3DXCOLOR* pC2
);

Parameters

pOut
A pointer to a D3DXCOLOR structure that is the result of the operation.
pC1
A pointer to a source D3DXCOLOR structure.
pC2
A pointer to a source D3DXCOLOR structure.

Return Values

The function returns a pointer to a D3DXCOLOR structure that is the result of the blending operation.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXColorModulate function can be used as a parameter for another function.

This function blends together two given colors by multiplying matching color components:

    pOut->r = pC1->r * pC2->r;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXColorLerp, D3DXColorNegative, D3DXColorScale


D3DXColorNegative

The D3DXColorNegative function creates the negative color value of the given color value.

D3DXCOLOR* D3DXColorNegative(
  D3DXCOLOR* pOut,
  const D3DXCOLOR* pC
);

Parameters

pOut
A pointer to a D3DXCOLOR structure that is the result of the operation.
pC
A pointer to a source D3DXCOLOR structure.

Return Values

The function returns a pointer to a D3DXCOLOR structure that is the negative color value of the given color value.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXColorNegative function can be used as a parameter for another function.

This function returns the negative color value by subtracting 1.0 from the color components of the given D3DXCOLOR structure:

    pOut->r = 1.0f - pC->r;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXColorLerp, D3DXColorModulate, D3DXColorScale


D3DXColorScale

The D3DXColorScale function scales a color value.

D3DXCOLOR* D3DXColorScale(
  D3DXCOLOR* pOut,
  const D3DXCOLOR* pC,
  float s
);

Parameters

pOut
A pointer to a D3DXCOLOR structure that is the result of the operation.
pC
A pointer to a source D3DXCOLOR structure.
s
The scale factor. It just scales the color, treating it like a 4-D vector. There are no limits on the value of s. If s is 1, then the resulting color is the original color.

Return Values

The function returns a pointer to a D3DXCOLOR structure that is the scaled color value.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXColorScale function can be used as a parameter for another function.

This function computes the scaled color value by multiplying the color components of the given D3DXCOLOR structure by the specified scale factor:

    pOut->r = pC->r * s;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXColorLerp, D3DXColorModulate, D3DXColorNegative


D3DXColorSubtract

The D3DXColorSubtract function subtracts two color values to create a new color value.

D3DXCOLOR* D3DXColorSubtract(
  D3DXCOLOR* pOut,
  const D3DXCOLOR* pC1,
  const D3DXCOLOR* pC2
);

Parameters

pOut
A pointer to a D3DXCOLOR structure that is the result of the operation.
pC1
A pointer to a source D3DXCOLOR structure.
pC2
A pointer to a source D3DXCOLOR structure.

Return Values

This function returns a pointer to a D3DXCOLOR structure that is the difference between two color values.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXColorSubtract function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXColorAdd


D3DXCreateMatrixStack

The D3DXCreateMatrixStack function creates an instance of the ID3DXMatrixStack interface.

HRESULT D3DXCreateMatrixStack(
  DWORD flags,
  ID3DXMatrixStack** ppStack
);

Parameters

flags
Not implemented. Specify zero.
ppStack
The address of a pointer filled with an ID3DXMatrixStack interface pointer if the function succeeds.

Return Values

If the function succeeds, the return value is S_OK.

If the function fails, the return value may be one of the following values:

D3DXERR_NOMEMORY
D3DXERR_NULLPOINTER

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.


D3DXMatrixAffineTransformation

The D3DXMatrixAffineTransformation function builds an affine transformation matrix.

D3DXMATRIX* D3DXMatrixAffineTransformation(
  D3DXMATRIX* pOut,
  float scaling,
  const D3DXVECTOR3* pRotationCenter,
  const D3DXQUATERNION* pRotation,
  const D3DXVECTOR3* pTranslation
);

Parameters

pOut
A pointer to the D3DXMATRIX structure that is the result of the operation.
scaling
The scaling factor.
pRotationCenter
A pointer to a D3DXVECTOR3 structure, a point identifying the center of rotation. If this argument is NULL, it is treated as identity.
pRotation
A pointer to a D3DXQUATERNION structure, specifying the rotation. If this argument is NULL, it is treated as identity.
pTranslation
A pointer to a D3DXVECTOR3 structure, representing the translation. If this argument is NULL, it is treated as identity.

Return Values

A pointer to a D3DXMATRIX structure that is an affine transformation matrix.

Remarks

The D3DXMatrixAffineTransformation function calculates the affine transformation matrix with the following formula: Ms * Mrc-1 * Mr * Mrc * Mt, where Ms is the scaling matrix, Mrc is the center of rotation matrix, Mr is the rotation matrix, and Mt is the translation matrix.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixAffineTransformation function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.


D3DXMatrixfDeterminant

The D3DXMatrixfDeterminant function returns the determinant of the given matrix.

float D3DXMatrixfDeterminant(
  const D3DXMATRIX* pM
);

Parameters

pM
A pointer to the source D3DXMATRIX structure.

Return Values

The value of the matrix, the determinant.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.


D3DXMatrixIdentity

The D3DXMatrixIdentity function creates an identity matrix.

D3DXMATRIX* D3DXMatrixIdentity(
  D3DXMATRIX* pOut
);

Parameters

pOut
A pointer to the D3DXMATRIX structure that is the result of the operation.

Return Values

A pointer to a D3DXMATRIX structure that is the identity matrix.

Remarks

The identity matrix is a matrix in which all coefficients are 0 except the [1,1][2,2][3,3][4,4] coefficients, which are set to 1. The identity matrix is special in that when it is applied to vertices, they are unchanged. The identity matrix is used as the starting point for matrices that will modify vertex values to create rotations, translations, and any other transformations that can be represented by a 4×4 matrix.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixIdentity function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXMatrixIsIdentity


D3DXMatrixInverse

The D3DXMatrixInverse function calculates the inverse of the given matrix.

D3DXMATRIX* D3DXMatrixInverse(
  D3DXMATRIX* pOut,
  float* pfDeterminant,
  const D3DXMATRIX* pM
);

Parameters

pOut
A pointer to the D3DXMATRIX structure that is the result of the operation.
pfDeterminant
After this function returns, this parameter points to a float value that is the determinant of the given matrix, pM.
pM
A pointer to the source D3DXMATRIX structure.

Return Values

A pointer to a D3DXMATRIX structure that is the inverse of the given matrix.

Remarks

Matrix inversion may fail, in which case NULL will be returned by the D3DXMatrixInverse function. Note that the determinant of pM is returned if the pfDeterminant parameter is non-NULL.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixInverse function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.


D3DXMatrixIsIdentity

The D3DXMatrixIsIdentity function determines if the given matrix is an identity matrix.

BOOL D3DXMatrixIsIdentity(
  const D3DXMATRIX* pM
);

Parameters

pM
A pointer to the D3DXMATRIX structure that will be tested for identity.

Return Values

If the given matrix is an identity matrix, this function returns TRUE; otherwise, this function returns FALSE.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXMatrixIdentity


D3DXMatrixLookAt

The D3DXMatrixLookAt function builds a right-handed, look-at matrix.

D3DXMATRIX* D3DXMatrixLookAt(
  D3DXMATRIX* pOut,
  const D3DXVECTOR3* pEye,
  const D3DXVECTOR3* pAt,
  const D3DXVECTOR3* pUp
);

Parameters

pOut
A pointer to the D3DXMATRIX structure that is the result of the operation.
pEye
A pointer to the D3DXVECTOR3 structure that defines the eye point. This value is used in translation.
pAt
A pointer to the D3DXVECTOR3 structure that defines the camera look-at target.
pUp
A pointer to the D3DXVECTOR3 structure that defines the current world's up, usually [0, 1, 0].

Return Values

A pointer to a D3DXMATRIX structure that is a right-handed, look-at matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixLookAt function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXMatrixLookAtLH


D3DXMatrixLookAtLH

The D3DXMatrixLookAtLH function builds a left-handed, look-at matrix.

D3DXMATRIX* D3DXMatrixLookAtLH(
  D3DXMATRIX* pOut,
  const D3DXVECTOR3* pEye,
  const D3DXVECTOR3* pAt,
  const D3DXVECTOR3* pUp
);

Parameters

pOut
A pointer to the D3DXMATRIX structure that is the result of the operation.
pEye
A pointer to the D3DXVECTOR3 structure that defines the eye point. This value is used in translation.
pAt
A pointer to the D3DXVECTOR3 structure that defines the camera look-at target.
pUp
A pointer to the D3DXVECTOR3 structure that defines the current world's up, usually [0, 1, 0].

Return Values

A pointer to a D3DXMATRIX structure that is a left-handed, look-at matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixLookAtLH function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXMatrixLookAt


D3DXMatrixMultiply

The D3DXMatrixMultiply function determines the product of two given matrices.

D3DXMATRIX* D3DXMatrixMultiply(
  D3DXMATRIX* pOut,
  const D3DXMATRIX* pM1,
  const D3DXMATRIX* pM2
);

Parameters

pOut
A pointer to the D3DXMATRIX structure that is the result of the operation.
pM1
A pointer to a source D3DXMATRIX structure.
pM2
A pointer to a source D3DXMATRIX structure.

Return Values

A pointer to a D3DXMATRIX structure that is the product of two matrices.

Remarks

The result represents the transformation M2 followed by the transformation M1 (Out = M1 * M2).

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixMultiply function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXQuaternionMultiply


D3DXMatrixOrtho

The D3DXMatrixOrtho function builds a right-handed orthogonal projection matrix.

D3DXMATRIX* D3DXMatrixOrtho(
  D3DXMATRIX* pOut,
  float w,
  float h,
  float zn,
  float zf
);

Parameters

pOut
A pointer to the D3DXMATRIX structure that is the result of the operation.
w
The width of the view-volume.
h
The height of the view-volume.
zn
The minimum z-value of the view volume.
zf
The maximum z-value of the view volume.

Return Values

A pointer to a D3DXMATRIX structure that is a right-handed orthogonal projection matrix.

Remarks

An orthogonal matrix is an invertible matrix for which the inverse of the matrix is equal to the transpose of the matrix.

All of the parameters of the D3DXMatrixOrtho function are distances in camera-space. The parameters describe the dimensions of the view-volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixOrtho function can be used as a parameter for another function.

The default projection matrix setup by the D3DXCreateContext and D3DXCreateContextEx functions is a left-handed perspective projection with a field-of-view (fov) of pi/2 radians.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXMatrixOrthoLH, D3DXMatrixOrthoOffCenter, D3DXMatrixOrthoOffCenterLH


D3DXMatrixOrthoLH

The D3DXMatrixOrthoLH function builds a left-handed orthogonal projection matrix.

D3DXMATRIX* D3DXMatrixOrthoLH(
  D3DXMATRIX* pOut,
  float w,
  float h,
  float zn,
  float zf
);

Parameters

pOut
A pointer to the D3DXMATRIX structure that is the result of the operation.
w
The width of the view-volume.
h
The height of the view-volume.
zn
The minimum z-value of the view volume.
zf
The maximum z-value of the view volume.

Return Values

A pointer to a D3DXMATRIX structure that is a left-handed orthogonal projection matrix.

Remarks

An orthogonal matrix is an invertible matrix for which the inverse of the matrix is equal to the transpose of the matrix.

All of the parameters of the D3DXMatrixOrthoLH function are distances in camera-space. The parameters describe the dimensions of the view-volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixOrthoLH function can be used as a parameter for another function.

The default projection matrix setup by the D3DXCreateContext and D3DXCreateContextEx functions is a left-handed perspective projection with a field-of-view (fov) of pi/2 radians.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXMatrixOrtho, D3DXMatrixOrthoOffCenter, D3DXMatrixOrthoOffCenterLH


D3DXMatrixOrthoOffCenter

The D3DXMatrixOrthoOffCenter function builds a customized right-handed orthogonal projection matrix.

D3DXMATRIX* D3DXMatrixOrthoOffCenter(
  D3DXMATRIX* pOut,
  float l,
  float r,
  float t,
  float b,
  float zn,
  float zf
);

Parameters

pOut
A pointer to the D3DXMATRIX structure that is the result of the operation.
l
The minimum x-value of view-volume.
r
The maximum x-value of view-volume.
t
The minimum y-value of view-volume.
b
The maximum y-value of view-volume.
zn
The minimum z-value of the view volume.
zf
The maximum z-value of the view volume.

Return Values

A pointer to a D3DXMATRIX structure that is a right-handed orthogonal projection matrix.

Remarks

An orthogonal matrix is an invertible matrix for which the inverse of the matrix is equal to the transpose of the matrix.

The D3DXMatrixOrtho function is a special case of the D3DXMatrixOrthoOffCenter function, in order to create the same projection using D3DXMatrixOrthoOffCenter, you should use the following values: l = -w/2, r = w/2, b = -h/2, and t = h/2.

All of the parameters of the D3DXMatrixOrthoOffCenter function are distances in camera-space. The parameters describe the dimensions of the view-volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixOrthoOffCenter function can be used as a parameter for another function.

The default projection matrix setup by the D3DXCreateContext and D3DXCreateContextEx functions is a left-handed perspective projection with a field-of-view (fov) of pi/2 radians.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXMatrixOrtho, D3DXMatrixOrthoLH, D3DXMatrixOrthoOffCenterLH


D3DXMatrixOrthoOffCenterLH

The D3DXMatrixOrthoOffCenterLH function builds a customized left-handed orthogonal projection matrix.

D3DXMATRIX* D3DXMatrixOrthoOffCenterLH(
  D3DXMATRIX* pOut,
  float l,
  float r,
  float t,
  float b,
  float zn,
  float zf
);

Parameters

pOut
A pointer to the D3DXMATRIX structure that is the result of the operation.
l
The minimum x-value of view-volume.
r
The maximum x-value of view-volume.
t
The minimum y-value of view-volume.
b
The maximum y-value of view-volume.
zn
The minimum z-value of the view volume.
zf
The maximum z-value of the view volume.

Return Values

A pointer to a D3DXMATRIX structure that is a left-handed orthogonal projection matrix.

Remarks

An orthogonal matrix is an invertible matrix for which the inverse of the matrix is equal to the transpose of the matrix.

The D3DXMatrixOrthoLH function is a special case of the D3DXMatrixOrthoOffCenterLH function, in order to create the same projection using D3DXMatrixOrthoOffCenterLH, you should use the following values: l = -w/2, r = w/2, b = -h/2, and t = h/2.

All of the parameters of the D3DXMatrixOrthoOffCenterLH function are distances in camera-space. The parameters describe the dimensions of the view-volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixOrthoOffCenterLH function can be used as a parameter for another function.

The default projection matrix setup by the D3DXCreateContext and D3DXCreateContextEx functions is a left-handed perspective projection with a field-of-view (fov) of pi/2 radians.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXMatrixOrtho, D3DXMatrixOrthoLH, D3DXMatrixOrthoOffCenter


D3DXMatrixPerspective

The D3DXMatrixPerspective function builds a right-handed perspective projection matrix

D3DXMATRIX* D3DXMatrixPerspective(
  D3DXMATRIX* pOut,
  float w,
  float h,
  float zn,
  float zf
);

Parameters

pOut
A pointer to the D3DXMATRIX structure that is the result of the operation.
w
The width of the view-volume at the near view-plane.
h
The height of the view-volume at the near view-plane.
zn
The z-value of the near view-plane.
zf
The z-value of the far view-plane.

Return Values

A pointer to a D3DXMATRIX structure that is a right-handed perspective projection matrix.

Remarks

All of the parameters of the D3DXMatrixPerspective function are distances in camera-space. The parameters describe the dimensions of the view-volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspective function can be used as a parameter for another function.

The default projection matrix setup by the D3DXCreateContext and D3DXCreateContextEx functions is a left-handed perspective projection with a field-of-view (fov) of pi/2 radians.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXMatrixPerspectiveLH, D3DXMatrixPerspectiveFov, D3DXMatrixPerspectiveFovLH, D3DXMatrixPerspectiveOffCenter, D3DXMatrixPerspectiveOffCenterLH


D3DXMatrixPerspectiveFov

The D3DXMatrixPerspectiveFov function builds a right-handed perspective projection matrix based on a given field of view.

D3DXMATRIX* D3DXMatrixPerspectiveFov(
  D3DXMATRIX* pOut,
  float fovy,
  float aspect,
  float zn,
  float zf
);

Parameters

pOut
A pointer to the D3DXMATRIX structure that is the result of the operation.
fovy
The field of view in radians.
aspect
The aspect ratio.
zn
The z-value of the near view-plane.
zf
The z-value of the far view-plane.

Return Values

A pointer to a D3DXMATRIX structure that is a right-handed perspective projection matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspectiveFov function can be used as a parameter for another function.

The default projection matrix setup by the D3DXCreateContext and D3DXCreateContextEx functions is a left-handed perspective projection with a field-of-view (fov) of pi/2 radians.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXMatrixPerspective, D3DXMatrixPerspectiveLH, D3DXMatrixPerspectiveFovLH, D3DXMatrixPerspectiveOffCenter, D3DXMatrixPerspectiveOffCenterLH


D3DXMatrixPerspectiveFovLH

The D3DXMatrixPerspectiveFovLH function builds a left-handed perspective projection matrix based on a given field of view.

D3DXMATRIX* D3DXMatrixPerspectiveFovLH(
  D3DXMATRIX* pOut,
  float fovy,
  float aspect,
  float zn,
  float zf
);

Parameters

pOut
A pointer to the D3DXMATRIX structure that is the result of the operation.
fovy
The field of view in radians.
aspect
The aspect ratio.
zn
The z-value of the near view-plane.
zf
The z-value of the far view-plane.

Return Values

A pointer to a D3DXMATRIX structure that is a left-handed perspective projection matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspectiveFovLH function can be used as a parameter for another function.

The default projection matrix setup by the D3DXCreateContext and D3DXCreateContextEx functions is a left-handed perspective projection with a field-of-view (fov) of pi/2 radians.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXMatrixPerspective, D3DXMatrixPerspectiveLH, D3DXMatrixPerspectiveFov, D3DXMatrixPerspectiveOffCenter, D3DXMatrixPerspectiveOffCenterLH


D3DXMatrixPerspectiveLH

The D3DXMatrixPerspectiveLH function builds a left-handed perspective projection matrix

D3DXMATRIX* D3DXMatrixPerspectiveLH(
  D3DXMATRIX* pOut,
  float w,
  float h,
  float zn,
  float zf
);

Parameters

pOut
A pointer to the D3DXMATRIX structure that is the result of the operation.
w
The width of the view-volume at the near view-plane.
h
The height of the view-volume at the near view-plane.
zn
The z-value of the near view-plane.
zf
The z-value of the far view-plane.

Return Values

A pointer to a D3DXMATRIX structure that is a left-handed perspective projection matrix.

Remarks

All of the parameters of the D3DXMatrixPerspectiveLH function are distances in camera-space. The parameters describe the dimensions of the view-volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspectiveLH function can be used as a parameter for another function.

The default projection matrix setup by the D3DXCreateContext and D3DXCreateContextEx functions is a left-handed perspective projection with a field-of-view (fov) of pi/2 radians.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXMatrixPerspective, D3DXMatrixPerspectiveFov, D3DXMatrixPerspectiveFovLH, D3DXMatrixPerspectiveOffCenter, D3DXMatrixPerspectiveOffCenterLH


D3DXMatrixPerspectiveOffCenter

The D3DXMatrixPerspectiveOffCenter function builds a customized right-handed perspective projection matrix.

D3DXMATRIX* D3DXMatrixPerspectiveOffCenter(
  D3DXMATRIX* pOut,
  float l,
  float r,
  float t,
  float b,
  float zn,
  float zf
);

Parameters

pOut
A pointer to the D3DXMATRIX structure that is the result of the operation.
l
The x-value of the near view-plane.
r
The x-value of the far view-plane.
t
The y-value of the near view-plane.
b
The y-value of the far view-plane.
zn
The z-value of the near view-plane.
zf
The z-value of the far view-plane.

Return Values

A pointer to a D3DXMATRIX structure that is a right-handed perspective projection matrix.

Remarks

All of the parameters of the D3DXMatrixPerspectiveOffCenter function are distances in camera-space. The parameters describe the dimensions of the view-volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspectiveOffCenter function can be used as a parameter for another function.

The default projection matrix setup by the D3DXCreateContext and D3DXCreateContextEx functions is a left-handed perspective projection with a field-of-view (fov) of pi/2 radians.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXMatrixPerspective, D3DXMatrixPerspectiveLH, D3DXMatrixPerspectiveFov, D3DXMatrixPerspectiveFovLH, D3DXMatrixPerspectiveOffCenterLH


D3DXMatrixPerspectiveOffCenterLH

The D3DXMatrixPerspectiveOffCenterLH function builds a customized left-handed perspective projection matrix.

D3DXMATRIX* D3DXMatrixPerspectiveOffCenterLH(
  D3DXMATRIX* pOut,
  float l,
  float r,
  float t,
  float b,
  float zn,
  float zf
);

Parameters

pOut
A pointer to the D3DXMATRIX structure that is the result of the operation.
l
The x-value of the near view-plane.
r
The x-value of the far view-plane.
t
The y-value of the near view-plane.
b
The y-value of the far view-plane.
zn
The z-value of the near view-plane.
zf
The z-value of the far view-plane.

Return Values

A pointer to a D3DXMATRIX structure that is a left-handed perspective projection matrix.

Remarks

All of the parameters of the D3DXMatrixPerspectiveOffCenterLH function are distances in camera-space. The parameters describe the dimensions of the view-volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspectiveOffCenterLH function can be used as a parameter for another function.

The default projection matrix setup by the D3DXCreateContext and D3DXCreateContextEx functions is a left-handed perspective projection with a field-of-view (fov) of pi/2 radians.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXMatrixPerspective, D3DXMatrixPerspectiveLH, D3DXMatrixPerspectiveFov, D3DXMatrixPerspectiveFovLH, D3DXMatrixPerspectiveOffCenter


D3DXMatrixReflect

The D3DXMatrixReflect function builds a matrix which reflects the coordinate system about a plane.

D3DXMATRIX* D3DXMatrixReflect(
  D3DXMATRIX* pOut,
  const D3DXPLANE* pPlane
);

Parameters

pOut
A pointer to the D3DXMATRIX structure that is the result of the operation.
pPlane
A pointer to the source D3DXPLANE structure.

Return Values

A pointer to a D3DXMATRIX structure that reflects the coordinate system about the given plane.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixReflect function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.


D3DXMatrixRotationAxis

The D3DXMatrixRotationAxis function builds a matrix which rotates around an arbitrary axis.

D3DXMATRIX* D3DXMatrixRotationAxis(
  D3DXMATRIX* pOut,
  const D3DXVECTOR3* pV,
  float angle
);

Parameters

pOut
A pointer to the D3DXMATRIX structure that is the result of the operation.
pV
A pointer to the D3DXVECTOR3 structure that identifies the axis angle.
angle
The angle of rotation, in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Return Values

A pointer to a D3DXMATRIX structure rotated around the specified axis.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationAxis function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXMatrixRotationQuaternion, D3DXMatrixRotationX, D3DXMatrixRotationY, D3DXMatrixRotationYawPitchRoll, D3DXMatrixRotationZ


D3DXMatrixRotationQuaternion

The D3DXMatrixRotationQuaternion function builds a matrix from a quaternion.

D3DXMATRIX* D3DXMatrixRotationQuaternion(
  D3DXMATRIX* pOut,
  const D3DXQUATERNION* pQ
);

Parameters

pOut
A pointer to the D3DXMATRIX structure that is the result of the operation.
pQ
A pointer to the source D3DXQUATERNION structure.

Return Values

A pointer to a D3DXMATRIX structure built from the given quaternion.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationQuaternion function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXMatrixRotationAxis, D3DXMatrixRotationX, D3DXMatrixRotationY, D3DXMatrixRotationYawPitchRoll, D3DXMatrixRotationZ


D3DXMatrixRotationX

The D3DXMatrixRotationX function builds a matrix which rotates around the x-axis.

D3DXMATRIX* D3DXMatrixRotationX(
  D3DXMATRIX* pOut,
  float angle
);

Parameters

pOut
A pointer to the D3DXMATRIX structure that is the result of the operation.
angle
The angle of rotation in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Return Values

A pointer to a D3DXMATRIX structure rotated around the x-axis.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationX function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXMatrixRotationAxis, D3DXMatrixRotationQuaternion, D3DXMatrixRotationY, D3DXMatrixRotationYawPitchRoll, D3DXMatrixRotationZ


D3DXMatrixRotationY

The D3DXMatrixRotationY function builds a matrix which rotates around the y-axis.

D3DXMATRIX* D3DXMatrixRotationY(
  D3DXMATRIX* pOut,
  float angle
);

Parameters

pOut
A pointer to the D3DXMATRIX structure that is the result of the operation.
angle
The angle of rotation in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Return Values

A pointer to a D3DXMATRIX structure rotated around the y-axis.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationY function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXMatrixRotationAxis, D3DXMatrixRotationQuaternion, D3DXMatrixRotationX, D3DXMatrixRotationYawPitchRoll, D3DXMatrixRotationZ


D3DXMatrixRotationYawPitchRoll

The D3DXMatrixRotationYawPitchRoll function builds a matrix with a specified yaw, pitch, and roll.

D3DXMATRIX* D3DXMatrixRotationYawPitchRoll(
  D3DXMATRIX* pOut,
  float yaw,
  float pitch,
  float roll,
);

Parameters

pOut
A pointer to the D3DXMATRIX structure that is the result of the operation.
yaw
The yaw around the y-axis in radians.
pitch
The pitch around the x-axis in radians.
roll
The roll around the z-axis in radians.

Return Values

A pointer to a D3DXMATRIX structure with the specified yaw, pitch, and roll.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationYawPitchRoll function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXMatrixRotationAxis, D3DXMatrixRotationQuaternion, D3DXMatrixRotationX, D3DXMatrixRotationY, D3DXMatrixRotationZ


D3DXMatrixRotationZ

The D3DXMatrixRotationZ function builds a matrix which rotates around the z-axis.

D3DXMATRIX* D3DXMatrixRotationZ(
  D3DXMATRIX* pOut,
  float angle
);

Parameters

pOut
A pointer to the D3DXMATRIX structure that is the result of the operation.
angle
The angle of rotation in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Return Values

A pointer to a D3DXMATRIX structure rotated around the z-axis.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationZ function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXMatrixRotationAxis, D3DXMatrixRotationQuaternion, D3DXMatrixRotationX, D3DXMatrixRotationY, D3DXMatrixRotationYawPitchRoll


D3DXMatrixScaling

The D3DXMatrixScaling function builds a matrix which scales along the x-, y-, and z-axes.

D3DXMATRIX* D3DXMatrixScaling(
  D3DXMATRIX* pOut,
  float sx,
  float sy,
  float sz,
);

Parameters

pOut
A pointer to the D3DXMATRIX structure that is the result of the operation.
sx
A scaling factor that is applied along the x-axis.
sy
A scaling factor that is applied along the y-axis.
sz
A scaling factor that is applied along the z-axis.

Return Values

A pointer to a D3DXMATRIX structure that is the scaled matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixScaling function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.


D3DXMatrixShadow

The D3DXMatrixShadow function builds a matrix which flattens geometry into a plane.

D3DXMATRIX* D3DXMatrixShadow(
  D3DXMATRIX* pOut,
  const D3DXVECTOR4* pLight,
  const D3DXPLANE* pPlane
);

Parameters

pOut
A pointer to the D3DXMATRIX structure that is the result of the operation.
pLight
A pointer to a D3DXVECTOR4 structure describing the light's position.
pPlane
The pointer to the source D3DXPLANE structure.

Return Values

A pointer to a D3DXMATRIX structure which flattens geometry into a plane.

Remarks

The D3DXMatrixShadow function flattens geometry into a plane, as if casting a shadow from a light.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixShadow function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.


D3DXMatrixTransformation

The D3DXMatrixTransformation function builds a transformation matrix.

D3DXMATRIX* D3DXMatrixTransformation(
  D3DXMATRIX* pOut,
  const D3DXVECTOR3* pScalingCenter,
  const D3DXQUATERNION* pScalingRotation,
  const D3DXVECTOR3* pScaling,
  const D3DXVECTOR3* pRotationCenter,
  const D3DXQUATERNION* pRotation,
  const D3DXVECTOR3* pTranslation,
);

Parameters

pOut
A pointer to the D3DXMATRIX structure that is the result of the operation.
pScalingCenter
A pointer to a D3DXVECTOR3 structure, identifying the scaling center point. If this argument is NULL, it is treated as identity.
pScalingRotation
A pointer to a D3DXQUATERNION structure, specifying the scaling rotation If this argument is NULL, it is treated as identity.
pScaling
A pointer to a D3DXVECTOR3 structure, the scaling vector. If this argument is NULL, it is treated as identity.
pRotationCenter
A pointer to a D3DXVECTOR3 structure, a point identifying the center of rotation. If this argument is NULL, it is treated as identity.
pRotation
A pointer to a D3DXQUATERNION structure, specifying the rotation. If this argument is NULL, it is treated as identity.
pTranslation
A pointer to a D3DXVECTOR3 structure, representing the translation. If this argument is NULL, it is treated as identity.

Return Values

A pointer to a D3DXMATRIX structure that is the transformation matrix.

Remarks

The D3DXMatrixTransformation function calculates the transformation matrix with the following formula: Msc-1 * Msr-1 * Ms * Msr * Msc * Mrc-1 * Mr * Mrc * Mt, where Msc is the center scaling matrix, Msr is the scaling rotation matrix, Ms is the scaling matrix, Mrc is the center of rotation matrix, Mr is the rotation matrix, and Mt is the translation matrix.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixTransformation function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXMatrixAffineTransformation


D3DXMatrixTranslation

The D3DXMatrixTranslation function builds a matrix using the specified offsets.

D3DXMATRIX* D3DXMatrixTranslation(
  D3DXMATRIX* pOut,
  float x,
  float y,
  float z,
);

Parameters

pOut
A pointer to the D3DXMATRIX structure that is the result of the operation.
x
The x-coordinate offset.
y
The y-coordinate offset.
z
The z-coordinate offset.

Return Values

A pointer to a D3DXMATRIX structure that is the translated matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixTranslation function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.


D3DXMatrixTranspose

The D3DXMatrixTranspose function returns the matrix transpose of the given matrix.

D3DXMATRIX* D3DXMatrixTranspose(
  D3DXMATRIX* pOut,
  const D3DXMATRIX* pM
);

Parameters

pOut
A pointer to the D3DXMATRIX structure that is the result of the operation.
pM
The pointer to the source D3DXMATRIX structure.

Return Values

A pointer to the D3DXMATRIX structure that is the matrix transpose of the given matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixTranspose function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.


D3DXPlaneDot

The D3DXPlaneDot function computes the dot-product of a plane and a 4-D vector.

float D3DXPlaneDot(
  const D3DXPLANE* pP,
  const D3DXVECTOR4* pV
);

Parameters

pP
A pointer to a source D3DXPLANE structure.
pV
A pointer to a D3DXVECTOR4 structure.

Return Values

The dot-product of the given plane and 4-D vector.

Remarks

Given a plane (a, b, c, d) and a 4-D vector (x, y, z, w) the return value of this function is a*x + b*y + c*z + d*w. The D3DXPlaneDot function is useful for determining the plane's relationship with a homogeneous coordinate. For example, this function could be used to determine if a particular coordinate is on a particular plane, or on which side of a particular plane a particular coordinate lies.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXPlaneDotCoord, D3DXPlaneDotNormal


D3DXPlaneDotCoord

The D3DXPlaneDotCoord function computes the dot-product of a plane and a 3-D vector. The w parameter of the vector is assumed to be 1.

float D3DXPlaneDotCoord(
  const D3DXPLANE* pP,
  const D3DXVECTOR3* pV
);

Parameters

pP
A pointer to a source D3DXPLANE structure.
pV
A pointer to a source D3DXVECTOR3 structure.

Return Values

The dot-product of the given plane and 3-D vector.

Remarks

Given a plane (a, b, c, d) and a 3-D vector (x, y, z) the return value of this function is a*x + b*y + c*z + d*1. The D3DXPlaneDotCoord function is useful for determining the plane's relationship with a coordinate in 3-D space.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXPlaneDot, D3DXPlaneDotNormal


D3DXPlaneDotNormal

The D3DXPlaneDotNormal function computes the dot-product of a plane and a 3-D vector. The w parameter of the vector is assumed to be 0.

float D3DXPlaneDotNormal(
  const D3DXPLANE* pP,
  const D3DXVECTOR3* pV
);

Parameters

pP
A pointer to a source D3DXPLANE structure.
pV
A pointer to a source D3DXVECTOR3 structure.

Return Values

The dot-product of the given plane and 3-D vector.

Remarks

Given a plane (a, b, c, d) and a 3-D vector (x, y, z) the return value of this function is a*x + b*y + c*z + d*0. The D3DXPlaneDotNormal function is useful for figuring out the angle between the normal of the plane, and another normal.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXPlaneDot, D3DXPlaneDotCoord


D3DXPlaneFromPointNormal

The D3DXPlaneFromPointNormal function constructs a plane from a point and a normal.

D3DXPLANE* D3DXPlaneFromPointNormal(
  D3DXPLANE* pOut,
  const D3DXVECTOR3* pPoint,
  const D3DXVECTOR3* pNormal
);

Parameters

pOut
A pointer to the D3DXPLANE structure that is the result of the operation.
pPoint
A pointer to a D3DXVECTOR3 structure. This is the point used to construct the plane.
pNormal
A pointer to a D3DXVECTOR3 structure. This is the normal used to construct the plane.

Return Values

A pointer to the D3DXPLANE structure constructed from the given point and normal.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXPlaneFromPointNormal function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXPlaneFromPoints


D3DXPlaneFromPoints

The D3DXPlaneFromPoints function constructs a plane from 3 points.

D3DXPLANE* D3DXPlaneFromPoints(
  D3DXPLANE* pOut,
  const D3DXVECTOR3* pV1,
  const D3DXVECTOR3* pV2,
  const D3DXVECTOR3* pV3
);

Parameters

pOut
A pointer to the D3DXPLANE structure that is the result of the operation.
pV1
A pointer to a D3DXVECTOR3 structure. This is one of the points used to construct the plane.
pV2
A pointer to a D3DXVECTOR3 structure. This is one of the points used to construct the plane.
pV3
A pointer to a D3DXVECTOR3 structure. This is one of the points used to construct the plane.

Return Values

A pointer to the D3DXPLANE structure constructed from the given points.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXPlaneFromPoints function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXPlaneFromPointNormal


D3DXPlaneIntersectLine

The D3DXPlaneIntersectLine function finds the intersection between a plane and a line.

D3DXVECTOR3* D3DXPlaneIntersectLine(
  D3DXVECTOR3* pOut,
  const D3DXPLANE* pP,
  const D3DXVECTOR3* pV1,
  const D3DXVECTOR3* pV2
);

Parameters

pOut
A pointer to a D3DXVECTOR3 structure, identifying the intersection between the specified plane and line.
pP
A pointer to the source D3DXPLANE structure.
pV1
A pointer to a source D3DXVECTOR3 structure, defining a line starting point.
pV2
A pointer to a source D3DXVECTOR3 structure, defining a line ending point.

Return Values

A pointer to a D3DXVECTOR3 structure that is the intersection between the specified plane and line.

Remarks

If the line is parallel to the plane, NULL is returned.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXPlaneIntersectLine function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.


D3DXPlaneTransform

The D3DXPlaneTransform function transforms a plane by a given matrix.

D3DXPLANE* D3DXPlaneTransform(
  D3DXPLANE* pOut,
  const D3DXPLANE* pP,
  const D3DXMATRIX* pM
);

Parameters

pOut
A pointer to the D3DXPLANE structure that is the result of the operation.
pP
A pointer to the source D3DXPLANE structure.
pM
A pointer to the source D3DMATRIX structure.

Return Values

A pointer to a D3DXPLANE structure, representing the transformed plane.

Remarks

The matrix, pM, must be an affine transform.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXPlaneTransform function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.


D3DXQuaternionBaryCentric

The D3DXQuaternionBaryCentric function returns a quaternion in Barycentric coordinates.

D3DXQUATERNION* D3DXQuaternionBaryCentric(
  D3DXQUATERNION* pOut,
  const D3DXQUATERNION* pQ1,
  const D3DXQUATERNION* pQ2,
  const D3DXQUATERNION* pQ3,
  const D3DXQUATERNION* pQ4,
  float f,
  float g
);

Parameters

pOut
A pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ1
A pointer to a source D3DXQUATERNION structure.
pQ2
A pointer to a source D3DXQUATERNION structure.
pQ3
A pointer to a source D3DXQUATERNION structure.
pQ4
A pointer to a source D3DXQUATERNION structure.
f
A weighting factor. See remarks.
g
A weighting factor. See remarks.

Return Values

A pointer to a D3DXQUATERNION structure in Barycentric coordinates.

Remarks

In order to compute the Barycentric coordinates, the D3DXQuaternionBaryCentric function implements the following series of spherical linear interpolation operations: Slerp(Slerp(Q1, Q2, f+g), Slerp(Q1, Q3, f+g), g/(f+g))

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionBaryCentric function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.


D3DXQuaternionConjugate

The D3DXQuaternionConjugate function returns the conjugate of the given quaternion.

D3DXQUATERNION* D3DXQuaternionConjugate(
  D3DXQUATERNION* pOut,
  const D3DXQUATERNION* pQ
);

Parameters

pOut
A pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ
A pointer to the source D3DXQUATERNION structure.

Return Values

A pointer to a D3DXQUATERNION structure that is the conjugate of the given quaternion.

Remarks

Given a quaternion (x, y, z, w), the D3DXQuaternionConjugate function will return the quaternion (-x, -y, -z, w).

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionConjugate function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXQuaternionInverse


D3DXQuaternionDot

The D3DXQuaternionDot function returns the dot-product of two quaternions.

float D3DXQuaternionDot(
  D3DXQUATERNION* pQ1,
  const D3DXQUATERNION* pQ2
);

Parameters

pQ1
A pointer to a source D3DXQUATERNION structure.
pQ2
A pointer to a source D3DXQUATERNION structure.

Return Values

The dot-product of two quaternions.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.


D3DXQuaternionExp

The D3DXQuaternionExp function calculates the exponential

D3DXQUATERNION* D3DXQuaternionExp(
  D3DXQUATERNION* pOut,
  const D3DXQUATERNION* pQ
);

Parameters

pOut
A pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ
A pointer to the source D3DXQUATERNION structure.

Return Values

A pointer to a D3DXQUATERNION structure that is the exponential.

Remarks

The D3DXQuaternionExp function only works with pure quaternions, where w == 0.

This function is implemented in the following manner:

q = (0, theta * v)

exp(q) = (cos(theta), sin(theta) * v)

The D3DXQuaternionExp and D3DXQuaternionLn functions are useful when using the D3DXQuaternionSquad function. Given a set of quaternion keys (q0, q1, q2, ..., qn), you can compute the inner quadrangle points (a1, a2, a3, ..., an-1) as follows, in order to insure that the tangents are continuous across adjacent segments:

        a1    a2    a3
  q0    q1    q2    q3    q4

a[i] = q[i] * exp( -(ln(inv(q[i])*q[i+1]) + ln(inv(q[i])*q[i-1])) / 4 )

Once (a1, a2, a3, ...) are computed, you can use the results to interpolate along the curve:

qt = Squad(t, q[i], a[i], a[i+1], q[i+1])

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionExp function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXQuaternionLn, D3DXQuaternionSquad


D3DXQuaternionIdentity

The D3DXQuaternionIdentity function returns the identity quaternion.

D3DXQUATERNION* D3DXQuaternionIdentity(
  D3DXQUATERNION* pOut
);

Parameters

pOut
A pointer to the D3DXQUATERNION structure that is the result of the operation.

Return Values

A pointer to the D3DXQUATERNION structure that is the identity quaternion.

Remarks

Given a quaternion (x, y, z, w), the D3DXQuaternionIdentity function will return the quaternion (0, 0, 0, 1).

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionIdentity function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXQuaternionIsIdentity


D3DXQuaternionInverse

The D3DXQuaternionInverse function conjugates and re-normalizes a given quaternion.

D3DXQUATERNION* D3DXQuaternionInverse(
  D3DXQUATERNION* pOut,
  const D3DXQUATERNION* pQ
);

Parameters

pOut
A pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ
A pointer to the source D3DXQUATERNION structure.

Return Values

A pointer to a D3DXQUATERNION structure that is the inverse quaternion of the given quaternion.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionInverse function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXQuaternionConjugate, D3DXQuaternionNormalize


D3DXQuaternionIsIdentity

The D3DXQuaternionIsIdentity function determines if the given quaternion is an identity quaternion.

BOOL D3DXQuaternionIsIdentity(
  const D3DXQUATERNION* pQ
);

Parameters

pQ
A pointer to the D3DXQUATERNION structure that will be tested for identity.

Return Values

If the given quaternion is an identity quaternion, this function returns TRUE; otherwise, this function returns FALSE.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXQuaternionIdentity


D3DXQuaternionLength

The D3DXQuaternionLength function returns the length of the specified quaternion.

float D3DXQuaternionLength(
  const D3DXQUATERNION* pQ
);

Parameters

pQ
A pointer to the source D3DXQUATERNION structure.

Return Values

The quaternion's length.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXQuaternionLengthSq


D3DXQuaternionLengthSq

The D3DXQuaternionLengthSq function returns the square of the length of the specified quaternion.

float D3DXQuaternionLengthSq(
  const D3DXQUATERNION* pQ
);

Parameters

pQ
A pointer to the source D3DXQUATERNION structure.

Return Values

The quaternion's squared length.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXQuaternionLength


D3DXQuaternionLn

The D3DXQuaternionLn function calculates the natural logarithm.

D3DXQUATERNION* D3DXQuaternionLn(
  D3DXQUATERNION* pOut,
  const D3DXQUATERNION* pQ
);

Parameters

pOut
A pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ
A pointer to the source D3DXQUATERNION structure.

Return Values

A pointer to a D3DXQUATERNION structure that is the natural logarithm.

Remarks

The D3DXQuaternionLn function only works for unit quaternions.

This function is implemented in the following manner:

q = (cos(theta), sin(theta) * v)

|v| = 1

ln(q) = (0, theta * v)

The D3DXQuaternionExp and D3DXQuaternionLn functions are useful when using the D3DXQuaternionSquad function. Given a set of quaternion keys (q0, q1, q2, ..., qn), you can compute the inner quadrangle points (a1, a2, a3, ..., an-1), in order to insure that the tangents are continuous across adjacent segments:

        a1    a2    a3
  q0    q1    q2    q3    q4

a[i] = q[i] * exp( -(ln(inv(q[i])*q[i+1]) + ln(inv(q[i])*q[i-1])) / 4 )

Once (a1, a2, a3, ...) are computed, you can use the results to interpolate along the curve:

qt = Squad(t, q[i], a[i], a[i+1], q[i+1])

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionLn function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXQuaternionExp, D3DXQuaternionSquad


D3DXQuaternionMultiply

The D3DXQuaternionMultiply function multiplies two quaternions.

D3DXQUATERNION* D3DXQuaternionMultiply(
  D3DXQUATERNION* pOut,
  const D3DXQUATERNION* pQ1,
  const D3DXQUATERNION* pQ2
);

Parameters

pOut
A pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ1
A pointer to a source D3DXQUATERNION structure.
pQ2
A pointer to a source D3DXQUATERNION structure.

Return Values

A pointer to a D3DXQUATERNION structure that is the product of two quaternions.

Remarks

The result represents the rotation Q2 followed by the rotation Q1 (Out = Q2 * Q1). Note that the output is actually Q2*Q1 (not Q1*Q2). This is done so D3DXQuaternionMultiply will maintain the same semantics as D3DXMatrixMultiply, since unit quaternions can be considered as another way to represent rotation matrices.

Transformations are concatenated in the same order for both the D3DXQuaternionMultiply and D3DXMatrixMultiply functions. For example, assuming mX and mY represent the same rotations as qX and qY, both m and q will represent the same rotations.

D3DXMatrixMultiply(&m, &mX, &mY);

D3DXQuaternionMultiply(&q, &qX, &qY);

The multiplication of quaternions is not commutative.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionMultiply function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXMatrixMultiply


D3DXQuaternionNormalize

The D3DXQuaternionNormalize function returns the normal of the given quaternion.

D3DXQUATERNION* D3DXQuaternionNormalize(
  D3DXQUATERNION* pOut,
  const D3DXQUATERNION* pQ
);

Parameters

pOut
A pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ
The pointer to the source D3DXQUATERNION structure.

Return Values

A pointer to a D3DXQUATERNION structure that is the normal of the given quaternion.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionNormalize function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXQuaternionInverse


D3DXQuaternionRotationAxis

The D3DXQuaternionRotationAxis function rotates a given quaternion about an arbitrary axis.

D3DXQUATERNION* D3DXQuaternionRotationAxis(
  D3DXQUATERNION* pOut,
  const D3DXVECTOR3* pV,
  float angle
);

Parameters

pOut
A pointer to the D3DXQUATERNION structure that is the result of the operation.
pV
A pointer to the D3DXVECTOR3 structure that identifies the axis angle.
angle
The angle of rotation, in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Return Values

A pointer to a D3DXQUATERNION structure rotated around the specified axis.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionRotationAxis function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXQuaternionRotationMatrix, D3DXQuaternionRotationYawPitchRoll


D3DXQuaternionRotationMatrix

The D3DXQuaternionRotationMatrix function builds a quaternion from a rotation matrix.

D3DXQUATERNION* D3DXQuaternionRotationMatrix(
  D3DXQUATERNION* pOut,
  const D3DXMATRIX* pM
);

Parameters

pOut
A pointer to the D3DXQUATERNION structure that is the result of the operation.
pM
A pointer to the source D3DXMATRIX structure.

Return Values

A pointer to the D3DXQUATERNION structure built from a given rotation matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionRotationMatrix function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXQuaternionRotationAxis, D3DXQuaternionRotationYawPitchRoll


D3DXQuaternionRotationYawPitchRoll

The D3DXQuaternionRotationYawPitchRoll function builds a quaternion with the given yaw, pitch, and roll.

D3DXQUATERNION* D3DXQuaternionRotationYawPitchRoll(
  D3DXQUATERNION* pOut,
  float yaw,
  float pitch,
  float roll
);

Parameters

pOut
A pointer to the D3DXQUATERNION structure that is the result of the operation.
yaw
The yaw around the y-axis in radians.
pitch
The pitch around the x-axis in radians.
roll
The roll around the z-axis in radians.

Return Values

A pointer to a D3DXQUATERNION structure with the specified yaw, pitch, and roll.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionRotationYawPitchRoll function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXQuaternionRotationAxis, D3DXQuaternionRotationMatrix


D3DXQuaternionSlerp

The D3DXQuaternionSlerp function interpolates between two quaternions, using spherical linear interpolation.

D3DXQUATERNION* D3DXQuaternionSlerp(
  D3DXQUATERNION* pOut,
  const D3DXQUATERNION* pQ1,
  const D3DXQUATERNION* pQ2,
  float t
);

Parameters

pOut
A pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ1
A pointer to a source D3DXQUATERNION structure.
pQ2
A pointer to a source D3DXQUATERNION structure.
t
This value specifies how far to interpolate between the two given quaternions.

Return Values

A pointer to a D3DXQUATERNION structure that is the result of the interpolation.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionSlerp function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.


D3DXQuaternionSquad

The D3DXQuaternionSquad function interpolates between quaternions, using spherical quadrangle interpolation.

D3DXQUATERNION* D3DXQuaternionSquad(
  D3DXQUATERNION* pOut,
  const D3DXQUATERNION* pQ1,
  const D3DXQUATERNION* pQ2,
  const D3DXQUATERNION* pQ3,
  const D3DXQUATERNION* pQ4,
  float t
);

Parameters

pOut
A pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ1
A pointer to a source D3DXQUATERNION structure.
pQ2
A pointer to a source D3DXQUATERNION structure.
pQ3
A pointer to a source D3DXQUATERNION structure.
pQ4
A pointer to a source D3DXQUATERNION structure.
t
The parameter indicates how far to interpolate between the quaternions.

Return Values

A pointer to a D3DXQUATERNION structure that is the result of the spherical quadrangle interpolation.

Remarks

The function uses the following sequence of spherical linear interpolation operations: Slerp(Slerp(Q1, Q4, t), Slerp(Q2, Q3, t), 2t(1-t))

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionSquad function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXQuaternionExp, D3DXQuaternionLn


D3DXQuaternionToAxisAngle

The D3DXQuaternionToAxisAngle function computes a quaternin's axis and angle of rotation.

void D3DXQuaternionToAxisAngle(
  const D3DXQUATERNION* pQ,
  D3DXVECTOR3* pAxis,
  float* pAngle
);

Parameters

pQ
A pointer to the source D3DXQUATERNION structure.
pAxis
When this function returns, this parameter will point to a D3DXVECTOR3 structure that identifies the quaternion's axis.
pAngle
When this function returns, this parameter will point to a float value that identifies the quaternion's angle of rotation in radians.

Return Values

None.

Remarks

This function expects unit quaternions.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.


D3DXVec2Add

The D3DXVec2Add function adds two 2-D vectors.

D3DXVECTOR2* D3DXVec2Add(
  D3DXVECTOR2* pOut,
  const D3DXVECTOR2* pV1,
  const D3DXVECTOR2* pV2
);

Parameters

pOut
A pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
A pointer to a source D3DXVECTOR2 structure.
pV2
A pointer to a source D3DXVECTOR2 structure.

Return Values

A pointer to a D3DXVECTOR2 structure that is the sum of the two given vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Add function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXVec2Subtract, D3DXVec2Scale


D3DXVec2BaryCentric

The D3DXVec2BaryCentric function returns a point in Barycentric coordinates, using the specified 2-D vectors.

D3DXVECTOR2* D3DXVec2BaryCentric(
  D3DXVECTOR2* pOut,
  const D3DXVECTOR2* pV1,
  const D3DXVECTOR2* pV2,
  D3DXVECTOR2* pV3,
  float f,
  float g
);

Parameters

pOut
A pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
A pointer to a source D3DXVECTOR2 structure.
pV2
A pointer to a source D3DXVECTOR2 structure.
pV3
A pointer to a source D3DXVECTOR2 structure.
f
A weighting factor. See remarks.
g
A weighting factor. See remarks.

Return Values

A pointer to a D3DXVECTOR2 structure in Barycentric coordinates.

Remarks

The D3DXVec2BaryCentric function provides a way to understand points in and around a triangle, independent of where the triangle is actually located. This function returns the resulting point by using the following equation: V1 + f(V2-V1) + g(V3-V1).

Any point in the plane V1V2V3 can be represented by the barycentric coordinate (f,g).The parameter f controls how much V2 gets weighted into the result and the parameter g controls how much V3 gets weighted into the result. Lastly, 1-f-g controls how much V1 gets weighted into the result.

Note the following relations:

  • If (f>=0 && g>=0 && 1-f-g>=0), the point is inside the triangle V1V2V3.
  • If (f==0 && g>=0 && 1-f-g>=0), the point is on the line V1V3.
  • If (f>=0 && g==0 && 1-f-g>=0), the point is on the line V1V2.
  • If (f>=0 && g>=0 && 1-f-g==0), the point is on the line V2V3.

Barycentric coordinates are a form of general coordinates. In this context, using barycentric coordinates simply represents a change in coordinate systems; what holds true for Cartesian coordinates holds true for Barycentric coordinates.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2BaryCentric function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.


D3DXVec2CCW

The D3DXVec2CCW function returns the z-component by taking the cross product of two 2-D vectors.

float D3DXVec2CCW(
  const D3DXVECTOR2* pV1,
  const D3DXVECTOR2* pV2
);

Parameters

pV1
A pointer to a source D3DXVECTOR2 structure.
pV2
A pointer to a source D3DXVECTOR2 structure.

Return Values

The z-component.

Remarks

This function determines the z-component by determining the cross-product based on the following formula: ((x1,y1,0) cross (x2,y2,0)); or, in code:

pV1->x * pV2->y - pV1->y * pV2->x

If the value of the z-component is positive, the vector V2 is counter-clockwise from the vector V1. This information is useful for back-face culling.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXVec2Dot


D3DXVec2Dot

The D3DXVec2Dot function determines the dot-product of two 2-D vectors.

float D3DXVec2Dot(
  const D3DXVECTOR2* pV1,
  const D3DXVECTOR2* pV2
);

Parameters

pV1
A pointer to a source D3DXVECTOR2 structure.
pV2
A pointer to a source D3DXVECTOR2 structure.

Return Values

The dot-product.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXVec2CCW


D3DXVec2Hermite

The D3DXVec2Hermite function performs a Hermite spline interpolation, using the specified 2-D vectors.

D3DXVECTOR2* D3DXVec2Hermite(
  D3DXVECTOR2* pOut,
  const D3DXVECTOR2* pV1,
  const D3DXVECTOR2* pT1,
  const D3DXVECTOR2* pV2,
  const D3DXVECTOR2* pT2,
  float s
);

Parameters

pOut
A pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
A pointer to a source D3DXVECTOR2 structure, a position vector.
pT1
A pointer to a source D3DXVECTOR2 structure, a tangent vector.
pV2
A pointer to a source D3DXVECTOR2 structure, a position vector.
pT2
A pointer to a source D3DXVECTOR2 structure, a tangent vector.
s
A weighting factor. See remarks.

Return Values

A pointer to a D3DXVECTOR2 structure that is the result of the Hermite spline interpolation.

Remarks

The D3DXVec2Hermite function interpolates from (positionA, tangentA) to (positionB, tangentB) using hermite spline interpolation. This function interpolates between the position V1 and the tangent T1 (when s is equal to zero) and between the position V2 and the tangent T2 (when s is equal to one).

Hermite splines are useful for controlling animation, since the curve runs through all the control points. Also, since the position and tangent are explicitly specified at the ends of each segment, it is easy to create a C2 continuous curve as long as you make sure that your starting position and tangent match the ending values of the last segment.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Hermite function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.


D3DXVec2Length

The D3DXVec2Length function returns the length of the specified 2-D vector.

float D3DXVec2Length(
  const D3DXVECTOR2* pV
);

Parameters

pV
A pointer to the source D3DXVECTOR2 structure.

Return Values

The vector's length.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXVec2LengthSq


D3DXVec2LengthSq

The D3DXVec2LengthSq function returns the square of the length of the specified 2-D vector.

float D3DXVec2LengthSq(
  const D3DXVECTOR2* pV
);

Parameters

pV
A pointer to the souce D3DXVECTOR2 structure.

Return Values

The vector's squared length.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXVec2Length


D3DXVec2Lerp

The D3DXVec2Lerp function performs a linear interpolation between two 2-D vectors.

D3DXVECTOR2* D3DXVec2Lerp(
  D3DXVECTOR2* pOut,
  const D3DXVECTOR2* pV1,
  const D3DXVECTOR2* pV2,
  float s
);

Parameters

pOut
A pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
A pointer to a source D3DXVECTOR2 structure.
pV2
A pointer to a source D3DXVECTOR2 structure.
s
This value linearly interpolates between the two given vectors.

Return Values

A pointer to a D3DXVECTOR2 structure that is the result of the linear interpolation.

Remarks

This function performs the linear interpolation based on the following formula: V1 + s(V2-V1).

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Lerp function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.


D3DXVec2Maximize

The D3DXVec2Maximize function returns a 2-D vector that is made up of the largest components of the two specified 2-D vectors.

D3DXVECTOR2* D3DXVec2Maximize(
  D3DXVECTOR2* pOut,
  const D3DXVECTOR2* pV1,
  const D3DXVECTOR2* pV2
);

Parameters

pOut
A pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
A pointer to a source D3DXVECTOR2 structure.
pV2
A pointer to a source D3DXVECTOR2 structure.

Return Values

A pointer to a D3DXVECTOR2 structure that is made up of the largest components of the two specified vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Maximize function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXVec2Minimize


D3DXVec2Minimize

The D3DXVec2Minimize function returns a 2-D vector that is made up of the smallest components of the two specified 2-D vectors.

D3DXVECTOR2* D3DXVec2Minimize(
  D3DXVECTOR2* pOut,
  const D3DXVECTOR2* pV1,
  const D3DXVECTOR2* pV2
);

Parameters

pOut
A pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
A pointer to a source D3DXVECTOR2 structure.
pV2
A pointer to a source D3DXVECTOR2 structure.

Return Values

A pointer to a D3DXVECTOR2 structure that is made up of the smallest components of the two specified vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Minimize function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXVec2Maximize


D3DXVec2Normalize

The D3DXVec2Normalize function returns the normalized version of the specified 2-D vector.

D3DXVECTOR2* D3DXVec2Normalize(
  D3DXVECTOR2* pOut,
  const D3DXVECTOR2* pV
);

Parameters

pOut
A pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV
A pointer to the source D3DXVECTOR2 structure.

Return Values

A pointer to a D3DXVECTOR2 structure that is the normalized version of the specified vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Normalize function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.


D3DXVec2Scale

The D3DXVec2Scale function scales the specified 2-D vector.

D3DXVECTOR2* D3DXVec2Scale(
  D3DXVECTOR2* pOut,
  const D3DXVECTOR2* pV,
  float s
);

Parameters

pOut
A pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV
A pointer to the source D3DXVECTOR2 structure.
s
The scaling value.

Return Values

A pointer to a D3DXVECTOR2 structure that is the scaled vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Scale function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXVec2Add, D3DXVec2Subtract


D3DXVec2Subtract

The D3DXVec2Subtract function subtracts two 2-D vectors.

D3DXVECTOR2* D3DXVec2Subtract(
  D3DXVECTOR2* pOut,
  const D3DXVECTOR2* pV1,
  const D3DXVECTOR2* pV2
);

Parameters

pOut
A pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
A pointer to a source D3DXVECTOR2 structure.
pV2
A pointer to a source D3DXVECTOR2 structure.

Return Values

A pointer to a D3DXVECTOR2 structure that is the difference of two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Subtract function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXVec2Add, D3DXVec2Scale


D3DXVec2Transform

The D3DXVec2Transform function transforms a 2-D vector by a given matrix.

D3DXVECTOR4* D3DXVec2Transform(
  D3DXVECTOR4** pOut,
  const D3DXVECTOR2* pV,
  const D3DXMATRIX* pM
);

Parameters

pOut
A pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV
A pointer to the source D3DXVECTOR2 structure.
pM
A pointer to the source D3DXMATRIX structure.

Return Values

A pointer to a D3DXVECTOR4 structure that is the transformed vector.

Remarks

This function transform the given vector, pV (x, y, 0, 1), by the given matrix, pM.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Transform function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXVec2TransformCoord, D3DXVec2TransformNormal


D3DXVec2TransformCoord

The D3DXVec2TransformCoord function transforms a 2-D vector by a given matrix, projecting the result back into w = 1.

D3DXVECTOR2* D3DXVec2TransformCoord(
  D3DXVECTOR2* pOut,
  const D3DXVECTOR2* pV,
  const D3DXMATRIX* pM
);

Parameters

pOut
A pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV
The pointer to the source D3DXVECTOR2 structure.
pM
The pointer to the source D3DXMATRIX structure.

Return Values

A pointer to a D3DXVECTOR2 structure that is the transformed vector.

Remarks

This function transform the given vector, pV (x, y, 0, 1), by the given matrix, pM, projecting the result back into w=1.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2TransformCoord function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXVec2Transform, D3DXVec2TransformNormal


D3DXVec2TransformNormal

The D3DXVec2TransformNormal function transforms the 2-D vector normal by the given matrix.

D3DXVECTOR2* D3DXVec2TransformNormal(
  D3DXVECTOR2* pOut,
  const D3DXVECTOR2* pV,
  const D3DXMATRIX* pM
);

Parameters

pOut
A pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV
A pointer to the source D3DXVECTOR2 structure.
pM
A pointer to the source D3DXMATRIX structure.

Return Values

A pointer to a D3DXVECTOR2 structure that is the transformed vector.

Remarks

This function transforms the vector normal (x, y, 0, 0) of the given vector, pV, by the given matrix, pM.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2TransformNormal function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXVec2Transform, D3DXVec2TransformCoord


D3DXVec3Add

The D3DXVec3Add function adds two 3-D vectors.

D3DXVECTOR3* D3DXVec3Add(
  D3DXVECTOR3* pOut,
  const D3DXVECTOR3* pV1,
  const D3DXVECTOR3* pV2
);

Parameters

pOut
A pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
A pointer to a source D3DXVECTOR3 structure.
pV2
A pointer to a source D3DXVECTOR3 structure.

Return Values

A pointer to a D3DXVECTOR3 structure that is the sum of the two given 3-D vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Add function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXVec3Subtract, D3DXVec3Scale


D3DXVec3BaryCentric

The D3DXVec3BaryCentric function returns a point in Barycentric coordinates, using the specified 3-D vectors.

D3DXVECTOR3* D3DXVec3BaryCentric(
  D3DXVECTOR3* pOut,
  const D3DXVECTOR3* pV1,
  const D3DXVECTOR3* pV2,
  D3DXVECTOR3* pV3,
  float f,
  float g
);

Parameters

pOut
A pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
A pointer to a source D3DXVECTOR3 structure.
pV2
A pointer to a source D3DXVECTOR3 structure.
pV3
A pointer to a source D3DXVECTOR3 structure.
f
A weighting factor. See remarks.
g
A weighting factor. See remarks.

Return Values

A pointer to a D3DXVECTOR3 structure in Barycentric coordinates.

Remarks

The D3DXVec3BaryCentric function provides a way to understand points in and around a triangle, independent of where the triangle is actually located. This function returns the resulting point by using the following equation: V1 + f(V2-V1) + g(V3-V1).

Any point in the plane V1V2V3 can be represented by the barycentric coordinate (f,g).The parameter f controls how much V2 gets weighted into the result and the parameter g controls how much V3 gets weighted into the result. Lastly, 1-f-g controls how much V1 gets weighted into the result.

Note the following relations:

  • If (f>=0 && g>=0 && 1-f-g>=0), the point is inside the triangle V1V2V3.
  • If (f==0 && g>=0 && 1-f-g>=0), the point is on the line V1V3.
  • If (f>=0 && g==0 && 1-f-g>=0), the point is on the line V1V2.
  • If (f>=0 && g>=0 && 1-f-g==0), the point is on the line V2V3.

Barycentric coordinates are a form of general coordinates. In this context, using barycentric coordinates simply represents a change in coordinate systems; what holds true for Cartesian coordinates holds true for Barycentric coordinates.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3BaryCentric function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.


D3DXVec3Cross

The D3DXVec3Cross function determines the cross-product of two 3-D vectors.

D3DXVECTOR3* D3DXVec3Cross(
  D3DXVECTOR3* pOut,
  const D3DXVECTOR3* pV1,
  const D3DXVECTOR3* pV2
);

Parameters

pOut
A pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
A pointer to a source D3DXVECTOR3 structure.
pV2
A pointer to a source D3DXVECTOR3 structure.

Return Values

A pointer to a D3DXVECTOR3 structure that is the cross product of two 3-D vectors.

Remarks

This function determines the cross-product with the following code:

    D3DXVECTOR3 v;

    v.x = pV1->y * pV2->z - pV1->z * pV2->y;
    v.y = pV1->z * pV2->x - pV1->x * pV2->z;
    v.z = pV1->x * pV2->y - pV1->y * pV2->x;

    *pOut = v;

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Cross function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXVec3Dot


D3DXVec3Dot

The D3DXVec3Dot function determines the dot-product of two 3-D vectors.

float D3DXVec3Dot(
  const D3DXVECTOR3* pV1,
  const D3DXVECTOR3* pV2
);

Parameters

pV1
A pointer to a source D3DXVECTOR3 structure.
pV2
A pointer to a source D3DXVECTOR3 structure.

Return Values

The dot-product.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXVec3Cross


D3DXVec3Hermite

The D3DXVec3Hermite function performs a Hermite spline interpolation, using the specified 3-D vectors.

D3DXVECTOR3* D3DXVec3Hermite(
  D3DXVECTOR3* pOut,
  const D3DXVECTOR3* pV1,
  const D3DXVECTOR3* pT1,
  const D3DXVECTOR3* pV2,
  const D3DXVECTOR3* pT2,
  float s
);

Parameters

pOut
A pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
A pointer to a source D3DXVECTOR3 structure, a position vector.
pT1
A pointer to a source D3DXVECTOR3 structure, a tangent vector.
pV2
A pointer to a source D3DXVECTOR3 structure, a position vector.
pT2
A pointer to a source D3DXVECTOR3 structure, a tangent vector.
s
A weighting factor. See remarks.

Return Values

A pointer to a D3DXVECTOR3 structure that is the result of the Hermite spline interpolation.

Remarks

The D3DXVec3Hermite function interpolates from (positionA, tangentA) to (positionB, tangentB) using hermite spline interpolation. This function interpolates between the position V1 and the tangent T1 (when s is equal to zero) and between the position V2 and the tangent T2 (when s is equal to one).

Hermite splines are useful for controlling animation, since the curve runs through all the control points. Also, since the position and tangent are explicitly specified at the ends of each segment, it is easy to create a C2 continuous curve as long as you make sure that your starting position and tangent match the ending values of the last segment.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Hermite function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.


D3DXVec3Length

The D3DXVec3Length function returns the length of the specified 3-D vector.

float D3DXVec3Length(
  const D3DXVECTOR3* pV
);

Parameters

pV
A pointer to the source D3DXVECTOR3 structure.

Return Values

The vector's length.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXVec3LengthSq


D3DXVec3LengthSq

The D3DXVec3LengthSq function returns the square of the length of the specified 3-D vector.

float D3DXVec3LengthSq(
  const D3DXVECTOR3* pV
);

Parameters

pV
A pointer to the source D3DXVECTOR3 structure.

Return Values

The vector's squared length.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXVec3Length


D3DXVec3Lerp

The D3DXVec3Lerp function performs a linear interpolation between two 3-D vectors.

D3DXVECTOR3* D3DXVec3Lerp(
  D3DXVECTOR3* pOut,
  const D3DXVECTOR3* pV1,
  const D3DXVECTOR3* pV2,
  float s
);

Parameters

pOut
A pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
A pointer to a source D3DXVECTOR3 structure.
pV2
A pointer to a source D3DXVECTOR3 structure.
s
This value linearly interpolates between the two given vectors.

Return Values

A pointer to a D3DXVECTOR3 structure that is the result of the linear interpolation.

Remarks

This function performs the linear interpolation based on the following formula: V1 + s(V2-V1).

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Lerp function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.


D3DXVec3Maximize

The D3DXVec3Maximize function returns a 3-D vector that is made up of the largest components of the two specified 3-D vectors.

D3DXVECTOR3* D3DXVec3Maximize(
  D3DXVECTOR3* pOut,
  const D3DXVECTOR3* pV1,
  const D3DXVECTOR3* pV2
);

Parameters

pOut
A pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
A pointer to a source D3DXVECTOR3 structure.
pV2
A pointer to a source D3DXVECTOR3 structure.

Return Values

A pointer to a D3DXVECTOR3 structure that is made up of the largest components of the two specified vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Maximize function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXVec3Minimize


D3DXVec3Minimize

The D3DXVec3Minimize function returns a 3-D vector that is made up of the smallest components of the two specified 3-D vectors.

D3DXVECTOR3* D3DXVec3Minimize(
  D3DXVECTOR3* pOut,
  const D3DXVECTOR3* pV1,
  const D3DXVECTOR3* pV2
);

Parameters

pOut
A pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
A pointer to a source D3DXVECTOR3 structure.
pV2
A pointer to a source D3DXVECTOR3 structure.

Return Values

A pointer to a D3DXVECTOR3 structure that is made up of the smallest components of the two specified vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Minimize function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXVec3Maximize


D3DXVec3Normalize

The D3DXVec3Normalize function returns the normalized version of the specified 3-D vector.

D3DXVECTOR3* D3DXVec3Normalize(
  D3DXVECTOR3* pOut,
  const D3DXVECTOR3* pV
);

Parameters

pOut
A pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV
A pointer to the source D3DXVECTOR3 structure.

Return Values

A pointer to a D3DXVECTOR3 structure that is the normalized version of the specified vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Normalize function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.


D3DXVec3Scale

The D3DXVec3Scale function scales the specified 3-D vector.

D3DXVECTOR3* D3DXVec3Scale(
  D3DXVECTOR3* pOut,
  const D3DXVECTOR3* pV,
  float s
);

Parameters

pOut
A pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV
A pointer to the source D3DXVECTOR3 structure.
s
The scaling value.

Return Values

A pointer to a D3DXVECTOR3 structure that is the scaled vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Scale function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXVec3Add, D3DXVec3Subtract


D3DXVec3Subtract

The D3DXVec3Subtract function subtracts two 3-D vectors.

D3DXVECTOR3* D3DXVec3Subtract(
  D3DXVECTOR3* pOut,
  const D3DXVECTOR3* pV1,
  const D3DXVECTOR3* pV2
);

Parameters

pOut
A pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
A pointer to a source D3DXVECTOR3 structure.
pV2
A pointer to a source D3DXVECTOR3 structure.

Return Values

A pointer to a D3DXVECTOR3 structure that is the difference of two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Subtract function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXVec3Add, D3DXVec3Scale


D3DXVec3Transform

The D3DXVec3Transform function transforms a 3-D vector by a given matrix.

D3DXVECTOR4* D3DXVec3Transform(
  D3DXVECTOR4* pOut,
  const D3DXVECTOR3* pV,
  const D3DXMATRIX* pM
);

Parameters

pOut
A pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV
A pointer to the source D3DXVECTOR3 structure.
pM
A pointer to the source D3DXMATRIX structure.

Return Values

A pointer to a D3DXVECTOR4 structure that is the transformed vector.

Remarks

This function transform the given vector, pV (x, y, z, 1), by the given matrix, pM.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Transform function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXVec3TransformCoord, D3DXVec3TransformNormal


D3DXVec3TransformCoord

The D3DXVec3TransformCoord function transforms a 3-D vector by a given matrix, projecting the result back into w = 1.

D3DXVECTOR3* D3DXVec3TransformCoord(
  D3DXVECTOR3* pOut,
  const D3DXVECTOR3* pV,
  const D3DXMATRIX* pM
);

Parameters

pOut
A pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV
A pointer to the source D3DXVECTOR3 structure.
pM
The pointer to the source D3DXMATRIX structure.

Return Values

A pointer to a D3DXVECTOR3 structure that is the transformed vector.

Remarks

This function transform the given vector, pV (x, y, z, 1), by the given matrix, pM, projecting the result back into w=1.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3TransformCoord function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXVec3Transform, D3DXVec3TransformNormal


D3DXVec3TransformNormal

The D3DXVec3TransformNormal function transforms the 3-D vector normal by the given matrix.

D3DXVECTOR3* D3DXVec3TransformNormal(
  D3DXVECTOR3* pOut,
  const D3DXVECTOR3* pV,
  const D3DXMATRIX* pM
);

Parameters

pOut
A pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV
A pointer to the source D3DXVECTOR3 structure.
pM
The pointer to the source D3DXMATRIX structure.

Return Values

A pointer to a D3DXVECTOR3 structure that is the transformed vector.

Remarks

This function transforms the vector normal (x, y, z, 0) of the given vector, pV, by the given matrix, pM.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3TransformNormal function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.


D3DXVec4Add

The D3DXVec4Add function adds two 4-D vectors.

D3DXVECTOR4* D3DXVec4Add(
  D3DXVECTOR4* pOut,
  const D3DXVECTOR4* pV1,
  const D3DXVECTOR4* pV2
);

Parameters

pOut
A pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
A pointer to a source D3DXVECTOR4 structure.
pV2
A pointer to a source D3DXVECTOR4 structure.

Return Values

A pointer to a D3DXVECTOR4 structure that is the sum of the two given vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Add function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXVec4Subtract, D3DXVec4Scale


D3DXVec4BaryCentric

The D3DXVec4BaryCentric function returns a point in Barycentric coordinates, using the specified 4-D vectors.

D3DXVECTOR4* D3DXVec4BaryCentric(
  D3DXVECTOR4* pOut,
  const D3DXVECTOR4* pV1,
  const D3DXVECTOR4* pV2,
  const D3DXVECTOR4* pV3,
  float f,
  float g
);

Parameters

pOut
A pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
A pointer to a source D3DXVECTOR4 structure.
pV2
A pointer to a source D3DXVECTOR4 structure.
pV3
A pointer to a source D3DXVECTOR4 structure.
f
A weighting factor. See remarks.
g
A weighting factor. See remarks.

Return Values

A pointer to a D3DXVECTOR4 structure in Barycentric coordinates.

Remarks

The D3DXVec4BaryCentric function provides a way to understand points in and around a triangle, independent of where the triangle is actually located. This function returns the resulting point by using the following equation: V1 + f(V2-V1) + g(V3-V1).

Any point in the plane V1V2V3 can be represented by the barycentric coordinate (f,g).The parameter f controls how much V2 gets weighted into the result and the parameter g controls how much V3 gets weighted into the result. Lastly, 1-f-g controls how much V1 gets weighted into the result.

Note the following relations:

  • If (f>=0 && g>=0 && 1-f-g>=0), the point is inside the triangle V1V2V3.
  • If (f==0 && g>=0 && 1-f-g>=0), the point is on the line V1V3.
  • If (f>=0 && g==0 && 1-f-g>=0), the point is on the line V1V2.
  • If (f>=0 && g>=0 && 1-f-g==0), the point is on the line V2V3.

Barycentric coordinates are a form of general coordinates. In this context, using barycentric coordinates simply represents a change in coordinate systems; what holds true for Cartesian coordinates holds true for Barycentric coordinates.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4BaryCentric function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.


D3DXVec4Cross

The D3DXVec4Cross function determines the cross-product in 4 dimensions.

D3DXVECTOR4* D3DXVec4Cross(
  D3DXVECTOR4* pOut,
  const D3DXVECTOR4* pV1,
  const D3DXVECTOR4* pV2,
  const D3DXVECTOR4* pV3
);

Parameters

pOut
A pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
A pointer to a source D3DXVECTOR4 structure.
pV2
A pointer to a source D3DXVECTOR4 structure.
pV3
A pointer to a source D3DXVECTOR4 structure.

Return Values

A pointer to a D3DXVECTOR4 structure that is the cross product.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Cross function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXVec4Dot


D3DXVec4Dot

The D3DXVec4Dot function determines the dot-product of two 4-D vectors.

float D3DXVec4Dot(
  const D3DXVECTOR4* pV1,
  const D3DXVECTOR4* pV2
);

Parameters

pV1
A pointer to a source D3DXVECTOR4 structure.
pV2
A pointer to a source D3DXVECTOR4 structure.

Return Values

The dot-product.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXVec4Cross


D3DXVec4Hermite

The D3DXVec4Hermite function performs a Hermite spline interpolation, using the specified 4-D vectors.

D3DXVECTOR4* D3DXVec4Hermite(
  D3DXVECTOR4* pOut,
  const D3DXVECTOR4* pV1,
  const D3DXVECTOR4* pT1,
  const D3DXVECTOR4* pV2,
  const D3DXVECTOR4* pT2,
  float s
);

Parameters

pOut
A pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
A pointer to a source D3DXVECTOR4 structure, a position vector.
pT1
A pointer to a source D3DXVECTOR4 structure, a tangent vector.
pV2
A pointer to a source D3DXVECTOR4 structure, a position vector.
pT2
A pointer to a source D3DXVECTOR4 structure, a tangent vector.
s
A weighting factor. See remarks.

Return Values

A pointer to a D3DXVECTOR4 structure that is the result of the Hermite spline interpolation.

Remarks

The D3DXVec4Hermite function interpolates from (positionA, tangentA) to (positionB, tangentB) using hermite spline interpolation. This function interpolates between the position V1 and the tangent T1 (when s is equal to zero) and between the position V2 and the tangent T2 (when s is equal to one).

Hermite splines are useful for controlling animation, since the curve runs through all the control points. Also, since the position and tangent are explicitly specified at the ends of each segment, it is easy to create a C2 continuous curve as long as you make sure that your starting position and tangent match the ending values of the last segment.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Hermite function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.


D3DXVec4Length

The D3DXVec4Length function returns the length of the specified 4-D vector.

float D3DXVec4Length(
  const D3DXVECTOR4* pV
);

Parameters

pV
A pointer to the source D3DXVECTOR4 structure.

Return Values

The vector's length.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXVec4LengthSq


D3DXVec4LengthSq

The D3DXVec4LengthSq function returns the square of the length of the specified 4-D vector.

float D3DXVec4LengthSq(
  const D3DXVECTOR4* pV
);

Parameters

pV
A pointer to the source D3DXVECTOR4 structure.

Return Values

The vector's squared length.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXVec4Length


D3DXVec4Lerp

The D3DXVec4Lerp function performs a linear interpolation between two 4-D vectors.

D3DXVECTOR4* D3DXVec4Lerp(
  D3DXVECTOR4* pOut,
  const D3DXVECTOR4* pV1,
  const D3DXVECTOR4* pV2,
  float s
);

Parameters

pOut
A pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
A pointer to a source D3DXVECTOR4 structure.
pV2
A pointer to a source D3DXVECTOR4 structure.
s
This value linearly interpolates between the two given vectors.

Return Values

A pointer to a D3DXVECTOR4 structure that is the result of the linear interpolation.

Remarks

This function performs the linear interpolation based on the following formula: V1 + s(V2-V1).

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Lerp function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.


D3DXVec4Maximize

The D3DXVec4Maximize function returns a 4-D vector that is made up of the largest components of the two specified 4-D vectors.

D3DXVECTOR4* D3DXVec4Maximize(
  D3DXVECTOR4* pOut,
  const D3DXVECTOR4* pV1,
  const D3DXVECTOR4* pV2
);

Parameters

pOut
A pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
A pointer to a source D3DXVECTOR4 structure.
pV2
A pointer to a source D3DXVECTOR4 structure.

Return Values

A pointer to a D3DXVECTOR4 structure that is made up of the largest components of the two specified vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Maximize function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXVec4Minimize


D3DXVec4Minimize

The D3DXVec4Minimize function returns a 4-D vector that is made up of the smallest components of the two specified 4-D vectors.

D3DXVECTOR4* D3DXVec4Minimize(
  D3DXVECTOR4* pOut,
  const D3DXVECTOR4* pV1,
  const D3DXVECTOR4* pV2
);

Parameters

pOut
A pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
A pointer to a source D3DXVECTOR4 structure.
pV2
A pointer to a source D3DXVECTOR4 structure.

Return Values

A pointer to a D3DXVECTOR4 structure that is made up of the smallest components of the two specified vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Minimize function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXVec4Maximize


D3DXVec4Normalize

The D3DXVec4Normalize function returns the normalized version of the specified 4-D vector.

D3DXVECTOR4* D3DXVec4Normalize(
  D3DXVECTOR4* pOut,
  const D3DXVECTOR4* pV
);

Parameters

pOut
A pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV
A pointer to the source D3DXVECTOR4 structure.

Return Values

A pointer to a D3DXVECTOR4 structure that is the normalized version of the specified vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Normalize function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.


D3DXVec4Scale

The D3DXVec4Scale function scales the specified 4-D vector.

D3DXVECTOR4* D3DXVec4Scale(
  D3DXVECTOR4* pOut,
  const D3DXVECTOR4* pV,
  float s
);

Parameters

pOut
A pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV
A pointer to the source D3DXVECTOR4 structure.
s
The scaling value.

Return Values

A pointer to the D3DXVECTOR4 structure that is the scaled vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Scale function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXVec4Add, D3DXVec4Subtract


D3DXVec4Subtract

The D3DXVec4Subtract function subtracts two 4-D vectors.

D3DXVECTOR4* D3DXVec4Subtract(
  D3DXVECTOR4* pOut,
  const D3DXVECTOR4* pV1,
  const D3DXVECTOR4* pV2
);

Parameters

pOut
A pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
A pointer to a source D3DXVECTOR4 structure.
pV2
A pointer to a source D3DXVECTOR4 structure.

Return Values

A pointer to a D3DXVECTOR4 structure that is the difference of two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Subtract function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.

See Also

D3DXVec3Add, D3DXVec3Scale


D3DXVec4Transform

The D3DXVec4Transform function transforms a 4-D vector by a given matrix.

D3DXVECTOR4* D3DXVec4Transform(
  D3DXVECTOR4* pOut,
  const D3DXVECTOR4* pV,
  const D3DXMATRIX* pM
);

Parameters

pOut
A pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV
A pointer to the source D3DXVECTOR4 structure.
pM
A pointer to the source D3DXMATRIX structure.

Return Values

A pointer to a D3DXVECTOR4 structure that is the transformed 4-D vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Transform function can be used as a parameter for another function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.
Library: Use d3dx.lib.


Shape Drawing Functions

The 3-D shape drawing application programming interface (API) provided by the Direct3DX utility library supplies functions to draw simple geometric shapes.

This section contains information about the following Direct3DX global functions:

  • D3DXCreateBox
  • D3DXCreateCylinder
  • D3DXCreatePolygon
  • D3DXCreateSphere
  • D3DXCreateTeapot
  • D3DXCreateTorus

All shapes are returned as vertex-buffers. Since shapes are vertex-buffers, the flexible vertex format type can be found by querying the vertex-buffer itself. Each vertex buffer is filled with vertices, all of which can be used to draw a primitive as a triangle-list.

For more information, see Flexible Vertex Format Flags.


D3DXCreateBox

The D3DXCreateBox function creates a box (cuboid) of given dimensions.

HRESULT D3DXCreateBox(
  LPDIRECT3DDEVICE7 pDevice,
  float width,
  float height,
  float depth,
  DWORD numTexCoords,
  ID3DXSimpleShape** ppShape
);

Parameters

pDevice
A pointer to the IDirect3DDevice7 interface of the device.
width
The width of the box, taken along the x-axis.
height
The height of the box, taken along the y-axis.
depth
The depth of the box, taken along the z-axis.
numTexCoords
The number of texture coordinates desired in the output vertex-buffer. The default value is 1. D3DX_DEFAULT is a valid input for this parameter.
ppShape
The address of a pointer to the output vertex-buffer, an ID3DXSimpleShape interface.

Return Values

If the function succeeds, the return value is S_OK.

If the function fails, the return value may be one of the following values:

CLASS_E_NOAGGREGATION
D3DERR_INVALIDPRIMITIVETYPE
D3DERR_INVALIDRAMPTEXTURE
D3DERR_INVALIDVERTEXFORMAT
D3DERR_INVALIDVERTEXTYPE
D3DERR_VBUF_CREATE_FAILED
D3DXERR_INVALIDPARAMETER
D3DXERR_NOMEMORY
D3DXERR_NULLPOINTER
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY
DDERR_WASSTILLDRAWING

Remarks

This function returns a vertex buffer that can be used later for drawing or manipulation by the application.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxshapes.h.
Library: Use d3dx.lib.

See Also

D3DXCreateCylinder, D3DXCreatePolygon, D3DXCreateSphere, D3DXCreateTeapot, D3DXCreateTorus


D3DXCreateCylinder

The D3DXCreateCylinder function creates a cylinder of given dimensions.

HRESULT D3DXCreateCylinder(
  LPDIRECT3DDEVICE7 pDevice,
  float baseRadius,
  float topRadius,
  float height,
  DWORD numSlices,
  DWORD numStacks,
  DWORD numTexCoords,
  ID3DXSimpleShape** ppShape
);

Parameters

pDevice
A pointer to the IDirect3DDevice7 interface of the device.
baseRadius
The base-radius of the cylinder. The default value is 1.0f. This parameter should be greater than or equal to 0.0f.
topRadius
The top-radius of the cylinder. The default value is 1.0f. This parameter should be greater than or equal to 0.0f.
height
The height of the cylinder. The default value is 1.0f. This parameter should be greater than or equal to 0.0f.
numSlices
The number of slices about the main axis. The default value is 8. D3DX_DEFAULT is a valid input for this parameter.
numStacks
The number of stacks along the main axis. The default value is 8. D3DX_DEFAULT is a valid input for this parameter.
numTexCoords
The number of texture coordinates desired in the output vertex-buffer. The default value is 1. D3DX_DEFAULT is a valid input for this parameter.
ppShape
The address of a pointer to the output vertex-buffer, an ID3DXSimpleShape interface.

Return Values

If the function succeeds, the return value is S_OK.

If the function fails, the return value may be one of the following values:

CLASS_E_NOAGGREGATION
D3DERR_INVALIDPRIMITIVETYPE
D3DERR_INVALIDRAMPTEXTURE
D3DERR_INVALIDVERTEXFORMAT
D3DERR_INVALIDVERTEXTYPE
D3DERR_VBUF_CREATE_FAILED
D3DXERR_INVALIDPARAMETER
D3DXERR_NOMEMORY
D3DXERR_NULLPOINTER
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY
DDERR_WASSTILLDRAWING

Remarks

This function returns a vertex buffer that can be used later for drawing or manipulation by the application.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxshapes.h.
Library: Use d3dx.lib.

See Also

D3DXCreateBox, D3DXCreatePolygon, D3DXCreateSphere, D3DXCreateTeapot, D3DXCreateTorus


D3DXCreatePolygon

The D3DXCreatePolygon function creates an n-sided polygon.

HRESULT D3DXCreatePolygon(
  LPDIRECT3DDEVICE7 pDevice,
  float sideSize,
  DWORD numSides,
  DWORD numTexCoords,
  ID3DXSimpleShape** ppShape
);

Parameters

pDevice
A pointer to the IDirect3DDevice7 interface of the device.
sideSize
The length of a side.
numSides
The number of sides.
numTexCoords
The number of texture coordinates desired in the output vertex-buffer. The default value is 1. D3DX_DEFAULT is a valid input for this parameter.
ppShape
The address of a pointer to the output vertex-buffer, an ID3DXSimpleShape interface.

Return Values

If the function succeeds, the return value is S_OK.

If the function fails, the return value may be one of the following values:

CLASS_E_NOAGGREGATION
D3DERR_INVALIDPRIMITIVETYPE
D3DERR_INVALIDRAMPTEXTURE
D3DERR_INVALIDVERTEXFORMAT
D3DERR_INVALIDVERTEXTYPE
D3DERR_VBUF_CREATE_FAILED
D3DXERR_INVALIDPARAMETER
D3DXERR_NOMEMORY
D3DXERR_NULLPOINTER
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY
DDERR_WASSTILLDRAWING

Remarks

This function returns a vertex buffer that can be used later for drawing or manipulation by the application.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxshapes.h.
Library: Use d3dx.lib.

See Also

D3DXCreateBox, D3DXCreateCylinder, D3DXCreateSphere, D3DXCreateTeapot, D3DXCreateTorus


D3DXCreateSphere

The D3DXCreateSphere function creates a sphere of given dimensions.

HRESULT D3DXCreateSphere(
  LPDIRECT3DDEVICE7 pDevice,
  float radius,
  DWORD numSlices,
  DWORD numStacks,
  DWORD numTexCoords,
  ID3DXSimpleShape** ppShape
);

Parameters

pDevice
A pointer to the IDirect3DDevice7 interface of the device.
radius
The radius of the sphere. The default value is 1.0f. This parameter should be greater than or equal to 0.0f.
numSlices
The number of slices about the main axis. The default value is 8. D3DX_DEFAULT is a valid input for this parameter.
numStacks
The number of stacks along the main axis. The default value is 8. D3DX_DEFAULT is a valid input for this parameter.
numTexCoords
The number of texture coordinates desired in the output vertex-buffer. The default value is 1. D3DX_DEFAULT is a valid input for this parameter.
ppShape
The address of a pointer to the output vertex-buffer, an ID3DXSimpleShape interface.

Return Values

If the function succeeds, the return value is S_OK.

If the function fails, the return value may be one of the following values:

CLASS_E_NOAGGREGATION
D3DERR_INVALIDPRIMITIVETYPE
D3DERR_INVALIDRAMPTEXTURE
D3DERR_INVALIDVERTEXFORMAT
D3DERR_INVALIDVERTEXTYPE
D3DERR_VBUF_CREATE_FAILED
D3DXERR_INVALIDPARAMETER
D3DXERR_NOMEMORY
D3DXERR_NULLPOINTER
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY
DDERR_WASSTILLDRAWING

Remarks

This function returns a vertex buffer that can be used later for drawing or manipulation by the application.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxshapes.h.
Library: Use d3dx.lib.

See Also

D3DXCreateBox, D3DXCreateCylinder, D3DXCreatePolygon, D3DXCreateTeapot, D3DXCreateTorus


D3DXCreateTeapot

The D3DXCreateTeapot function creates a teapot.

HRESULT D3DXCreateTeapot(
  LPDIRECT3DDEVICE7 pDevice,
  DWORD numTexCoords,
  ID3DXSimpleShape** ppShape
);

Parameters

pDevice
A pointer to the IDirect3DDevice7 interface of the device.
numTexCoords
The number of texture coordinates desired in the output vertex-buffer. The default value is 1. D3DX_DEFAULT is a valid input for this parameter.
ppShape
The address of a pointer to the output vertex-buffer, an ID3DXSimpleShape interface.

Return Values

If the function succeeds, the return value is S_OK.

If the function fails, the return value may be one of the following values:

CLASS_E_NOAGGREGATION
D3DERR_INVALIDPRIMITIVETYPE
D3DERR_INVALIDRAMPTEXTURE
D3DERR_INVALIDVERTEXFORMAT
D3DERR_INVALIDVERTEXTYPE
D3DERR_VBUF_CREATE_FAILED
D3DXERR_INVALIDPARAMETER
D3DXERR_NOMEMORY
D3DXERR_NULLPOINTER
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY
DDERR_WASSTILLDRAWING

Remarks

This function returns a vertex buffer that can be used later for drawing or manipulation by the application.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxshapes.h.
Library: Use d3dx.lib.

See Also

D3DXCreateBox, D3DXCreateCylinder, D3DXCreatePolygon, D3DXCreateSphere, D3DXCreateTorus


D3DXCreateTorus

The D3DXCreateTorus function creates a torus of given dimensions.

HRESULT D3DXCreateTorus(
  LPDIRECT3DDEVICE7 pDevice,
  float innerRadius,
  float outerRadius,
  DWORD numSides,
  DWORD numRings,
  DWORD numTexCoords,
  ID3DXSimpleShape** ppShape
);

Parameters

pDevice
A pointer to the IDirect3DDevice7 interface of the device.
innerRadius
The inner-radius of the torus. The default value is 1.0f. This parameter should be greater than or equal to 0.0f.
outerRadius
The outer-radius of the torus. The default value is 1.0f. This parameter should be greater than or equal to 0.0f.
numSides
The number of sides in the cross-section. The default value is 8. D3DX_DEFAULT is a valid input for this parameter.
numRings
The number of rings making up the torus. The default value is 8. D3DX_DEFAULT is a valid input for this parameter.
numTexCoords
The number of texture coordinates desired in the output vertex-buffer. The default value is 1. D3DX_DEFAULT is a valid input for this parameter.
ppShape
The address of a pointer to the output vertex-buffer, an ID3DXSimpleShape interface.

Return Values

If the function succeeds, the return value is S_OK.

If the function fails, the return value may be one of the following values:

CLASS_E_NOAGGREGATION
D3DERR_INVALIDPRIMITIVETYPE
D3DERR_INVALIDRAMPTEXTURE
D3DERR_INVALIDVERTEXFORMAT
D3DERR_INVALIDVERTEXTYPE
D3DERR_VBUF_CREATE_FAILED
D3DXERR_INVALIDPARAMETER
D3DXERR_NOMEMORY
D3DXERR_NULLPOINTER
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY
DDERR_WASSTILLDRAWING

Remarks

The D3DXCreateTorus method draws a doughnut, centered at (0, 0, 0) whose axis is aligned with the z-axis. The inner-radius of the torus is the radius of the cross-section (the minor-radius) and the outer-radius of the torus is the radius of the central hole.

This function returns a vertex buffer that can be used later for drawing or manipulation by the application.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxshapes.h.
Library: Use d3dx.lib.

See Also

D3DXCreateBox, D3DXCreateCylinder, D3DXCreatePolygon, D3DXCreateSphere, D3DXCreateTeapot


Sprite Helper Functions

The sprite helper application programming interface (API) provided by the Direct3DX utility library supplies functions to facilitate sprite rendering.

This section contains information about the following Direct3DX global functions:

  • D3DXBuildSpriteTransform
  • D3DXDrawSpriteSimple
  • D3DXDrawSpriteTransform
  • D3DXDrawSprite3D
  • D3DXPrepareDeviceForSprite

Note C++ programmers can take advantage of default values in the Direct3DX sprite library, see specific functions for details.


D3DXBuildSpriteTransform

The D3DXBuildSpriteTransform function creates a matrix that corresponds to a transformation from the -0.5 to +0.5 centered rectangle to a particular RECT structure on the screen. Additionally, an angle of rotation can be specified for that RECT structure.

void D3DXBuildSpriteTransform(
  D3DXMATRIX* pMatrixTransform,
  const RECT* prectDest,
  float angleRad = 0.0f,
  const D3DXVECTOR2* pOffset
);

Parameters

pMatrixTransform
A pointer to the result matrix, a D3DXMATRIX structure. This matrix will be returned with new values that correspond to the transformation specified by the prectDest, angleRad and pOffset parameters.
prectDest
A pointer to the target rectangle for the sprite, indicating in screen coordinates where the sprite should be located. The sprite will be stretched to fill this RECT structure
angleRad
Angle of rotation around the center of the RECT, indicating what angle to rotate the sprite. The rotation is applied around the center of the sprite. It is counter-clockwise and must be specified in radians. See D3DXToRadian to convert degrees to radians.
pOffset
A pointer to a D3DXVECTOR2 structure, defining the offset from the center of the source RECT to use as the center of rotation. This parameter indicates the offset from the center-point of the sprite that should be treated as the sprite center for the purposes of rotation. By default, a value of NULL is equivalent to a vector of (0, 0).

Return Values

None.

Remarks

The D3DXBuildSpriteTransform function is provided as a helper function to use the D3DXDrawSpriteTransform function.

Note that C programmers will not be able to take advantage of the default value for the angleRad parameter.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxsprite.h.
Library: Use d3dx.lib.


D3DXDrawSpriteSimple

The D3DXDrawSpriteSimple function renders a sprite onto a Direct3D device. This function must be called in between calls to IDirect3DDevice7::BeginScene and IDirect3DDevice7::EndScene.

HRESULT D3DXDrawSpriteSimple(
  LPDIRECTDRAWSURFACE7 pd3dTexture,
  LPDIRECT3DDEVICE7 pd3dDevice,
  const D3DXVECTOR3* ppointDest,
  float alpha = 1.0f,
  float scale = 1.0f,
  float angleRad = 0.0f,
  const D3DXVECTOR2* pOffset = NULL,
  const RECT *pSourceRect = NULL
);

Parameters

pd3dTexture
A pointer to the surface, an IDirectDrawSurface7 interface, containing the texture, indicating which surface should be used as the source image for the sprite. If this is NULL, it is assumed that the application has already called IDirect3DDevice7::SetTexture for texture stage zero.
pd3dDevice
A pointer to an IDirect3DDevice7 interface. The sprite will be rendered to this device. It is assumed that render states are set up for this device (see D3DXPrepareDeviceForSprite).
ppointDest
A pointer to a D3DXVECTOR3 structure. The target point for the sprite. The vector indicates in screen coordinates where the center of the sprite should be rendered. The components of the vector must be in screen space. Typically, the z-component of the vector will be set to zero; but can be set to any value for applications that are using a z-buffer instead of rendering back-to-front.
alpha
The alpha value to apply to sprite, indicating the opacity of the sprite. 1.0 means totally opaque; and 0.0 means totally transparent. Note that if you are using alpha, then you should render from back to front in order to avoid rendering artifacts. This alpha value is combined with the alpha (if any) present in texture image.
scale
A uniform scale that is applied to the source RECT to specify the size of the image rendered. By default, the value is 1.0, which means that the sprite will be rendered at the same width and height as the source.
angleRad
Angle of rotation around the center of the RECT, indicating what angle to rotate the sprite. The rotation is applied around the center of the sprite. It is counter-clockwise and must be specified in radians. See D3DXToRadian to convert degrees to radians.
pOffset
A pointer to a D3DXVECTOR2 structure, defining the offset from the center of the source RECT to use as the center of rotation. This parameter indicates the offset from the center-point of the sprite that should be treated as the sprite center for the purposes of the ppointDest and angleRad parameters.
pSourceRect
A pointer to a RECT structure that indicates what portion of the source texture to use for the sprite. If this parameter is NULL, then the entire source image is used for the sprite; however, you can specify a sub-rectangle of the source image instead. If the source texture was created by using Direct3DX, then the RECT structure should be specified in the coordinates of the original image. So, you do not have to be concerned with any stretching or scaling that Direct3DX may have done to make the image work with your current Direct3D device. Additionally, mirroring can be specified easily by swapping the left and top and the right and bottom parameters of this RECT structure.

Return Values

If the function succeeds, the return value is S_OK.

If the function fails, the return value may be one of the following values:

D3DXERR_NULLPOINTER
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

C programmers will not be able to take advantage of the default values for the alpha, scale, angleRad, pOffset, and pSourceRect parameters.

The D3DXDrawSpriteSimple function performs blitting of source images onto a 3-D rendering device. This function only calls IDirect3DDevice7::SetTexture on the first render stage with the parameter pd3dTexture, if that parameter is non-NULL.

This function supports scaling, rotation, alpha blending, mirroring, and placement. For a broader range of effects such as shearing and perspective, use the D3DXDrawSpriteTransform function.

This function assumes that D3DXPrepareDeviceForSprite has been called on the device or that caller has in some other way correctly prepared the render states.

The rotation angle is specified in radians. Both rotations and scales are applied around the center of the sprite; where the center of the sprite is half the width and height of the sprite, plus the offset parameter. Use the offset parameter if you want the sprite's center to be something other than the image center.

The destination point indicates where you would like to place the center of the sprite. Advanced users who are mixing 2-D and 3-D rendering should remember that these coordinates are assumed to be fully transformed (i.e. in screen space and should set the z-component of the ppointDest parameter accordingly). In general, advanced users may want to use the D3DXDrawSprite3D function instead for greater control.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxsprite.h.
Library: Use d3dx.lib.

See Also

D3DXDrawSpriteTransform, D3DXDrawSprite3D, D3DXPrepareDeviceForSprite


D3DXDrawSpriteTransform

The D3DXDrawSpriteTransform function provides a mechanism for rendering a sprite that is transformed by a specified matrix. This function must be called in between calls to IDirect3DDevice7::BeginScene and IDirect3DDevice7::EndScene.

HRESULT D3DXDrawSpriteTransform(
  LPDIRECTDRAWSURFACE7 pd3dTexture,
  LPDIRECT3DDEVICE7 pd3dDevice,
  const D3DXMATRIX* pMatrixTransform,
  float alpha = 1.0f,
  const RECT* pSourceRect = NULL
);

Parameters

pd3dTexture
A pointer to the surface containing the texture, an IDirectDrawSurface7 interface, indicating which surface should be used as the source image for the sprite. If this parameter is NULL, it is assumed that the application has already called IDirect3DDevice7::SetTexture for texture stage zero.
pd3dDevice
A pointer to the Direct3D rendering device, an IDirect3DDevice7 interface. It is assumed that render states are set up, for more information, see D3DXPrepareDeviceForSprite.
pMatrixTransform
A pointer to a 4x4 matrix, a D3DXMATRIX structure, that specifies the transformation that will be applied to the default -.5 to +.5 rectangle. This nmatrix will transform the sprite to screen space. By default, the sprite is located at (-0.5, -0.5) to (+0.5, +0.5). It is centered around the origin to ease rotations, and it has a width and height of one, to ease scaling.
alpha
The alpha value to apply to the sprite: 1.0 means totally opaque; and 0.0 means totally transparent. Note that if you are using alpha, then you should render from back to front in order to avoid rendering artifacts. Furthermore, you should avoid scenarios where semi-transparent objects intersect. This alpha is combined with the alpha (if any) present in texture image.
pSourceRect
A pointer to a RECT structure that indicates what portion of the source texture to use for the sprite. If this parameter is NULL, then the entire source image is used for the sprite; however, you can specify a sub-rectangle of the source image instead. If the source texture was created by using Direct3DX, then the RECT structure should be specified in the coordinates of the original image. So, you do not have to be concerned with any stretching or scaling that Direct3DX may have done to make the image work with your current Direct3D device. Additionally, X and Y mirroring can be specified easily by swapping the left and top and the right and bottom parameters of this RECT structure.

Return Values

If the function succeeds, the return value is S_OK.

If the function fails, the return value may be one of the following values:

D3DXERR_NULLPOINTER
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

C programmers will not be able to take advantage of the default values for the alpha and pSourceRect parameters.

This D3DXDrawSpriteTransform function supports effects that can be specified with a matrix, alpha blending, and choosing a sub-rectangle (a value of NULL for the source sub-rectangle means that the entire texture is used). For total control of the sprite, you should use the D3DXDrawSprite3D function.

This function takes a general 4x4 matrix, which is used to transform the points of a default RECT structure (left=-.5, top=-.5, right=+.5, bottom=+.5), and transforms source images onto a Direct3D rendering device. This default RECT structure was chosen so that it was centered around the origin to ease setting up rotations. In addition, these dimensions were chosen to produce a width and height of one to ease setting up scales.

This function only calls IDirect3DDevice7::SetTexture on the first render stage with the parameter pd3dTexture if that parameter is non-null. This function assumes that D3DXPrepareDeviceForSprite has been called on the device or that caller has in some other way correctly prepared the render states.

Note that if the transformed points have a value for w (the homogenous coordinate) that is not one, then this function will invert it and pass that value to Direct3D as the rhw field of a D3DTLVERTEX structure. If the value for w is zero, then it will use one as the rhw.

Once the matrix is applied to the unit square centered at the (0, 0, 0, 1) origin, these coordinates are assumed to be fully transformed to screen space. Advanced users are advised that the z and w elements will be passed to Direct3D Immediate Mode in a D3DTLVERTEX structure. The w element will be converted into an rhw element. A value for zero for w will result in an rhw value of one.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxsprite.h.
Library: Use d3dx.lib.

See Also

D3DXBuildSpriteTransform


D3DXDrawSprite3D

Given four points, the D3DXDrawSprite3D function will draw the sprite filling those points. The points are expected to be in screen coordinates. This function must be called in between calls to IDirect3DDevice7::BeginScene and IDirect3DDevice7::EndScene.

HRESULT D3DXDrawSprite3D(
  LPDIRECTDRAWSURFACE7 pd3dTexture,
  LPDIRECT3DDEVICE7 pd3dDevice,
  const D3DXVECTOR4 quad[4],
  float alpha = 1.0f,
  const RECT* pSourceRect = NULL,
);

Parameters

pd3dTexture
A pointer to the surface containing the texture, an IDirectDrawSurface7 interface, indicating which surface should be used as the source image for the sprite. If this parameter is NULL, it is assumed that the application has already called IDirect3DDevice7::SetTexture for texture stage zero.
pd3dDevice
A pointer to the Direct3D rendering device, an IDirect3DDevice7 interface. It is assumed that render states are set up, for more information, see D3DXPrepareDeviceForSprite.
quad
An array of D3DXVECTOR4 structures representing an array of 4 points in screen coordinates in the following order: upper-left, upper-right, lower-right, lower-left. If these vectors contain a w value, then this function will take the reciprocal of that value to pass as the rhw value (reciprocal homogenous). The z- and w-coordinates are used to fill in the z and rhw coordinates in a D3DTLVERTEX that is passed to the IDirect3DDevice7::DrawPrimitive method.
alpha
The alpha value to apply to the sprite: 1.0 means totally opaque; and 0.0 means totally transparent. Note that if you are using alpha, then you should render from back to front in order to avoid rendering artifacts. Furthermore, you should avoid scenarios where semi-transparent objects intersect. This alpha is combined with the alpha (if any) present in texture image.
pSourceRect
A pointer to a RECT structure that indicates what portion of the source texture to use for the sprite. If this parameter is NULL, then the entire source image is used for the sprite; however, you can specify a sub-rectangle of the source image instead. If the source texture was created by using Direct3DX, then the RECT structure should be specified in the coordinates of the original image. So, you do not have to be concerned with any stretching or scaling that Direct3DX may have done to make the image work with your current Direct3D device. Additionally, X and Y mirroring can be specified easily by swapping the left and top and the right and bottom parameters of this RECT structure.

Return Values

If the function succeeds, the return value is S_OK.

If the function fails, the return value may be one of the following values:

D3DXERR_NULLPOINTER
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

C programmers will not be able to take advantage of the default values for the alpha and pSourceRect parameters.

The D3DXDrawSprite3D function is not recommended for non-convex triangles.

This function renders a texture onto a 3-D quadrilateral. The quadrilateral ABCD is broken into two triangles ABC and ACD which are rendered through a call to the IDirect3DDevice7::DrawPrimitive method.

For sophisticated applications that seek greater control, look at the IDirect3DDevice7::DrawPrimitive method.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxsprite.h.
Library: Use d3dx.lib.


D3DXPrepareDeviceForSprite

The D3DXPrepareDeviceForSprite function sets a number of render-states to prepare the device for use by the other sprite helper functions. In particular, it sets up alpha-blending and bilinear filtering. A parameter controls whether the z buffer is enabled.

HRESULT D3DXPrepareDeviceForSprite(
  LPDIRECT3DDEVICE7 pd3dDevice,
  BOOL ZEnable = FALSE
);

Parameters

pd3dDevice
A pointer to the Direct3D device, an IDirect3DDevice7 interface, to be prepared for use with Direct3DX sprite services.
ZEnable
A flag indicating whether the sprites should check and update the z buffer surface as part of rendering. Since, in typical applications, sprites are rendered from back-to-front, the default value is FALSE. Sophisticated applications that want to mix 2-D and 3-D may want to set this value to TRUE. If ZEnable is FALSE, or you are using alpha-blending, then it is necessary to render your sprites from back-to-front.

Return Values

If the function succeeds, the return value is S_OK; otherwise the function returns D3DXERR_NULLPOINTER.

Remarks

C programmers will not be able to take advantage of the default value for the ZEnable parameter.

Call this function to set up all the render states necessary for the D3DXDrawSpriteSimple and D3DXDrawSprite3D functions to work correctly. Note that advanced users may decide not to call this function; in which case the D3DXDrawSpriteSimple and D3DXDrawSprite3D functions will use whatever render and texture states are set up on the device.

Note The D3DXPrepareDeviceForSprite function modifies render states and may impact performance negatively on some 3-D hardware if it is called too often per frame. If the render state changes (other than through calls to D3DXDrawSpriteSimple or D3DXDrawSprite3D), you will need to call this function again before calling D3DXDrawSpriteSimple or D3DXDrawSprite3D.

The D3DXPrepareDeviceForSprite function modifies the rendering first texture stage and it modifies some render states for the entire device. Here is the exact list:

    SetTextureStageState(0, D3DTSS_COLORARG1,         D3DTA_TEXTURE);
    SetTextureStageState(0, D3DTSS_COLOROP,           D3DTOP_SELECTARG1);
    SetTextureStageState(0, D3DTSS_ALPHAARG1,         D3DTA_TEXTURE);
    SetTextureStageState(0, D3DTSS_ALPHAARG2,         D3DTA_DIFFUSE);
    SetTextureStageState(0, D3DTSS_ALPHAOP,           D3DTOP_MODULATE);
    SetTextureStageState(0, D3DTSS_MINFILTER,         D3DTFN_LINEAR);
    SetTextureStageState(0, D3DTSS_MAGFILTER,         D3DTFG_LINEAR);

    SetRenderState(D3DRENDERSTATE_SRCBLEND,           D3DBLEND_SRCALPHA);
    SetRenderState(D3DRENDERSTATE_DESTBLEND,          D3DBLEND_INVSRCALPHA);
    SetRenderState(D3DRENDERSTATE_ALPHABLENDENABLE,   TRUE);

Depending on the value of the ZEnable parameter, this function will either call

    SetRenderState(D3DRENDERSTATE_ZENABLE,            FALSE);

or

    SetRenderState(D3DRENDERSTATE_ZENABLE,            TRUE);

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxsprite.h.
Library: Use d3dx.lib.


Texturing Functions

The texturing application programming interface (API) provided by the Direct3DX utility library supplies functions to convert texture formats, create and load textures, filter textures, and generate mipmaps.

The functions of the texturing API can be organized into the following groups:

Create | D3DXCreateCubeMapTexture
 | D3DXCreateTexture
 | D3DXCreateTextureFromFile
Load | D3DXLoadTextureFromFile
 | D3DXLoadTextureFromMemory
 | D3DXLoadTextureFromSurface
Miscellaneous | D3DXCheckTextureRequirements


D3DXCheckTextureRequirements

The D3DXCheckTextureRequirements function returns information about texture creation. It provides an easy mechanism to determine the closest surface type that works with the current Direct3DDevice device. Given an ideal texture format, width, and height, and a mipmapping flag, it returns the closest match that works with the chosen device.

HRESULT D3DXCheckTextureRequirements(
  LPDIRECT3DDEVICE7 pd3dDevice,
  LPDWORD pFlags,
  LPDWORD pWidth,
  LPDWORD pHeight,
  D3DX_SURFACEFORMAT* pPixelFormat,
);

Parameters

pd3dDevice
A pointer to the Direct3D device, an IDirect3DDevice7 interface, associated with the texture.
pFlags
A pointer to a DWORD value. This parameter allows you to specify the D3DX_TEXTURE_NOMIPMAP flag if mipmap generation is not desired. This value can be NULL. The D3DX_TEXTURE_NOMIPMAP flag may be returned in the case where mipmap creation is not supported.
pWidth
A pointer to a DWORD value, indicating the width in pixels. If you specify zero or D3DX_DEFAULT, the width will be taken from the file. This parameter returns the corrected width.
pHeight
A pointer to a DWORD value, indicating the height in pixels. If you specify zero or D3DX_DEFAULT, the height will be taken from the file. This parameter returns the corrected height.
pPixelFormat
A pointer to a member of the D3DX_SURFACEFORMAT enumerated type. The input value for this parameter should be the desired texture format. The return value will be the closest texture format that is supported by the hardware.

Return Values

If the function succeeds, the return value is S_OK.

If the function fails, the return value may be one of the following values:

D3DXERR_INVALIDPARAMETER
D3DXERR_NOMATCHFOUND
D3DXERR_NULLPOINTER

Remarks

This function provides a helper to determine what resizing and format conversion the D3DXCreateTexture, D3DXCreateTextureFromFile, and D3DXCreateCubeMapTexture functions will need to do. In most cases, the create functions can be used directly without performing this step.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.


D3DXCreateCubeMapTexture

The D3DXCreateCubeMapTexture function creates a blank cube-map texture.

HRESULT D3DXCreateCubeMapTexture(
  LPDIRECT3DDEVICE7 pd3dDevice,
  LPDWORD pFlags,
  DWORD cubefaces,
  D3DCOLOR colorEmptyFaces,
  LPDWORD pWidth,
  LPDWORD pHeight,
  D3DX_SURFACEFORMAT* pPixelFormat,
  LPDIRECTDRAWPALETTE pDDPal,
  LPDIRECTDRAWSURFACE7* ppDDSurf,
  LPDWORD pNumMipMaps
);

Parameters

pd3dDevice
A pointer to the Direct3D device, an IDirect3DDevice7 interface, associated with the texture.
pFlags
A pointer to a DWORD value. This parameter allows you to specify the D3DX_TEXTURE_NOMIPMAP flag if mipmap generation is not desired. This value can be NULL. The D3DX_TEXTURE_NOMIPMAP flag may be returned in the case where mipmap creation is not supported.
cubefaces
This parameter allows you to specify which faces of the cube map to generate. For more information, see remarks.
colorEmptyFaces
This parameter, a D3DCOLOR type, allows you to specify a single A8R8G8B8 color to take the place of the missing surfaces in the cube map (the faces that were not specified in the cubefaces parameter).
pWidth
A pointer to a DWORD value, indicating the width in pixels. If you specify zero or D3DX_DEFAULT, the width will be taken from the file. This parameter returns the corrected width.
pHeight
A pointer to a DWORD value, indicating the height in pixels. If you specify zero or D3DX_DEFAULT, the height will be taken from the file. This parameter returns the corrected height.
pPixelFormat
A pointer to a member of the D3DX_SURFACEFORMAT enumerated type, indicating the surface format. D3DX_DEFAULT is not valid for this parameter. This parameter returns the used surface format.
pDDPal
A pointer to the DirectDraw palette, an IDirectDrawPalette interface, that is set (if present) on paletted surfaces. It is ignored even if it is set, for non-paletted surfaces. So, it allows specification of the palette to use if the resulting surface is an 8-bit palettized surface.
ppDDSurf
The address of a pointer to the DirectDrawSurface object, the texture created that matched the specifications and the current hardware.
pNumMipMaps
A pointer to a DWORD value. The number of mipmaps generated for a particular face of the cube map.

Return Values

If the function succeeds, the return value is S_OK.

If the function fails, the return value may be one of the following values:

D3DERR_TEXTURE_NO_SUPPORT
D3DXERR_D3DXNOTSTARTEDYET
D3DXERR_INVALIDPARAMETER
D3DXERR_NOMATCHFOUND
D3DXERR_NULLPOINTER
DDERR_INCOMPATIBLEPRIMARY
DDERR_INVALIDCAPS
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDPIXELFORMAT
DDERR_NOALPHAHW
DDERR_NOCOOPERATIVELEVELSET
DDERR_NODIRECTDRAWHW
DDERR_NOEMULATION
DDERR_NOEXCLUSIVEMODE
DDERR_NOFLIPHW
DDERR_NOMIPMAPHW
DDERR_NOOVERLAYHW
DDERR_NOZBUFFERHW
DDERR_OUTOFMEMORY
DDERR_OUTOFVIDEOMEMORY
DDERR_PRIMARYSURFACEALREADYEXISTS
DDERR_UNSUPPORTEDMODE

Remarks

Cube maps may have up to 6 faces; and they may specify a color to use for the missing faces. See the Direct3D Immediate Mode documentation for more details about how to use cube maps for creating the illusion of reflections and refraction.

For the cubefaces parameter, D3DX_DEFAULT, 0, and DDSCAPS2_CUBEMAP_ALLFACES all indicate to create all 6 faces of the cube map. Any combination of DDSCAPS2_CUBEMAP_POSITIVEX, DDSCAPS2_CUBEMAP_NEGATIVEX, DDSCAPS2_CUBEMAP_POSITIVEY, DDSCAPS2_CUBEMAP_NEGATIVEY, DDSCAPS2_CUBEMAP_POSITIVEZ, or DDSCAPS2_CUBEMAP_NEGATIVEZ, is valid.

Unless the pFlags parameter is set to specifically prevent creating mipmaps, mipmaps are generated until reaching the minimum level size of 1x1.

For more information on mipmaps, see Texture Filtering With Mipmaps.

Width, height and pixelformat are altered based on available hardware. For example, mipmap dimensions may be required to be powers of 2 and width may be required to be equal to height for square textures. Also, if the specified pixel format is unavailable, a best fit will be made.

This function creates a surface whose size and pixel format has been adjusted to match the requirements of the current device. The surface created is a system memory which is marked as Texture-Managed; see the Direct3D Immediate Mode documentation for more details.

The surface created may be larger or smaller than that specified by the width and height parameters. The pixel format chosen may not be the format passed in. Attention to the actual width, height, and pixel formats is necessary only if you plan to directly access the surface returned by this function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

D3DXCreateTexture


D3DXCreateTexture

The D3DXCreateTexture function creates an empty texture object.

HRESULT D3DXCreateTexture(
  LPDIRECT3DDEVICE7 pd3dDevice,
  LPDWORD pFlags,
  LPDWORD pWidth,
  LPDWORD pHeight,
  D3DX_SURFACEFORMAT* pPixelFormat,
  LPDIRECTDRAWPALETTE pDDPal,
  LPDIRECTDRAWSURFACE7* ppDDSurf,
  LPDWORD pNumMipMaps
);

Parameters

pd3dDevice
The Direct3D device, an IDirect3DDevice7 interface, associated with the texture.
pFlags
A pointer to a DWORD value. This parameter allows you to specify the D3DX_TEXTURE_NOMIPMAP flag if mipmap generation is not desired. This value can be NULL. The D3DX_TEXTURE_NOMIPMAP flag may be returned in the case where mipmap creation is not supported.
pWidth
A pointer to a DWORD value, indicating the width in pixels. This parameter returns the corrected width.
pHeight
A pointer to a DWORD value, indicating the height in pixels. This parameter returns the corrected height.
pPixelFormat
A pointer to a member of the D3DX_SURFACEFORMAT enumerated type. D3DX_DEFAULT is not valid for this parameter. The input value for this parameter should be the desired texture format. The return value will be the closest texture format that is supported by the hardware.
pDDPal
A pointer to the DirectDraw palette, an IDirectDrawPalette interface, that is set (if present) on paletted surfaces. It is ignored even if it is set, for non-paletted surfaces. So, it allows specification of the palette to use if the resulting surface is an 8-bit palettized surface.
ppDDSurf
The address of a pointer to the DirectDrawSurface object, the texture created that matched the specifications and the current hardware.
pNumMipMaps
A pointer to a DWORD value. The number of mipmaps generated for a particular face of the cube map.

Return Values

If the function succeeds, the return value is S_OK.

If the function fails, the return value may be one of the following values:

D3DXERR_D3DXNOTSTARTEDYET
D3DXERR_INVALIDPARAMETER
D3DXERR_NOMATCHFOUND
D3DXERR_NULLPOINTER
DDERR_INCOMPATIBLEPRIMARY
DDERR_INVALIDCAPS
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDPIXELFORMAT
DDERR_NOALPHAHW
DDERR_NOCOOPERATIVELEVELSET
DDERR_NODIRECTDRAWHW
DDERR_NOEMULATION
DDERR_NOEXCLUSIVEMODE
DDERR_NOFLIPHW
DDERR_NOMIPMAPHW
DDERR_NOOVERLAYHW
DDERR_NOZBUFFERHW
DDERR_OUTOFMEMORY
DDERR_OUTOFVIDEOMEMORY
DDERR_PRIMARYSURFACEALREADYEXISTS
DDERR_UNSUPPORTEDMODE

Remarks

Unless the pFlags parameter is set to specifically prevent creating mipmaps, mipmaps are generated until reaching the minimum level size of 1x1.

For more information on mipmaps, see Texture Filtering With Mipmaps.

Width, height and pixel format are altered based on available hardware. For example, mipmap dimensions may be required to be powers of 2 and width may be required to be equal to height for square textures. Also, if the specified pixel format is unavailable, a best fit will be made.

This function creates a surface whose size and pixel format has been adjusted to match the requirements of the current device. The surface created is system memory which is marked as Texture-Managed; see Direct3D Immediate Mode documentation for more details.

The surface created may be larger or smaller than that specified by the width and height parameters. The pixel format chosen may not be the format passed in. Attention to the actual width, height, and pixel format is necessary only if you plan to directly access the surface returned by this function. (Doing so is not advised however, because you will find that the surface may have different properties on different devices.)

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

D3DXCreateCubeMapTexture


D3DXCreateTextureFromFile

The D3DXCreateTextureFromFile function creates a texture object from a stand-alone file or from the resource.

HRESULT D3DXCreateTextureFromFile(
  LPDIRECT3DDEVICE7 pd3dDevice,
  LPDWORD pFlags,
  LPDWORD pWidth,
  LPDWORD pHeight,
  D3DX_SURFACEFORMAT* pPixelFormat,
  LPDIRECTDRAWPALETTE pDDPal,
  LPDIRECTDRAWSURFACE7* ppDDSurf,
  LPDWORD pNumMipMaps,
  LPSTR pSrcName,
  D3DX_FILTERTYPE filterType
);

Parameters

pd3dDevice
The Direct3D device, an IDirect3DDevice7 interface, associated with the texture.
pFlags
A pointer to a DWORD value. This parameter allows you to specify the D3DX_TEXTURE_NOMIPMAP flag if mipmap generation is not desired. This value can be NULL. The D3DX_TEXTURE_NOMIPMAP flag may be returned in the case where mipmap creation is not supported.
pWidth
A pointer to a DWORD value, indicating the width in pixels. If you specify zero or D3DX_DEFAULT, the width will be taken from the file. This parameter returns the corrected width.
pHeight
A pointer to a DWORD value, indicating the height in pixels. If you specify zero or D3DX_DEFAULT, the height will be taken from the file. This parameter returns the corrected height.
pPixelFormat
A pointer to a member of the D3DX_SURFACEFORMAT enumerated type. D3DX_DEFAULT is not valid for this parameter. The input value for this parameter should be the desired texture format. The return value will be the closest texture format that is supported by the hardware. If D3DX_SF_UNKNOWN is passed in, pixel format closest to the bitmap will be chosen.
pDDPal
A pointer to the DirectDraw palette, an IDirectDrawPalette interface, that is set (if present) on paletted surfaces. It is ignored even if it is set, for non-paletted surfaces.
ppDDSurf
The address of a pointer to a DirectDrawSurface object, the texture created that matched the specifications and the current hardware.
pNumMipMaps
A pointer to a DWORD value. The number of mipmaps generated.
pSrcName
A pointer to the file name string. The following file types are supported: BMP, DIB, and DDS; for more information, see remarks.
filterType
A member of the D3DX_FILTERTYPE enumerated type, indicating what filtering function should be used for any necessary resizing or mipmap generation.

Return Values

If the function succeeds, the return value is S_OK.

If the function fails, the return value may be NULL or one of the following values:

D3DERR_TEXTURE_NO_SUPPORT
D3DXERR_D3DXNOTSTARTEDYET
D3DXERR_INVALIDFILEFORMAT
D3DXERR_INVALIDPARAMETER
D3DXERR_NOMATCHFOUND
D3DXERR_NOMEMORY
D3DXERR_NULLPOINTER
D3DXERR_UNSUPPORTEDFILEFORMAT
DDERR_DCALREADYCREATED
DDERR_GENERIC
DDERR_INCOMPATIBLEPRIMARY
DDERR_INVALIDCAPS
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDPIXELFORMAT
DDERR_INVALIDRECT
DDERR_INVALIDSURFACETYPE
DDERR_NOALPHAHW
DDERR_NOCOOPERATIVELEVELSET
DDERR_NODIRECTDRAWHW
DDERR_NOEMULATION
DDERR_NOEXCLUSIVEMODE
DDERR_NOFLIPHW
DDERR_NOMIPMAPHW
DDERR_NOOVERLAYHW
DDERR_NOTFOUND
DDERR_NOTLOCKED
DDERR_NOZBUFFERHW
DDERR_OUTOFMEMORY
DDERR_OUTOFVIDEOMEMORY
DDERR_PRIMARYSURFACEALREADYEXISTS
DDERR_SURFACEBUSY
DDERR_SURFACELOST
DDERR_UNSUPPORTED
DDERR_UNSUPPORTEDMODE
DDERR_WASSTILLDRAWING

Remarks

Only BMP and DIB files are supported from the resource portion of the executable.

In the pSrcName parameter, TGA is supported for the following cases: 16-, 24-, and 32-bpp direct color and 8-bpp palettized. Also, 8- and 16-bpp gray scale is supported. RLE versions of the preceding TGA formats are also supported. Note that colorkeying and premultiplied alpha are not currently supported for TGA files.

Specifying a numeric ID for the pSrcName parameter instructs the D3DXLoadTextureFromFile function to load bitmap images from the executable's resource; otherwise, pSrcName is assumed to be a file name. Note that you cannot use the string resource name, since the D3DXCreateTextureFromFile function treats a string pointer as a file name.

Unless the pFlags parameter is set to specifically prevent creating mipmaps, mipmaps are generated until reaching the minimum level size of 1x1.

For more information on mipmaps, see Texture Filtering With Mipmaps.

Width, height and pixel format are altered based on available hardware. For example, mipmap dimensions may be required to be powers of 2 and width may be required to be equal to height for square textures. Also, if the specified pixel format is unavailable, a best fit will be made.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

D3DXLoadTextureFromFile


D3DXLoadTextureFromFile

The D3DXLoadTextureFromFile function loads a texture from a file into a mipmap level, performing the necessary color conversion and re-scaling.

HRESULT D3DXLoadTextureFromFile(
  LPDIRECT3DDEVICE7 pd3dDevice,
  LPDIRECTDRAWSURFACE7 pTexture,
  DWORD mipMapLevel,
  LPSTR pSrcName,
  RECT* pSrcRect,
  RECT* pDestRect,
  D3DX_FILTERTYPE filterType
);

Parameters

pd3dDevice
A pointer to the Direct3D device, an IDirect3DDevice7 interface, associated with the texture.
pTexture
A pointer to the DirectDrawSurface that was created with either the D3DXCreateTextureFromFile or D3DXCreateTexture functions. This parameter points to the texture surface object.
mipMapLevel
Indicates mipmap level. See remarks.
pSrcName
A pointer to the file name string. The following file types are supported: BMP, DIB, and DDS; for more information, see remarks.
pSrcRect
A pointer to a RECT structure, identifying the source rectangle. If NULL is specified for this parameter, the whole surface is used.
pDestRect
A pointer to a RECT structure, identifying the destination rectangle. If NULL is specified for this parameter, the whole surface is used.
filterType
A member of the D3DX_FILTERTYPE enumerated type, indicating the filter used for mipmap generation.

Return Values

If the function succeeds, the return value is S_OK.

If the function fails, the return value may be NULL or one of the following values:

D3DERR_TEXTURE_NO_SUPPORT
D3DXERR_D3DXNOTSTARTEDYET
D3DXERR_INVALIDFILEFORMAT
D3DXERR_INVALIDPARAMETER
D3DXERR_NOMATCHFOUND
D3DXERR_NOMEMORY
D3DXERR_NULLPOINTER
D3DXERR_UNSUPPORTEDFILEFORMAT
DDERR_DCALREADYCREATED
DDERR_GENERIC
DDERR_INCOMPATIBLEPRIMARY
DDERR_INVALIDCAPS
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDPIXELFORMAT
DDERR_INVALIDRECT
DDERR_INVALIDSURFACETYPE
DDERR_NOALPHAHW
DDERR_NOCOOPERATIVELEVELSET
DDERR_NODIRECTDRAWHW
DDERR_NOEMULATION
DDERR_NOEXCLUSIVEMODE
DDERR_NOFLIPHW
DDERR_NOMIPMAPHW
DDERR_NOOVERLAYHW
DDERR_NOTFOUND
DDERR_NOTLOCKED
DDERR_NOZBUFFERHW
DDERR_OUTOFMEMORY
DDERR_OUTOFVIDEOMEMORY
DDERR_PRIMARYSURFACEALREADYEXISTS
DDERR_SURFACEBUSY
DDERR_SURFACELOST
DDERR_UNSUPPORTED
DDERR_UNSUPPORTEDMODE
DDERR_WASSTILLDRAWING

Remarks

This function provides a mechanism to copy pixels from a file to a surface.

Concerning the mipMapLevel parameter:

  • If the specified mipmap level does not exist, as error is returned.
  • If D3DX_DEFAULT is specified and an equal number of mipmap levels exist, then all of the source mipmap levels are loaded.
  • If the source has mipmap levels and the destination does not, the top level is used.
  • If the destination has mipmap levels and the source does not, expansion is used.
  • If there are unequal numbers of mipmap levels between the source and destination, expansion is used.

In the pSrcName parameter, TGA is supported for the following cases: 16-, 24-, and 32-bpp direct color and 8-bpp palettized. Also, 8- and 16-bpp gray scale is supported. RLE versions of the preceding TGA formats are also supported. Note that colorkeying and premultiplied alpha are not currently supported for TGA files.

If the destination surface was created by Direct3DX, then the RECT structure should be specified in the original coordinates of that surface.

This function supports a full range of color-conversion for all surface formats that can be described by a D3DX_SURFACEFORMAT structure. It also implements filtered re-scaling and updates mipmaps automatically.

By taking pDestRect in the space of the original image, the application does not have to worry about how the surface may have been resized as part of the D3DXCreateTexture routine. For example, if an image was 100x150 pixels, then it may end up being 128x256 or 256x256 on different configurations. In both cases, the RECT structure to use to update the upper left quadrant is (0, 0, 50, 75); as if no resizing had taken place.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

D3DXCreateTextureFromFile, D3DXLoadTextureFromMemory, D3DXLoadTextureFromSurface


D3DXLoadTextureFromMemory

The D3DXLoadTextureFromMemory function loads a mipmap level from memory, performing the necessary color conversion.

HRESULT D3DXLoadTextureFromMemory(
  LPDIRECT3DDEVICE7 pd3dDevice,
  LPDIRECTDRAWSURFACE7 pTexture,
  DWORD mipMapLevel,
  LPVOID pMemory,
  LPDIRECTDRAWPALETTE pDDPal,
  D3DX_SURFACEFORMAT srcPixelFormat,
  DWORD srcPitch,
  RECT* pDestRect,
  D3DX_FILTERTYPE filterType
);

Parameters

pd3dDevice
A pointer to the Direct3D device, an IDirect3DDevice7 interface, associated with the texture.
pTexture
A pointer to the DirectDrawSurface that was created with either the D3DXCreateTextureFromFile or D3DXCreateTexture functions. This parameter points to the texture surface object.
mipMapLevel
Indicates mipmap level. See remarks.
pMemory
A pointer to the source memory from which the texture will be loaded.
pDDPal
A pointer to the DirectDraw palette, an IDirectDrawPalette interface, that the application passes in optionally if the memory is supposed to be paletteized.
srcPixelFormat
A pointer to a member of the D3DX_SURFACEFORMAT enumerated type, indicating the pixel format of the source.
srcPitch
The pitch of the memory, or D3DX_DEFAULT. This parameter is based on the srcPixelFormat, parameter.
pDestRect
A pointer to a RECT structure, identifying the destination rectangle. If NULL is specified for this parameter, the whole surface is used.
filterType
A member of the D3DX_FILTERTYPE enumerated type, indicating the filter used for mipmap generation.

Return Values

If the function succeeds, the return value is S_OK.

If the function fails, the return value may be one of the following values:

D3DXERR_D3DXNOTSTARTEDYET
D3DXERR_INVALIDPARAMETER
D3DXERR_NOMEMORY
D3DXERR_NULLPOINTER
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOTFOUND
DDERR_SURFACELOST
DDERR_UNSUPPORTED

Remarks

This function provides a mechanism to copy some pixels from memory to a surface.

If the destination surface was created by Direct3DX, then the RECT structure should be specified in the original coordinates of that surface.

Concerning the mipMapLevel parameter:

  • If the specified mipmap level does not exist, as error is returned.
  • If D3DX_DEFAULT is specified and an equal number of mipmap levels exist, then all of the source mipmap levels are loaded.
  • If the source has mipmap levels and the destination does not, the top level is used.
  • If the destination has mipmap levels and the source does not, expansion is used.
  • If there are unequal numbers of mipmap levels between the source and destination, expansion is used.

This function assumes that the source (memory) has been loaded in full.

This function supports a full range of color-conversion for all surface formats that can be described by a D3DX_SURFACEFORMAT structure. It also implements filtered re-scaling and updates mipmaps automatically.

By taking pDestRect in the space of the original image, the application does not have to worry about how the surface may have been resized as part of the D3DXCreateTexture routine. For example, if an image was 100x150 pixels, then it may end up being 128x256 or 256x256 on different configurations. In both cases, the RECT structure to use to update the upper left quadrant is (0, 0, 50, 75); as if no resizing had taken place.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

D3DXLoadTextureFromFile, D3DXLoadTextureFromSurface


D3DXLoadTextureFromSurface

The D3DXLoadTextureFromSurface function loads a texture from a DirectDrawSurface into a mipmap level, performing the necessary color conversion.

HRESULT D3DXLoadTextureFromSurface(
  LPDIRECT3DDEVICE7 pd3dDevice,
  LPDIRECTDRAWSURFACE7 pTexture,
  DWORD mipMapLevel,
  LPDIRECTDRAWSURFACE7 pSurfaceSrc,
  RECT* pSrcRect,
  RECT* pDestRect,
  D3DX_FILTERTYPE filterType
);

Parameters

pd3dDevice
A pointer to the Direct3D device, an IDirect3DDevice7 interface, associated with the texture.
pTexture
A pointer to the DirectDrawSurface that was created with either the D3DXCreateTextureFromFile or D3DXCreateTexture functions. This parameter points to the texture surface object.
mipMapLevel
Indicates mipmap level. See remarks.
pSurfaceSrc
A pointer to the source surface, an IDirectDrawSurface7 interface. The surface object that contains the pixels to load from.
pSrcRect
A pointer to a RECT structure, identifying the source rectangle. If NULL is specified for this parameter, the whole surface is used.
pDestRect
A pointer to a RECT structure, identifying the destination rectangle. If NULL is specified for this parameter, the whole surface is used.
filterType
A member of the D3DX_FILTERTYPE enumerated type, indicating what filtering function should be used for any necessary resizing or mipmap generation.

Return Values

If the function succeeds, the return value is S_OK.

If the function fails, the return value may be one of the following values:

D3DXERR_D3DXNOTSTARTEDYET
D3DXERR_INVALIDPARAMETER
D3DXERR_NOMEMORY
D3DXERR_NULLPOINTER
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOTFOUND
DDERR_SURFACELOST
DDERR_UNSUPPORTED

Remarks

This function provides a mechanism to copy one surface to another.

Concerning the mipMapLevel parameter:

  • If the specified mipmap level does not exist, as error is returned.
  • If D3DX_DEFAULT is specified and an equal number of mipmap levels exist, then all of the source mipmap levels are loaded.
  • If the source has mipmap levels and the destination does not, the top level is used.
  • If the destination has mipmap levels and the source does not, expansion is used.
  • If there are unequal numbers of mipmap levels between the source and destination, expansion is used.

If the source or destination surface was created by Direct3DX, then the RECT structure should be specified in the original coordinates of that surface.

This function supports a full range of color-conversion for all surface formats that can be described by a D3DX_SURFACEFORMAT structure. It also implements filtered re-scaling and updates mipmaps automatically.

By taking pDestRect in the space of the original image, the application does not have to worry about how the surface may have been resized as part of the D3DXCreateTexture routine. For example, if an image was 100x150 pixels, then it may end up being 128x256 or 256x256 on different configurations. In both cases, the RECT structure to use to update the upper left quadrant is (0, 0, 50, 75); as if no resizing had taken place.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.
Library: Use d3dx.lib.

See Also

D3DXLoadTextureFromFile, D3DXLoadTextureFromMemory


Macros

This section contains reference information for the macros provided by the Direct3DX utility library.

  • D3DXToDegree
  • D3DXToRadian


D3DXToDegree

The D3DXToDegree macro converts radians into degrees.

D3DXToDegree( radian ) ((radian) * (180.0f / D3DX_PI))

Parameters

radian
The value, in radians, that you want to convert to degrees.

Return Values

The macro returns the radian value in degrees.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.

See Also

D3DXToRadian


D3DXToRadian

The D3DXToRadian macro converts degrees into radians.

D3DXToRadian( degree ) ((degree) * (D3DX_PI / 180.0f))

Parameters

degree
The value, in degrees, that you want to convert to radians.

Return Values

The macro returns the degree value in radians.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.

See Also

D3DXToDegree


Structures

This section contains information about the following structures used with the Direct3DX utility library:

  • D3DX_DEVICEDESC
  • D3DX_VIDMODEDESC
  • D3DXCOLOR
  • D3DXMATRIX
  • D3DXPLANE
  • D3DXQUATERNION
  • D3DXVECTOR2
  • D3DXVECTOR3
  • D3DXVECTOR4


D3DX_DEVICEDESC

The D3DX_DEVICEDESC structure describes a device that can render in 3-D.

typedef struct _D3DX_DEVICEDESC {
  DWORD       deviceIndex;
  DWORD       hwLevel;
  GUID        ddGuid;
  GUID        d3dDeviceGuid;
  GUID        ddDeviceID;
  char        driverDesc[D3DX_DRIVERDESC_LENGTH];
  HMONITOR    monitor;
  BOOL        onPrimary;
} D3DX_DEVICEDESC;

Members

deviceIndex
Unique number (DWORD) for the device.
hwLevel
Level of acceleration afforded. This is one of the predefined Device Indices, and exists in this structure for informational purposes only. More than one device on the system may have the same hwLevel. To refer to a particular device with the D3DX utility library, use the value in the deviceIndex member instead.
ddGuid
The DirectDraw globally unique identifier (GUID).
d3dDeviceGuid
The Direct3DDevice GUID.
ddDeviceID
The IDirectDraw7::GetDeviceIdentifier GUID. This GUID is unique to a particular driver revision on a particular video card.
driverDesc
String describing the driver. The maximum string length allowed is 256 characters.
monitor
Handle to the video monitor used by this device (multiple monitor specific). Devices that use different monitors on a multiple monitor system report different values in this field. Therefore, to test for a multiple monitor system, an application should look for more than one different monitor handle in the list of Direct3DX devices.
onPrimary
Indicates if this device is on the primary monitor (multiple monitor specific).

Remarks

The following statement defines the constant used by the driverDesc character array parameter:

#define D3DX_DRIVERDESC_LENGTH    256

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.


D3DX_VIDMODEDESC

The D3DX_VIDMODEDESC structure describes the display mode.

typedef struct  _D3DX_VIDMODEDESC {
  DWORD width;
  DWORD height;
  DWORD bpp;
  DWORD refreshRate;
} D3DX_VIDMODEDESC;

Members

width
The screen width.
height
The screen height.
bpp
The bits per pixel.
refreshRate
The refresh rate.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.


D3DXCOLOR

The D3DX_DEVICEDESC structure describes color values.

typedef struct D3DXCOLOR {
  FLOAT r, g, b, a;
} D3DXCOLOR;

Members

r
The red component of the color.
g
The green component of the color.
b
The blue component of the color.
a
The alpha component of the color.

Remarks

C++ programmers can take advantage of operator overloading and type casting. The C++ implementation of the D3DXCOLOR structure implements overloaded constructors and overloaded assignment, unary, and binary (including equality) operators. For more information, see C++ Specific Features.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.

See Also

D3DXColorNegative, D3DXColorAdd, D3DXColorSubtract, D3DXColorScale, D3DXColorModulate, D3DXColorLerp


D3DXMATRIX

The D3DXMATRIX structure describes a matrix.

typedef struct D3DXMATRIX {
  union
  {
    float m[4][4];
  };
} D3DXMATRIX;

Remarks

In Direct3DX, the m23 element of a projection matrix cannot be a negative number. If your application needs to use a negative value in this location, it should scale the entire projection matrix by -1, instead.

C++ programmers can take advantage of operator overloading and type casting. The C++ implementation of the D3DXMATRIX structure implements overloaded constructors and overloaded assignment, unary, and binary (including equality) operators. For more information, see C++ Specific Features.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.

See Also

D3DXMatrixIdentity, D3DXMatrixIsIdentity, D3DXMatrixfDeterminant, D3DXMatrixMultiply, D3DXMatrixTranspose, D3DXMatrixInverse, D3DXMatrixScaling, D3DXMatrixTranslation, D3DXMatrixRotationX, D3DXMatrixRotationY, D3DXMatrixRotationZ, D3DXMatrixRotationAxis, D3DXMatrixRotationQuaternion, D3DXMatrixRotationYawPitchRoll, D3DXMatrixTransformation, D3DXMatrixAffineTransformation, D3DXMatrixLookAt, D3DXMatrixPerspective, D3DXMatrixPerspectiveFov, D3DXMatrixPerspectiveOffCenter, D3DXMatrixOrtho, D3DXMatrixOrthoOffCenter, D3DXMatrixShadow, D3DXMatrixReflect


D3DXPLANE

The D3DXPLANE structure describes a plane.

typedef struct D3DXPLANE {
  float a, b, c, d;
} D3DXPLANE;

Members

a
The a coefficient of the clipping plane in the general plane equation. See remarks.
b
The b coefficient of the clipping plane in the general plane equation. See remarks.
c
The c coefficient of the clipping plane in the general plane equation. See remarks.
d
The d coefficient of the clipping plane in the general plane equation. See remarks.

Remarks

The members of the D3DXPLANE structure take the form of the general plane equation. They fit into the general plane equation such that ax + by + cz + dw = 0.

C++ programmers can take advantage of operator overloading and type casting. The C++ implementation of the D3DXPLANE structure implements overloaded constructors and overloaded unary and binary operators. For more information, see C++ Specific Features.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.

See Also

D3DXPlaneDot, D3DXPlaneDotCoord, D3DXPlaneDotNormal, D3DXPlaneIntersectLine, D3DXPlaneFromPointNormal, D3DXPlaneFromPoints, D3DXPlaneTransform


D3DXQUATERNION

The D3DXQUATERNION structure describes a quaternion.

typedef struct D3DXQUATERNION {
  float x, y, z, w;
} D3DXQUATERNION;

Members

x
The x-component.
y
The y-component.
z
The z-component.
w
The w-component.

Remarks

Quaternions add a fourth element to the [x, y, z] values that define a vector, resulting in arbitrary 4-D vectors. However, the following illustrates how each element of a unit quaternion relates to an axis-angle rotation (where q represents a unit quaternion (x, y, z, w), axis is normalized, and theta is the desired CCW rotation about the axis):

q.x = sin(theta/2) * axis.x
q.y = sin(theta/2) * axis.y
q.z = sin(theta/2) * axis.z
q.w = cos(theta/2)

C++ programmers can take advantage of operator overloading and type casting. The C++ implementation of the D3DXQUATERNION structure implements overloaded constructors and overloaded assignment, unary and binary (including equality) operators. For more information, see C++ Specific Features.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.

See Also

D3DXPlaneDot, D3DXPlaneDotCoord, D3DXPlaneDotNormal, D3DXPlaneIntersectLine, D3DXPlaneFromPointNormal, D3DXPlaneFromPoints, D3DXPlaneTransform


D3DXVECTOR2

The D3DXVECTOR2 structure describes a vector in two-dimensional (2-D) space.

typedef struct D3DXVECTOR2 {
  float x, y;
} D3DXVECTOR2;

Members

x
The x component.
y
The y component.

Remarks

C++ programmers can take advantage of operator overloading and type casting. The C++ implementation of the D3DXVECTOR2 structure implements overloaded constructors and overloaded assignment, unary and binary (including equality) operators. For more information, see C++ Specific Features.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.

See Also

D3DXVec2Length, D3DXVec2LengthSq, D3DXVec2Dot, D3DXVec2CCW, D3DXVec2Add, D3DXVec2Subtract, D3DXVec2Minimize, D3DXVec2Maximize, D3DXVec2Scale, D3DXVec2Lerp, D3DXVec2Normalize, D3DXVec2Hermite, D3DXVec2Hermite, D3DXVec2Transform, D3DXVec2TransformCoord, D3DXVec2TransformNormal


D3DXVECTOR3

The D3DXVECTOR3 structure describes a vector in three-dimensional (3-D) space.

typedef struct D3DXVECTOR3 {
  float x, y, z;
} D3DXVECTOR3;

Members

x
The x-component.
y
The y-component.
z
The z-component.

Remarks

C++ programmers can take advantage of operator overloading and type casting. The C++ implementation of the D3DXVECTOR3 structure implements overloaded constructors and overloaded assignment, unary and binary (including equality) operators. For more information, see C++ Specific Features.

D3DXVec3Length, D3DXVec3LengthSq, D3DXVec3Dot, D3DXVec3Cross, D3DXVec3Add, D3DXVec3Subtract, D3DXVec3Minimize, D3DXVec3Maximize, D3DXVec3Scale, D3DXVec3Lerp, D3DXVec3Normalize, D3DXVec3Hermite, D3DXVec3BaryCentric, D3DXVec3Transform, D3DXVec3TransformCoord, D3DXVec3TransformNormal

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.


D3DXVECTOR4

The D3DXVECTOR4 structure describes a vector in four-dimensional (4-D) space.

typedef struct D3DXVECTOR4 {
  float x, y, z, w;
} D3DXVECTOR4;

Members

x
The x-component.
y
The y-component.
z
The z-component.
w
The w-component.

Remarks

C++ programmers can take advantage of operator overloading and type casting. The C++ implementation of the D3DXVECTOR4 structure implements overloaded constructors and overloaded assignment, unary and binary (including equality) operators. For more information, see C++ Specific Features.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxmath.h.

See Also

D3DXVec4Length, D3DXVec4LengthSq, D3DXVec4Dot, D3DXVec4Add, D3DXVec4Subtract, D3DXVec4Minimize, D3DXVec4Maximize, D3DXVec4Scale, D3DXVec4Lerp, D3DXVec4Cross, D3DXVec4Normalize, D3DXVec4Hermite, D3DXVec4BaryCentric, D3DXVec4Transform


C++ Specific Features

C++ programmers can take advantage of the constructor overloading, operator overloading, and type casting extensions offered by the Direct3DX utility library. The extensions are implemented in the following structures:

  • D3DXCOLOR Extensions
  • D3DXMATRIX Extensions
  • D3DXPLANE Extensions
  • D3DXQUATERNION Extensions
  • D3DXVECTOR2 Extensions
  • D3DXVECTOR3 Extensions
  • D3DXVECTOR4 Extensions


D3DXCOLOR Extensions

The D3DX_DEVICEDESC supplies the following operator overloads and type casts.

#ifdef __cplusplus
public:
  D3DXCOLOR() {}
  D3DXCOLOR( DWORD argb );
  D3DXCOLOR( const float * );
  D3DXCOLOR( const D3DCOLORVALUE& );
  D3DXCOLOR( float r, float g, float b, float a );

  // casting
  operator DWORD () const;

  operator float * ();
  operator const float * () const;

  operator D3DCOLORVALUE * ();
  operator const D3DCOLORVALUE * () const;

  // assignment operators
  D3DXCOLOR& operator += ( const D3DXCOLOR& );
  D3DXCOLOR& operator -= ( const D3DXCOLOR& );
  D3DXCOLOR& operator *= ( float );
  D3DXCOLOR& operator /= ( float );

  // unary operators
  D3DXCOLOR operator + () const;
  D3DXCOLOR operator - () const;

  // binary operators
  D3DXCOLOR operator + ( const D3DXCOLOR& ) const;
  D3DXCOLOR operator - ( const D3DXCOLOR& ) const;
  D3DXCOLOR operator * ( float ) const;
  D3DXCOLOR operator / ( float ) const;

  friend D3DXCOLOR operator * (float, const D3DXCOLOR& );

  BOOL operator == ( const D3DXCOLOR& ) const;
  BOOL operator != ( const D3DXCOLOR& ) const;

#endif //__cplusplus


D3DXMATRIX Extensions

The D3DXMATRIX structure supplies the following operator overloads and type casts.

#ifdef __cplusplus
public:
  D3DXMATRIX() {};
  D3DXMATRIX( const float * );
  D3DXMATRIX( const D3DMATRIX& );
  D3DXMATRIX( float m00, float m01, float m02, float m03,
              float m10, float m11, float m12, float m13,
              float m20, float m21, float m22, float m23,
              float m30, float m31, float m32, float m33 );

  // access grants
  float& operator () ( UINT iRow, UINT iCol );
  float  operator () ( UINT iRow, UINT iCol ) const;

  // casting operators
  operator float* ();
  operator const float* () const;

  operator D3DMATRIX* ();
  operator const D3DMATRIX* () const;

  // assignment operators
  D3DXMATRIX& operator *= ( const D3DXMATRIX& );
  D3DXMATRIX& operator += ( const D3DXMATRIX& );
  D3DXMATRIX& operator -= ( const D3DXMATRIX& );
  D3DXMATRIX& operator *= ( float );
  D3DXMATRIX& operator /= ( float );

  // unary operators
  D3DXMATRIX operator + () const;
  D3DXMATRIX operator - () const;

  // binary operators
  D3DXMATRIX operator * ( const D3DXMATRIX& ) const;
  D3DXMATRIX operator + ( const D3DXMATRIX& ) const;
  D3DXMATRIX operator - ( const D3DXMATRIX& ) const;
  D3DXMATRIX operator * ( float ) const;
  D3DXMATRIX operator / ( float ) const;

  friend D3DXMATRIX operator * ( float, const D3DXMATRIX& );

  BOOL operator == ( const D3DXMATRIX& ) const;
  BOOL operator != ( const D3DXMATRIX& ) const;

#endif //__cplusplus

  union
  {
    float m[4][4];
#ifdef __cplusplus
    struct
    {
      float m00, m01, m02, m03;
      float m10, m11, m12, m13;
      float m20, m21, m22, m23;
      float m30, m31, m32, m33;
    };
#endif //__cplusplus


D3DXPLANE Extensions

The D3DXPLANE structure supplies the following operator overloads and type casts.

#ifdef __cplusplus
public:
  D3DXPLANE() {}
  D3DXPLANE( const float* );
  D3DXPLANE( float a, float b, float c, float d );

  // casting
  operator float* ();
  operator const float* () const;

  // unary operators
  D3DXPLANE operator + () const;
  D3DXPLANE operator - () const;

  // binary operators
  BOOL operator == ( const D3DXPLANE& ) const;
  BOOL operator != ( const D3DXPLANE& ) const;

#endif //__cplusplus


D3DXQUATERNION Extensions

The D3DXQUATERNION structure supplies the following operator overloads and type casts.

#ifdef __cplusplus
public:
  D3DXQUATERNION() {}
  D3DXQUATERNION( const float * );
  D3DXQUATERNION( float x, float y, float z, float w );

  // casting
  operator float* ();
  operator const float* () const;

  // assignment operators
  D3DXQUATERNION& operator += ( const D3DXQUATERNION& );
  D3DXQUATERNION& operator -= ( const D3DXQUATERNION& );
  D3DXQUATERNION& operator *= ( const D3DXQUATERNION& );
  D3DXQUATERNION& operator *= ( float );
  D3DXQUATERNION& operator /= ( float );

  // unary operators
  D3DXQUATERNION  operator + () const;
  D3DXQUATERNION  operator - () const;

  // binary operators
  D3DXQUATERNION operator + ( const D3DXQUATERNION& ) const;
  D3DXQUATERNION operator - ( const D3DXQUATERNION& ) const;
  D3DXQUATERNION operator * ( const D3DXQUATERNION& ) const;
  D3DXQUATERNION operator * ( float ) const;
  D3DXQUATERNION operator / ( float ) const;

  friend D3DXQUATERNION operator * (float, const D3DXQUATERNION& );

  BOOL operator == ( const D3DXQUATERNION& ) const;
  BOOL operator != ( const D3DXQUATERNION& ) const;

#endif //__cplusplus


D3DXVECTOR2 Extensions

The D3DXVECTOR2 structure supplies the following operator overloads and type casts.

#ifdef __cplusplus
public:
  D3DXVECTOR2() {};
  D3DXVECTOR2( const float * );
  D3DXVECTOR2( float x, float y );

  // casting
  operator float* ();
  operator const float* () const;

  // assignment operators
  D3DXVECTOR2& operator += ( const D3DXVECTOR2& );
  D3DXVECTOR2& operator -= ( const D3DXVECTOR2& );
  D3DXVECTOR2& operator *= ( float );
  D3DXVECTOR2& operator /= ( float );

  // unary operators
  D3DXVECTOR2 operator + () const;
  D3DXVECTOR2 operator - () const;

  // binary operators
  D3DXVECTOR2 operator + ( const D3DXVECTOR2& ) const;
  D3DXVECTOR2 operator - ( const D3DXVECTOR2& ) const;
  D3DXVECTOR2 operator * ( float ) const;
  D3DXVECTOR2 operator / ( float ) const;

  friend D3DXVECTOR2 operator * ( float, const D3DXVECTOR2& );

  BOOL operator == ( const D3DXVECTOR2& ) const;
  BOOL operator != ( const D3DXVECTOR2& ) const;

public:
#endif //__cplusplus


D3DXVECTOR3 Extensions

The D3DXVECTOR3 structure supplies the following operator overloads and type casts.

#ifdef __cplusplus
public:
  D3DXVECTOR3() {};
  D3DXVECTOR3( const float * );
  D3DXVECTOR3( const D3DVECTOR& );
  D3DXVECTOR3( float x, float y, float z );

  // casting
  operator float* ();
  operator const float* () const;

  operator D3DVECTOR* ();
  operator const D3DVECTOR* () const;

  // assignment operators
  D3DXVECTOR3& operator += ( const D3DXVECTOR3& );
  D3DXVECTOR3& operator -= ( const D3DXVECTOR3& );
  D3DXVECTOR3& operator *= ( float );
  D3DXVECTOR3& operator /= ( float );

  // unary operators
  D3DXVECTOR3 operator + () const;
  D3DXVECTOR3 operator - () const;

  // binary operators
  D3DXVECTOR3 operator + ( const D3DXVECTOR3& ) const;
  D3DXVECTOR3 operator - ( const D3DXVECTOR3& ) const;
  D3DXVECTOR3 operator * ( float ) const;
  D3DXVECTOR3 operator / ( float ) const;

  friend D3DXVECTOR3 operator * ( float, const struct D3DXVECTOR3& );

  BOOL operator == ( const D3DXVECTOR3& ) const;
  BOOL operator != ( const D3DXVECTOR3& ) const;

public:
#endif //__cplusplus


D3DXVECTOR4 Extensions

The D3DXVECTOR4 structure supplies the following operator overloads and type casts.

#ifdef __cplusplus
public:
  D3DXVECTOR4() {};
  D3DXVECTOR4( const float* );
  D3DXVECTOR4( float x, float y, float z, float w );

  // casting
  operator float* ();
  operator const float* () const;

  // assignment operators
  D3DXVECTOR4& operator += ( const D3DXVECTOR4& );
  D3DXVECTOR4& operator -= ( const D3DXVECTOR4& );
  D3DXVECTOR4& operator *= ( float );
  D3DXVECTOR4& operator /= ( float );

  // unary operators
  D3DXVECTOR4 operator + () const;
  D3DXVECTOR4 operator - () const;

  // binary operators
  D3DXVECTOR4 operator + ( const D3DXVECTOR4& ) const;
  D3DXVECTOR4 operator - ( const D3DXVECTOR4& ) const;
  D3DXVECTOR4 operator * ( float ) const;
  D3DXVECTOR4 operator / ( float ) const;

  friend D3DXVECTOR4 operator * ( float, const D3DXVECTOR4& );

  BOOL operator == ( const D3DXVECTOR4& ) const;
  BOOL operator != ( const D3DXVECTOR4& ) const;

public:
#endif //__cplusplus


Enumerated Types

This section contains information about the following enumerated types used with the Direct3DX utility library:

  • D3DX_FILTERTYPE
  • D3DX_SURFACECLASS
  • D3DX_SURFACEFORMAT


D3DX_FILTERTYPE

The D3DX_FILTERTYPE enumerated type defines the filtering types for the Direct3DX texturing functions.

typedef enum _D3DX_FILTERTYPE {
  D3DX_FT_POINT    = 0x01,
  D3DX_FT_LINEAR   = 0x02,
  D3DX_FT_DEFAULT  = D3DX_DEFAULT
} D3DX_FILTERTYPE;
D3DX_FT_POINT
Point sampling only. No filtering.
D3DX_FT_LINEAR
Bilinear filtering.
D3DX_FT_DEFAULT
The default filter type.

Remarks

The members of the D3DX_FILTERTYPE enumerated type are the various filter types for the generation of mipmaps.

Direct3DX supports two kinds of filtering: bilinear (D3DX_FT_LINEAR) and point-sampling (D3DX_FT_POINT). For higher quality resizing and mipmap generation, choose bilinear filtering. For faster operation, choose D3DX_FT_POINT.

Note To avoid blurring in images that have text in them, point-sampling and disabling mipmapping may work better in some specific cases.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.

See Also

D3DXLoadTextureFromMemory, D3DXLoadTextureFromSurface


D3DX_SURFACECLASS

The D3DX_SURFACECLASS enumerated type defines the known surface classes that you can retrieve information about.

typedef enum _D3DX_SURFACECLASS {
  D3DX_SC_DEPTHBUFFER       = 0x01,
  D3DX_SC_STENCILBUFFER     = 0x02,
  D3DX_SC_COLORTEXTURE      = 0x04,
  D3DX_SC_BUMPMAP           = 0x08,
  D3DX_SC_LUMINANCEMAP      = 0x10,
  D3DX_SC_COLORRENDERTGT    = 0x20
} D3DX_SURFACECLASS;
D3DX_SC_DEPTHBUFFER
All ddpfs which have the DDPF_ZPIXELS or the DDPF_ZBUFFER flags set.
D3DX_SC_STENCILBUFFER
All ddpfs which have the DDPF_STENCILBUFFER flag set.
D3DX_SC_COLORTEXTURE
All the surfaces that have color information in them and can be used for texturing.
D3DX_SC_BUMPMAP
All ddpfs which have the DDPF_BUMPLUMINANCE or the DDPF_BUMPDUDV flags set.
D3DX_SC_LUMINANCEMAP
All ddpfs which have the DDPF_BUMPLUMINANCE or the DDPF_LUMINANCE flags set.
D3DX_SC_COLORRENDERTGT
All the surfaces that contain color information and can be used as render targets.

Remarks

You can query the various surface formats a device supports for various surface classes.

The members of the D3DX_SURFACECLASS enumerated type are the various types of two-dimensional (2-D) surfaces classified according to their usage. Note that a number of them overlap, for example D3DX_SC_STENCILBUFFER and D3DX_SC_DEPTHBUFFER overlap (since in the DirectX 7.0 implementation the stencil and depth bits are part of the same pixel format).

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.

See Also

D3DXGetMaxSurfaceFormats, D3DXGetSurfaceFormat


D3DX_SURFACEFORMAT

The D3DX_SURFACEFORMAT enumerated type defines the various types of surface formats that can be enumerated. All of the Direct3DX surface classes are represented here:

typedef enum _D3DX_SURFACEFORMAT {
  D3DX_SF_UNKNOWN    = 0,
  D3DX_SF_R8G8B8     = 1,
  D3DX_SF_A8R8G8B8   = 2,
  D3DX_SF_X8R8G8B8   = 3,
  D3DX_SF_R5G6B5     = 4,
  D3DX_SF_R5G5B5     = 5,
  D3DX_SF_PALETTE4   = 6,
  D3DX_SF_PALETTE8   = 7,
  D3DX_SF_A1R5G5B5   = 8,
  D3DX_SF_X4R4G4B4   = 9,
  D3DX_SF_A4R4G4B4   =10,
  D3DX_SF_L8         =11,
  D3DX_SF_A8L8       =12,
  D3DX_SF_U8V8       =13,
  D3DX_SF_U5V5L6     =14,
  D3DX_SF_U8V8L8     =15,
  D3DX_SF_UYVY       =16,
  D3DX_SF_YUY2       =17,
  D3DX_SF_DXT1       =18,
  D3DX_SF_DXT3       =19,
  D3DX_SF_DXT5       =20,
  D3DX_SF_R3G3B2     =21,
  D3DX_SF_A8         =22,
  D3DX_SF_TEXTUREMAX =23,

  D3DX_SF_Z16S0      =256,
  D3DX_SF_Z32S0      =257,
  D3DX_SF_Z15S1      =258,
  D3DX_SF_Z24S8      =259,
  D3DX_SF_S1Z15      =260,
  D3DX_SF_S8Z24      =261,
  D3DX_SF_DEPTHMAX   =262,

  D3DX_SF_FORCEMAX  = (DWORD)(-1)
} D3DX_SURFACEFORMAT;
D3DX_SF_UNKNOWN
The surface format is unknown.
D3DX_SF_R8G8B8
24-bit RGB pixel format.
D3DX_SF_A8R8G8B8
32-bit ARGB pixel format with alpha.
D3DX_SF_X8R8G8B8
32-bit RGB pixel format where 8 bits are reserved for each color.
D3DX_SF_R5G6B5
16-bit RGB pixel format.
D3DX_SF_R5G5B5
16-bit pixel format where 5 bits are reserved for color and 1 bit is reserved for transparency.
D3DX_SF_PALETTE4
The surface is 4-bit color indexed.
D3DX_SF_PALETTE8
The surface is 8-bit color indexed.
D3DX_SF_A1R5G5B5
16-bit pixel format where 5 bits are reserved for color and 1 bit is reserved for alpha (transparent texel).
D3DX_SF_X4R4G4B4
16-bit RGB pixel format where 4 bits are reserved for each color.
D3DX_SF_A4R4G4B4
16-bit ARGB pixel format.
D3DX_SF_L8
8-bit luminance-only.
D3DX_SF_A8L8
16-bit alpha-luminance.
D3DX_SF_U8V8
16-bit bump-map format.
D3DX_SF_U5V5L6
16-bit bump-map format with luminance.
D3DX_SF_U8V8L8
24-bit bump-map format with luminance.
D3DX_SF_UYVY
UYVY format (PC98 compliance).
D3DX_SF_YUY2
YUY2 format (PC98 compliance).
D3DX_SF_DXT1
S3 texture compression technique 1.
D3DX_SF_DXT3
S3 texture compression technique 3.
D3DX_SF_DXT5
S3 texture compression technique 5.
D3DX_SF_R3G3B2
8-bit RGB texture format.
D3DX_SF_A8
8-bit alpha-only.
D3DX_SF_TEXTUREMAX
Final texture format.
D3DX_SF_Z16S0
16-bit z-buffer bit depth.
D3DX_SF_Z32S0
32-bit z-buffer bit depth.
D3DX_SF_Z15S1
16-bit depth-buffer format with 1-bit reserved for the stencil buffer.
D3DX_SF_Z24S8
32-bit depth-buffer with 8 bits reserved for the stencil buffer.
D3DX_SF_S1Z15
16-bit depth buffer with 1 bit reserved for the stencil buffer (LSB).
D3DX_SF_S8Z24
32-bit depth-buffer with 8 bits reserved for the stencil buffer (LSB).
D3DX_SF_DEPTHMAX
Maximum depth-buffer pixel format.
D3DX_SF_FORCEMAX
Force the maximum.

Remarks

Note that there is no DDPIXELFORMAT structure in Direct3DX; rather the values of the D3DX_SURFACEFORMAT enumeration indicate the pixel format.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Windows CE: Unsupported.
Version: Requires DirectX 7.0.
Header: Declared in d3dxcore.h.

See Also

D3DXGetMaxSurfaceFormats, D3DXGetSurfaceFormat


Hardware Acceleration Level Constants

The Direct3DX hardware acceleration level constants represent pre-defined hardware acceleration levels and may be used as a default value anywhere a device index (DWORD) is required. The following table lists all of the hardware acceleration level constants provided by the Direct3DX utility library:

D3DX_DEFAULT
The highest level of acceleration available on the primary DirectDraw device.
D3DX_HWLEVEL_RASTER
Rasterization acceleration. In most cases, this will be the most useful level.
D3DX_HWLEVEL_REFERENCE
Reference implementation. This is the slowest level of acceleration.
D3DX_HWLEVEL_TL
Transform and lighting acceleration.
D3DX_HWLEVEL_2D
2-D acceleration only. Specifying this level will implement the RGB rasterizer.


Return Values

Errors are represented by 32-bit values. This table lists the values that can be returned by Direct3DX methods and functions. See the individual descriptions for lists of the values that each can return.

D3DX_OK
No error occurred.
D3DXERR_BADD3DXCONTEXT
The requested operation failed because the Direct3DX context is invalid.
D3DXERR_BITBLTFAILED
A call to the BitBlt method failed.
D3DXERR_CANNOTRESIZEFULLSCREEN
The requested operation failed because resize does not work in full-screen mode.
D3DXERR_CANNOTRESIZENONWINDOWED
The requested operation failed because resize does not work for non-windowed contexts.
D3DXERR_CAPSNOTSUPPORTED
The requested device capabilities are not supported.
D3DXERR_COLORDEPTHTOOLOW
The requested operation failed because Direct3DX only supports color depths of 16-bit or greater.
D3DXERR_COULDNTUPDATECAPS
The capabilities database failed to update after changing the display mode.
D3DXERR_D3DXNOTSTARTEDYET
The requested operation failed because Direct3DX has not been initialized. Initialize Direct3DX by calling the D3DXInitialize function and trying again.
D3DXERR_ENUMFORMATSFAILED
An error occurred while enumerating surface formats.
D3DXERR_FAILEDDRAWTEXT
Text failed to render to the surface.
D3DXERR_FAILEDGETCAPS
Device capabilities could not be obtained.
D3DXERR_FAILEDQUATSLERP
A slerping operation between two quaternions failed.
D3DXERR_FRONTBUFFERALREADYEXISTS
The requested operation failed because a front buffer already exists.
D3DXERR_FULLSCREENPRIMARYEXISTS
The requested operation failed because the application is using the primary surface in full-screen mode.
D3DXERR_GETDCFAILED
Device information could not be retrieved.
D3DXERR_IFLERROR
An error occurred in the image file loading library.
D3DXERR_INITFAILED
Direct3DX failed to initialize itself.
D3DXERR_INVALIDD3DXDEVICEINDEX
The requested operation failed because the device index passed in is invalid.
D3DXERR_INVALIDFILEFORMAT
The file format is invalid.
D3DXERR_INVALIDMODE
The requested operation failed because the display mode is invalid.
D3DXERR_INVALIDPARAMETER
The requested operation failed because one or more of the parameters passed is invalid.
D3DXERR_MIPLEVELABSENT
The requested operation failed because there is no such mipmap level for this surface.
D3DXERR_NOBACKBUFFERAVAILABLE
The requested operation failed because the back-buffer surface has not been created.
D3DXERR_NODIRECTDRAWAVAILABLE
The requested operation failed because a DirectDraw object has not been created.
D3DXERR_NODIRECT3DAVAILABLE
The requested operation failed because a Direct3D object has not been created.
D3DXERR_NODIRECT3DDEVICEAVAILABLE
The requested operation failed because a Direct3D device has not been created.
D3DXERR_NOMATCHFOUND
No suitable match found.
D3DXERR_NOMEMORY
The requested operation failed because the system is out of memory.
D3DXERR_NOPRIMARYAVAILABLE
The requested operation failed because the primary surface has not been created.
D3DXERR_NOTEXTURE
The requested operation failed because there is no surface backing up this texture.
D3DXERR_NOTINITIALIZED
The requested operation failed because Direct3DX is not initialized.
D3DXERR_NOZBUFFER
The z-buffer surface could not be created.
D3DXERR_NOZBUFFERAVAILABLE
The requested operation failed because the z buffer surface has not been created.
D3DXERR_NULLHWND
The requested operation failed because a HWND cannot be NULL in windowed mode.
D3DXERR_NULLPOINTER
The requested operation failed because a NULL pointer was passed as a parameter.
D3DXERR_SINGULARMATRIX
The matrix cannot be inverted.
D3DXERR_STARTUPFAILED
Direct3DX failed to start up.
D3DXERR_SURFACENOTPALETTED
The requested operation failed because the surface is not paletted.
D3DXERR_UNSUPPORTEDFILEFORMAT
The requested operation failed because the image file format is unrecognized.


Direct3DX Utility Library Samples

[Visual Basic]

This section pertains only to application development in C and C++. DirectX for Visual Basic does not include support for the Direct3DX utility library.

[C++]

This section provides summaries of the following sample applications in the DirectX SDK that are primarily intended to demonstrate use of the Direct3DX utility library.

  • EnvMap Sample
  • Gravity Sample
  • Particle Sample
  • Sprite Sample
  • Tentacle Sample
  • TrivFS Sample
  • TrivWin Sample

Although DirectX samples include Microsoft® Visual C++® project workspace files, you might need to verify other settings in your development environment to ensure that the samples compile properly. For more information, see Compiling DirectX Samples and Other DirectX Applications.

All Direct3DX samples are written with C and C++ developers in mind.


EnvMap Sample

[Visual Basic]

This topic pertains only to application development in C and C++. DirectX for Visual Basic does not include support for the Direct3DX utility library.

[C++]

Description

The EnvMap sample demonstrates cubic environment mapping.

Path

Source: (SDK root)\Samples\Multimedia\D3dx\Src\EnvMap

Executable: (SDK root)\Samples\Multimedia\D3dx\Bin\EnvMap.exe

User's Guide

No user input is required.

Programming Notes

This sample demonstrates how to create reflective effects by displaying a reflective sphere inside a cube. A cube map is a special texture surface created by rendering a scene in six orthogonal directions. It is used for traditional environment-mapping effects.

This sample uses the Direct3DX utility library helper classes.


Gravity Sample

[Visual Basic]

This topic pertains only to application development in C and C++. DirectX for Visual Basic does not include support for the Direct3DX utility library.

[C++]

Description

The Gravity sample displays a cluster of particles swirling around the center of the universe.

Path

Source: (SDK root)\Samples\Multimedia\D3dx\Src\Gravity

Executable: (SDK root)\Samples\Multimedia\D3dx\Bin\Gravity.exe

User's Guide

No user input is required.

Programming Notes

This sample illustrates the fundamentals of creating a 3-D environment and animating a group of objects in it. A variety of lighting effects are used. The sample also demonstrates the shape creation methods and the Direct3DX matrix stack.

This sample uses the Direct3DX utility library helper classes.


Particle Sample

[Visual Basic]

This topic pertains only to application development in C and C++. DirectX for Visual Basic does not include support for the Direct3DX utility library.

[C++]

Description

The Particle sample demonstrates the use of billboard effects.

Path

Source: (SDK root)\Samples\Multimedia\D3dx\Src\Particle

Executable: (SDK root)\Samples\Multimedia\D3dx\Bin\Particle.exe

User's Guide

The following keys are used to control the display. NUM LOCK must be on.

Move | W, S
Slide | Arrows
Turn | Numpad 4, 6
Pitch | Numpad 2, 8
Change color | SPACE
Toggle ground | G
Toggle reflection | R
Toggle location | ENTER
Pause | PAUSE
Exit | ESC

Programming Notes

Each of the particles displayed is actually a billboarded face with a texture map applied. Lighting effects and reflections on the ground plane are implemented.

This sample uses the Direct3DX utility library helper classes.


Sprite Sample

[Visual Basic]

This topic pertains only to application development in C and C++. DirectX for Visual Basic does not include support for the Direct3DX utility library.

[C++]

Description

The Sprite sample shows how to use the 3-D engine for doing classic 2-D sprite operations.

Path

Source: (SDK root)\Samples\Multimedia\D3dx\Src\Sprite

Executable: (SDK root)\Samples\Multimedia\D3dx\Bin\Sprite.exe

User's Guide

No user input is required.

Programming Notes

This sample uses the Direct3DX utility library helper classes.


Tentacle Sample

[Visual Basic]

This topic pertains only to application development in C and C++. DirectX for Visual Basic does not include support for the Direct3DX utility library.

[C++]

Description

The Tentacle sample lets the user interact with a 3-D environment.

Path

Source: (SDK root)\Samples\Multimedia\D3dx\Src\Tentacle

Executable: (SDK root)\Samples\Multimedia\D3dx\Bin\Tentacle.exe

User's Guide

Keyboard controls (NUM LOCK must be on)

Move | W, S
Slide | Arrow Keys
Turn | Numpad 4, 6
Pitch | Numpad 2, 8
Roll | Numpad 7, 9
Toggle Wireframe | F2
Exit | ESC

Mouse controls

Rotate left arm | LButton
Rotate right arm | RButton
Rotate base | LButton+RButton
Twist left arm | SHIFT+LButton
Twist right arm | SHIFT+RButton
Twist base | Shift+LButton+RButton
Stretch left finger | CTRL+LButton
Stretch right finger | CTRL+RButton

Programming Notes

The program demonstrates the vertex blending and user clip plane features that are new to DirectX 7.0. It also shows reflective effects and lens flares.

This sample uses the Direct3DX utility library helper classes.


TrivFS Sample

[Visual Basic]

This topic pertains only to application development in C and C++. DirectX for Visual Basic does not include support for the Direct3DX utility library.

[C++]

Description

The TrivFS sample rotates a triangle about the y-axis.

Path

Source: (SDK root)\Samples\Multimedia\D3dx\Src\TrivFS

Executable: (SDK root)\Samples\Multimedia\D3dx\Bin\TrivFS.exe

User's Guide

No user input is required.

Programming Notes

This sample demonstrates using the D3DX utility library to initialize a full-screen application.


TrivWin Sample

[Visual Basic]

This topic pertains only to application development in C and C++. DirectX for Visual Basic does not include support for the Direct3DX utility library.

[C++]

Description

The TrivWin sample rotates a triangle about the y-axis.

Path

Source: (SDK root)\Samples\Multimedia\D3dx\Src\TrivWin

Executable: (SDK root)\Samples\Multimedia\D3dx\Bin\TrivWin.exe

User's Guide

No user input is required.

Programming Notes

This sample demonstrates using the D3DX utility library to initialize a windowed application.

This sample uses the Direct3DX utility library helper classes.


Direct3D Retained Mode Documentation

Direct3D Retained Mode version 6.0, and documentation for the API, is included with this SDK. No future development for Direct3D Retained Mode is anticipated.

Although Direct3D Retained Mode is not part of DirectX Foundation, your C, C++, and Visual Basic applications can access its features and services. Documentation for the Direct3D Retained Mode API is included in this SDK. For more information, see Direct3D Retained Mode.

Note: The documentation for Direct3D Retained Mode includes complete overview and reference material presented for C and C++ developers, and includes new reference material for Visual Basic developers.


DirectDraw

This section provides information about the DirectDraw® component of the DirectX® application programming interface (API). Information is divided into the following groups:

  • About DirectDraw
  • Why Use DirectDraw?
  • Getting Started: Basic Graphics Concepts
  • DirectDraw Architecture
  • DirectDraw Essentials
  • DirectDraw Tutorials
  • DirectDraw Reference
  • DirectDraw Tools and Samples


About DirectDraw

DirectDraw® is the component of the DirectX® application programming interface (API) that allows you to directly manipulate display memory, the hardware blitter, hardware overlay support, and flipping surface support. DirectDraw provides this functionality while maintaining compatibility with existing Microsoft® Windows®-based applications and device drivers.

DirectDraw is a software interface that provides direct access to display devices while maintaining compatibility with the Windows graphics device interface (GDI). It is not a high-level application programming interface (API) for graphics. DirectDraw provides a device-independent way for games and Windows subsystem software, such as three-dimensional (3-D) graphics packages and digital video codecs, to gain access to the features of specific display devices.

DirectDraw works with a wide variety of display hardware, ranging from simple SVGA monitors to advanced hardware implementations that provide clipping, stretching, and non-RGB color format support. The interface is designed so that your applications can enumerate the capabilities of the underlying hardware and then use any supported hardware-accelerated features. Features that are not implemented in hardware are emulated by DirectX.

DirectDraw provides device-dependent access to display memory in a device-independent way. Essentially, DirectDraw manages display memory. Your application need only recognize some basic device dependencies that are standard across hardware implementations, such as RGB and YUV color formats and the pitch between raster lines. You need not call specific procedures to use the blitter or manipulate palette registers. Using DirectDraw, you can manipulate display memory with ease, taking full advantage of the blitting and color decompression capabilities of different types of display hardware without becoming dependent on a particular piece of hardware.

DirectDraw provides excellent game graphics on computers running Windows 95 and later and Windows NT® version 4.0 or Windows 2000.


Why Use DirectDraw?

The DirectDraw component brings many powerful features to you, the Windows graphics programmer:

  • The hardware abstraction layer (HAL) of DirectDraw provides a consistent interface through which to work directly with the display hardware, getting maximum performance.
  • DirectDraw assesses the video hardware's capabilities, making use of special hardware features whenever possible. For example, if your video card supports hardware blitting, DirectDraw delegates blits to the video card, greatly increasing performance. Additionally, DirectDraw provides a hardware emulation layer (HEL) to support features when the hardware does not.
  • DirectDraw exists under Windows, gaining the advantage of 32-bit memory addressing and a flat memory model that the operating system provides. DirectDraw presents video and system memory as large blocks of storage, not as small segments. If you've ever used segment:offset addressing, you will quickly begin to appreciate this "flat" memory model.
  • DirectDraw makes it easy for you to implement page flipping with multiple back buffers in full-screen applications. For more information, see Page Flipping and Back Buffering.
  • Support for clipping in windowed or full-screen applications.
  • Support for 3-D z-buffers.
  • Support for hardware-assisted overlays with z-ordering.
  • Access to image-stretching hardware.
  • Simultaneous access to standard and enhanced display-device memory areas.
  • Other features include custom and dynamic palettes, exclusive hardware access, and resolution switching.

These features combine to make it possible for you to write applications that easily outperform standard Windows GDI-based applications and even MS-DOS applications.


Getting Started: Basic Graphics Concepts

This section provides an overview of graphics programming with DirectDraw. Each concept discussed here begins with a non-technical overview, followed by some specific information about how DirectDraw supports it.

You don't need to be a graphics guru to benefit from this overview—in fact, if you are one you might want to skip this section entirely and move on to the more detailed information in the DirectDraw Essentials section. If you're familiar with Windows programming in C and C++ or Visual Basic, you won't have difficulty digesting this information. When you finish reading these topics, you will have a solid understanding of basic DirectDraw graphics programming concepts.

The following topics are discussed:

  • Device-Independent Bitmaps
  • Drawing Surfaces
  • Blitting
  • Page Flipping and Back Buffering
  • Introduction to Rectangles


Device-Independent Bitmaps

Windows, and therefore DirectX, uses the device-independent bitmap (DIB) as its native graphics file format. Essentially, a DIB is a file containing an image's dimensions, the number of colors it uses, values describing those colors, and data that describes each pixel. Additionally, a DIB contains some lesser-used parameters, like information about file compression, significant colors (if all are not used), and physical dimensions of the image (in case it will end up in print). DIB files usually have the .bmp file extension, although they might occasionally have a .dib extension.

[C++]

Because the DIB is so pervasive in Windows programming, the Platform SDK already contains many functions that you can use with DirectX. For example, the following application-defined function, taken from the Ddutil.cpp file that comes with the DirectX APIs in the Platform SDK, combines Win32® and DirectX functions to load a DIB onto a DirectX surface.

extern "C" IDirectDrawSurface * DDLoadBitmap(IDirectDraw *pdd,
    LPCSTR szBitmap, int dx, int dy)
{
    HBITMAP             hbm;
    BITMAP              bm;
    DDSURFACEDESC       ddsd;
    IDirectDrawSurface *pdds;

    //
    //  This is the Win32 part.
    //  Try to load the bitmap as a resource.
    //  If that fails, try it as a file.
   //
    hbm = (HBITMAP)LoadImage(
            GetModuleHandle(NULL), szBitmap,
            IMAGE_BITMAP, dx, dy, LR_CREATEDIBSECTION);

    if (hbm == NULL)
        hbm = (HBITMAP)LoadImage(
                NULL, szBitmap, IMAGE_BITMAP, dx, dy,
                LR_LOADFROMFILE|LR_CREATEDIBSECTION);

    if (hbm == NULL)
        return NULL;

    //
    // Get the size of the bitmap.
    //
    GetObject(hbm, sizeof(bm), &bm);

    //
    // Now, return to DirectX function calls.
    // Create a DirectDrawSurface for this bitmap.
    //
    ZeroMemory(&ddsd, sizeof(ddsd));
    ddsd.dwSize = sizeof(ddsd);
    ddsd.dwFlags = DDSD_CAPS | DDSD_HEIGHT |DDSD_WIDTH;
    ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN;
    ddsd.dwWidth = bm.bmWidth;
    ddsd.dwHeight = bm.bmHeight;

    if (pdd->CreateSurface(&ddsd, &pdds, NULL) != DD_OK)
        return NULL;

    DDCopyBitmap(pdds, hbm, 0, 0, 0, 0);

    DeleteObject(hbm);

    return pdds;
}

For more detailed information about DIB files, see the Platform SDK.

[C++,Visual Basic]


Drawing Surfaces

Drawing surfaces receive video data to eventually be displayed on the screen as images (bitmaps, to be exact). In most Windows programs, you get access to the drawing surface using a Win32 function such as GetDC, which stands for get the device context (DC). After you have the device context, you can start painting the screen. However, Win32 graphics functions are provided by an entirely different part of the system, the graphics device interface (GDI). The GDI is a system component that provides an abstraction layer that enables standard Windows applications to draw to the screen.

The drawback of GDI is that it wasn't designed for high-performance multimedia software, it was made to be used by business applications like word processors and spreadsheet applications. GDI provides access to a video buffer in system memory, not video memory, and doesn't take advantage of special features that some video cards provide. In short, GDI is great for most business applications, but its performance is too slow for multimedia or game software.

On the other hand, DirectDraw can give you drawing surfaces that represent actual video memory. This means that when you use DirectDraw, you can write directly to the memory on the video card, making your graphics routines extremely fast. These surfaces are represented as contiguous blocks of memory, making it easy to perform addressing within them.

For more detailed information, see Surfaces.


Blitting

The term blit is shorthand for "bit block transfer," which is the process of transferring blocks of data from one place in memory to another. Graphics programmers use blitting to transfer graphics from one place in memory to another. Blits are often used to perform sprite animation, which is discussed later.

For more information on blitting in DirectDraw, see Blitting to Surfaces.


Page Flipping and Back Buffering

Page flipping is key in multimedia, animation, and game software. Software page flipping is analogous to the way animation can be done with a pad of paper. On each page the artist changes the figure slightly, so that when you flip between sheets rapidly the drawing appears animated.

Page flipping in software is very similar to this process. Initially, you set up a series of DirectDraw surfaces that are designed to "flip" to the screen the way artist's paper flips to the next page. The first surface is referred to as the primary surface, and the surfaces behind it are called back buffers. Your application writes to a back buffer, then flips the primary surface so that the back buffer appears on screen. While the system is displaying the image, your software is again writing to a back buffer. The process continues as long as you're animating, allowing you to animate images quickly and efficiently.

DirectDraw makes it easy for you to set up page flipping schemes, from a relatively simple double-buffered scheme (a primary surface with one back buffer) to more sophisticated schemes that add additional back buffers. For more information see DirectDraw Tutorials and Flipping Surfaces.


Introduction to Rectangles

Throughout DirectDraw and Windows programming, objects on the screen are referred to in terms of bounding rectangles. The sides of a bounding rectangle are always parallel to the sides of the screen, so the rectangle can be described by two points, the top-left corner and bottom-right corner. Most applications use the RECT structure to carry information about a bounding rectangle to use when blitting to the screen or performing hit detection.

[C++]

In C++, the RECT structure has the following definition:

typedef struct tagRECT {
    LONG    left;    // This is the top-left corner's x-coordinate.
    LONG    top;     // The top-left corner's y-coordinate.
    LONG    right;   // The bottom-right corner's x-coordinate.
    LONG    bottom;  // The bottom-right corner's y-coordinate.
} RECT, *PRECT, NEAR *NPRECT, FAR *LPRECT;
[Visual Basic]

In Visual Basic, the RECT type has the following definition:

Type RECT
    Left As Long     // This is the top-left corner's x-coordinate.
    Top As Long      // The top-left corner's y-coordinate.
    Right As Long    // The bottom-right corner's x-coordinate.
    Bottom As Long   // The bottom-right corner's y-coordinate.
End Type

In the preceding example, the left and top members are the x- and y-coordinates of a bounding rectangle's top-left corner. Similarly, the right and bottom members make up the coordinates of the bottom-right corner. The following diagram illustrates how you can visualize these values.

In the interest of efficiency, consistency, and ease of use, all DirectDraw blitting functions work with rectangles. However, you can create the illusion of nonrectangular blit operations by using transparent blitting. For more information, see Transparent Blitting.


DirectDraw Architecture

This section contains general information about the relationship between the DirectDraw component and the rest of DirectX, the operating system, and the system hardware. The following topics are discussed:

  • Architectural Overview for DirectDraw
  • DirectDraw Object Types
  • Hardware Abstraction Layer (HAL)
  • Software Emulation
  • System Integration


Architectural Overview for DirectDraw

Multimedia software requires high-performance graphics. Through DirectDraw, Microsoft enables a much higher level of efficiency and speed in graphics-intensive applications for Windows than is possible with GDI, while maintaining device independence. DirectDraw provides tools to perform such key tasks as:

  • Manipulating multiple display surfaces
  • Accessing the video memory directly
  • Page flipping
  • Back buffering
  • Managing the palette
  • Clipping

Additionally, DirectDraw enables you to query the display hardware's capabilities at run time, then provide the best performance possible given the host computer's hardware capabilities.

As with other DirectX components, DirectDraw uses the hardware to its greatest possible advantage, and provides software emulation for most features when hardware support is unavailable. Device independence is possible through use of the hardware abstraction layer, or HAL. For more information about the HAL, see the hardware abstraction layer.

[C++]

The DirectDraw component provides services through COM-based interfaces. In the most recent iteration, these interfaces are IDirectDraw7, IDirectDrawSurface7, IDirectDrawPalette, IDirectDrawClipper, and IDirectDrawVideoPort. Note that, in addition to these interfaces, DirectDraw continues to support all previous versions. The DirectDraw component doesn't expose an IDirectDraw3, IDirectDraw5, or IDirectDraw6 interface, the interface versions skipped from IDirectDraw2 to IDirectDraw4 and then from IDirectDraw4 to IDirectDraw7.

For more information about COM concepts that you should understand to create applications with the DirectX APIs in the Platform SDK, see The Component Object Model.

The DirectDraw object represents the display adapter and exposes its methods through the IDirectDraw, IDirectDraw2, IDirectDraw4,and IDirectDraw7 interfaces. In most cases you will use the DirectDrawCreateEx function to create the newest iteration of a DirectDraw object, but you can also create one with the CoCreateInstance COM function. For more information, see Creating DirectDraw Objects by Using CoCreateInstance.

After creating a DirectDraw object, you can create surfaces for it by calling the IDirectDraw7::CreateSurface method. Surfaces represent the memory on the display hardware, but can exist on either video memory or system memory. DirectDraw extends support for palettes, clipping (useful for windowed applications), and video ports through its other interfaces.

[Visual Basic]

The DirectDraw component provides services through classes in the DirectX for Visual Basic type library. In the most recent iteration, these classes are DirectDraw7, DirectDrawSurface7, DirectDrawPalette, DirectDrawClipper.

In addition, the type library provides objects used to enumerate drivers, modes and surfaces. These are DirectDrawEnum, DirectDrawEnumModes, and DirectDrawEnumSurfaces.

The DirectDraw object created from the DirectDraw7 class represents the display adapter. To create this object you will use the DirectDrawCreate method of the global DirectX7 object.

After creating a DirectDraw object, you can create surfaces for it by calling the DirectDraw7.CreateSurface method. Surfaces represent the memory on the display hardware, but can exist on either video memory or system memory. DirectDraw extends support for palettes, and clipping (useful for windowed applications) through its other interfaces.


DirectDraw Object Types

You can think of DirectDraw as being composed of several objects that work together. This section briefly describes the objects you use when working with the DirectDraw component, organized by object type. For detailed information, see DirectDraw Essentials.

[C++]

The DirectDraw component uses the following objects:

DirectDraw object
The DirectDraw object is the heart of all DirectDraw applications. It's the first object you create, and you use it to make all other related objects. You create a DirectDraw object by calling the DirectDrawCreateEx function. DirectDraw objects expose their functionality through the IDirectDraw, IDirectDraw2, IDirectDraw4,and IDirectDraw7 interfaces. For more information, see The DirectDraw Object.
DirectDrawSurface object
The DirectDrawSurface object (casually referred to as a "surface") represents an area in memory that holds data to be displayed on the monitor as images or moved to other surfaces. You usually create a surface by calling the IDirectDraw7::CreateSurface method of the DirectDraw object with which it will be associated. DirectDrawSurface objects expose their functionality through the IDirectDrawSurface, IDirectDrawSurface2, IDirectDrawSurface3, IDirectDrawSurface4,and IDirectDrawSurface7 interfaces. For more information, see Surfaces.
DirectDrawPalette object
The DirectDrawPalette object (casually referred to as a "palette") represents a 16- or 256-color indexed palette to be used with a surface. It contains a series of indexed RGB triplets that describe colors associated with values within a surface. You do not use palettes with surfaces that use a pixel format depth greater than 8 bits. You can create a DirectDrawPalette object by calling the IDirectDraw7::CreatePalette method. DirectDrawPalette objects expose their functionality through the IDirectDrawPalette interface. For more information, see Palettes.
DirectDrawClipper object
The DirectDrawClipper object (casually referred to as a "clipper") helps you prevent blitting to certain portions of a surface or beyond the bounds of a surface. You can create a clipper by calling the IDirectDraw7::CreateClipper method. DirectDrawClipper objects expose their functionality through the IDirectDrawClipper interface. For more information, see Clippers.
DirectDrawVideoPort object
The DirectDrawVideoPort object represents video-port hardware present in some systems. This hardware allows direct access to the frame buffer without accessing the CPU or using the PCI bus. You can create a DirectDrawVideoPort object by calling a QueryInterface method for the DirectDraw object, specifying the IID_IDDVideoPortContainer reference identifier. DirectDrawVideoPort objects expose their functionality through the IDDVideoPortContainer and IDirectDrawVideoPort interfaces. For more information, see Video Ports.
[Visual Basic]

The DirectDraw component uses the following objects:

DirectDraw object
The DirectDraw object is the heart of all DirectDraw applications. It's the first object you create, and you use it to make all other related objects. You create a DirectDraw object by calling the DirectX7.DirectDrawCreate method. DirectDraw objects expose their functionality through the methods of the DirectDraw7 object. For more information, see The DirectDraw Object.
DirectDrawSurface object
The DirectDrawSurface object (casually referred to as a "surface") represents an area in memory that holds data to be displayed on the monitor as images or moved to other surfaces. You create a surface by calling the DirectDraw7.CreateSurface method of the DirectDraw object with which it will be associated. DirectDrawSurface objects expose their functionality through the methods of the DirectDrawSurface7 object. For more information, see Surfaces.
DirectDrawPalette object
The DirectDrawPalette object (casually referred to as a "palette") represents a 16- or 256-color indexed palette to be used with a surface. It contains a series of indexed RGB triplets that describe colors associated with values within a surface. You do not use palettes with surfaces that use a pixel format depth greater than 8 bits. You can create a DirectDrawPalette object by calling the DirectDraw7.CreatePalette method. DirectDrawPalette objects expose their functionality through the DirectDrawPalette interface. For more information, see Palettes.
DirectDrawClipper object
The DirectDrawClipper object (casually referred to as a "clipper") helps you prevent blitting to certain portions of a surface or beyond the bounds of a surface. You can create a clipper by calling the DirectDraw7.CreateClipper method. DirectDrawClipper objects expose their functionality through the DirectDrawClipper interface. For more information, see Clippers.


Hardware Abstraction Layer (HAL)

DirectDraw provides device independence through the hardware abstraction layer (HAL). The HAL is a device-specific interface, provided by the device manufacturer, that DirectDraw uses to work directly with the display hardware. Applications never interact with the HAL. Rather, with the infrastructure that the HAL provides, DirectDraw exposes a consistent set of interfaces and methods that an application uses to display graphics. The device manufacturer implements the HAL in a combination of 16-bit and 32-bit code under Windows. Under Windows NT/Windows 2000, the HAL is always implemented in 32-bit code. The HAL can be part of the display driver or a separate DLL that communicates with the display driver through a private interface that driver's creator defines.

The DirectDraw HAL is implemented by the chip manufacturer, board producer, or original equipment manufacturer (OEM). The HAL implements only device-dependent code and performs no emulation. If a function is not performed by the hardware, the HAL does not report it as a hardware capability. Additionally, the HAL does not validate parameters; DirectDraw does this before the HAL is invoked.


Software Emulation

When the hardware does not support a feature through the hardware abstraction layer (HAL), DirectDraw attempts to emulate it. This emulated functionality is provided through the hardware emulation layer (HEL). The HEL presents its capabilities to DirectDraw just as the HAL would. And, as with the HAL, applications never work directly with the HEL. The result is transparent support for almost all major features, regardless of whether a given feature is supported by hardware or through the HEL.

Obviously, software emulation cannot equal the performance that hardware features provide. You can query for the features the hardware supports by using the IDirectDraw7::GetCaps method in C++ or the corresponding DirectDraw7.GetCaps method in Visual Basic. By examining these capabilities during application initialization, you can adjust application parameters to provide optimum performance over varying levels of hardware performance.

In some cases, certain combinations of hardware supported features and emulation can result in slower performance than emulation alone. For example, if the display device driver supports DirectDraw but not stretch blitting, noticeable performance losses will occur when stretch blitting from video memory surfaces. This happens because video memory is often slower than system memory, forcing the CPU to wait when accessing video memory surfaces. If your application uses a feature that isn't supported by the hardware, it is sometimes best to create surfaces in system memory, thereby avoiding performance losses created when the CPU accesses video memory.

For more information, see Hardware Abstraction Layer (HAL).


System Integration

The following diagram shows the relationships between DirectDraw, the graphics device interface (GDI), the hardware abstraction layer (HAL), the hardware emulation layer (HEL) and the hardware.

As the preceding diagram shows, a DirectDraw object exists alongside GDI, and both have direct access to the hardware through a device-dependent abstraction layer. Unlike GDI, DirectDraw makes use of special hardware features whenever possible. If the hardware does not support a feature, DirectDraw attempts to emulate it by using the HEL. DirectDraw can provide surface memory in the form of a device context, making it possible for you to use GDI functions to work with surface objects.


DirectDraw Essentials

This section contains general information about the DirectDraw® component of DirectX®. Information is organized into the following groups:

  • Cooperative Levels
  • Display Modes
  • The DirectDraw Object
  • Surfaces
  • Palettes
  • Clippers
  • Multiple-Monitor Systems
  • Advanced DirectDraw Topics


Cooperative Levels

In the following topics, this section introduces the concept of cooperative levels and describes some common usage situations:

  • About Cooperative Levels
  • Testing Cooperative Levels


About Cooperative Levels

Cooperative levels describe how DirectDraw interacts with the display and how it reacts to events that might affect the display. Use the IDirectDraw7::SetCooperativeLevel method in C++ or the corresponding DirectDraw7.SetCooperativeLevel method in Visual Basic to set cooperative level of DirectDraw. For the most part, you use DirectDraw cooperative levels to determine whether your application runs as a full-screen program with exclusive access to the display or as a windowed application. However, DirectDraw cooperative levels can also have the following effects:

  • Enable DirectDraw to use Mode X resolutions. For more information, see Mode X and Mode 13 Display Modes.
  • Prevent DirectDraw from releasing exclusive control of the display or rebooting if the user presses CTRL + ALT + DEL (exclusive mode only).
  • Enable DirectDraw to minimize or maximize the application in response to activation events.

The normal cooperative level indicates that your DirectDraw application will operate as a windowed application. At this cooperative level you won't be able to change the primary surface's palette or perform page flipping.

Because applications can use DirectDraw with multiple windows, IDirectDraw7::SetCooperativeLevel and DirectDraw7.SetCooperativeLevel does not require a window handle to be specified if the application is requesting the DDSCL_NORMAL mode. By passing a NULL in C++ or Nothing in Visual Basic to the window handle, all of the windows can be used simultaneously in normal Windows mode.

At the full-screen and exclusive cooperative level, you can use the hardware to its fullest. In this mode, you can set custom and dynamic palettes, change display resolutions, and implement page flipping. The exclusive (full-screen) mode does not prevent other applications from allocating surfaces, nor does it exclude them from using DirectDraw or GDI. However, it does prevent applications other than the one currently with exclusive access from changing the display mode or palette.

DirectDraw takes control of window activation events for full-screen, exclusive mode applications, sending WM_ACTIVATEAPP messages to the window handle registered through the SetCooperativeLevel method as needed. DirectDraw only sends activation events to the top-level window. If your application creates child windows that require activation event messages, it is your responsibility to subclass the child windows.

SetCooperativeLevel maintains a binding between a process and a window handle. If SetCooperativeLevel is called once in a process, a binding is established between the process and the window. If it is called again in the same process with a different non-null window handle, it returns the DDERR_HWNDALREADYSET error value. Some applications may receive this error value when DirectSound® specifies a different window handle than DirectDraw—they should specify the same, top-level application window handle.

[C++]

Note Developers using Microsoft Foundation Classes (MFC) should keep in mind that the window handle given to the SetCooperativeLevel method should identify the application's top-level window, not a derived child window. To retrieve your MFC application's top level window handle, you could use the following code:

    HWND hwndTop = AfxGetMainWnd()->GetSafeHwnd();

See also Multiple-Monitor Systems.

[C++,Visual Basic]


Testing Cooperative Levels

Developers often use messages such as WM_ACTIVATEAPP and WM_DISPLAYCHANGE as notifications that their applications should restore or re-create the surfaces being used. In some cases, applications take action when they don't need to, or don't take action when they should. The IDirectDraw7::TestCooperativeLevel method in C++ or the corresponding DirectDraw7.TestCooperativeLevel method in Visual Basic makes it possible for your application to retrieve more information about the DirectDraw object's cooperative level and take appropriate steps to continue execution without mishap.

The TestCooperativeLevel method succeeds, returning DD_OK, if your application can restore its surfaces (if it has not already done so) and continue to execute. Failure codes, on the other hand, are interpreted differently depending on the cooperative-level your application uses:

Full-screen applications

Full-screen applications receive the DDERR_NOEXCLUSIVEMODE return value if they lose exclusive device access–for example, if the user pressed ALT+TAB to switch away from the current application. In this case, applications might call TestCooperativeLevel in a loop, exiting only when the method returns DD_OK (meaning that exclusive mode was returned). In the body of the loop, the application should relinquish control of the CPU to prevent using cycles unnecessarily. Windows supports functions such as the WaitMessage or Sleep Win32 functions for this purpose.

Any existing surfaces should be restored by calling the IDirectDrawSurface7::Restore or IDirectDraw7::RestoreAllSurfaces methods in C++ or DirectDrawSurface7.Restore in Visual Basic, and their contents reloaded before displaying them.

Windowed applications

Windowed applications (those that use the normal cooperative level) receive DDERR_EXCLUSIVEMODEALREADYSET if another application has taken exclusive device access. In this case, no action should be taken until the application with exclusive access loses it. This situation is similar to the case for a full-screen application; a windowed application might loop until TestCooperativeLevel returns DD_OK before restoring and reloading its surfaces. As mentioned previously, in a loop like this applications should avoid unnecessarily using CPU cycles by relinquishing CPU control periodically during the loop.

The TestCooperativeLevel method returns DDERR_WRONGMODE to windowed applications when the display mode has changed. In this case, the application should destroy and re-create any surfaces before continuing execution.


Display Modes

This section contains general information about DirectDraw display modes. The following topics are discussed:

  • About Display Modes
  • Determining Supported Display Modes
  • Setting Display Modes
  • Restoring Display Modes
  • Mode X and Mode 13 Display Modes
  • Support for High Resolutions and True-Color Bit Depths


About Display Modes

A display mode is a hardware setting that describes the dimensions and bit-depth of graphics that the display hardware sends to the monitor from the primary surface. Display modes are described by their defining characteristics: width, height, and bit-depth. For instance, most display adapters can display graphics 640 pixels wide and 480 pixels tall, where each pixel is 8 bits of data. In shorthand, this display mode is called 640×480×8. As the dimensions of a display mode get larger or as the bit-depth increases, more display memory is required.

There are two types of display modes: palettized and non-palettized. For palettized display modes, each pixel is a value representing an index into an associated palette. The bit depth of the display mode determines the number of colors that can be in the palette. For instance, in an 8-bit palettized display mode, each pixel is a value from 0 to 255. In such a display mode, the palette can contain 256 entries.

Non-palettized display modes, as their name states, do not use palettes. The bit depth of a non-palettized display mode indicates the total number of bits that are used to describe a pixel.

The primary surface and any surfaces in the primary flipping chain match the display mode's dimensions, bit depth and pixel format. For more information, see Pixel Formats.


Determining Supported Display Modes

[C++]

Because display hardware varies, not all devices will support all display modes. To determine the display modes supported on a given system, call the IDirectDraw7::EnumDisplayModes method. By setting the appropriate values and flags, the EnumDisplayModes method can list all supported display modes or confirm that a single display mode that you specify is supported. The method's first parameter, dwFlags, controls extra options for the method; in most cases, you will set dwFlags to 0 to ignore extra options. The second parameter, lpDDSurfaceDesc, is the address of a DDSURFACEDESC2 structure that describes a given display mode to be confirmed; you'll usually set this parameter to NULL to request that all modes be listed. The third parameter, lpContext, is a pointer that you want DirectDraw to pass to your callback function; if you don't need any extra data in the callback function, use NULL here. Last, you set the lpEnumModesCallback parameter to the address of the callback function that DirectDraw will call for each supported mode.

The callback function you supply when calling EnumDisplayModes must match the prototype for the EnumModesCallback function. For each display mode that the hardware supports, DirectDraw calls your callback function passing two parameters. The first parameter is the address of a DDSURFACEDESC2 structure that describes one supported display mode, and the second parameter is the address of the application-defined data you specified when calling EnumDisplayModes, if any.

Examine the values in the DDSURFACEDESC2 structure to determine the display mode it describes. The key structure members are the dwWidth, dwHeight, and ddpfPixelFormat members. The dwWidth and dwHeight members describe the display mode's dimensions, and the ddpfPixelFormat member is a DDPIXELFORMAT structure that contains information about the mode's bit depth.

The DDPIXELFORMAT structure carries information describing the mode's bit depth and tells you whether or not the display mode uses a palette. If the dwFlags member contains the DDPF_PALETTEINDEXED1, DDPF_PALETTEINDEXED2, DDPF_PALETTEINDEXED4, or DDPF_PALETTEINDEXED8 flag, the display mode's bit depth is 1, 2, 4 or 8 bits, and each pixel is an index into an associated palette. If dwFlags contains DDPF_RGB, then the display mode is non-palettized and its bit depth is provided in the dwRGBBitCount member of the DDPIXELFORMAT structure.

[Visual Basic]

Because display hardware varies, not all devices will support all display modes. To determine the display modes supported on a given system, call the DirectDraw7.GetDisplayModesEnum method. The method returns a DirectDrawEnumModes object which is then used to retrieve descriptions of the supported display modes. By setting the appropriate values and flags, the GetDisplayModesEnum method fills the DirectDrawEnumModes object with the a list of all supported display modes or confirm that a single display mode that you specify is supported. The method's first parameter, flags, controls extra options for the method; in most cases, you will set flags to DDEDM_DEFAULT to ignore extra options. The second parameter, ddsd, is a DDSURFACEDESC2 type that describes a given display mode to be confirmed; you'll usually set this parameter to Nothing to request that all modes be listed.

After the DirectDrawEnumModes object is returned from the GetDisplayModesEnum method you can call the DirectDrawEnumModes.GetCount method to find out how many supported display modes are available. You then call DirectDrawEnumModes.GetItem to return a description of a single display mode from the collection of display modes in the DirectDrawEnumModes object.

Examine the values in the DDSURFACEDESC2 type retrieved from the GetItem method to determine the display mode it describes. The key type members are the lWidth, lHeight, and ddpfPixelFormat members. The lWidth and lHeight members describe the display mode's dimensions, and the ddpfPixelFormat member is a DDPIXELFORMAT type that contains information about the mode's bit depth.

The DDPIXELFORMAT type carries information describing the mode's bit depth and tells you whether or not the display mode uses a palette. If the lFlags member contains the DDPF_PALETTEINDEXED1, DDPF_PALETTEINDEXED2, DDPF_PALETTEINDEXED4, or DDPF_PALETTEINDEXED8 flag, the display mode's bit depth is 1, 2, 4 or 8 bits, and each pixel is an index into an associated palette. If lFlags contains DDPF_RGB, then the display mode is non-palettized and its bit depth is provided in the lRGBBitCount member of the DDPIXELFORMAT type.


Setting Display Modes

You can set the display mode by using the IDirectDraw7::SetDisplayMode method in C++ or DirectDraw7.SetDisplayMode method in Visual Basic. The SetDisplayMode method accepts four parameters that describe the dimensions, bit depth, and refresh rate of the mode to be set. The method uses a fifth parameter to indicate special options for the given mode; this is currently only used to differentiate between Mode 13 and the Mode X 320×200×8 display mode.

[C++]

Although you can specify the desired display mode's bit depth, you cannot specify the pixel format that the display hardware will use for that bit depth. To determine the RGB bitmasks that the display hardware uses for the current bit depth, call IDirectDraw7::GetDisplayMode after setting the display mode. If the current display mode is not palettized, you can examine the mask values in the dwRBitMask, dwGBitMask, and dwBBitMask members in the DDPIXELFORMAT to determine the correct red, green, and blue bits. For more information, see Pixel Format Masks.

Modes can be changed by more than one application as long as they are all sharing a display card. You can change the bit depth of the display mode only if your application has exclusive access to the DirectDraw object. All DirectDrawSurface objects lose surface memory and become inoperative when the mode is changed. A surface's memory must be reallocated by using the IDirectDrawSurface7::Restore method.

The DirectDraw exclusive (full-screen) mode does not bar other applications from allocating DirectDrawSurface objects, nor does it exclude them from using DirectDraw or GDI functionality. However, it does prevent applications other than the one that obtained exclusive access from changing the display mode or palette.

Note You can only call the IDirectDraw7::SetDisplayMode method from the thread that created the application window. For single threaded applications (the vast majority), this restriction isn't an issue.

[Visual Basic]

Although you can specify the desired display mode's bit depth, you cannot specify the pixel format that the display hardware will use for that bit depth. To determine the RGB bitmasks that the display hardware uses for the current bit depth, call DirectDraw7.GetDisplayMode after setting the display mode. If the current display mode is not palettized, you can examine the mask values in the lRBitMask, lGBitMask, and lBBitMask members of the DDPIXELFORMAT type to determine the correct red, green, and blue bits. For more information, see Pixel Format Masks.

Modes can be changed by more than one application as long as they are all sharing a display card. You can change the bit depth of the display mode only if your application has exclusive access to the DirectDraw object. All DirectDrawSurface objects lose surface memory and become inoperative when the mode is changed. A surface's memory must be reallocated by using the DirectDrawSurface7.Restore method.

The DirectDraw exclusive (full-screen) mode does not bar other applications from allocating DirectDrawSurface objects, nor does it exclude them from using DirectDraw or GDI functionality. However, it does prevent applications other than the one that obtained exclusive access from changing the display mode or palette.


Restoring Display Modes

[C++]

You can explicitly restore the display hardware to its original mode by calling the IDirectDraw7::RestoreDisplayMode method. If the display mode was set by calling IDirectDraw7::SetDisplayMode and your application takes the exclusive cooperative level, the original display mode is reset automatically when you set the application's cooperative level back to normal. (This behavior was first offered in the IDirectDraw2 interface, and is offered by all newer versions of the interface.)

If you're using the IDirectDraw interface, you must always explicitly restore the display mode by using the RestoreDisplayMode method.

[Visual Basic]

You can explicitly restore the display hardware to its original mode by calling the DirectDraw7.RestoreDisplayMode method. If the display mode was set by calling DirectDraw7.SetDisplayMode and your application takes the exclusive cooperative level, the original display mode is reset automatically when you set the application's cooperative level back to normal.


Mode X and Mode 13 Display Modes

DirectDraw supports both Mode 13 and Mode X display modes. Mode 13 is the linear unflippable 320×200×8 bits per pixel palettized mode known widely by its hexadecimal BIOS mode number: 13. For more information, see Mode 13 Support. Mode X is a hybrid display mode derived from the standard VGA Mode 13. This mode allows the use of up to 256 kilobytes (KB) of display memory (rather than the 64 KB allowed by Mode 13) by using the VGA display adapter's EGA multiple video plane system.

DirectDraw provides two Mode X modes (320×200×8 and 320×240×8) for all display cards. Some cards also support linear low-resolution modes. In linear low-resolution modes, the primary surface can be locked and directly accessed. This is not possible in Mode X modes.

[C++]

Mode X modes are available only if an application uses the DDSCL_ALLOWMODEX, DDSCL_FULLSCREEN, and DDSCL_EXCLUSIVE flags when calling the IDirectDraw7::SetCooperativeLevel method. If DDSCL_ALLOWMODEX is not specified, the IDirectDraw7::EnumDisplayModes method will not enumerate Mode X modes, and the IDirectDraw7::SetDisplayMode method will fail if a Mode X mode is requested.

Windows 95 and Windows NT/Windows 2000 do not natively support Mode X modes; therefore, when your application is in a Mode X mode, you cannot use the IDirectDrawSurface7::Lock or IDirectDrawSurface7::Blt methods to lock or blit to the primary surface. You also cannot use either the IDirectDrawSurface7::GetDC method on the primary surface, or GDI with a screen DC. Mode X modes are indicated by the DDSCAPS_MODEX flag in the DDSCAPS2 structure, which is part of the DDSURFACEDESC2 structure returned by the IDirectDrawSurface7::GetCaps and IDirectDraw7::EnumDisplayModes methods.

[Visual Basic]

Mode X modes are available only if an application uses the DDSCL_ALLOWMODEX, DDSCL_FULLSCREEN, and DDSCL_EXCLUSIVE flags when calling the DirectDraw7.SetCooperativeLevel method. If DDSCL_ALLOWMODEX is not specified when setting the cooperative level, the DirectDraw7.GetDisplayModesEnum method will not enumerate Mode X modes, and the DirectDraw7.SetDisplayMode method will fail if a Mode X mode is requested.

Windows 95 and Windows NT/Windows 2000 do not natively support Mode X modes; therefore, when your application is in a Mode X mode, you cannot use the DirectDrawSurface7.Lock or DirectDrawSurface7.Blt methods to lock or blit to the primary surface. You also cannot use either the DirectDrawSurface7.GetDC method on the primary surface, or GDI with a screen DC. Mode X modes are indicated by the DDSCAPS_MODEX flag in the DDSCAPS2 type, which is part of the DDSURFACEDESC2 type returned by the DirectDrawSurface7.GetCaps and DirectDrawEnumModes methods.


Support for High Resolutions and True-Color Bit Depths

DirectDraw supports all of the screen resolutions and depths supported by the display device driver. DirectDraw allows an application to change the mode to any one supported by the computer's display driver, including all supported 24- and 32-bpp (true-color) modes.

DirectDraw also supports HEL blitting in true-color surfaces. If the display device driver supports blitting at these resolutions, the hardware blitter will be used for display-memory-to-display-memory blits. Otherwise, the HEL will be used to perform the blits.

[C++]

DirectDraw checks a list of known display modes against the display restrictions of the installed monitor. If DirectDraw determines that the requested mode is not compatible with the monitor, the call to the IDirectDraw7::SetDisplayMode method fails. Only modes that are supported on the installed monitor will be enumerated when you call the IDirectDraw7::EnumDisplayModes method.

[Visual Basic]

DirectDraw checks a list of known display modes against the display restrictions of the installed monitor. If DirectDraw determines that the requested mode is not compatible with the monitor, the call to the DirectDraw7.SetDisplayMode method fails. Only modes that are supported on the installed monitor will be enumerated when you call the DirectDraw7.GetDisplayModesEnum method.


The DirectDraw Object

This section contains information about DirectDraw objects and how you can manipulate them through their IDirectDraw, IDirectDraw2, IDirectDraw4, or IDirectDraw7 interfaces. The following topics are discussed:

  • What Are DirectDraw Objects?
  • What's New in IDirectDraw7?
  • Parent and Child Object Lifetimes
  • Multiple DirectDraw Objects per Process
  • Creating DirectDraw Objects by Using CoCreateInstance


What Are DirectDraw Objects?

[C++]

The DirectDraw object is the heart of all DirectDraw applications and is an integral part of Direct3D® applications as well. It is the first object you create and, through it, you create all other related objects. For DirectX 7.0, a new method is introduced for creating the latest iteration of the DirectDraw object. The DirectDrawCreateEx function creates a DirectDraw object capable of exposing the newest set of Direct3D interfaces. In previous versions, you created a DirectDraw object by calling the DirectDrawCreate function, which returns an IDirectDraw interface. If you wanted to work with a different iteration of the interface (such as IDirectDraw7) to take advantage of new features it provides, you can query for it. (See Getting an IDirectDraw7 Interface.) In DirectX 7.0, you can still query for the IDirectDraw7 interface after creating the DirectDraw object using DirectDrawCreate, but it will not support the new set of features of Direct3D. To use the new functionality of Direct3D, you must return an IDirectDraw7 interface using the DirectDrawCreateEx function. Note that you can create multiple DirectDraw objects, one for each display device installed in a system.

[Visual Basic]

The DirectDraw object is the heart of all DirectDraw applications and is an integral part of Direct3D® applications as well. It is the first object you create and, through it, you create all other related objects. In Visual Basic, calling the DirectX7.DirectDrawCreate method creates a DirectDraw7 object capable of exposing the newest set of Direct3D interfaces.

The DirectDraw object represents the display device and makes use of hardware acceleration if the display device for which it was created supports hardware acceleration. Each unique DirectDraw object can manipulate the display device and create surfaces, palettes, and clipper objects that are dependent on (or are, "connected to") the object that created them. For example, to create surfaces, you call the IDirectDraw7::CreateSurface method in C++ or the DirectDraw7.CreateSurface method in Visual Basic. Or, if you need a palette object to apply to a surface, call the IDirectDraw7::CreatePalette method in C++ or the DirectDraw7.CreatePalette method in Visual Basic. Additionally, the IDirectDraw7 interface and DirectDraw7 object exposes similar methods to create clipper objects.

You can create more than one instance of a DirectDraw object at a time. The simplest example of this is using two monitors on a Windows 95 or Windows NT 4.0 and earlier system. Although these operating systems don't support dual monitors on their own, it is possible to write a DirectDraw HAL for each display device. The display device Windows and GDI recognizes is the one that will be used when you create the instance of the default DirectDraw object. The display device that Windows and GDI do not recognize can be addressed by another, independent DirectDraw object that must be created by using the second display device's globally unique identifier (GUID). This GUID can be obtained by using the DirectDrawEnumerate function in C++ or the DirectDrawEnum.GetGuid method in Visual Basic.

The DirectDraw object manages all of the objects it creates. It controls the default palette (if the primary surface is in 8-bits-per-pixel mode), the default color key, and the hardware display mode. It tracks what resources have been allocated and what resources remain to be allocated.


What's New in IDirectDraw7?

[C++]

This section details new features provided by the IDirectDraw7 interface and describes its new features or how it behaves differently than its predecessor, IDirectDraw4. (Note that there is no IDirectDraw3 interface, IDirectDraw4 is the direct predecessor of IDirectDraw7.). The following topics are discussed:

  • New Features in IDirectDraw7
  • Getting an IDirectDraw7 Interface

The most obvious difference between the IDirectDraw7 interface is the tighter integration with Direct3D textures. In previous versions of the DirectX, textures were created through the IDirect3DTexture interface. In DirectX 7.0, texture management has been moved to the IDirectDrawSurface7 interface. These methods include:

  • IDirectDrawSurface7::SetPriority
  • IDirectDrawSurface7::GetPriority
  • IDirectDrawSurface7::SetLOD
  • IDirectDrawSurface7::GetLOD

Additional features added in this version include support for stereo flipping surfaces and refresh rate enumeration and cubic environment mapping.

[C++,Visual Basic]


New Features in IDirectDraw7

[C++]

Although there are no new methods added to the IDirectDraw7 interface in DirectX 7.0, there is a tighter relationship between IDirectDraw7 and Direct3D. IDirectDraw7 objects will support QueryInterface for any IDirect3D interface, but will only allow subsequent QueryInterface calls for the same level of interface. This means that once IDirect3D7 has been obtained from any DirectDraw object, no earlier Direct3D interfaces will be available from that object. Similarly, once any legacy Direct3D interface has been obtained from a DirectDraw object, IDirect3D7 will not be available from that object.

Additionally, IDirectDraw7 created surfaces do not allow Direct3D related QueryInterface calls (they will return E_NOINTERFACE). Applications may only obtain IDirect3DTexture interfaces from surfaces created by IDirectDraw4 or lower interfaces.

The practical result is that to use legacy Direct3D interfaces, applications should not use DirectDraw 7.0 interface versions, and to use DirectX 7.0 Direct3D interfaces, applications should use DirectX 7.0 DirectDraw interfaces.

A new DirectDraw object creation function, DirectDrawCreateEx, has been added in this release to obtain an IDirectDraw7 interface and is further discussed in the next section Getting an IDirectDraw7 Interface.

[C++,Visual Basic]


Getting an IDirectDraw7 Interface

[C++]

DirectX 7.0 has a new function to create an IDirectDraw7 interface, DirectDrawCreateEx. This function is the only way to create the newest iteration of this DirectDraw object which supports the new features of DirectDraw and Direct3D. The IDirectDraw7 interface supersedes the IDirectDraw4 interface. This new interface can be obtained by using the DirectDrawCreateEx function, as the following C++ example shows:

// Initialize DirectDraw

LPDIRECTDRAW7 lpDD7;
HRESULT hr;
if (FAILED(hr = DirectDrawCreateEx(NULL, (VOID**)&lpDD7, IID_IDirectDraw7, NULL)))
    return FALSE;

if (FAILED(hr = lpDD7->SetCooperativeLevel(NULL, DDSCL_NORMAL)))
    return FALSE;

After getting an IDirectDraw7 interface, you can begin calling its methods to take advantage of new features, performance improvements, and behavioral differences. Because some methods might change with the release of a new interface, mixing methods from an interface and its replacement (between IDirectDraw4 and IDirectDraw7, for example) can cause unpredictable results.

[Visual Basic]

In Visual Basic, the DirectDraw object is obtained by calling the DirectX7.DirectDrawCreate method.


Parent and Child Object Lifetimes

[Visual Basic]

The information in this topic pertains only to applications written in C++.

[C++]

All objects you'll use in DirectDraw programming—the DirectDraw object, surfaces, palettes, clippers, and such—only exist in memory for as long as another object, such as an application, needs them. The time that passes from the moment when an object is created and placed in memory to when it is released and subsequently removed from memory is known as the object's lifetime. The Component Object Model (COM) followed by all DirectX components dictates that an object must keep track of how many other objects require its services. This number, known as a reference count, determines the object's lifetime. COM also dictates that an object expose the IUnknown::AddRef and IUnknown::Release methods to enable applications to explicitly manage its reference count; make sure you use these methods in accordance to COM rules.

You aren't the only one who is using the IUnknown methods to manage reference counts for objects—DirectDraw objects use them internally, too. When you use the IDirectDraw7 interface (in contrast to IDirectDraw2 or IDirectDraw) to create a "child" object like a surface, the child uses the IUnknown::AddRef method of the "parent" DirectDraw object to increment the parent's reference count.

When your application no longer needs an object, call the Release method to decrement its reference count. When the count reaches zero, the object is removed from memory. When a child object's reference count reaches zero, it calls the parent's IUnknown::Release method to indicate that there is one less object who will be needing the parent's services.

Implicitly allocated objects, such as the back-buffer surfaces in a flipping chain that you create with a single IDirectDraw7::CreateSurface call, are automatically deallocated when their parent DirectDrawSurface object is released. Also, you can only release a DirectDraw object from the thread that created the application window. For single-threaded applications, this restriction obviously doesn't apply, as there is only one thread. If your application created a primary flipping chain of two surfaces (created by a single CreateSurface call) that used an attached DirectDrawClipper object, the code to release these objects safely might look like:

// For this example, the g_lpDDraw, g_lpDDSurface, and
// g_lpDDClip are valid pointers to objects.
void ReleaseDDrawObjects(void)
{
    // If the DirectDraw object pointer is valid,
    // it should be safe to release it and the objects it owns.
    if(g_lpDDraw)
    {
        // Release the DirectDraw object. (This call wouldn't
        // be safe if the children were created through IDirectDraw2
        // or IDirectDraw. See the following note for
        // more information)
        g_lpDDraw->Release(), g_lpDDraw = NULL;

        // Now, release the clipper that is attached to the surfaces.
        if(g_lpDDClip)
            g_lpDDClip->Release(), g_lpDDClip = NULL;

        // Now, release the primary flipping chain. Note
        // that this is only valid because the flipping
        // chain surfaces were created with a single
        // CreateSurface call. If they were explicitly
        // created and attached, then they must also be
        // explicitly released.
        if(g_lpDDSurface)
            g_lpDDSurface->Release(), g_lpDDSurface = NULL;
    }
}

Note Earlier versions of the DirectDraw interface (IDirectDraw2 and IDirectDraw, to be exact) behave differently than the most recent interface. When using these early interfaces, DirectDraw automatically releases all child objects when the parent itself is released. As a result, if you use these older interfaces, the order in which you release objects is critical. In this case, you should release the children of a DirectDraw object before releasing the DirectDraw object itself (or not release them at all, counting on the parent to do cleanup for you). Because the DirectDraw object releases the child objects, if you release the parent before the children, you are very likely to incur a memory fault for attempting to dereference a pointer that was invalidated when the parent object released its children.

Some older applications relied on the automatic release of child objects and neglected to properly release some objects when no longer needed. At the time, this practice didn't cause any negative side effects, however doing so when using the IDirectDraw7 interface might result in memory leaks.


Multiple DirectDraw Objects per Process

[Visual Basic]

The information in this topic pertains only to applications written in C++.

[C++]

DirectDraw allows a process to call the DirectDrawCreate function as many times as necessary. A unique and independent interface to a unique and independent DirectDraw object is returned after each call. Each DirectDraw object can be used as desired; there are no dependencies between the objects. Each object behaves exactly as if it had been created by a unique process.

DirectDraw objects are independent of one another and the DirectDrawSurface, DirectDrawPalette, and DirectDrawClipper objects they create should not be used with other DirectDraw objects because they are automatically released when the parent DirectDraw object is destroyed. If they are used with another DirectDraw object, they might stop functioning if their parent object is destroyed, causing the remaining DirectDraw object to malfunction.

The exception is DirectDrawClipper objects created by using the DirectDrawCreateClipper function. These objects are independent of any particular DirectDraw object and can be used with one or more DirectDraw objects.


Creating DirectDraw Objects by Using CoCreateInstance

[Visual Basic]

The information in this topic pertains only to applications written in C++.

[C++]

You can create a DirectDraw object by using the CoCreateInstance function and the IDirectDraw7::Initialize method rather than the DirectDrawCreate function. The following steps describe how to create the DirectDraw object:

  1. Initialize COM at the start of your application by calling CoInitialize and specifying NULL.
    if (FAILED(CoInitialize(NULL)))
    return FALSE;
  2. Create the DirectDraw object by using CoCreateInstance and the IDirectDraw7::Initialize method.
    ddrval = CoCreateInstance(&CLSID_DirectDraw,
    NULL, CLSCTX_ALL, &IID_IDirectDraw7, &lpdd);
if(!FAILED(ddrval))
    ddrval = IDirectDraw7_Initialize(lpdd, NULL);

    In this call to CoCreateInstance, the first parameter, CLSID_DirectDraw, is the class identifier of the DirectDraw driver object class, the IID_IDirectDraw7 parameter identifies the particular DirectDraw interface to be created, and the lpdd parameter points to the DirectDraw object that is retrieved. If the call is successful, this function returns an uninitialized object.

  3. Before you use the DirectDraw object, you must call IDirectDraw7::Initialize. This method takes the driver GUID parameter that the DirectDrawCreate function typically uses (NULL in this case). After the DirectDraw object is initialized, you can use and release it as if it had been created by using the DirectDrawCreate function. If you do not call the Initialize method before using one of the methods associated with the DirectDraw object, a DDERR_NOTINITIALIZED error will occur.

Before you close the application, close the COM library by using the CoUninitialize function.

CoUninitialize();


Surfaces

This section contains information about DirectDrawSurface objects. The following topics are discussed:

  • Basic Concepts of Surfaces
  • Creating Surfaces
  • Flipping Surfaces
  • Blitting to Surfaces
  • Losing and Restoring Surfaces
  • COM Reference Count Semantics for Surfaces
  • Enumerating Surfaces
  • Updating Surface Characteristics
  • Accessing Surface Memory Directly
  • Gamma and Color Controls
  • Overlay Surfaces
  • Compressed Texture Surfaces
  • Private Surface Data
  • Surface Uniqueness Values
  • Using Non-local Video Memory Surfaces
  • Surfaces and Device Contexts


Basic Concepts of Surfaces

This section contains information about the basic concepts associated with DirectDrawSurface objects. The following topics are discussed:

  • What Are Surfaces?
  • Surface Interfaces
  • Width vs. Pitch
  • Color Keying
  • Pixel Formats


What Are Surfaces?

A surface, or DirectDrawSurface object, represents a linear area of display memory. A surface usually resides in the display memory of the display card, although surfaces can exist in system memory. Unless specifically instructed otherwise during the creation of the DirectDrawSurface object, DirectDraw object will put the DirectDrawSurface object wherever the best performance can be achieved given the requested capabilities. DirectDrawSurface objects can take advantage of specialized processors on display cards, not only to perform certain tasks faster, but to perform some tasks in parallel with the system CPU.

[C++]

Using the IDirectDraw7::CreateSurface method, you can create a single surface object, complex surface-flipping chains, or three-dimensional surfaces. The CreateSurface method creates the requested surface or flipping chain and retrieves a pointer to the primary surface's IDirectDrawSurface7 interface through which the object exposes its functionality.

The IDirectDrawSurface7 interface enables you to indirectly access memory through blit methods, such as IDirectDrawSurface7::BltFast. The surface object can provide a device context to the display that you can use with GDI functions. Additionally, you can use IDirectDrawSurface7 methods to directly access display memory. For example, you can use the IDirectDrawSurface7::Lock method to lock the display memory and retrieve the address corresponding to that surface. Addresses of display memory might point to visible frame buffer memory (primary surface) or to nonvisible buffers (off-screen or overlay surfaces). Nonvisible buffers usually reside in display memory, but can be created in system memory if required by hardware limitations or if DirectDraw is performing software emulation. In addition, the IDirectDrawSurface7 interface extends other methods that you can use to set or retrieve palettes, or to work with specific types or surfaces, like flipping chains or overlays.

[Visual Basic]

Using the DirectDraw7.CreateSurface method, you can create a single surface object, complex surface-flipping chains, or three-dimensional surfaces. The CreateSurface method creates the requested surface or flipping chain and retrieves a pointer to the primary surface's DirectDrawSurface7 object through which it exposes its functionality.

The DirectDrawSurface7 object enables you to indirectly access memory through blit methods, such as DirectDrawSurface7.BltFast. The surface object can provide a device context to the display that you can use with GDI functions. Additionally, you can use DirectDrawSurface7 methods to directly access display memory. For example, you can use the DirectDrawSurface7.Lock method to lock the display memory and retrieve the address corresponding to that surface. Addresses of display memory might point to visible frame buffer memory (primary surface) or to nonvisible buffers (off-screen or overlay surfaces). Nonvisible buffers usually reside in display memory, but can be created in system memory if required by hardware limitations or if DirectDraw is performing software emulation. In addition, the DirectDrawSurface7 class extends other methods that you can use to set or retrieve palettes, or to work with specific types or surfaces, like flipping chains or overlays.

From this illustration, you can see that all surface are created by a DirectDraw object and are often used closely with palettes. Although each surface object can be assigned a palette, palettes aren't required for anything but primary surfaces that use pixel formats of 8-bits in depth or less.


Surface Interfaces

[C++]

DirectDrawSurface objects expose their functionality through the IDirectDrawSurface, IDirectDrawSurface2, IDirectDrawSurface3, IDirectDrawSurface4, and IDirectDrawSurface7 interfaces. Each new interface version provides the same utility as its predecessors, with additional options available through new methods.

When you create a surface by calling the IDirectDraw7::CreateSurface method (or another creation method from IDirectDraw7), you receive a pointer to the surface's IDirectDrawSurface7 interface. This behavior is different than previous versions of DirectX. Before the introduction of the IDirectDraw7 interface, the CreateSurface method provided a pointer to a surface's IDirectDrawSurface interface. If you wanted to work with a different iteration of the interface, you had to query for it. When using IDirectDraw7 this isn't the case, although you are free to query a surface for a previous iteration of an interface if you choose.

[Visual Basic]

DirectDrawSurface objects are created from the DirectDrawSurface7 class. You call the DirectDraw7.CreateSurface method to return a DirectDrawSurface object.


Width vs. Pitch

Although the terms width and pitch are often used informally, they have very important (and distinctly different) meanings. As a result, you should understand the meanings for each, and how to interpret the values that DirectDraw uses to describe them.

[C++]

DirectDraw uses the DDSURFACEDESC2 structure to carry information describing a surface. Among other things, this structure is defined to contain information about a surface's dimensions, as well as how those dimensions are represented in memory. The structure uses the dwHeight and dwWidth members to describe the logical dimensions of the surface. Both of these members are measured in pixels. Therefore, the dwHeight and dwWidth values for a 640×480 surface are the same whether it is an 8-bit palettized surface or a 24-bit RGB surface.

The DDSURFACEDESC2 structure contains information about how a surface is represented in memory through the lPitch member. The value in the lPitch member describes the surface's memory pitch (also called stride). Pitch is the distance, in bytes, between two memory addresses that represent the beginning of one bitmap line and the beginning of the next bitmap line. Because pitch is measured in bytes rather than pixels, a 640×480×8 surface will have a very different pitch value than a surface with the same dimensions but a different pixel format. Additionally, the pitch value sometimes reflects bytes that DirectDraw has reserved as a cache, so it is not safe to assume that pitch is simply the width multiplied by the number of bytes per pixel. Rather, you could visualize the difference between width and pitch as shown in the following illustration.

[Visual Basic]

DirectDraw uses the DDSURFACEDESC2 type to carry information describing a surface. Among other things, this structure is defined to contain information about a surface's dimensions, as well as how those dimensions are represented in memory. The structure uses the lHeight and lWidth members to describe the logical dimensions of the surface. Both of these members are measured in pixels. Therefore, the lHeight and lWidth values for a 640×480 surface are the same whether it is an 8-bit palettized surface or a 24-bit RGB surface.

The DDSURFACEDESC2 type contains information about how a surface is represented in memory through the lPitch member. The value in the lPitch member describes the surface's memory pitch (also called stride). Pitch is the distance, in bytes, between two memory addresses that represent the beginning of one bitmap line and the beginning of the next bitmap line. Because pitch is measured in bytes rather than pixels, a 640×480×8 surface will have a very different pitch value than a surface with the same dimensions but a different pixel format. Additionally, the pitch value sometimes reflects bytes that DirectDraw has reserved as a cache, so it is not safe to assume that pitch is simply the width multiplied by the number of bytes per pixel. Rather, you could visualize the difference between width and pitch as shown in the following illustration.

In this figure, the front buffer and back buffer are both 640×480×8, and the cache is 384×480×8.

[C++]

Pitch values are useful when you are directly accessing surface memory. For example, after calling the IDirectDrawSurface7::Lock method, the lpSurface member of the associated DDSURFACEDESC2 structure contains the address of the top-left pixel of the locked area of the surface, and the lPitch member is the surface pitch. You access pixels horizontally by incrementing or decrementing the surface pointer by the number of bytes per pixel, and you move up or down by adding the pitch value to, or subtracting it from, the current surface pointer.

When accessing surfaces directly, take care to stay within the memory allocated for the dimensions of the surface and stay out of any memory reserved for cache. Additionally, when you lock only a portion of a surface, you must stay within the rectangle you specify when locking the surface. Failing to follow these guidelines will have unpredictable results. When rendering directly into surface memory, always use the pitch returned by the Lock method (or the IDirectDrawSurface7::GetDC method). Do not assume a pitch based solely on the display mode. If your application works on some display adapters but looks garbled on others, this may be the cause of your problem.

[Visual Basic]

Pitch values are useful when you are directly accessing surface memory. For example, after calling the DirectDrawSurface7.Lock method, the lPitch member is the surface pitch. You access pixels horizontally by incrementing or decrementing the surface pointer by the number of bytes per pixel, and you move up or down by adding the pitch value to, or subtracting it from, the current surface pointer.

When accessing surfaces directly, take care to stay within the memory allocated for the dimensions of the surface and stay out of any memory reserved for cache. Additionally, when you lock only a portion of a surface, you must stay within the rectangle you specify when locking the surface. Failing to follow these guidelines will have unpredictable results. When rendering directly into surface memory, always use the pitch returned by the Lock method (or the DirectDrawSurface7.GetDC method). Do not assume a pitch based solely on the display mode. If your application works on some display adapters but looks garbled on others, this may be the cause of your problem.

For more information, see Accessing Surface Memory Directly.


Color Keying

DirectDraw supports source and destination color keying for blits and overlay surfaces. Color keys enable you to display one image on top of another selectively, so that only certain pixels from the foreground rectangle are displayed, or only certain pixels on the background rectangle are overwritten.

[C++]

You supply a single color key or a range of colors for source or destination color keying by calling the IDirectDrawSurface7::SetColorKey method.

[Visual Basic]

You supply a single color key or a range of colors for source or destination color keying by calling the DirectDrawSurface7.SetColorKey method.

For more information about color keying, see the following topics:

  • Overlay Color Keys
  • Transparent Blitting


Pixel Formats

[C++]

Pixel formats dictate how data for each pixel in surface memory is to be interpreted. DirectDraw uses the DDPIXELFORMAT structure to describe various pixel formats. The DDPIXELFORMAT contains members to describe the following traits of a pixel format:

  • Palettized or non-palettized pixel format
  • If non-palettized, whether the pixel format is RGB or YUV
  • Bit depth
  • Bitmasks for the pixel format's components

You can retrieve information about an existing surface's pixel format by calling the IDirectDrawSurface7::GetPixelFormat method.

[Visual Basic]

Pixel formats dictate how data for each pixel in surface memory is to be interpreted. DirectDraw uses the DDPIXELFORMAT type to describe various pixel formats. The DDPIXELFORMAT contains members to describe the following traits of a pixel format:

  • Palettized or non-palettized pixel format
  • If non-palettized, whether the pixel format is RGB or YUV
  • Bit depth
  • Bitmasks for the pixel format's components

You can retrieve information about an existing surface's pixel format by calling the DirectDrawSurface7.GetPixelFormat method.


Creating Surfaces

The DirectDrawSurface object represents a surface that usually resides in the display memory, but can exist in system memory if display memory is exhausted or if it is explicitly requested.

[C++]

Use the IDirectDraw7::CreateSurface method to create one surface or to simultaneously create multiple surfaces (a complex surface). When calling CreateSurface, you specify the dimensions of the surface, whether it is a single surface or a complex surface, and the pixel format (if the surface won't be using an indexed palette). All these characteristics are contained in a DDSURFACEDESC2 structure, whose address you send with the call. If the hardware can't support the requested capabilities or if it previously allocated those resources to another DirectDrawSurface object, the call will fail.

[Visual Basic]

Use the DirectDraw7.CreateSurface method to create one surface or to simultaneously create multiple surfaces (a complex surface). When calling CreateSurface, you specify the dimensions of the surface, whether it is a single surface or a complex surface, and the pixel format (if the surface won't be using an indexed palette). All these characteristics are contained in a DDSURFACEDESC2 type, whose address you send with the call. If the hardware can't support the requested capabilities or if it previously allocated those resources to another DirectDrawSurface object, the call will fail.

Creating single surfaces or multiple surfaces is a simple matter that requires only a few lines of code. There are a few common situations (and some less common ones) in which you will need to create surfaces. The following situations are discussed:

  • Creating the Primary Surface
  • Creating an Off-Screen Surface
  • Creating Complex Surfaces and Flipping Chains
  • Creating Wide Surfaces
  • Creating Client Memory Surfaces
[C++]

By default, for all surfaces except client memory surfaces, DirectDraw attempts to create a surface in local video memory. If there isn't enough local video memory available to hold the surface, DirectDraw will try to use non-local video memory (on some Accelerated Graphics Port-equipped systems), and fall back on system memory if all other types of memory are unavailable. You can explicitly request that a surface be created in a certain type of memory by including the appropriate flags in the associated DDSCAPS2 structure when calling IDirectDraw7::CreateSurface.

[Visual Basic]

By default, for all surfaces except client memory surfaces, DirectDraw attempts to create a surface in local video memory. If there isn't enough local video memory available to hold the surface, DirectDraw will try to use non-local video memory (on some Accelerated Graphics Port-equipped systems), and fall back on system memory if all other types of memory are unavailable. You can explicitly request that a surface be created in a certain type of memory by including the appropriate flags in the associated DDSCAPS2 type when calling DirectDraw7.CreateSurface.


Creating the Primary Surface

The primary surface is the surface currently visible on the monitor and is identified by the DDSCAPS_PRIMARYSURFACE flag. You can only have one primary surface for each DirectDraw object.

When you create a primary surface, remember that the dimensions and pixel format implicitly match the current display mode. Therefore, this is the one time you don't need to declare a surface's dimensions or pixel format. If you do specify them, the call will fail and return DDERR_INVALIDPARAMS—even if the information you used matches the current display mode.

[C++]

The following example shows how to prepare the DDSURFACEDESC2 structure members relevant for creating the primary surface.

DDSURFACEDESC2 ddsd;
ddsd.dwSize = sizeof(ddsd);

// Tell DirectDraw which members are valid.
ddsd.dwFlags = DDSD_CAPS;

// Request a primary surface.
ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;

After creating the primary surface, you can retrieve information about its dimensions and pixel format by calling its IDirectDrawSurface7::GetSurfaceDesc method.

[Visual Basic]

The following example shows how to prepare the DDSURFACEDESC2 type members relevant for creating the primary surface.

Dim ddsd As DDSURFACEDESC2

// Tell DirectDraw which members are valid.
ddsd.lFlags = DDSD_CAPS;

// Request a primary surface.
ddsd.ddsCaps.lCaps = DDSCAPS_PRIMARYSURFACE;

After creating the primary surface, you can retrieve information about its dimensions and pixel format by calling its DirectDrawSurface7.GetSurfaceDesc method.

See also Display Modes.


Creating an Off-Screen Surface

[C++]

An off-screen surface is often used to cache bitmaps that will later be blitted to the primary surface or a back buffer. You must declare the dimensions of an off-screen surface by including the DDSD_WIDTH and DDSD_HEIGHT flags and the corresponding values in the dwWidth and dwHeight members. Additionally, you must include the DDSCAPS_OFFSCREENPLAIN flag in the accompanying DDSCAPS2 structure.

By default, DirectDraw creates a surface in display memory unless it will not fit, in which case it creates the surface in system memory. You can explicitly choose display or system memory by including the DDSCAPS_SYSTEMMEMORY or DDSCAPS_VIDEOMEMORY flags in the dwCaps member of the DDSCAPS2 structure. The method fails, returning an error, if it can't create the surface in the specified location.

The following example shows how to prepare for creating a simple off-screen surface:

DDSURFACEDESC2 ddsd;
ddsd.dwSize = sizeof(ddsd);

// Tell DirectDraw which members are valid.
ddsd.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH;

// Request a simple off-screen surface, sized
// 100 by 100 pixels.
//
// (This assumes that the off-screen surface we are about
// to create will match the pixel format of the
// primary surface.)
ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN;
ddsd.dwHeight = 100;
ddsd.dwWidth = 100;

Additionally, you can create surfaces whose pixel format differs from the primary surface's pixel format. However, in this case there is one drawback—you are limited to using system memory. The following code fragment shows how to prepare the DDSURFACEDESC2 structure members in order to create an 8-bit palettized surface (assuming that the current display mode is something other than 8-bits per pixel).

ZeroMemory(&ddsd, sizeof(ddsd));
ddsd.dwSize  = sizeof(ddsd);
ddsd.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT;
ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN | DDSCAPS_SYSTEMMEMORY;
ddsd.dwHeight = 100;
ddsd.dwWidth  = 100;
ddsd.ddpfPixelFormat.dwSize  = sizeof(DDPIXELFORMAT);
ddsd.ddpfPixelFormat.dwFlags = DDPF_RGB | DDPF_PALETTEINDEXED8;

// Set the bit depth for an 8-bit surface, but DO NOT
// specify any RGB mask values. The masks must be zero
// for a palettized surface.
ddsd.ddpfPixelFormat.dwRGBBitCount = 8;
[Visual Basic]

An off-screen surface is often used to cache bitmaps that will later be blitted to the primary surface or a back buffer. You must declare the dimensions of an off-screen surface by including the DDSD_WIDTH and DDSD_HEIGHT flags and the corresponding values in the lWidth and lHeight members. Additionally, you must include the DDSCAPS_OFFSCREENPLAIN flag in the accompanying DDSCAPS2 type.

By default, DirectDraw creates a surface in display memory unless it will not fit, in which case it creates the surface in system memory. You can explicitly choose display or system memory by including the DDSCAPS_SYSTEMMEMORY or DDSCAPS_VIDEOMEMORY flags in the lCaps member of the DDSCAPS2 type. The method fails, returning an error, if it can't create the surface in the specified location.

The following example shows how to prepare for creating a simple off-screen surface:

Dim ddsd As DDSURFACEDESC2

// Tell DirectDraw which members are valid.
ddsd.lFlags = DDSD_CAPS Or DDSD_HEIGHT Or DDSD_WIDTH

// Request a simple off-screen surface, sized
// 100 by 100 pixels.
//
// (This assumes that the off-screen surface we are about
// to create will match the pixel format of the
// primary surface.)
ddsd.ddsCaps.lCaps = DDSCAPS_OFFSCREENPLAIN
ddsd.lHeight = 100
ddsd.lWidth = 100

Additionally, you can create surfaces whose pixel format differs from the primary surface's pixel format. However, in this case there is one drawback—you are limited to using system memory. The following code fragment shows how to prepare the DDSURFACEDESC2 type members in order to create an 8-bit palettized surface (assuming that the current display mode is something other than 8-bits per pixel).

ddsd.lFlags = DDSD_CAPS Or DDSD_HEIGHT Or DDSD_WIDTH Or DDSD_PIXELFORMAT
ddsd.ddsCaps.lCaps = DDSCAPS_OFFSCREENPLAIN Or DDSCAPS_SYSTEMMEMORY
ddsd.lHeight = 100
ddsd.lWidth  = 100
ddsd.ddpfPixelFormat.lFlags = DDPF_RGB Or DDPF_PALETTEINDEXED8

// Set the bit depth for an 8-bit surface, but DO NOT
// specify any RGB mask values. The masks must be zero
// for a palettized surface.
ddsd.ddpfPixelFormat.lRGBBitCount = 8

In previous versions of DirectX, the maximum width of off-screen surfaces was limited to the width of the primary surface. Beginning with DirectX 5.0, you can create surfaces as wide as you need, permitting that the display hardware can support them. Be careful when declaring wide off-screen surfaces; if the video card memory cannot hold a surface as wide as you request, the surface is created in system memory. If you explicitly choose video memory and the hardware can't support it, the call fails. For more information, see Creating Wide Surfaces.


Creating Complex Surfaces and Flipping Chains

[C++]

You can also create complex surfaces. A complex surface is a set of surfaces created with a single call to the IDirectDraw7::CreateSurface method. If the DDSCAPS_COMPLEX flag is set when you call CreateSurface call, DirectDraw implicitly creates one or more surfaces in addition to the surface explicitly specified. You manage complex surfaces just like a single surface—a single call to the IDirectDraw::Release method releases all surfaces, and a single call to the IDirectDrawSurface7::Restore method restores them all. However, implicitly created surfaces cannot be detached. For more information, see IDirectDrawSurface7::DeleteAttachedSurface.

[Visual Basic]

You can also create complex surfaces. A complex surface is a set of surfaces created with a single call to the DirectDraw7.CreateSurface method. If the DDSCAPS_COMPLEX flag is set when you call CreateSurface call, DirectDraw implicitly creates one or more surfaces in addition to the surface explicitly specified. You manage complex surfaces just like a single surface—a single call to the DirectDrawSurface7.Restore method restores them all. However, implicitly created surfaces cannot be detached. For more information, see DirectDrawSurface7.DeleteAttachedSurface.

One of the most useful complex surfaces you can create is a flipping chain. Usually, a flipping chain is made of a primary surface and one or more back buffers. The DDSCAPS_FLIP flag indicates that a surface is part of a flipping chain. Creating a flipping chain this way requires that you also include the DDSCAPS_COMPLEX flag.

[C++]

The following example shows how to prepare for creating a primary surface flipping chain.

DDSURFACEDESC2 ddsd2;
ddsd2.dwSize = sizeof(ddsd2);

// Tell DirectDraw which members are valid.
ddsd2.dwFlags = DDSD_CAPS | DDSD_BACKBUFFERCOUNT;

// Request a primary surface with a single
// back buffer
ddsd2.ddsCaps.dwCaps = DDSCAPS_COMPLEX | DDSCAPS_FLIP |
DDSCAPS_PRIMARYSURFACE;
ddsd2.dwBackBufferCount = 1;

The previous example constructs a double-buffered flipping environment—a single call to the IDirectDrawSurface7::Flip method exchanges the surface memory of the primary surface and the back buffer. If you specify 2 for the value of the dwBackBufferCount member of the DDSURFACEDESC2 structure, two back buffers are created, and each call to Flip rotates the surfaces in a circular pattern, providing a triple-buffered flipping environment. For more information, see Flipping Surfaces.

[Visual Basic]

The following example shows how to prepare for creating a primary surface flipping chain.

Dim ddsd2 As DDSURFACEDESC2

// Tell DirectDraw which members are valid.
ddsd2.lFlags = DDSD_CAPS Or DDSD_BACKBUFFERCOUNT

// Request a primary surface with a single
// back buffer
ddsd2.ddsCaps.lCaps = DDSCAPS_COMPLEX Or DDSCAPS_FLIP Or
DDSCAPS_PRIMARYSURFACE
ddsd2.lBackBufferCount = 1

The previous example constructs a double-buffered flipping environment—a single call to the DirectDrawSurface7.Flip method exchanges the surface memory of the primary surface and the back buffer. If you specify 2 for the value of the lBackBufferCount member of the DDSURFACEDESC2 type, two back buffers are created, and each call to Flip rotates the surfaces in a circular pattern, providing a triple-buffered flipping environment. For more information, see Flipping Surfaces.

Note To create a flipping chain that comprises surfaces that will be used as 3-D render targets, be sure to include the DDSCAPS_3DDEVICE capability flag in the surface description, as well as the DDSCAPS_COMPLEX and DDSCAPS_FLIP flags.

[C++]

Unlike the CreateSurface method exposed by the IDirectDraw3 and earlier interfaces, you cannot use IDirectDraw7::CreateSurface to implicitly create a flipping chain of render target surfaces with an attached depth-buffer. The DDSURFACEDESC2 structure that the IDirectDraw7::CreateSurface method accepts doesn't contain a field to specify a depth-buffer bit depth. As a result, applications must create a depth-buffer surface explicitly, then attach it to the back-buffer render target surface. For more information, see Depth Buffers.


Creating Wide Surfaces

DirectDraw allows you to create off-screen surfaces in video memory that are wider that the primary surface. This is only possible when display device support for wide surfaces is present.

[C++]

To check for wide surface support, call IDirectDraw7::GetCaps and look for the DDCAPS2_WIDESURFACES flag in the dwCaps2 member of the first DDCAPS structure you send with the call. If the flag is present, you can create video memory off-screen surfaces that are wider that the primary surface.

If you attempt to create a wide surface in video memory when the DDCAPS2_WIDESURFACES flag isn't present, the attempt will fail and return DDERR_INVALIDPARAMS. Note that attempting to create extremely large surfaces might still fail, even if the driver exposes the DDCAPS2_WIDESURFACES flag.

Wide surfaces are always supported for system memory surfaces, video port surfaces, and execute buffers.

[Visual Basic]

To check for wide surface support, call DirectDraw7.GetCaps and look for the DDCAPS2_WIDESURFACES flag in the lCaps2 member of the first DDCAPS type you send with the call. If the flag is present, you can create video memory off-screen surfaces that are wider that the primary surface.

If you attempt to create a wide surface in video memory when the DDCAPS2_WIDESURFACES flag isn't present, the attempt will fail and raise a DDERR_INVALIDPARAMS error. Note that attempting to create extremely large surfaces might still fail, even if the driver exposes the DDCAPS2_WIDESURFACES flag.

Wide surfaces are always supported for system memory surfaces.


Creating Client Memory Surfaces

Client memory surfaces are simply DirectDrawSurface objects that use system memory that your application has previously allocated to hold image data. Creating such a surface isn't common, but it isn't difficult to do and it can be useful for applications that need to use DirectDraw surface features on existing memory buffers.

[C++]

When creating surfaces, DirectDraw needs information about the dimensions of the surface (measured in pixels) and the surface pitch (measured in bytes), as well as the surface's pixel format. However, unlike creating other types of surfaces, this information for client memory surfaces doesn't tell DirectDraw how you want the surface to be created, it tells DirectDraw how you've already created it. You set these characteristics, plus the memory address of the buffer you've allocated, in the DDSURFACEDESC2 structure you pass to the IDirectDraw7::CreateSurface method.

A client memory surfaces works just like a normal system-memory surface, with the exception that DirectDraw does not attempt to free the surface memory when it's no longer needed; freeing client allocated memory is the application's responsibility.

The following example shows how you might allocate memory and create a DirectDrawSurface object for a 64×64 pixel 24-bit RGB surface:

// For this example, g_lpDD is a valid IDirectDraw7 interface pointer.

#define WIDTH  64 // in pixels
#define HEIGHT 64
#define DEPTH  3  // in bytes (3bytes == 24 bits)

    HRESULT hr;
    LPVOID  lpSurface  = NULL;
    HLOCAL  hMemHandle = NULL;
    DDSURFACEDESC2 ddsd2;
    LPDIRECTDRAWSURFACE7 lpDDS;

    // Allocate memory for a 64 by 64, 24-bit per pixel buffer.
    // REMEMBER: The application is responsible for freeing this
    //           buffer when it is no longer needed.
    if (lpSurface = malloc((size_t)WIDTH*HEIGHT*DEPTH))
        ZeroMemory(lpSurface, (DWORD)WIDTH*HEIGHT*DEPTH);
    else
        return DDERR_OUTOFMEMORY;

    // Initialize the surface description.
    ZeroMemory(&ddsd2, sizeof(DDSURFACEDESC2));
    ZeroMemory(&ddsd2.ddpfPixelFormat, sizeof(DDPIXELFORMAT));
    ddsd2.dwSize = sizeof(ddsd2);
    ddsd2.dwFlags = DDSD_WIDTH | DDSD_HEIGHT | DDSD_LPSURFACE |
                    DDSD_PITCH | DDSD_PIXELFORMAT | DDSD_CAPS;
    ddsd2.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN |
                           DDSCAPS_SYSTEMMEMORY;
    ddsd2.dwWidth = WIDTH;
    ddsd2.dwHeight= HEIGHT;
    ddsd2.lPitch  = (LONG)DEPTH * WIDTH;
    ddsd2.lpSurface = lpSurface;

    // Set up the pixel format for 24-bit RGB (8-8-8).
    ddsd2.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT);
    ddsd2.ddpfPixelFormat.dwFlags= DDPF_RGB;
    ddsd2.ddpfPixelFormat.dwRGBBitCount = (DWORD)DEPTH*8;
    ddsd2.ddpfPixelFormat.dwRBitMask    = 0x00FF0000;
    ddsd2.ddpfPixelFormat.dwGBitMask    = 0x0000FF00;
    ddsd2.ddpfPixelFormat.dwBBitMask    = 0x000000FF;

    // Create the surface
    hr = g_lpDD->CreateSurface(&ddsd2, &lpDDS, NULL);
    return hr;
[Visual Basic]

When creating surfaces, DirectDraw needs information about the dimensions of the surface (measured in pixels) and the surface pitch (measured in bytes), as well as the surface's pixel format. However, unlike creating other types of surfaces, this information for client memory surfaces doesn't tell DirectDraw how you want the surface to be created, it tells DirectDraw how you've already created it. You set these characteristics, plus the memory address of the buffer you've allocated, in the DDSURFACEDESC2 type you pass to the DirectDraw7.CreateSurface method.

A client memory surfaces works just like a normal system-memory surface, with the exception that DirectDraw does not attempt to free the surface memory when it's no longer needed; freeing client allocated memory is the application's responsibility.

The following example shows how you might allocate memory and create a DirectDrawSurface object for a 64×64 pixel 24-bit RGB surface:

'For this example, dd is a valid DirectDraw7 object.

Const cWIDTH = 64 'in pixels
Const cHEIGHT = 64
Const cDEPTH = 3 'in bytes (3 bytes = 24 bits)

Dim ddsd2 As DDSURFACEDESC2
Dim dds As DirectDrawSurface7
Private Sub Form_Load()

'Initialize the surface description.
With ddsd2
    .lFlags = DDSD_WIDTH Or DDSD_HEIGHT Or DDSD_PITCH Or DDSD_PIXELFORMAT Or DDSD_CAPS
    .ddsCaps.lCaps = DDSCAPS_OFFSCREENPLAIN Or DDSCAPS_SYSTEMMEMORY
    .lWidth = cWIDTH
    .lHeight = cHEIGHT
    .lPitch = cDEPTH * cWIDTH
    'Set up the pixel format for 24-bit RGB (8-8-8).
    With .ddpfPixelFormat
        .lFlags = DDPF_RGB
        .lRGBBitCount = cDEPTH * 8
        .lRBitMask = &HFF0000
        .lGBitMask = &HFF00&
        .lBBitMask = &HFF&
    End With
End With

'Create the surface.
Set dds = dd.CreateSurface(ddsd2)

End Sub


Flipping Surfaces

Any surface in DirectDraw can be constructed as a flipping surface. A flipping surface is any piece of memory that can be swapped between a front buffer and a back buffer. (This construct is commonly referred to as a flipping chain). Often, the front buffer is the primary surface, but it doesn't have to be.

[C++]

Typically, when you use the IDirectDrawSurface7::Flip method to request a surface flip operation, the pointers to surface memory for the primary surface and back buffers are swapped. Flipping is performed by switching pointers that the display device uses for referencing memory, not by copying surface memory. (The exception to this is when DirectDraw is emulating the flip, in which case it simply copies the surfaces. DirectDraw emulates flip operations if a back buffer cannot fit into display memory or if the hardware doesn't support DirectDraw.) When a flipping chain contains a primary surface and more than one back buffer, the pointers are switched in a circular pattern, as shown in the following illustration.

[Visual Basic]

Typically, when you use the DirectDrawSurface7.Flip method to request a surface flip operation, the pointers to surface memory for the primary surface and back buffers are swapped. Flipping is performed by switching pointers that the display device uses for referencing memory, not by copying surface memory. (The exception to this is when DirectDraw is emulating the flip, in which case it simply copies the surfaces. DirectDraw emulates flip operations if a back buffer cannot fit into display memory or if the hardware doesn't support DirectDraw.) When a flipping chain contains a primary surface and more than one back buffer, the pointers are switched in a circular pattern, as shown in the following illustration.

Other surfaces that are attached to a DirectDraw object, but not part of the flipping chain, are unaffected when the Flip method is called.

Remember, DirectDraw flips surfaces by swapping surface memory pointers within DirectDrawSurface objects, not by swapping the objects themselves. This means that, to blit to the back buffer in any type of flipping scheme, you always use the same DirectDrawSurface object — the one that was the back buffer when you created the flipping chain. Conversely, you always perform a flip operation by calling the front surface's Flip method.

[C++]

When working with visible surfaces, such as a primary surface flipping chain or a visible overlay surface flipping chain, the Flip method is asynchronous unless you include the DDFLIP_WAIT flag. On these visible surfaces, the Flip method can return before the actual flip operation occurs in the hardware (because the hardware doesn't flip until the next vertical refresh occurs). While the actual flip operation is pending, the back buffer behind the currently visible surface can't be locked or blitted by calling the IDirectDrawSurface7::Lock, IDirectDrawSurface7::Blt, IDirectDrawSurface7::BltFast, or IDirectDrawSurface7::GetDC methods. If you attempt to call these methods while a flip operation is pending, they will fail and return DDERR_WASSTILLDRAWING. However, if you are using a triple buffered scheme, the rearmost buffer is still available.

[Visual Basic]

When working with visible surfaces, such as a primary surface flipping chain or a visible overlay surface flipping chain, the Flip method is asynchronous unless you include the DDFLIP_WAIT flag. On these visible surfaces, the Flip method can return before the actual flip operation occurs in the hardware (because the hardware doesn't flip until the next vertical refresh occurs). While the actual flip operation is pending, the back buffer behind the currently visible surface can't be locked or blitted by calling the DirectDrawSurface7.Lock, DirectDrawSurface7.Blt, DirectDrawSurface7.BltColorFill, DirectDrawSurface7.BltFast, DirectDrawSurface7.BltFx, DirectDrawSurface7.BltToDC or DirectDrawSurface7.GetDC methods. If you attempt to call these methods while a flip operation is pending, they will fail and raise the DDERR_WASSTILLDRAWING error. However, if you are using a triple buffered scheme, the rearmost buffer is still available.


Blitting to Surfaces

This section is a guide to copying pixels from one DirectDraw surface to another, or from one part of a surface to another.

The following topics are covered:

  • Blitting Basics
  • Blitting with BltFast
  • Blitting with Blt
  • Blit Timing
  • Transparent Blitting
  • Color Fills
  • Blitting to Multiple Windows


Blitting Basics

[C++]

Two methods are available for copying images to a DirectDraw surface: IDirectDrawSurface7::Blt and IDirectDrawSurface7::BltFast. (A third method, IDirectDrawSurface7::BltBatch, is not implemented in this version of DirectX.) These methods are called on the destination surface and receive the source surface as a parameter. The destination and source surfaces can be one and the same, and you don't have to worry about overlap—DirectDraw takes care to preserve all source pixels before overwriting them.

Of the two implemented methods, Blt is the more flexible and BltFast is the faster—but only if there is no hardware blitter. You can determine the blitting capabilities of the hardware from the DDCAPS structure obtained in the lpDDDriverCaps parameter of the IDirectDraw7::GetCaps method. If the dwCaps member contains DDCAPS_BLT, the hardware has at least minimal blitting capabilities.

[Visual Basic]

Five methods are available for copying images to a DirectDraw surface: DirectDrawSurface7.Blt, DirectDrawSurface7.BltColorFill, DirectDrawSurface7.BltFast, DirectDrawSurface7.BltFx and DirectDrawSurface7.BltToDC. These methods are called on the destination surface and receive the source surface as a parameter. The destination and source surfaces can be one and the same, and you don't have to worry about overlap—DirectDraw takes care to preserve all source pixels before overwriting them.

Of the implemented methods, Blt is the more flexible and BltFast is the faster—but only if there is no hardware blitter. You can determine the blitting capabilities of the hardware from the DDCAPS type obtained in the hwCaps parameter of the DirectDraw7.GetCaps method. If the lCaps member contains DDCAPS_BLT, the hardware has at least minimal blitting capabilities.


Blitting with BltFast

[C++]

When using IDirectDrawSurface7::BltFast, you supply a valid rectangle in the source surface from which the pixels are to be copied (or NULL to specify the entire surface), and an x-coordinate and y-coordinate in the destination surface. The source rectangle must be able to fit in the destination surface with its top left corner at that point, or the call will fail with a return value of DDERR_INVALIDRECT. BltFast cannot be used on surfaces that have an attached clipper.

No stretching, mirroring, or other effects can be performed when using BltFast.

BltFast Example

The following example copies pixels from an off-screen surface, lpDDSOffOne, to the primary surface, lpDDSPrimary. The flags ensure that the operation will take place as soon as the blitter is free, and that transparent pixels in the source image will not be copied. (For more information on the meaning of these flags, see Blit Timing and Transparent Blitting .)

lpDDSPrimary->BltFast(
        100, 200,    // Upper left xy of destination
        lpDDSOffOne, // Source surface
        NULL,        // Source rectangle = entire surface
        DDBLTFAST_WAIT | DDBLTFAST_SRCCOLORKEY );
[Visual Basic]

When using DirectDrawSurface7.BltFast, you supply a valid rectangle in the source surface from which the pixels are to be copied (or an empty RECT type to specify the entire surface), and an x-coordinate and y-coordinate in the destination surface. The source rectangle must be able to fit in the destination surface with its top left corner at that point, or the call will fail and raise an error value of DDERR_INVALIDRECT. BltFast cannot be used on surfaces that have an attached clipper.

No stretching, mirroring, or other effects can be performed when using BltFast.

BltFast Example

The following example copies pixels from an off-screen surface, DDSOffOne, to the primary surface, DDSPrimary. The flags ensure that the operation will take place as soon as the blitter is free, and that transparent pixels in the source image will not be copied. (For more information on the meaning of these flags, see Blit Timing and Transparent Blitting.)

DDSPrimary.BltFast(
        100, 200,    // Upper left xy of destination
        DDSOffOne,   // Source surface
        SrcRect,     // Source rectangle, empty RECT = entire surface
        DDBLTFAST_WAIT Or DDBLTFAST_SRCCOLORKEY )


Blitting with Blt

[C++]

When using the IDirectDrawSurface7::Blt method, you supply a valid rectangle in the source surface (or NULL to specify the entire surface), and a rectangle in the destination surface to which the source image will be copied (again, NULL means the rectangle covers the entire surface). If a clipper is attached to the destination surface, the bounds of the destination rectangle can fall outside the surface and clipping will be performed. If there is no clipper, the destination rectangle must fall entirely within the surface or else the method will fail with DDERR_INVALIDRECT. (For more information on clipping, see Clippers.)

Scaling

The Blt method automatically re-scales the source image to fit the destination rectangle. If resizing is not your intention, for best performance you should make sure that your source and destination rectangles are exactly the same size, or else use IDirectDrawSurface7:BltFast. (See Blitting with BltFast.)

Hardware acceleration for scaling depends on the DDFXCAPS_BLT* flags in the dwFXCaps member of the DDCAPS structure for the device. If, for example, a device has the DDFXCAPS_BLTSTRETCHXN capability but not DDFXCAPS_BLTSTRETCHX, it can assist when the x-axis of the source rectangle is being multiplied by a whole number but not when non-integral (arbitrary) scaling is being done.

Devices might also support arithmetic scaling, which is scaling by interpolation rather than simple multiplication or deletion of pixels. For instance, if an axis was being increased by one-third, the pixels would be recolored to provide a closer approximation to the original image than would be produced by the doubling of every third pixel on that axis.

Applications cannot control the type of scaling done by the driver, except by setting the DDBLTFX_ARITHSTRETCHY flag in the dwDDFX member of the DDBLTFX structure passed to Blt. This flag requests that arithmetic stretching be done on the y-axis. Arithmetic stretching on the x-axis and arithmetic shrinking are not currently supported in the DirectDraw API, but a driver may perform them by default.

Other Effects

If you do not require any special effects other than scaling when using Blt, you can pass NULL as the lpDDBltFx parameter. Otherwise you can choose among a variety of effects specified in a DDBLTFX structure. Among these, color fills and mirroring are supported by the HEL, so they are always available. Most other effects depend on hardware support.

For a complete view of the effects capabilities of the HEL, run the DDraw Caps utility supplied with the DirectX SDK and select HEL FX Caps from the HEL menu. For an explanation of the various flags, see DDCAPS. You can also check HEL capabilities within your own application by using the IDirectDraw7::GetCaps method.

When you specify an effect that requires a value in one of the members of the DDBLTFX structure passed to the IDirectDrawSurface7::Blt method, you must also include the appropriate flags in the dwFlags parameter to show which members of the structure are valid.

Some effects require only the setting of a flag in the dwFlags member of DDBLTFX. One of these is DDBLTFX_NOTEARING. You can use this flag when you are blitting animated images directly to the front buffer, so that the blit is timed to coincide with the screen refresh and the possibility of tearing is minimized. Mirroring and rotation are also set by using flags.

Blitting effects include the standard raster operations (ROPs) used by GDI functions such as BitBlt. The only ROPs supported by the HEL are SRCCOPY (the default), BLACKNESS, and WHITENESS. Hardware support for other ROPs can be examined in the DDCAPS structure for the driver. If you wish to use any of the standard ROPS with the Blt method, you flag them in the dwROP member of the DDBLTFX structure.

The dwDDROP member of the DDBLTFX structure is for specifying ROPs specific to DirectDraw. However, no such ROPs are currently defined.

Alpha and Z Values

Opacity and depth values are not currently supported in DirectDraw blits. If alpha values are stored in the pixel format, they simply overwrite any alpha values in the destination rectangle. Values from alpha buffers and z-buffers are ignored. The members of the DDBLTFX structure that have to do with alpha channels and z-buffers (members whose names begin with "dwAlpha" and "dwZ"), and the corresponding flags for Blt, are not used. The same applies to the DDBLTFX_ZBUFFERBASEDEST and DDBLTFX_ZBUFFERRANGE flags in the dwDDFX member of the DDBLTFX structure.

Although z-buffers are currently used only in Direct3D applications, you can use IDirectDrawSurface7::Blt to set the depth value for a z-buffer surface, by setting the DDBLT_DEPTHFILL flag. For more information, see Clearing Depth Buffers.

For an overview of the use of alpha channels and z-buffers in Direct3D, see the following topics:

  • Alpha-blending States
  • What Are Depth Buffers?

Blt Example

The following example, in which it is assumed that lpDDS is a valid IDirectDrawSurface7 pointer, creates a symmetrical image within the surface by mirroring a rectangle from left to right:

RECT     rcSource, rcDest;
DDBLTFX  ddbltfx;

ZeroMemory(&ddbltfx, sizeof(ddbltfx));
ddbltfx.dwSize = sizeof(ddbltfx);
ddbltfx.dwDDFX = DDBLTFX_MIRRORLEFTRIGHT;

rcSource.top = 0; rcSource.left = 0;
rcSource.bottom = 100; rcSource.right = 200;
rcDest.top = 0; rcDest.left = 201;
rcDest.bottom = 100; rcDest.right = 401;

HRESULT hr = lpDDS->Blt(&rcDest,
                        lpDDS,
                        &rcSource,
                        DDBLT_WAIT | DDBLT_DDFX,
                        &ddbltfx);
[Visual Basic]

When using the DirectDrawSurface7.Blt method, you supply a valid rectangle in the source surface (or an empty RECT to specify the entire surface), and a rectangle in the destination surface to which the source image will be copied (again, passing an empty RECT means the rectangle covers the entire surface). If a clipper is attached to the destination surface, the bounds of the destination rectangle can fall outside the surface and clipping will be performed. If there is no clipper, the destination rectangle must fall entirely within the surface or else the method will raise the DDERR_INVALIDRECT error. (For more information on clipping, see Clippers.)

Scaling

The Blt method automatically re-scales the source image to fit the destination rectangle. If resizing is not your intention, for best performance you should make sure that your source and destination rectangles are exactly the same size, or else use DirectDrawSurface7.BltFast. (See Blitting with BltFast.)

Hardware acceleration for scaling depends on the DDFXCAPS_BLT* flags in the lFXCaps member of the DDCAPS type for the device. If, for example, a device has the DDFXCAPS_BLTSTRETCHXN capability but not DDFXCAPS_BLTSTRETCHX, it can assist when the x-axis of the source rectangle is being multiplied by a whole number but not when non-integral (arbitrary) scaling is being done.

Devices might also support arithmetic scaling, which is scaling by interpolation rather than simple multiplication or deletion of pixels. For instance, if an axis was being increased by one-third, the pixels would be recolored to provide a closer approximation to the original image than would be produced by the doubling of every third pixel on that axis.

Applications cannot control the type of scaling done by the driver, except by setting the DDBLTFX_ARITHSTRETCHY flag in the lDDFX member of the DDBLTFX type passed to Blt. This flag requests that arithmetic stretching be done on the y-axis. Arithmetic stretching on the x-axis and arithmetic shrinking are not currently supported in the DirectDraw API, but a driver may perform them by default.

Other Effects

If you want to use any special effects other than scaling use the DirectDrawSurface7.BltFx method. In this method, you can choose among a variety of effects specified in a DDBLTFX type. Among these, color fills and mirroring are supported by the HEL, so they are always available. Most other effects depend on hardware support.

For a complete view of the effects capabilities of the HEL, run the DDraw Caps utility supplied with the DirectX SDK and select HEL FX Caps from the HEL menu. For an explanation of the various flags, see DDCAPS. You can also check HEL capabilities within your own application by using the DirectDraw7.GetCaps method.

When you specify an effect that requires a value in one of the members of the DDBLTFX structure passed to the DirectDrawSurface7.BltFx method, you must also include the appropriate flags in the flags parameter to show which members of the type are valid.

Some effects require only the setting of a flag in the lDDFX member of DDBLTFX. One of these is DDBLTFX_NOTEARING. You can use this flag when you are blitting animated images directly to the front buffer, so that the blit is timed to coincide with the screen refresh and the possibility of tearing is minimized. Mirroring and rotation are also set by using flags.

Blitting effects include the standard raster operations (ROPs) used by GDI functions such as BitBlt. The only ROPs supported by the HEL are SRCCOPY (the default), BLACKNESS, and WHITENESS. Hardware support for other ROPs can be examined in the DDCAPS type for the driver. If you wish to use any of the standard ROPS with the BltFx method, you flag them in the lROP member of the DDBLTFX type.

The lDDROP member of the DDBLTFX type is for specifying ROPs specific to DirectDraw. However, no such ROPs are currently defined.

Alpha and Z Values

Opacity and depth values are not currently supported in DirectDraw blits. If alpha values are stored in the pixel format, they simply overwrite any alpha values in the destination rectangle. Values from alpha buffers and z-buffers are ignored. The members of the DDBLTFX type that have to do with alpha channels and z-buffers (members whose names begin with "lAlpha" and "lZ"), and the corresponding flags for BltFx, are not used. The same applies to the DDBLTFX_ZBUFFERBASEDEST and DDBLTFX_ZBUFFERRANGE flags in the lDDFX member of the DDBLTFX structure.

Although z-buffers are currently used only in Direct3D applications, you can use DirectDrawSurface7.Blt to set the depth value for a z-buffer surface, by setting the DDBLT_DEPTHFILL flag. For more information, see Clearing Depth Buffers.

For an overview of the use of alpha channels and z-buffers in Direct3D, see the following topics:

  • Alpha-blending States
  • What Are Depth Buffers?

Blt Example

The following example, in which it is assumed that DDS is a valid DirectDrawSurface7 object, creates a symmetrical image within the surface by mirroring a rectangle from left to right:

rcSource As RECT
rcDest As RECT
ddbltfx as DDBLTFX

ddbltfx.lDDFX = DDBLTFX_MIRRORLEFTRIGHT

rcSource.top = 0
rcSource.left = 0
rcSource.bottom = 100
rcSource.right = 200
rcDest.top = 0
rcDest.left = 201
rcDest.bottom = 100
rcDest.right = 401

DDS.BltFx(rcDest,
          DDS,
          rcSource,
          DDBLT_WAIT Or DDBLT_DDFX,
          ddbltfx);


Blit Timing

[C++]

When you copy pixels to a surface using either IDirectDrawSurface7::Blt or IDirectDrawSurface7::BltFast, the method might fail with DDERR_WASSTILLDRAWING because the hardware blitter was not ready to accept the command.

If your application has no urgent business to perform while waiting for the blitter to come back into a state of readiness, you can specify the DDBLT_WAIT flag in the dwFlags parameter of Blt, or the equivalent DDBLTFAST_WAIT flag for BltFast. The flag causes the method to wait until the blit can be handed off to the blitter (or until an error other than DDERR_WASSTILLDRAWING occurs).

Blt accepts another flag, DDBLT_ASYNC, that takes advantage of any hardware FIFO (first in, first out) queuing capabilities.

[Visual Basic]

When you copy pixels to a surface using either DirectDrawSurface7.Blt, DirectDrawSurface7.BltColorFill, DirectDrawSurface7.BltFast, DirectDrawSurface7.BltFx or DirectDrawSurface7.BltToDC, the method might fail and raise a DDERR_WASSTILLDRAWING error because the hardware blitter was not ready to accept the command.

If your application has no urgent business to perform while waiting for the blitter to come back into a state of readiness, you can specify the DDBLT_WAIT flag in the flags parameter of Blt, or the equivalent DDBLTFAST_WAIT flag for BltFast. The flag causes the method to wait until the blit can be handed off to the blitter (or until an error other than DDERR_WASSTILLDRAWING occurs).

Blt accepts another flag, DDBLT_ASYNC, that takes advantage of any hardware FIFO (first in, first out) queuing capabilities.


Transparent Blitting

This section discusses the theory and practice of using transparent blitting to copy parts of a rectangular image selectively, using source and destination color keys.

The concepts are introduced in the following topic:

  • What Is Transparent Blitting?

Information about the implementation of transparent blitting in DirectDraw is contained in the following topics:

  • Color Key Format
  • Setting Color Keys
  • Blitting with Color Keys


What Is Transparent Blitting?

Transparent blitting enables you to create the illusion of nonrectangular blits when animating sprites. A sprite image is usually nonrectangular, but blits are always rectangular, so every pixel within the sprite's bounding rectangle becomes part of the data transfer. With transparent blitting, each pixel that is not part of the sprite image is treated as transparent when the blitter is moving the image to its destination, so that it does not overwrite the color in that pixel on the background image.

The artist creating the sprite chooses an arbitrary color or range of colors to be used as the transparency color key. This is typically a single uncommon color that the artist doesn't use for anything but transparency, and it is used to fill in all parts of the sprite rectangle that are not part of the desired image. At run time you set the color key for the surface containing the sprite. (If you wish, you can automatically set it to the color of the pixel in the upper left corner of the image.) Subsequent blits can take advantage of that color key, ignoring the pixels that match it. This type of color key is known as a source color key.

You can also use a color key on the destination surface, provided the hardware supports destination color keying. This destination color key is used for pixels that can be overwritten by a sprite. For example, the artist might be working on a foreground image that sprites are supposed to pass behind, such as the wall of a room with a window to the outside. The artist chooses an arbitrary color—one that isn't used elsewhere in the image—to represent the sky outside the window. When you set this color key for the destination surface and then blit a sprite to that surface, the sprite's pixels will overwrite only pixels that are using the destination color key. In the example, the sprite appears only in the window, but not on the wall or window frame. As a result, the sprite seems to be outside the room.

Source and destination color keys can be combined. In the example, the sprite could use a source color key so that its entire bounding rectangle does not block out the sky background.


Color Key Format

[C++]

A color key is described in a DDCOLORKEY structure. If the color key is a single color, both members of this structure should be assigned the same value. Otherwise the color key is a range of colors.

Color keys are specified using the pixel format of a surface. If a surface is in a palettized format, the color key is given as an index or a range of indices. If the surface is in a non-palattized display mode, the color keys are specified in the raw pixel format. For instance, to set a bright purple color key in 16-bit 5:6:5 mode, you would use a value of 0xf81F (All 5 red bits are set, and all 5 blue bits are set).

Some examples of valid color keys follow:

8-bit palettized mode

// Palette entry 26 is the color key.
dwColorSpaceLowValue = 26;
dwColorSpaceHighValue = 26;

16-bit color mode

// Color is bright purple
dwColorSpaceLowValue = 0xf81F;
dwColorSpaceHighValue = 0xf81F;

Support for a range of colors rather than a single color is hardware-dependent. Check the dwCKeyCaps member of the DDCAPS structure for the hardware. The HEL does not support color ranges.

[Visual Basic]

A color key is described in a DDCOLORKEY type. If the color key is a single color, both members of this structure should be assigned the same value. Otherwise the color key is a range of colors.

Color keys are specified using the pixel format of a surface. If a surface is in a palettized format, the color key is given as an index or a range of indices. If the surface is in a non-palattized display mode, the color keys are specified in the raw pixel format. For instance, to set a bright purple color key in 16-bit 5:6:5 mode, you would use a value of 0xf81F (All 5 red bits are set, and all 5 blue bits are set).

Some examples of valid color keys follow:

8-bit palettized mode

// Palette entry 26 is the color key.
low = 26
high = 26

24-bit true-color mode

// Color red in hex is the color key.
low = &H000000FF
high = &H000000FF

Support for a range of colors rather than a single color is hardware-dependent. Check the lCKeyCaps member of the DDCAPS type for the hardware. The HEL does not support color ranges.


Setting Color Keys

[C++]

You can set the source or destination color key for a surface either when creating it or afterwards.

To set a color key or keys when creating a surface, you assign the appropriate color values to one or both of the ddckCKSrcBlt and ddckCKDestBlt members of the DDSURFACEDESC2 structure that is passed to IDirectDraw7::CreateSurface. To enable the color key for blitting, you must also include one or both of DDSD_CKSRCBLT or DDSD_CKDESTBLT in the dwFlags member.

To set a color key for an existing surface you use the IDirectDrawSurface7::SetColorKey method. You specify a key in the lpDDColorKey parameter and set either DDCKEY_SRCBLT or DDCKEY_DESTBLT in the dwFlags parameter to indicated whether you are setting a source or destination key. If the DDCOLORKEY structure contains a range of colors, you must also set the DDCKEY_COLORSPACE flag. If this flag is not set, only the dwColorSpaceLowValue member of the structure is used.

[Visual Basic]

You can set the source or destination color key for a surface either when creating it or afterwards.

To set a color key or keys when creating a surface, you assign the appropriate color values to one or both of the ddckCKSrcBlt and ddckCKDestBlt members of the DDSURFACEDESC2 type that is passed to DirectDraw7.CreateSurface. To enable the color key for blitting, you must also include one or both of DDSD_CKSRCBLT or DDSD_CKDESTBLT in the lFlags member.

To set a color key for an existing surface you use the DirectDrawSurface7.SetColorKey method. You specify a key in the val parameter and set either DDCKEY_SRCBLT or DDCKEY_DESTBLT in the flags parameter to indicated whether you are setting a source or destination key. If the DDCOLORKEY type contains a range of colors, you must also set the DDCKEY_COLORSPACE flag. If this flag is not set, only the low member of the type is used.


Blitting with Color Keys

[C++]

If you want to use color keys for surfaces when calling the IDirectDrawSurface7::BltFast method, you must set one or both of the DDBLTFAST_SRCCOLORKEY or DDBLTFAST_DESTCOLORKEY flags in the dwTrans parameter.

In order to use colors keys when calling IDirectDrawSurface7:Blt, you pass one or both of the DDBLT_KEYSRC or DDBLT_KEYDEST flags in the dwFlags parameter. Alternatively, you can put the appropriate color values in the ddckDestColorkey and ddckSrcColorkey members of the DDBLTFX structure that is passed to the method through the lpDDBltFx parameter. In this case you must also set the DBLT_KEYSRCOVERRIDE or DDBLT_KEYDESTOVERRIDE flag, or both, in the dwFlags parameter, so that the selected keys are taken from the DDBLTFX structure rather than from the surface properties.

[Visual Basic]

If you want to use color keys for surfaces when calling the DirectDrawSurface7.BltFast method, you must set one or both of the DDBLTFAST_SRCCOLORKEY or DDBLTFAST_DESTCOLORKEY flags in the trans parameter.

In order to use colors keys when calling DirectDrawSurface7:Blt, you pass one or both of the DDBLT_KEYSRC or DDBLT_KEYDEST flags in the flags parameter. Alternatively, you can use the DirectDrawSurface7:BltFx method and put the appropriate color values in the ddckDestColorkey_high, ddckDestColorkey_low, ddckSrcColorkey_high and ddckSrcColorkey_low members of the DDBLTFX structure that is passed to the method through the BltFx parameter. In this case you must also set the DBLT_KEYSRCOVERRIDE or DDBLT_KEYDESTOVERRIDE flag, or both, in the flags parameter, so that the selected keys are taken from the DDBLTFX type rather than from the surface properties.


Color Fills

[C++]

In order to fill all or part of a surface with a single color, you can use the IDirectDrawSurface7::Blt method with the DDBLT_COLORFILL flag. This technique allows you to quickly erase an area or draw a solid-colored background.

The following example fills an entire surface with the color blue, after obtaining the numerical value for blue from the pixel format:

/* It is assumed that lpDDS is a valid pointer to
   an IDirectDrawSurface7 interface. */

HRESULT ddrval;
DDPIXELFORMAT ddpf;

ddpf.dwSize = sizeof(ddpf);
if (SUCCEEDED(lpDSS->GetPixelFormat(&ddpf))
{
    DDBLTFX ddbltfx;

    ddbltfx.dwSize = sizeof(ddbltfx);
    ddbltfx.dwFillColor = ddpf.dwBBitMask; // Pure blue

    ddrval = lpDDS->Blt(
        NULL,        // Destination is entire surface
        NULL,        // No source surface
        NULL,        // No source rectangle
        DDBLT_COLORFILL, &ddbltfx);

    switch(ddrval)
    {
        case DDERR_WASSTILLDRAWING:
            .
            .
            .
        case DDERR_SURFACELOST:
            .
            .
            .
        case DD_OK:
            .
            .
            .
        default:
    }
}
[Visual Basic]

In order to fill all or part of a surface with a single color, you can use the DirectDrawSurface7.BltColorFill method. This technique allows you to quickly erase an area or draw a solid-colored background.


Blitting to Multiple Windows

You can use a DirectDraw object and a DirectDrawClipper object to blit to multiple windows created by an application running at the normal cooperative level. For more information, see Using a Clipper with Multiple Windows.

Creating multiple DirectDraw objects that blit to each other's primary surface is not recommended.


Losing and Restoring Surfaces

The surface memory associated with a DirectDrawSurface object may be freed, while the DirectDrawSurface objects representing these pieces of surface memory are not necessarily released. When a DirectDrawSurface object loses its surface memory, many methods return DDERR_SURFACELOST and perform no other action.

[C++]

Surfaces can be lost because the display mode was changed or because another application received exclusive access to the display card and freed all of the surface memory currently allocated on the card. The IDirectDrawSurface7::Restore method re-creates these lost surfaces and reconnects them to their DirectDrawSurface object. If your application uses more than one surface, you can call the IDirectDraw7::RestoreAllSurfaces method to restore all of your surfaces at once.

[Visual Basic]

Surfaces can be lost because the display mode was changed or because another application received exclusive access to the display card and freed all of the surface memory currently allocated on the card. The DirectDrawSurface7.Restore method re-creates these lost surfaces and reconnects them to their DirectDrawSurface object. If your application uses more than one surface, you can call the DirectDraw7.RestoreAllSurfaces method to restore all of your surfaces at once.

Restoring a surface doesn't reload any bitmaps that may have existed in the surface prior to being lost. You must completely reconstitute the graphics they once held.


COM Reference Count Semantics for Surfaces

[Visual Basic]

The information in this topic pertains only to applications written in C++.

[C++]

Being built upon COM means that DirectDraw follows certain rules that employ reference counts to manage object lifetimes. For a conceptual overview, see the COM documentation; a DirectDraw-centered discussion of the topic is found in Parent and Child Object Lifetimes.

By COM rules, when an interface pointer is copied by setting it to another variable or passing to another object, that copy represents another reference to the object, and therefore the IUnknown::AddRef method of the interface must be called to reflect the change. Not only should you follow COM reference counting rules when working with DirectDraw objects, but you should become familiar with the situations in which DirectDraw internally updates reference counts. Some DirectDraw methods—mostly those involving complex surface flipping chains—affect the reference counts of the surfaces involved, while methods involving clippers or palettes affect the reference counts of those objects. Knowing about these situations can make the difference in your application's stability and can prevent memory leaks. This section presents information divided into the following topics:

  • When Reference Counts Will Change
  • Reference Counts for Complex Surfaces
  • Releasing Surfaces

Note: There are some things to remember about the reference count of the DirectDraw object, in addition to the relationships discussed in this section. For more information, see Parent and Child Object Lifetimes in The DirectDraw Object.


When Reference Counts Will Change

[Visual Basic]

The information in this topic pertains only to applications written in C++.

[C++]

There are several DirectDraw methods that affect the reference count of a surface, and a few that affect other objects you can associate with a surface. You can think of these situations as "surface-only changes" and "cross-object changes":

Surface-only changes
Surface-only changes, as the name states, only affect the reference count of a surface object. For example, you might use the IDirectDraw7::EnumSurfaces to enumerate the current surfaces that fit a particular description. When the method invokes the callback function that you provide, it passes a pointer to an IDirectDrawSurface7 interface, but it increments the reference count for the object before your application receives the pointer. It's your responsibility to release the object when you are finished with it. This will typically be at the end of your callback routine, or later if you choose to keep the object.

Most other surface-only changes affect the reference counts of complex surfaces, such as a flipping chain. Reference counts are a little more tricky for complex surfaces, because (in most cases) DirectDraw treats a complex surface as if it was a single object, even though it is a set of surfaces. In short, the IDirectDrawSurface7::GetAttachedSurface and IDirectDrawSurface7::AddAttachedSurface methods increment reference counts of surfaces, and IDirectDrawSurface7::DeleteAttachedSurface decrements the reference count. These methods don't affect the counts of any surfaces attached to the current surface. See the references for these methods and Reference Counts for Complex Surfaces for a additional details.

Cross-object changes
Cross-object reference count changes occur when you create an association between a surface and another object that performs a task for the surface, such as a clipper or a palette.

The IDirectDrawSurface7::SetClipper and IDirectDrawSurface7::SetPalette methods increment the reference count of the object being attached. After they are attached, the surface manages them; if the surface is released, it automatically releases any objects it is using. (For this reason, some applications release the interface for the object after these calls succeed. This is a perfectly valid practice.)

Once a clipper or palette is attached to a surface, you can call the IDirectDrawSurface7::GetClipper and IDirectDrawSurface7::GetPalette methods to retrieve them again. Because these methods return a copy of an interface pointer, they implicitly increment the reference count for the object being retrieved. When you're done with the interfaces, don't forget to release them—the objects that the interfaces represent won't disappear so long as the surface they are attached to still holds a reference to them.


Reference Counts for Complex Surfaces

[Visual Basic]

The information in this topic pertains only to applications written in C++.

[C++]

The methods you use to manipulate a complex surface like a flipping chain all use surface interface pointers, and therefore they all affect the reference counts of the surfaces. Because a complex surface is really a series of single surfaces, the reference count relationships require a little more consideration. As you might expect, the IDirectDrawSurface7::GetAttachedSurface method returns the surface interface for a surface attached to the current surface. It does this after incrementing the reference count of the interface being retrieved; it's up to you to release the interface when you no longer need it. The IDirectDrawSurface7::AddAttachedSurface method attaches a new surface to the current one. Similarly, AddAttachedSurface increments the count for the surface being attached. You would use the IDirectDrawSurface7::DeleteAttachedSurface method to remove the surface from the chain and implicitly decrease its reference count.

What isn't immediately clear about these methods is that they don't affect the reference counts of the other objects that make up the complex surface. The GetAttachedSurface method simply increments the reference count of the surface it's retrieving, it doesn't affect the counts of the surfaces on which it depends. (The same situation applies to an explicit call to IUnknown::AddRef.) This means that the reference count for primary surface in a complex surface can reach zero before its subordinate surfaces reach zero. When the primary surface reference count reaches zero, all other surfaces attached to it are released regardless of their current reference counts. (It's like a tree: if you cut the base, the whole thing falls. In this case, the primary surface is the base.) Attempts to access subordinate surfaces after the primary surface has been deallocated will result in memory faults.

To avoid problems, make sure that your application has released all subordinate surface references before attempting to release the primary surface. It might be helpful to track the references your application holds, only accessing subordinate surface interfaces when you're sure that you also hold a reference the primary surface.


Releasing Surfaces

[C++]

Like all COM interfaces, you must release surfaces by calling their IDirectDrawSurface7::Release method when you no longer need them.

Each surface you individually create must be explicitly released. However, if you implicitly created multiple surfaces with a single call to IDirectDraw7::CreateSurface, such as a flipping chain, you need only release the front buffer. In this case, any pointers you might have to back buffer surfaces are implicitly released and can no longer be used.

Explicitly releasing a back buffer surface doesn't affect the reference count of the other surfaces in the chain.

[Visual Basic]

You must release surfaces by setting the surface to Nothing when you no longer need them.

Each surface you individually create must be explicitly released. However, if you implicitly created multiple surfaces with a single call to DirectDraw7.CreateSurface, such as a flipping chain, you need only release the front buffer. In this case, any pointers you might have to back buffer surfaces are implicitly released and can no longer be used.


Enumerating Surfaces

[C++]

By calling the IDirectDraw7::EnumSurfaces method you can request that DirectDraw enumerate surfaces in various ways. The EnumSurfaces method enables you to look for surfaces that fit, or don't fit, a provided surface description. DirectDraw calls a EnumSurfacesCallback that you include with the call for each enumerated surface.

There are two general ways to search—you can search for surfaces that the DirectDraw object has already created, or for surfaces that the DirectDraw object is capable of creating at the time (given the surface description and available memory). You specify what type of search you want by combining flags in the method's dwFlags parameter.

Enumerating existing surfaces

This is the most common type of enumeration. You enumerate existing surfaces by calling EnumSurfaces, specifying a combination of the DDENUMSURFACES_DOESEXIST search-type flag and one of the matching flags (DDENUMSURFACES_MATCH, DDENUMSURFACES_NOMATCH, or DDENUMSURFACES_ALL) in the dwFlags parameter. If you're enumerating all existing surfaces, you can set the lpDDSD parameter to NULL, otherwise set it to the address of an initialized DDSURFACEDESC2 structure that describes the surface for which you're looking. You can set the third parameter, lpContext, to an address that will be passed to the enumeration function you specify in the fourth parameter, lpEnumSurfacesCallback.

The following code fragment shows what this call might look like to enumerate all of a DirectDraw object's existing surfaces.

HRESULT ddrval;
  ddrval = lpDD->EnumSurfaces(DDENUMSURFACES_DOESEXIST |
                              DDENUMSURFACES_ALL, NULL, NULL,
                              EnumCallback);
  if (FAILED(ddrval))
      return FALSE;

When searching for existing surfaces that fit a specific description, DirectDraw determines a match by comparing each member of the provided surface description to those of the existing surfaces. Only exact matches are enumerated. DirectDraw increments the reference counts of the enumerated surfaces, so make sure to release a surface if you don't plan to use it (or when you're done with it).

Enumerating possible surfaces

This type of enumeration is less common than enumerating existing surfaces, but it can be helpful to determine if a surface is supported before you attempt to create it. To perform this search, combine the DDENUMSURFACES_CANBECREATED and DDENUMSURFACES_MATCH flags when you call IDirectDraw7::EnumSurfaces (no other flag combinations are valid). The DDSURFACEDESC2 structure you use with the call must be initialized to contain information about the surface characteristics that DirectDraw will use.

To enumerate surfaces that use a particular pixel format, include the DDSD_PIXELFORMAT flag in the dwFlags member of the DDSURFACEDESC2 structure. Additionally, initialize the DDPIXELFORMAT structure in the surface description and set its dwFlags member to contain the desired pixel format flags—DDPF_RGB, DDPF_YUV, or both. You need not set any other pixel format values.

If you include the DDSD_HEIGHT and DDSD_WIDTH flags in the DDSURFACEDESC2 structure, you can specify the desired dimensions in the dwHeight and dwWidth members. If you exclude these flags, DirectDraw uses the dimensions of the primary surface.

The following code fragment shows what this call could look like to enumerate all valid surface characteristics for 96×96 RGB or YUV surfaces:

    DDSURFACEDESC2 ddsd;
    HRESULT        ddrval;
    ZeroMemory(&ddsd, sizeof(ddsd));

    ddsd.dwSize  = sizeof(ddsd);
    ddsd.dwFlags = DDSD_CAPS | DDSD_PIXELFORMAT |
                   DDSD_HEIGHT | DDSD_WIDTH;
    ddsd.ddpfPixelFormat.dwFlags = DDPF_YUV | DDPF_RGB;
    ddsd.dwHeight = 96;
    ddsd.dwWidth  = 96;

    ddrval = lpDD->EnumSurfaces(
                     DDENUMSURFACES_CANBECREATED | DDENUMSURFACES_MATCH,
                     &ddsd, NULL, EnumCallback);
    if (ddrval != DD_OK)
        return FALSE;

When DirectDraw enumerates possible surfaces, it actually attempts to create a temporary surface that has the desired characteristics. If the attempt succeeds, then DirectDraw calls the provided EnumSurfacesCallback function with only the characteristics that worked; it does not provide the callback function with pointer to the temporary surface. Do not assume that a surface isn't supported if it isn't enumerated. The attempt by DirectDraw to create a temporary surface could fail due to memory constraints that exist at the time of the call, resulting in those characteristics not being enumerated, even if the driver actually supports them.

[Visual Basic]

By calling the DirectDraw7.GetSurfacesEnum method you can request that DirectDraw enumerate surfaces in various ways. The GetSurfacesEnum method enables you to look for surfaces that fit, or don't fit, a provided surface description. This method creates a DirectDrawEnumSurfaces object which is then used to query for individual surface descriptions.

There are two general ways to search—you can search for surfaces that the DirectDraw object has already created, or for surfaces that the DirectDraw object is capable of creating at the time (given the surface description and available memory). You specify what type of search you want by combining flags in the method's flags parameter.

Enumerating existing surfaces

This is the most common type of enumeration. You enumerate existing surfaces by calling GetSurfacesEnum, specifying a combination of the DDENUMSURFACES_DOESEXIST search-type flag and one of the matching flags (DDENUMSURFACES_MATCH, DDENUMSURFACES_NOMATCH, or DDENUMSURFACES_ALL) in the flags parameter. If you're enumerating all existing surfaces, you can set the desc parameter to Nothing, otherwise set it to an initialized DDSURFACEDESC2 type that describes the surface for which you're looking.

The following code fragment shows what this call might look like to enumerate all of a DirectDraw object's existing surfaces. This assumes DD is a valid DirectDraw7 object and DDSurfEnum is a valid DirectDrawEnumSurfaces object.

    DD.GetSurfacesEnum(DDENUMSURFACES_DOESEXIST Or
                       DDENUMSURFACES_ALL, Nothing)
                       As DDSurfEnum

When searching for existing surfaces that fit a specific description, DirectDraw determines a match by comparing each member of the provided surface description to those of the existing surfaces. Only exact matches are filled into the DirectDrawEnumSurfaces object.

Enumerating possible surfaces

This type of enumeration is less common than enumerating existing surfaces, but it can be helpful to determine if a surface is supported before you attempt to create it. To perform this search, combine the DDENUMSURFACES_CANBECREATED and DDENUMSURFACES_MATCH flags when you call DirectDraw7.GetSurfacesEnum (no other flag combinations are valid). The DDSURFACEDESC2 type you use with the call must be initialized to contain information about the surface characteristics that DirectDraw will use.

To enumerate surfaces that use a particular pixel format, include the DDSD_PIXELFORMAT flag in the lFlags member of the DDSURFACEDESC2 type. Additionally, initialize the DDPIXELFORMAT type in the surface description and set its lFlags member to contain the desired pixel format flags—DDPF_RGB, DDPF_YUV, or both. You need not set any other pixel format values.

If you include the DDSD_HEIGHT and DDSD_WIDTH flags in the DDSURFACEDESC2 structure, you can specify the desired dimensions in the lHeight and lWidth members. If you exclude these flags, DirectDraw uses the dimensions of the primary surface.

The following code fragment shows what this call could look like to enumerate all valid surface characteristics for 96×96 RGB or YUV surfaces:

    Dim ddsd As DDSURFACEDESC2

    ddsd.lFlags = DDSD_CAPS Or DDSD_PIXELFORMAT Or
                  DDSD_HEIGHT Or DDSD_WIDTH
    ddsd.ddpfPixelFormat.lFlags = DDPF_YUV Or DDPF_RGB
    ddsd.lHeight = 96
    ddsd.lWidth  = 96

    DD.GetSurfacesEnum(
                       DDENUMSURFACES_CANBECREATED Or DDENUMSURFACES_MATCH,
                       ddsd) As DDSurfEnum

When DirectDraw enumerates possible surfaces, it actually attempts to create a temporary surface that has the desired characteristics. If the attempt succeeds, then DirectDraw fills the DirectDrawEnumSurfaces object with only the characteristics that worked; it does return the temporary surface. Do not assume that a surface isn't supported if it isn't enumerated. The attempt by DirectDraw to create a temporary surface could fail due to memory constraints that exist at the time of the call, resulting in those characteristics not being enumerated, even if the driver actually supports them.


Updating Surface Characteristics

[Visual Basic]

The information in this topic pertains only to applications written in C++.

[C++]

You can update the characteristics of an existing surface by using the IDirectDrawSurface7::SetSurfaceDesc method. With this method, you can change the pixel format and location of a DirectDrawSurface object's surface memory to system memory that your application has explicitly allocated. This is useful as it allows a surface to use data from a previously allocated buffer without copying. The new surface memory is allocated by the client application and, as such, the client application must also deallocate it.

When calling the IDirectDrawSurface7::SetSurfaceDesc method, the lpddsd parameter must be the address of a DDSURFACEDESC2 structure that describes the new surface memory as well as a pointer to that memory. Within the structure, you can only set the dwFlags member to reflect valid members for the location of the surface memory, dimensions, pitch, and pixel format. Therefore, dwFlags can only contain combinations of the DDSD_WIDTH, DDSD_HEIGHT, DDSD_PITCH, DDSD_LPSURFACE, and DDSD_PIXELFORMAT flags, which you set to indicate valid structure members.

Before you set the values in the structure, you must allocate memory to hold the surface. The size of the memory you allocate is important. Not only do you need to allocate enough memory to accommodate the surface's width and height, but you need to have enough to make room for the surface pitch, which must be a QWORD (8 byte) multiple. Remember, pitch is measured in bytes, not pixels.

When setting surface values in the structure, the lpSurface member is a pointer to the memory you allocated and the dwHeight and dwWidth members describe the surface dimensions in pixels. If you specify surface dimensions, you must fill the lPitch member to reflect the surface pitch as well. Pitch must be a QWORD multiple. Likewise, if you specify pitch, you must also specify a width value. Lastly, the ddpfPixelFormat member describes the pixel format for the surface. With the exception of the lpSurface member, if you don't specify a value for these members, the method defaults to using the value from the current surface.

There are some restrictions you must be aware of when using IDirectDrawSurface7::SetSurfaceDesc, some of which are common sense. For example, the lpSurface member of the DDSURFACEDESC2 structure must be a valid pointer to a system memory (the method doesn't support video memory pointers at this time). Also, the dwWidth and dwHeight members must be nonzero values. Lastly, you cannot reassign the primary surface or any surfaces within the primary's flipping chain.

You can set the same memory for multiple DirectDrawSurface objects, but you must take care that the memory is not deallocated while it is assigned to any surface object.

Using the SetSurfaceDesc method incorrectly will cause unpredictable behavior. The DirectDrawSurface object will not deallocate surface memory that it didn't allocate. Therefore, when the surface memory is no longer needed, it is your responsibility to deallocate it. However, when SetSurfaceDesc is called, DirectDraw frees the original surface memory that it implicitly allocated when creating the surface.


Accessing Surface Memory Directly

[C++]

You can directly access the frame buffer or off-screen surface memory by using the IDirectDrawSurface7::Lock method. When you call this method, the lpDestRect parameter is a pointer to a RECT structure that describes the rectangle on the surface you want to access directly. To request that the entire surface be locked, set lpDestRect to NULL. Also, you can specify a RECT that covers only a portion of the surface. Providing that no two rectangles overlap, two threads or processes can simultaneously lock multiple rectangles in a surface.

The Lock method fills a DDSURFACEDESC2 structure with all the information you need to properly access the surface memory. The structure includes information about the pitch (or stride) and the pixel format of the surface, if different from the pixel format of the primary surface. When you finish accessing the surface memory, call the IDirectDrawSurface7::Unlock method to unlock it.

While you have a surface locked, you can directly manipulate the contents. The following list describes some tips for avoiding common problems with directly rendering surface memory:

  • Never assume a constant display pitch. Always examine the pitch information returned by the IDirectDrawSurface7::Lock method. This pitch can vary for a number of reasons, including the location of the surface memory, the type of display card, or even the version of the DirectDraw driver. For more information, see Width vs. Pitch.
  • Make certain you blit to unlocked surfaces. DirectDraw blit methods will fail, returning DDERR_SURFACEBUSY or DDERR_LOCKEDSURFACES, if called on a locked surface. Similarly, GDI blit functions fail without returning error values if called on a locked surface that exists in display memory.
  • Limit your application's activity while a surface is locked. While a surface is locked, DirectDraw often holds the Win16Mutex (also known as the Win16Lock) so that gaining access to surface memory can occur safely. The Win16Mutex serializes access to GDI and USER dynamic-link libraries, shutting down Windows for the duration between the IDirectDrawSurface7::Lock and IDirectDrawSurface7::Unlock calls. The IDirectDrawSurface7::GetDC method implicitly calls Lock, and the IDirectDrawSurface7::ReleaseDC implicitly calls Unlock.
  • Always copy data aligned to display memory. (Windows 95 and Windows 98 use a page fault handler, Vflatd.386, to implement a virtual flat-frame buffer for display cards with bank-switched memory. The handler allows these display devices to present a linear frame buffer to DirectDraw. Copying data unaligned to display memory can cause the system to suspend operations if the copy spans memory banks.)

Unless you include the DDLOCK_NOSYSLOCK flag when you call the Lock method, locking the surface typically causes DirectDraw to take the Win16Mutex. During the Win16Mutex all other applications, including Windows, cease execution. Since the Win16Mutex stops applications from executing, standard debuggers cannot be used while the lock is held. Kernel debuggers can be used during this period. DirectDraw always takes the Win16Mutex when locking the primary surface.

If a blit is in progress when you call IDirectDrawSurface7::Lock, the method will return immediately with an error, as a lock cannot be obtained. To prevent the error, use the DDLOCK_WAIT flag to cause the method to wait until a lock can be successfully obtained.

Locking portions of the primary surface can interfere with the display of a software cursor. If the cursor intersects the locked rectangle, it is hidden for the duration of the lock. If it doesn't intersect the rectangle, it is frozen for the duration of the lock. Neither of these effects occurs if the entire surface is locked.

[Visual Basic]

You can directly access the frame buffer or off-screen surface memory by using the DirectDrawSurface7.Lock method. When you call this method, the r parameter is a RECT type that describes the rectangle on the surface you want to access directly. To request that the entire surface be locked, pass an empty RECT. Also, you can specify a RECT that covers only a portion of the surface.

The Lock method fills a DDSURFACEDESC2 type with all the information you need to properly access the surface memory. The structure includes information about the pitch (or stride) and the pixel format of the surface, if different from the pixel format of the primary surface. When you finish accessing the surface memory, call the DirectDrawSurface7.Unlock method to unlock it.

While you have a surface locked, you can directly manipulate the contents. The following list describes some tips for avoiding common problems with directly rendering surface memory:

  • Never assume a constant display pitch. Always examine the pitch information returned by the DirectDrawSurface7.Lock method. This pitch can vary for a number of reasons, including the location of the surface memory, the type of display card, or even the version of the DirectDraw driver. For more information, see Width vs. Pitch.
  • Make certain you blit to unlocked surfaces. DirectDraw blit methods will fail, raising DDERR_SURFACEBUSY or DDERR_LOCKEDSURFACES, if called on a locked surface. Similarly, GDI blit functions fail without returning error values if called on a locked surface that exists in display memory.
  • Limit your application's activity while a surface is locked. While a surface is locked, DirectDraw often holds the Win16Mutex (also known as the Win16Lock) so that gaining access to surface memory can occur safely. The Win16Mutex serializes access to GDI and USER dynamic-link libraries, shutting down Windows for the duration between the DirectDrawSurface7.Lock and DirectDrawSurface7.Unlock calls. The DirectDrawSurface7.GetDC method implicitly calls Lock, and the DirectDrawSurface7.ReleaseDC implicitly calls Unlock.
  • Always copy data aligned to display memory. (Windows 95 and Windows 98 use a page fault handler, Vflatd.386, to implement a virtual flat-frame buffer for display cards with bank-switched memory. The handler allows these display devices to present a linear frame buffer to DirectDraw. Copying data unaligned to display memory can cause the system to suspend operations if the copy spans memory banks.)

Unless you include the DDLOCK_NOSYSLOCK flag when you call the Lock method, locking the surface typically causes DirectDraw to take the Win16Mutex. During the Win16Mutex all other applications, including Windows, cease execution. Since the Win16Mutex stops applications from executing, standard debuggers cannot be used while the lock is held. Kernel debuggers can be used during this period. DirectDraw always takes the Win16Mutex when locking the primary surface.

If a blit is in progress when you call DirectDrawSurface7.Lock, the method will return immediately with an error, as a lock cannot be obtained. To prevent the error, use the DDLOCK_WAIT flag to cause the method to wait until a lock can be successfully obtained.

Locking portions of the primary surface can interfere with the display of a software cursor. If the cursor intersects the locked rectangle, it is hidden for the duration of the lock. If it doesn't intersect the rectangle, it is frozen for the duration of the lock. Neither of these effects occurs if the entire surface is locked.


Gamma and Color Controls

This section contains information about the gamma and color control interfaces used with DirectDrawSurface objects. Information is organized into the following topics:

  • What Are Gamma and Color Controls?
  • Using Gamma Controls
  • Using Color Controls
[C++]

Note You should not attempt to use both the IDirectDrawGammaControl and IDirectDrawColorControl interfaces on a single surface. Their effects are undefined when used together.

[Visual Basic]

Note You should not attempt to use both the DirectDrawGammaControl and DirectDrawColorControl objects on a single surface. Their effects are undefined when used together.


What Are Gamma and Color Controls?

[C++]

Through the gamma and color control interfaces, DirectDrawSurface objects enable you to change how the system displays the contents of the surface, without affecting the contents of the surface itself. You can think of these controls as very simple filters that DirectDraw applies to the data as it leaves a surface before being rendered on the screen. Surface objects implement the IDirectDrawGammaControl and IDirectDrawColorControl interfaces which expose methods to adjust how the surface's contents are filtered. You can retrieve a pointer to either interface by using the IUnknown::QueryInterface method of the target surface, specifying the IID_IDirectDrawGammaControl or IID_IDirectDrawColorControl reference identifiers.

Gamma controls, represented by the IDirectDrawGammaControl interface, make it possible for you to dynamically change how a surface's individual red, green, and blue levels map to the actual levels that the system displays. By setting gamma levels, you can cause the user's screen to flash colors—red when the user's character is shot, green when they pick up a new item, and so on—without blitting new images to the frame buffer to achieve the effect. Or, you might adjust color levels to apply a color bias to the images in the frame buffer. Although this interface is similar to the color control interface, this one is the easiest to use, making it the best choice for game applications. For details, see Using Gamma Controls.

The IDirectDrawColorControl interface allows you to control color in a surface much like the color controls you might find on a television. The similarity between IDirectDrawColorControl and the actual controls on a TV is no mistake—this interface is most appropriate for adjusting how broadcast video looks in an overlay surface, so it makes sense that it should provide similar control over colors. You can use color controls to allow a user to change video characteristics such as hue, saturation, contrast, and several others. For more information, see Using Color Controls.

[Visual Basic]

Through the gamma and color control interfaces, DirectDrawSurface objects enable you to change how the system displays the contents of the surface, without affecting the contents of the surface itself. You can think of these controls as very simple filters that DirectDraw applies to the data as it leaves a surface before being rendered on the screen. Surface objects implement the DirectDrawGammaControl and DirectDrawColorControl interfaces which expose methods to adjust how the surface's contents are filtered. You can retrieve a pointer to either interface by using the DirectDrawSurface7.GetDirectDrawColorControl and DirectDrawSurface7.GetDirectDrawGammaControl methods of the target surface.

Gamma controls, represented by the DirectDrawGammaControl class, make it possible for you to dynamically change how a surface's individual red, green, and blue levels map to the actual levels that the system displays. By setting gamma levels, you can cause the user's screen to flash colors—red when the user's character is shot, green when they pick up a new item, and so on—without blitting new images to the frame buffer to achieve the effect. Or, you might adjust color levels to apply a color bias to the images in the frame buffer. Although this interface is similar to the color control interface, this one is the easiest to use, making it the best choice for game applications. For details, see Using Gamma Controls.

The DirectDrawColorControl class allows you to control color in a surface much like the color controls you might find on a television. The similarity between DirectDrawColorControl and the actual controls on a TV is no mistake—this interface is most appropriate for adjusting how broadcast video looks in an overlay surface, so it makes sense that it should provide similar control over colors. You can use color controls to allow a user to change video characteristics such as hue, saturation, contrast, and several others. For more information, see Using Color Controls.


Using Gamma Controls

[C++]

The IDirectDrawGammaControl interface, which you retrieve by querying the surface with the IID_IDirectDrawGammaControl reference identifier, allows you to manipulate ramp levels that affect the red, green, and blue color components of pixels from the surface before they are sent to the digital-to-analog converter (DAC) for display. Although all surface types support the IDirectDrawGammaControl interface, you are only allowed to adjust gamma on the primary surface. Attempts to call IDirectDrawGammaControl::GetGammaRamp or IDirectDrawGammaControl::SetGammaRamp on a surface other than the primary surface will fail.

In the following topics, this section describes the general concept of ramp levels, and provides information about working with those levels through the methods of IDirectDrawGammaControl:

[Visual Basic]

The DirectDrawGammaControl object, which you retrieve by calling DirectDrawSurface7.GetDirectDrawGammaControl, allows you to manipulate ramp levels that affect the red, green, and blue color components of pixels from the surface before they are sent to the digital-to-analog converter (DAC) for display. Although all surface types support the DirectDrawGammaControl object, you are only allowed to adjust gamma on the primary surface. Attempts to call DirectDrawGammaControl.GetGammaRamp or DirectDrawGammaControl.SetGammaRamp on a surface other than the primary surface will fail.

In the following topics, this section describes the general concept of ramp levels, and provides information about working with those levels through the methods of DirectDrawGammaControl:

  • About Gamma Ramp Levels
  • Detecting Gamma Ramp Support
  • Setting and Retrieving Gamma Ramp Levels


About Gamma Ramp Levels

A gamma ramp in DirectDraw is a term used to describe a set of values that map the level of a particular color component (red, green, blue) for all pixels in the frame buffer to new levels that are received by the digital-to-analog converter (DAC) for display on the monitor. The remapping is performed by way of three simple look-up tables, one for each color component.

Here's how it works: DirectDraw takes a pixel from the frame buffer, and looks at it in terms of its individual red, green, and blue color components. Each component is represented by a value from 0 to 65535. DirectDraw takes the original value, and uses it to index into an 256-element array (the ramp), where each element contains a value that replaces the original one. DirectDraw performs this "look-up and replace" process for each color component of each pixel within the frame buffer, thereby changing the final colors for all of the on-screen pixels.

It's handy to visualize the ramp values by graphing them. The left graph of the two following graphs shows a ramp that doesn't modify colors at all, and the right graph shows a ramp that imposes a negative bias to the color component to which it is applied.

The array elements for the graph on the left would contain values identical to their index (0 in the element at index 0, and 65535 at index 255). This type of ramp is the default, as it doesn't change the input values before they're displayed. The right graph is a little more interesting; its ramp contains values that range from 0 in the first element to 32768 in the last element, with values ranging relatively uniformly in between. The effect is that the color component that uses this ramp appears muted on the display. You are not limited to using linear graphs; if your application needs to assign arbitrary mapping, it's free to do so. You can even set the entries to all zeroes to remove a particular color component completely from the display.


Detecting Gamma Ramp Support

[C++]

You can determine whether the hardware supports dynamic gamma ramp adjustment by calling the IDirectDraw7::GetCaps method. After the call, if the DDCAPS2_PRIMARYGAMMA flag is present in the dwCaps2 member of the associate DDCAPS structure, the hardware supports dynamic gamma ramps. DirectDraw does not attempt to emulate this feature, so if the hardware doesn't support it, you can't use it.

[Visual Basic]

You can determine whether the hardware supports dynamic gamma ramp adjustment by calling the DirectDraw7.GetCaps method. After the call, if the DDCAPS2_PRIMARYGAMMA flag is present in the lCaps2 member of the associate DDCAPS type, the hardware supports dynamic gamma ramps. DirectDraw does not attempt to emulate this feature, so if the hardware doesn't support it, you can't use it.


Setting and Retrieving Gamma Ramp Levels

[C++]

Gamma ramp levels are effectively look-up tables that DirectDraw uses to map the frame buffer color components to new levels that will be displayed. For more information, see About Gamma Ramp Levels. You set and retrieve ramp levels for the primary surface by calling the IDirectDrawGammaControl::SetGammaRamp and IDirectDrawGammaControl::GetGammaRamp methods. Both methods accept two parameters, but the first parameter is reserved for future use, and should be set to zero. The second parameter, lpRampData, is the address of a DDGAMMARAMP structure. The DDGAMMARAMP structure contains three 256-element arrays of WORDs, one array each to contain the red, green, and blue gamma ramps.

You can include the DDSGR_CALIBRATE value when calling the IDirectDrawGammaControl::SetGammaRamp to invoke the calibrator when setting new gamma levels. Calibrating gamma ramps incurs some processing overhead, and should not be used frequently. Setting a calibrated gamma ramp will provide a consistent and absolute gamma value for the viewer, regardless of the display adapter and monitor.

Not all systems support gamma calibration. To determine if gamma calibration is supported, call IDirectDraw7::GetCaps, and examine the dwCaps2 member of the associated DDCAPS structure after the method returns. If the DDCAPS2_CANCALIBRATEGAMMA capability flag is present, then gamma calibration is supported.

When setting new ramp levels, keep in mind that that the levels you set in the arrays are only used when your application is in full-screen, exclusive mode. Whenever your application changes to normal mode, the ramp levels are set aside, taking effect again when the application reinstates full-screen mode. In addition, remember that you cannot set ramp levels for any surface other than the primary.

Note Those very familiar with the Win32® API might wonder why DirectDraw exposes an interface like IDirectDrawGammaControl, when Win32 offers the GetDeviceGammaRamp and SetDeviceGammaRamp functions for the same surfaces. Although the Win32 API includes these functions, they do not always succeed on all Windows platforms like the methods of the IDirectDrawGammaControl interface.

[Visual Basic]

Gamma ramp levels are effectively look-up tables that DirectDraw uses to map the frame buffer color components to new levels that will be displayed. For more information, see About Gamma Ramp Levels. You set and retrieve ramp levels for the primary surface by calling the DirectDrawGammaControl.SetGammaRamp and DirectDrawGammaControl.GetGammaRamp methods. Both methods accept two parameters, the first parameter is used to specify calibration. The second parameter, gammaRamp, is a DDGAMMARAMP type. The DDGAMMARAMP type contains three 256-element arrays of Integers, one array each to contain the red, green, and blue gamma ramps.

You can include the DDSGR_CALIBRATE value in the flags parameter when calling the DirectDrawGammaControl.SetGammaRamp to invoke the calibrator when setting new gamma levels. Calibrating gamma ramps incurs some processing overhead, and should not be used frequently. Setting a calibrated gamma ramp will provide a consistent and absolute gamma value for the viewer, regardless of the display adapter and monitor.

Not all systems support gamma calibration. To determine if gamma calibration is supported, call DirectDraw7.GetCaps, and examine the lCaps2 member of the associated DDCAPS type after the method returns. If the DDCAPS2_CANCALIBRATEGAMMA capability flag is present, then gamma calibration is supported.

When setting new ramp levels, keep in mind that that the levels you set in the arrays are only used when your application is in full-screen, exclusive mode. Whenever your application changes to normal mode, the ramp levels are set aside, taking effect again when the application reinstates full-screen mode. In addition, remember that you cannot set ramp levels for any surface other than the primary.

Note Those very familiar with the Win32® API might wonder why DirectDraw exposes an interface like DirectDrawGammaControl, when Win32 offers the GetDeviceGammaRamp and SetDeviceGammaRamp functions for the same surfaces. Although the Win32 API includes these functions, they do not always succeed on all Windows platforms like the methods of the DirectDrawGammaControl object.


Using Color Controls

[C++]

You set and retrieve surface color controls through the IDirectDrawColorControl interface, which can be retrieved by querying the DirectDrawSurface object using the IID_IDirectDrawColorControl reference identifier.

Color control information is represented by a DDCOLORCONTROL structure, which is used with both methods of the interface, IDirectDrawColorControl::SetColorControls and IDirectDrawColorControl::GetColorControls. The first structure member, dwSize, should be set to the size of the structure, in bytes, before you use it. How you use the next member, dwFlags, depends on whether you are setting or retrieving color controls. If you are setting new color controls, set dwFlags to a combination of the appropriate flags to indicate which of the other structure members contain valid data that you've set. However, when retrieving color controls, you don't need to set the dwFlags before using it—it will contain flags telling you which members are valid after the IDirectDrawColorControl::GetColorControls method returns.

The remaining DDCOLORCONTROL structure members can contain values that describe the brightness, contrast, hue, saturation, sharpness, gamma, and whether color is used. Note that the structure contains information about gamma correction. This is a single gamma value that affects overall brightness, and it should not be confused with the gamma adjustment features provided through the IDirectDrawGammaControl interface.

[Visual Basic]

You set and retrieve surface color controls through the DirectDrawColorControl object, which can be retrieved by calling DirectDrawSurface7.GetDirectDrawColorControl.

Color control information is represented by a DDCOLORCONTROL type, which is used with both methods of the interface, DirectDrawColorControl.SetColorControls and DirectDrawColorControl.GetColorControls.

The DDCOLORCONTROL type members can contain values that describe the brightness, contrast, hue, saturation, sharpness, gamma, and whether color is used. Note that the structure contains information about gamma correction. This is a single gamma value that affects overall brightness, and it should not be confused with the gamma adjustment features provided through the DirectDrawGammaControl interface.


Overlay Surfaces

This section contains information about DirectDraw overlay surface support. The following topics are discussed:

  • Overlay Surface Overview
  • Significant DDCAPS Members and Flags
  • Source and Destination Rectangles
  • Boundary and Size Alignment
  • Minimum and Maximum Stretch Factors
  • Overlay Color Keys
  • Positioning Overlay Surfaces
  • Creating Overlay Surfaces
  • Overlay Z-Orders
  • Flipping Overlay Surfaces
[C++]

For information about implementing overlay surfaces, see Tutorial 6: Using Overlay Surfaces.

[C++,Visual Basic]


Overlay Surface Overview

Overlay surfaces, casually referred to as overlays, are surfaces with special hardware-supported capabilities. Overlay surfaces are frequently used to display live video, recorded video, or still bitmaps over the primary surface without blitting to the primary surface or changing the primary surface's contents in any way. Overlay surface support is provided entirely by the hardware; DirectDraw supports any capabilities as reported by the display device driver. DirectDraw does not emulate overlay surfaces.

An overlay surface is analogous to a clear piece of plastic that you draw on and place in front of the monitor. When the overlay is in front of the monitor, you can see both the overlay and the contents of the primary surface together, but when you remove it, the primary surface's contents are unchanged. In fact, the mechanics of overlays work much like the clear plastic analogy. When you display an overlay surface, you're telling the device driver where and how you want it to be visible. While the display device paints scan lines to the monitor, it checks the location of each pixel in the primary surface to see if an overlay should be visible there instead. If so, the display device substitutes data from the overlay surface for the corresponding pixel, as shown in the following illustration.

By using this method, the display adapter produces a composite of the primary surface and the overlay on the monitor, providing transparency and stretching effects, without modifying the contents of either surface. The composited surfaces are injected into the video stream and sent directly to the monitor. Because this on-the-fly processing and pixel substitution is handled at the hardware level, no noticeable performance loss occurs when displaying overlays. Additionally, this method makes it possible to seamlessly composite primary and overlay surfaces with different pixel formats.

[C++]

You create overlay surfaces by calling the IDirectDraw7::CreateSurface method, specifying the DDSCAPS_OVERLAY flag in the associated DDSCAPS2 structure. Overlay surfaces can only be created in video memory, so you must also include the DDSCAPS_VIDEOMEMORY flag. As with other types of surfaces, by including the appropriate flags you can create either a single overlay or a flipping chain made up of multiple overlay surfaces.

[Visual Basic]

You create overlay surfaces by calling the DirectDraw7.CreateSurface method, specifying the DDSCAPS_OVERLAY flag in the associated DDSCAPS2 type. Overlay surfaces can only be created in video memory, so you must also include the DDSCAPS_VIDEOMEMORY flag. As with other types of surfaces, by including the appropriate flags you can create either a single overlay or a flipping chain made up of multiple overlay surfaces.


Significant DDCAPS Members and Flags

[C++]

You can retrieve information about the supported overlay features by calling the IDirectDraw7::GetCaps method. The method fills a DDCAPS structure with information describing all features.

When reporting hardware features, the device driver sets flags in the dwCaps structure member to indicate when a given type of restriction is enforced by the hardware. After retrieving the driver capabilities, examine the flags in the dwCaps member for information about which restrictions apply. The DDCAPS structure contains nine members that carry information describing hardware restrictions for overlay surfaces. The following table lists the overlay related members and their corresponding flags:

Member | Flag
dwMaxVisibleOverlays | This member is always valid
dwCurrVisibleOverlays | This member is always valid
dwAlignBoundarySrc | DDCAPS_ALIGNBOUNDARYSRC
dwAlignSizeSrc | DDCAPS_ALIGNSIZESRC
dwAlignBoundaryDest | DDCAPS_ALIGNBOUNDARYDEST
dwAlignSizeDest | DDCAPS_ALIGNSIZEDEST
dwAlignStrideAlign | DDCAPS_ALIGNSTRIDE
dwMinOverlayStretch | DDCAPS_OVERLAYSTRETCH
dwMaxOverlayStretch | DDCAPS_OVERLAYSTRETCH

The dwMaxVisibleOverlays and dwCurrVisibleOverlays members carry information about the maximum number of overlays the hardware can display, and how many of them are currently visible.

Additionally, the hardware reports rectangle position and size alignment restrictions in the dwAlignBoundarySrc, dwAlignSizeSrc, dwAlignBoundaryDest, dwAlignSizeDest, and dwAlignStrideAlign members. The values in these members dictate how you must size and position source and destination rectangles when displaying overlay surfaces. For more information, see Source and Destination Rectangles and Boundary and Size Alignment.

Also, the hardware reports information about stretch factors in the dwMinOverlayStretch and dwMaxOverlayStretch members. For more information, see Minimum and Maximum Stretch Factors.

[Visual Basic]

You can retrieve information about the supported overlay features by calling the DirectDraw7.GetCaps method. The method fills a DDCAPS type with information describing all features.

When reporting hardware features, the device driver sets flags in the lCaps type member to indicate when a given type of restriction is enforced by the hardware. After retrieving the driver capabilities, examine the flags in the lCaps member for information about which restrictions apply. The DDCAPS type contains nine members that carry information describing hardware restrictions for overlay surfaces. The following table lists the overlay related members and their corresponding flags:

Member | Flag
lMaxVisibleOverlays | This member is always valid
lCurrVisibleOverlays | This member is always valid
lAlignBoundarySrc | DDCAPS_ALIGNBOUNDARYSRC
lAlignSizeSrc | DDCAPS_ALIGNSIZESRC
lAlignBoundaryDest | DDCAPS_ALIGNBOUNDARYDEST
lAlignSizeDest | DDCAPS_ALIGNSIZEDEST
lAlignStrideAlign | DDCAPS_ALIGNSTRIDE
lMinOverlayStretch | DDCAPS_OVERLAYSTRETCH
lMaxOverlayStretch | DDCAPS_OVERLAYSTRETCH

The lMaxVisibleOverlays and lCurrVisibleOverlays members carry information about the maximum number of overlays the hardware can display, and how many of them are currently visible.

Additionally, the hardware reports rectangle position and size alignment restrictions in the lAlignBoundarySrc, lAlignSizeSrc, lAlignBoundaryDest, lAlignSizeDest, and lAlignStrideAlign members. The values in these members dictate how you must size and position source and destination rectangles when displaying overlay surfaces. For more information, see Source and Destination Rectangles and Boundary and Size Alignment.

Also, the hardware reports information about stretch factors in the lMinOverlayStretch and lMaxOverlayStretch members. For more information, see Minimum and Maximum Stretch Factors.


Source and Destination Rectangles

[C++]

To display an overlay surface, you call the overlay surface's IDirectDrawSurface7::UpdateOverlay method, specifying the DDOVER_SHOW flag in the dwFlags parameter. The method requires you to specify a source and destination rectangle in the lpSrcRect and lpDestRect parameters. The source rectangle describes a rectangle on the overlay surface that will be visible on the primary surface. To request that the method use the entire surface, set the lpSrcRect parameter to NULL. The destination rectangle describes a portion of the primary surface on which the overlay surface will be displayed.

[Visual Basic]

To display an overlay surface, you call the overlay surface's DirectDrawSurface7.UpdateOverlay method, specifying the DDOVER_SHOW flag in the flags parameter. The method requires you to specify a source and destination rectangle in the RECT and rectD parameters. The source rectangle describes a rectangle on the overlay surface that will be visible on the primary surface. To request that the method use the entire surface, pass an empty RECT for the RECT parameter. The destination rectangle describes a portion of the primary surface on which the overlay surface will be displayed.

In addition, you can display an overlay with additional effects by calling DirectDrawSurface7.UpdateOverlayFx method. Note you must set the DDOVER_DDFX flag in the flags parameter to use overlay effects set in the ddoverfx parameter.

Source and destination rectangles do not need to be the same size. You can often specify a destination rectangle smaller or larger than the source rectangle, and the hardware will shrink or stretch the overlay appropriately when it is displayed.

To successfully display an overlay surface, you might need to adjust the size and position of both rectangles. Whether this is necessary depends on the restrictions imposed by the device driver. For more information, see Boundary and Size Alignment and Minimum and Maximum Stretch Factors.


Boundary and Size Alignment

[C++]

Due to various hardware limitations, some device drivers impose restrictions on the position and size of the source and destination rectangles used to display overlay surfaces. To find out which restrictions apply for a device, call the IDirectDraw7::GetCaps method and then examine the overlay-related flags in the dwCaps member of the DDCAPS structure. The following table shows the members and flags specific to boundary and size alignment restrictions:

Category | Flag | Member
Boundary (position) restrictions | DDCAPS_ALIGNBOUNDARYSRC | dwAlignBoundarySrc
 | DDCAPS_ALIGNBOUNDARYDEST | dwAlignBoundaryDest
Size restrictions | DDCAPS_ALIGNSIZESRC | dwAlignSizeSrc
 | DDCAPS_ALIGNSIZEDEST | dwAlignSizeDest

There are two types of restrictions, boundary restrictions and size restrictions. Both types of restrictions are expressed in terms of pixels (not bytes) and can apply to the source and destination rectangles. Also, these restrictions can vary depending on the pixel formats of the overlay and primary surface.

Boundary restrictions affect where you can position a source or destination rectangle. The values in the dwAlignBoundarySrc and dwAlignBoundaryDest members tell you how to align the top left corner of the corresponding rectangle. The x-coordinate of the top left corner of the rectangle (the left member of the RECT structure), must be a multiple of the reported value.

Size restrictions affect the valid widths for source and destination rectangles. The values in the dwAlignSizeSrc and dwAlignSizeDest members tell you how to align the width, in pixels, of the corresponding rectangle. Your rectangles must have a pixel width that is a multiple of the reported value. If you stretch the rectangle to comply with a minimum required stretch factor, be sure that the stretched rectangle is still size aligned. After stretching the rectangle, align its width by rounding up, not down, so you preserve the minimum stretch factor. For more information, see Minimum and Maximum Stretch Factors.

[Visual Basic]

Due to various hardware limitations, some device drivers impose restrictions on the position and size of the source and destination rectangles used to display overlay surfaces. To find out which restrictions apply for a device, call the DirectDraw7.GetCaps method and then examine the overlay-related flags in the lCaps member of the DDCAPS type. The following table shows the members and flags specific to boundary and size alignment restrictions:

Category | Flag | Member
Boundary (position) restrictions | DDCAPS_ALIGNBOUNDARYSRC | lAlignBoundarySrc
 | DDCAPS_ALIGNBOUNDARYDEST | lAlignBoundaryDest
Size restrictions | DDCAPS_ALIGNSIZESRC | lAlignSizeSrc
 | DDCAPS_ALIGNSIZEDEST | lAlignSizeDest

There are two types of restrictions, boundary restrictions and size restrictions. Both types of restrictions are expressed in terms of pixels (not bytes) and can apply to the source and destination rectangles. Also, these restrictions can vary depending on the pixel formats of the overlay and primary surface.

Boundary restrictions affect where you can position a source or destination rectangle. The values in the lAlignBoundarySrc and lAlignBoundaryDest members tell you how to align the top left corner of the corresponding rectangle. The x-coordinate of the top left corner of the rectangle (the left member of the RECT type), must be a multiple of the reported value.

Size restrictions affect the valid widths for source and destination rectangles. The values in the lAlignSizeSrc and lAlignSizeDest members tell you how to align the width, in pixels, of the corresponding rectangle. Your rectangles must have a pixel width that is a multiple of the reported value. If you stretch the rectangle to comply with a minimum required stretch factor, be sure that the stretched rectangle is still size aligned. After stretching the rectangle, align its width by rounding up, not down, so you preserve the minimum stretch factor. For more information, see Minimum and Maximum Stretch Factors.


Minimum and Maximum Stretch Factors

[C++]

Due to hardware limitations, some devices restrict how wide a destination rectangle can be compared with the corresponding source rectangle. DirectDraw communicates these restrictions as stretch factors. A stretch factor is the ratio between the widths of the source and destination rectangles. If the driver provides information about stretch factors, it sets the DDCAPS_OVERLAYSTRETCH flag in the DDCAPS structure after you call the IDirectDraw7::GetCaps method. Note that stretch factors are reported multiplied by 1000, so a value of 1300 actually means 1.3 (and 750 would be 0.75).

[Visual Basic]

Due to hardware limitations, some devices restrict how wide a destination rectangle can be compared with the corresponding source rectangle. DirectDraw communicates these restrictions as stretch factors. A stretch factor is the ratio between the widths of the source and destination rectangles. If the driver provides information about stretch factors, it sets the DDCAPS_OVERLAYSTRETCH flag in the DDCAPS type after you call the DirectDraw7.GetCaps method. Note that stretch factors are reported multiplied by 1000, so a value of 1300 actually means 1.3 (and 750 would be 0.75).

Devices that do not impose limits on stretching or shrinking an overlay destination rectangle often report a minimum and maximum stretch factor of 0.

The minimum stretch factor tells you how much wider or narrower than the source rectangle the destination rectangle needs to be. If the minimum stretch factor is greater than 1000, then you must increase the destination rectangle's width by that ratio. For instance, if the driver reports 1300, you must make sure that the destination rectangle's width is at least 1.3 times the width of the source rectangle. Similarly, a minimum stretch factor less than 1000 indicates that the destination rectangle can be smaller than the source rectangle by that ratio.

The maximum stretch factor tells the maximum amount you can stretch the width of the destination rectangle. For example, if the maximum stretch factor is 2000, you can specify destination rectangles that are up to, but not wider than, twice the width of the source rectangle. If the maximum stretch factor is less than 1000, then you must shrink the width of the destination rectangle by that ratio to be able to display the overlay.

After stretching, the destination rectangle must conform to any size alignment restrictions the device might require. Therefore, it's a good idea to stretch the destination rectangle before adjusting it to be size aligned. For more information, see Boundary and Size Alignment.

Hardware does not require that you adjust the height of destination rectangles. You can increase a destination rectangle's height to preserve aspect ratio without negative effects.


Overlay Color Keys

[C++]

Like other types of surfaces, overlay surfaces use source and destination color keys for controlling transparent blit operations between surfaces. Because overlay surfaces are not displayed by blitting, there needs to be a different way to control how an overlay surface is displayed over the primary surface when you call the IDirectDrawSurface7::UpdateOverlay method. This need is filled by overlay color keys. Overlay color keys, like their blit-related counterparts, have a source version and a destination version that you set by calling the IDirectDrawSurface7::SetColorKey method. (For more information, see Setting Color Keys.) You use the DDCKEY_SRCOVERLAY or DDCKEY_DESTOVERLAY flags to set a source or destination overlay color key. Overlay surfaces can employ blit and overlay color keys together to control blit operations and overlay display operations appropriately; the two types of color keys do not conflict with one another.

The IDirectDrawSurface7::UpdateOverlay method uses the source overlay color key to determine which pixels in the overlay surface should be considered transparent, allowing the contents of the primary surface to show through. Likewise, the method uses the destination overlay color key to determine the parts of the primary surface that will be covered up by the overlay surface when it is displayed. The resulting visual effect is the same as that created by blit-related color keys.

[Visual Basic]

Like other types of surfaces, overlay surfaces use source and destination color keys for controlling transparent blit operations between surfaces. Because overlay surfaces are not displayed by blitting, there needs to be a different way to control how an overlay surface is displayed over the primary surface when you call the DirectDrawSurface7.UpdateOverlay method. This need is filled by overlay color keys. Overlay color keys, like their blit-related counterparts, have a source version and a destination version that you set by calling the DirectDrawSurface7.SetColorKey method. (For more information, see Setting Color Keys.) You use the DDCKEY_SRCOVERLAY or DDCKEY_DESTOVERLAY flags to set a source or destination overlay color key. Overlay surfaces can employ blit and overlay color keys together to control blit operations and overlay display operations appropriately; the two types of color keys do not conflict with one another.

The DirectDrawSurface7.UpdateOverlay method uses the source overlay color key to determine which pixels in the overlay surface should be considered transparent, allowing the contents of the primary surface to show through. Likewise, the method uses the destination overlay color key to determine the parts of the primary surface that will be covered up by the overlay surface when it is displayed. The resulting visual effect is the same as that created by blit-related color keys.


Positioning Overlay Surfaces

[C++]

After initially displaying an overlay by calling the IDirectDrawSurface7::UpdateOverlay method, you can update the destination rectangle's by calling the IDirectDrawSurface7::SetOverlayPosition method.

Make sure that the positions you specify comply with any boundary alignment restrictions enforced by the hardware. For more information, see Boundary and Size Alignment. Also remember that SetOverlayPosition doesn't perform clipping for you; using coordinates that would potentially make the overlay run off the edge of the target surface will cause the method to fail, returning DDERR_INVALIDPOSITION.

[Visual Basic]

After initially displaying an overlay by calling the DirectDrawSurface7.UpdateOverlay method, you can update the destination rectangle's by calling the DirectDrawSurface7.SetOverlayPosition method.

Make sure that the positions you specify comply with any boundary alignment restrictions enforced by the hardware. For more information, see Boundary and Size Alignment. Also remember that SetOverlayPosition doesn't perform clipping for you; using coordinates that would potentially make the overlay run off the edge of the target surface will cause the method to fail, raising DDERR_INVALIDPOSITION.


Creating Overlay Surfaces

[C++]

Like creating all surfaces, you create an overlay surface by calling the IDirectDraw7::CreateSurface method. To create an overlay, include the DDSCAPS_OVERLAY flag in the associated DDSCAPS2 structure.

Overlay support varies widely across display devices. As a result, you cannot be sure that a given pixel format will be supported by most drivers and must therefore be prepared to work with a variety of pixel formats. You can request information about the non-RGB formats that a driver supports by calling the IDirectDraw7::GetFourCCCodes method.

[Visual Basic]

Like creating all surfaces, you create an overlay surface by calling the DirectDraw7.CreateSurface method. To create an overlay, include the DDSCAPS_OVERLAY flag in the associated DDSCAPS2 type.

Overlay support varies widely across display devices. As a result, you cannot be sure that a given pixel format will be supported by most drivers and must therefore be prepared to work with a variety of pixel formats. You can request information about the non-RGB formats that a driver supports by calling the DirectDraw7.GetFourCCCodes method.

When you attempt to create an overlay surface, it is advantageous to try creating a surface with the most desirable pixel format, falling back on other pixel formats if a given pixel format isn't supported.

You can create overlay surface flipping chains. For more information, see Creating Complex Surfaces and Flipping Chains.


Overlay Z-Orders

[C++]

Overlay surfaces are assumed to be on top of all other screen components, but when you display multiple overlay surfaces, you need some way to visually organize them. DirectDraw supports overlay z-ordering to manage the order in which overlays clip each other. Z-order values represent conceptual distances from the primary surface toward the viewer. They range from 0, which is just on top of the primary surface, to 4 billion, which is as close to the viewer as possible, and no two overlays can share the same z-order. You set z-order values by calling the IDirectDrawSurface7::UpdateOverlayZOrder method.

Destination color keys are affected only by the bits on the primary surface, not by overlays occluded by other overlays. Source color keys work on an overlay whether or not a z-order was specified for the overlay.

Overlays without a specified z-order are assumed to have a z-order of 0. Overlays that do not have a specified z-order behave in unpredictable ways when overlaying the same area on the primary surface.

A DirectDraw object does not track the z-orders of overlays displayed by other applications.

Note You can ensure proper clipping of multiple overlay surfaces by calling UpdateOverlayZOrder in response to WM_KILLFOCUS messages. When you receive this message, set your overlay surface to the rearmost z-order position by calling the UpdateOverlayZOrder method with the dwFlags parameter set to DDOVERZ_SENDTOBACK.

[Visual Basic]

Overlay surfaces are assumed to be on top of all other screen components, but when you display multiple overlay surfaces, you need some way to visually organize them. DirectDraw supports overlay z-ordering to manage the order in which overlays clip each other. Z-order values represent conceptual distances from the primary surface toward the viewer. They range from 0, which is just on top of the primary surface, to 4 billion, which is as close to the viewer as possible, and no two overlays can share the same z-order. You set z-order values by calling the DirectDrawSurface7.UpdateOverlayZOrder method.

Destination color keys are affected only by the bits on the primary surface, not by overlays occluded by other overlays. Source color keys work on an overlay whether or not a z-order was specified for the overlay.

Overlays without a specified z-order are assumed to have a z-order of 0. Overlays that do not have a specified z-order behave in unpredictable ways when overlaying the same area on the primary surface.

A DirectDraw object does not track the z-orders of overlays displayed by other applications.

Note You can ensure proper clipping of multiple overlay surfaces by calling UpdateOverlayZOrder in response to WM_KILLFOCUS messages. When you receive this message, set your overlay surface to the rearmost z-order position by calling the UpdateOverlayZOrder method with the flags parameter set to DDOVERZ_SENDTOBACK.


Flipping Overlay Surfaces

[C++]

Like other types of surfaces, you can create overlay flipping chains. After creating a flipping chain of overlays, call the IDirectDrawSurface7::Flip method to flip between them. For more information, see Flipping Surfaces.

Software decoders displaying video with overlay surfaces can use the DDFLIP_ODD and DDFLIP_EVEN flags when calling the Flip method to use features that reduce motion artifacts. If the driver supports odd-even flipping, the DDCAPS2_CANFLIPODDEVEN flag will be set in the DDCAPS structure after retrieving driver capabilities. If DDCAPS2_CANFLIPODDEVEN is set, you can include the DDOVER_BOB flag when calling the IDirectDrawSurface7::UpdateOverlay method to inform the driver that you want it to use the "Bob" algorithm to minimize motion artifacts. Later, when you call Flip with the DDFLIP_ODD or DDFLIP_EVEN flag, the driver will automatically adjust the overlay source rectangle to compensate for jittering artifacts.

[Visual Basic]

Like other types of surfaces, you can create overlay flipping chains. After creating a flipping chain of overlays, call the DirectDrawSurface7.Flip method to flip between them. For more information, see Flipping Surfaces.

Software decoders displaying video with overlay surfaces can use the DDFLIP_ODD and DDFLIP_EVEN flags when calling the Flip method to use features that reduce motion artifacts. If the driver supports odd-even flipping, the DDCAPS2_CANFLIPODDEVEN flag will be set in the DDCAPS type after retrieving driver capabilities. If DDCAPS2_CANFLIPODDEVEN is set, you can include the DDOVER_BOB flag when calling the DirectDrawSurface7.UpdateOverlay method to inform the driver that you want it to use the "Bob" algorithm to minimize motion artifacts. Later, when you call Flip with the DDFLIP_ODD or DDFLIP_EVEN flag, the driver will automatically adjust the overlay source rectangle to compensate for jittering artifacts.

If the driver doesn't set the DDCAPS2_CANFLIPODDEVEN flag when you retrieve hardware capabilities, UpdateOverlay will fail if you specify the DDOVER_BOB flag.

For more information about the Bob algorithm, see Solutions to Common Video Artifacts.


Compressed Texture Surfaces

[C++]

A surface can contain a bitmap to be used for texturing 3-D objects. When creating the surface you must specify the DDSCAPS_TEXTURE flag in the dwFlags member of the DDSCAPS structure.

[Visual Basic]

A surface can contain a bitmap to be used for texturing 3-D objects. When creating the surface you must specify the DDSCAPS_TEXTURE flag in the lCaps member of the DDSCAPS2 type.

For more information on the use of textures in Direct3D Immediate Mode, see Textures.

In order to reduce the amount of memory consumed by textures, DirectDraw supports the compression of texture surfaces.

Some Direct3D devices support compressed texture surfaces natively. On such devices, once you have created a compressed surface and loaded the data into it, the surface can be used in Direct3D just like any other texture surface. Direct3D handles decompression when the texture is mapped to a 3-D object.

Other devices do not support compressed texture surfaces natively. When using such devices, you may still find it useful to use compressed surfaces to represent textures on disk or for textures that are loaded into memory but not currently being used. You can use DirectDraw to convert the compressed textures to an uncompressed format before giving the texture to Direct3D.

For more information on texture compression in DirectDraw, see the following topics:

  • Creating Compressed Textures
  • Decompressing Compressed Textures
  • Transparency in Blits to Compressed Textures
  • Compressed Texture Formats

For information on using compressed textures in Direct3D Immediate Mode, see Texture Compression.


Creating Compressed Textures

[C++]

To describe a compressed texture surface in the DDSURFACEDESC2 structure when creating the surface, you must include the following steps:

  • Specify the DDSCAPS_TEXTURE flag in the dwFlags member of the DDSCAPS structure, just as you would for any texture.
  • Set the dwFourCC member of the DDPIXELFORMAT structure to one of the DXT codes described later.
  • Include DDPF_FOURCC in the dwFlags member of DDPIXELFORMAT. Do not set the DDPF_RGB flag.
  • Specify a width and height that are a multiple of 4 pixels.

There are two ways to load image data into a compressed texture surface:

  • Create a regular RGB or ARGB surface and load a normal bitmap into it, then use IDirectDrawSurface7::Blt or IDirectDrawSurface7::BltFast to blit from the uncompressed surface to the compressed surface. DirectDraw does the compression for you.
  • Load the compressed data from a file and copy it directly into the surface memory. (See Accessing Surface Memory Directly.) You can create and convert compressed texture (DDS) files using the DirectX Texture Tool (Dxtex.exe) supplied with the SDK. You can also create your own DDS files and either copy the data from compressed surfaces or else use your own routines to convert regular bitmap data to one of the compressed formats.

Note When you call IDirectDrawSurface7::Lock or IDirectDrawSurface7::GetSurfaceDesc on a compressed surface, the DDSD_LINEARSIZE flag is set in the dwFlags member of the DDSURFACEDESC structure, and the dwLinearSize member contains the number of bytes allocated to contain the compressed surface data. The dwLinearSize parameter resides in a union with the lPitch parameter, so these parameters are mutually exclusive, as are the flags DDSD_LINEARSIZE and DDSD_PITCH.

[Visual Basic]

To describe a compressed texture surface in the DDSURFACEDESC2 type when creating the surface, you must include the following steps:

  • Specify the DDSCAPS_TEXTURE flag in the lCaps member of the DDSCAPS2 type, just as you would for any texture.
  • Set the lFourCC member of the DDPIXELFORMAT type to one of the DXT codes described later.
  • Include DDPF_FOURCC in the lFlags member of DDPIXELFORMAT. Do not set the DDPF_RGB flag.
  • Specify a width and height that are a multiple of 4 pixels.

There are two ways to load image data into a compressed texture surface:

  • Create a regular RGB or ARGB surface and load a normal bitmap into it, then use DirectDrawSurface7.Blt or DirectDrawSurface7.BltFast to blit from the uncompressed surface to the compressed surface. DirectDraw does the compression for you.
  • Load the compressed data from a file and copy it directly into the surface memory. (See Accessing Surface Memory Directly.) You can create and convert compressed texture (DDS) files using the DirectX Texture Tool (Dxtex.exe) supplied with the SDK. You can also create your own DDS files and either copy the data from compressed surfaces or else use your own routines to convert regular bitmap data to one of the compressed formats.

Note When you call DirectDrawSurface7.Lock or DirectDrawSurface7.GetSurfaceDesc on a compressed surface, the DDSD_LINEARSIZE flag is set in the lFlags member of the DDSURFACEDESC2 type, and the lLinearSize member contains the number of bytes allocated to contain the compressed surface data. The lLinearSize parameter resides in a union with the lPitch parameter, so these parameters are mutually exclusive, as are the flags DDSD_LINEARSIZE and DDSD_PITCH.

The advantage of this behavior is that an application can copy the contents of a compressed surface to a file without having to calculate for itself how much storage is required for a surface of a particular width and height in the specific format.

The following table shows the five types of compressed textures. For more information on how the data is stored (you need to know this only if you are writing your own compression routines) see Compressed Texture Formats.

FOURCC | Description | Alpha premultiplied?
DXT1 | Opaque / one-bit alpha | n/a
DXT2 | Explicit alpha | Yes
DXT3 | Explicit alpha | No
DXT4 | Interpolated alpha | Yes
DXT5 | Interpolated alpha | No

Note When you blit from a non-premultiplied format to a premultiplied format, DirectDraw scales the colors based on the alpha values. Blitting from a premultiplied format to a non-premultiplied format is not supported. If you try to blit from a premultiplied-alpha source to a non-premultiplied-alpha destination, the method will return DDERR_INVALIDPARAMS. If you blit from a premultiplied-alpha source to a destination that has no alpha, the source color components, which have been scaled by alpha, will be copied as is.


Decompressing Compressed Textures

As with compressing a texture surface, decompressing a compressed texture is performed through DirectDraw blitting services. The HEL performs decompressing blits between system memory surfaces, so these always supported. Likewise, the HEL always performs blits for compressed managed textures (the DDSCAPS2_TEXTUREMANAGE capability). For other situations, the restrictions discussed in the following paragraphs apply.

If the driver supports the creation of compressed video-memory surfaces, then the driver can also perform decompressing blits from a compressed video-memory surface to an uncompressed video or system memory surface, so long as the destination surface has the DDSCAPS_OFFSCREENPLAIN capability.

Blits from compressed system-memory surfaces to uncompressed video-memory surfaces are largely unsupported and should not be attempted, even when the driver supports compressed textures. This does not mean that it is impossible to decompress a compressed system-memory surface and move its contents into a video memory surface; it merely requires an additional step:

To decompress a system memory surface into video memory:

  1. Create an uncompressed, off-screen plain surface in system memory of the desired dimensions and pixel format.
  2. Blit from the compressed system-memory surface to the uncompressed system-memory surface. (The DirectDraw HEL performs decompression in this case.)
  3. Blit the uncompressed surface to the uncompressed video-memory surface.


Transparency in Blits to Compressed Textures

DirectDraw provides a special trick for creating compressed textures with alpha from plain RGB surfaces. If a source color key is provided on the source RGB surface, DirectDraw assigns an alpha value of 0 to all pixels of that color in the destination. This technique is especially useful for creating DXT1 textures, since they effectively have only 1 bit of alpha information per pixel.

Note There are no flags that control this behavior. If you do not want any transparency in your compressed texture, do not set a source color key on the source surface.


Compressed Texture Formats

This section contains information on the internal organization of compressed texture formats. You don't need these details in order to use compressed textures, because DirectDraw handles conversion to and from compressed formats. However, you might find this information useful if you want to operate on compressed surface data directly.

DirectDraw uses a compression format that divides texture maps into 4x4 texel blocks. If the texture contains no transparency (is opaque), or if the transparency is specified by a one-bit alpha, an 8-byte block represents the texture map block. If the texture map does contain transparent texels, using an alpha channel, a 16-byte block represents it.

These two types of format are discussed in the following sections:

  • Opaque and One-bit Alpha Textures
  • Textures with Alpha Channels

Note Any single texture must specify that its data is stored as 64 or 128 bits per group of 16 texels. If 64-bit blocks—that is, format DXT1—are used for the texture, it is possible to mix the opaque and one-bit alpha formats on a per-block basis within the same texture. In other words, the comparison of the unsigned integer magnitude of color_0 and color_1 is performed uniquely for each block of 16 texels.

When 128-bit blocks are used, then the alpha channel must be specified in either explicit (format DXT2 or DXT3) or interpolated mode (format DXT4 or DXT5) for the entire texture. Note that as with color, once interpolated mode is selected then either 8 interpolated alphas or 6 interpolated alphas mode can be used on a block-by-block basis. Again the magnitude comparison of alpha_0 and alpha_1 is done uniquely on a block-by-block basis.


Opaque and One-bit Alpha Textures

Texture format DXT1 is for textures that are opaque or have a single transparent color.

For each opaque or one-bit alpha block, two 16-bit values (RGB 5:6:5 format) and a 4x4 bitmap with 2-bits-per-pixel are stored. This totals 64 bits for 16 texels, or 4-bits-per-texel. In the block bitmap, there are two bits per texel to select between the four colors, two of which are stored in the encoded data. The other two colors are derived from these stored colors by linear interpolation.

The one-bit alpha format is distinguished from the opaque format by comparing the two 16-bit color values stored in the block. They are treated as unsigned integers. If the first color is greater than the second, it implies that only opaque texels are defined. This means four colors will be used to represent the texels. In four-color encoding, there are two derived colors and all four colors are equally distributed in RGB color space. This format is analogous to RGB 5:6:5 format. Otherwise, for one-bit alpha transparency, three colors are used and the fourth is reserved to represent transparent texels.

In three-color encoding, there is one derived color and the fourth two-bit code is reserved to indicate a transparent texel (alpha information). This format is analogous to RGBA 5:5:5:1, where the final bit is used for encoding the alpha mask.

[C++]

The following piece of pseudocode illustrates the algorithm for deciding whether three- or four-color encoding is selected:

if (color_0 > color_1)
{
    // Four-color block: derive the other two colors.
    // 00 = color_0, 01 = color_1, 10 = color_2, 11 = color_3
    // These two bit codes correspond to the 2-bit fields
    // stored in the 64-bit block.
     color_2 = (2 * color_0 + color_1) / 3;
     color_3 = (color 0 + 2 * color_1) / 3;
}
else
{
    // Three-color block: derive the other color.
    // 00 = color_0,  01 = color_1,  10 = color_2,
    // 11 = transparent.
    // These two bit codes correspond to the 2-bit fields
    // stored in the 64-bit block.
     color_2 = (color_0 + color_1) / 2;
     color_3 = transparent;
}

The following tables show the memory layout for the 8-byte block. It is assumed that the first index corresponds to the y-coordinate and the second corresponds to the x-coordinate. For example, Texel[1][2] refers to the texture map pixel at (x,y) = (2,1).

Here is the memory layout for the 8-byte (64-bit) block:

Word address | 16-bit word
0 | Color_0
1 | Color_1
2 | Bitmap Word_0
3 | Bitmap Word_1

Color_0 and Color_1 (colors at the two extremes) are laid out as follows:

Bits | Color
4:0 (LSB) | Blue color component
10:5 | Green color component
15:11 | Red color component

Bitmap Word_0 is laid out as follows:

Bits | Texel
1:0 (LSB) | Texel[0][0]
3:2 | Texel[0][1]
5:4 | Texel[0][2]
7:6 | Texel[0][3]
9:8 | Texel[1][0]
11:10 | Texel[1][1]
13:12 | Texel[1][2]
15:14 (MSB) | Texel[1][3]

Bitmap Word_1 is laid out as follows:

Bits | Texel
1:0 (LSB) | Texel[2][0]
3:2 | Texel[2][1]
5:4 | Texel[2][2]
7:6 | Texel[2][3]
9:8 | Texel[3][0]
11:10 | Texel[3][1]
13:12 | Texel[3][2]
15:14 (MSB) | Texel[3][3]

Example of Opaque Color Encoding

As an example of opaque encoding, we will assume that the colors red and black are at the extremes. We will call red color_0 and black color_1. There will be four interpolated colors that form the uniformly distributed gradient between them. To determine the values for the 4x4 bitmap, the following calculations are used:

00 ? color_0
01 ? color_1
10 ? 2/3 color_0 + 1/3 color_1
11 ? 1/3 color_0 + 2/3 color_1

Example of One-bit Alpha Encoding

This format is selected when the unsigned 16-bit integer, color_0, is less than the unsigned 16-bit integer, color_1. An example of where this format could be used is leaves on a tree to be shown against a blue sky. Some texels could be marked as transparent while three shades of green are still available for the leaves. Two of these colors fix the extremes, and the third color is an interpolated color.

The bitmap encoding for the colors and the transparency is determined using the following calculations:

00 ? color_0
01 ? color_1
10 ? 1/2 color_0 + 1/2 color_1
11   ?   Transparent

[C++,Visual Basic]


Textures with Alpha Channels

There are two ways to encode texture maps that exhibit more complex transparency. In each case, a block that describes the transparency precedes the 64-bit block already described. The transparency is either represented as a 4x4 bitmap with four bits per pixel (explicit encoding), or with fewer bits and linear interpolation analogous to what is used for color encoding.

The transparency block and the color block are laid out as follows:

Word Address | 64-bit Block
3:0 | Transparency block
7:4 | Previously described 64-bit block

Explicit Texture Encoding

For explicit texture encoding (DXT2 and DXT3 formats), the alpha components of the texels that describe transparency are encoded in a 4x4 bitmap with 4 bits per texel. These 4 bits can be achieved through a variety of means such as dithering or by simply using the 4 most significant bits of the alpha data. However they are produced, they are used just as they are, without any form of interpolation.

Note The compression method of DirectDraw uses the 4 most significant bits.

The following tables illustrate how the alpha information is laid out in memory, for each 16-bit word.

This is the layout for Word 0:

Bits | Alpha
3:0 (LSB) | [0][0]
7:4 | [0][1]
11:8 | [0][2]
15:12 (MSB) | [0][3]

This is the layout for Word 1:

Bits | Alpha
3:0 (LSB) | [1][0]
7:4 | [1][1]
11:8 | [1][2]
15:12 (MSB) | [1][3]

This is the layout for Word 2:

Bits | Alpha
3:0 (LSB) | [2][0]
7:4 | [2][1]
11:8 | [2][2]
15:12 (MSB) | [2][3]

This is the layout for Word 3:

Bits | Alpha
3:0 (LSB) | [3][0]
7:4 | [3][1]
11:8 | [3][2]
15:12 (MSB) | [3][3]

Three-Bit Linear Alpha Interpolation

The encoding of transparency for the DXT4 and DXT5 formats is based on a concept similar to the linear encoding used for color. Two 8-bit alpha values and a 4x4 bitmap with three bits per pixel are stored in the first eight bytes of the block. The representative alpha values are used to interpolate intermediate alpha values. Additional information is available in the way the two alpha values are stored. If alpha_0 is greater than alpha_1, then six intermediate alpha values are created by the interpolation. Otherwise, four intermediate alpha values are interpolated between the specified alpha extremes. The two additional implicit alpha values are 0 (fully transparent) and 255 (fully opaque).

[C++]

The following pseudo-code illustrates this algorithm:

// 8-alpha or 6-alpha block?
if (alpha_0 > alpha_1) {
     // 8-alpha block:  derive the other 6 alphas.
    // 000 = alpha_0, 001 = alpha_1, others are interpolated
    alpha_2 = (6 * alpha_0 + alpha_1) / 7;      // bit code 010
    alpha_3 = (5 * alpha_0 + 2 * alpha_1) / 7;  // Bit code 011
    alpha_4 = (4 * alpha_0 + 3 * alpha_1) / 7;  // Bit code 100
    alpha_5 = (3 * alpha_0 + 4 * alpha_1) / 7;  // Bit code 101
    alpha_6 = (2 * alpha_0 + 5 * alpha_1) / 7;  // Bit code 110
    alpha_7 = (alpha_0 + 6 * alpha_1) / 7;      // Bit code 111
  }
else {  // 6-alpha block:  derive the other alphas.
    // 000 = alpha_0, 001 = alpha_1, others are interpolated
    alpha_2 = (4 * alpha_0 + alpha_1) / 5;      // Bit code 010
    alpha_3 = (3 * alpha_0 + 2 * alpha_1) / 5;  // Bit code 011
    alpha_4 = (2 * alpha_0 + 3 * alpha_1) / 5;  // Bit code 100
    alpha_5 = (alpha_0 + 4 * alpha_1) / 5;      // Bit code 101
    alpha_6 = 0;                                // Bit code 110
    alpha_7 = 255;                              // Bit code 111
}

The memory layout of the alpha block is as follows:

Byte | Alpha
0 | Alpha_0
1 | Alpha_1
2 | [0][2] (2 LSBs), [0][1], [0][0]
3 | [1][1] (1 LSB), [1][0], [0][3], [0][2] (1 MSB)
4 | [1][3], [1][2], [1][1] (2 MSBs)
5 | [2][2] (2 LSBs), [2][1], [2][0]
6 | [3][1] (1 LSB), [3][0], [2][3], [2][2] (1 MSB)
7 | [3][3], [3][2], [3][1] (2 MSBs)

[C++,Visual Basic]


Private Surface Data

[Visual Basic]

The information in this topic pertains only to applications written in C++.

[C++]

You can store any kind of application-specific data with a surface. For example, a surface representing a map in a game might contain information about terrain.

A surface can have more than one private data buffer. Each buffer is identified by a GUID which you supply when attaching the data to the surface.

To store private surface data, you use the IDirectDrawSurface7::SetPrivateData method, passing in a pointer to the source buffer, the size of the data, and an application-defined GUID for the data. Optionally, the source data can exist in the form of a COM object; in this case, you pass a pointer to the object's IUnknown interface pointer and you set the DDSPD_IUNKNOWNPOINTER flag. Another flag, DDSPD_VOLATILE, indicates that the data being attached to the surface is valid only as long as the contents of the surface do not change. (See Surface Uniqueness Values.)

SetPrivateData allocates an internal buffer for the data and copies it. You can then safely free the source buffer or object. The internal buffer or interface reference is released when IDirectDrawSurface7::FreePrivateData is called. This happens automatically when the surface is freed.

To retrieve private data for a surface, you must allocate a buffer of the correct size and then call the IDirectDrawSurface7::GetPrivateData method, passing the GUID that was assigned to the data by SetPrivateData. You are responsible for freeing any dynamic memory you use for this buffer. If the data is a COM object, this method retrieves the IUnknown pointer.

If you don't know how big a buffer to allocate, first call GetPrivateData with zero in *lpcbBufferSize. If the method fails with DDERR_MOREDATA, it returns the necessary number of bytes in *lpcbBufferSize.


Surface Uniqueness Values

[C++]

The uniqueness value of a surface allows you to determine whether the surface has changed. When DirectDraw creates a surface, it assigns a uniqueness value, which you can retrieve and store by using the IDirectDrawSurface7::GetUniquenessValue method. Then, whenever you need to determine whether the surface has changed, you call the method again and compare the new value against the old one. If it's different, the surface has changed.

The actual value returned by GetUniquenessValue is irrelevant, unless it is 0. DirectDraw assigns this value to a surface when it knows that the surface might be changed by some process beyond its control. When GetUniquenessValue returns 0, you know only that the state of the surface is indeterminate.

To force the uniqueness value for a surface to change, an application can use the IDirectDrawSurface7::ChangeUniquenessValue method. This method could be called, for example, by an application or component that changed the private data for a surface without changing the surface itself, and wished to notify some other process of the change. Most applications, however, never need to change the uniqueness value.

[Visual Basic]

The uniqueness value of a surface allows you to determine whether the surface has changed. When DirectDraw creates a surface, it assigns a uniqueness value, which you can retrieve and store by using the DirectDrawSurface7.GetUniquenessValue method. Then, whenever you need to determine whether the surface has changed, you call the method again and compare the new value against the old one. If it's different, the surface has changed.

The actual value returned by GetUniquenessValue is irrelevant, unless it is 0. DirectDraw assigns this value to a surface when it knows that the surface might be changed by some process beyond its control. When GetUniquenessValue returns 0, you know only that the state of the surface is indeterminate.

To force the uniqueness value for a surface to change, an application can use the DirectDrawSurface7.ChangeUniquenessValue method. This method could be called, for example, by an application or component that changed the private data for a surface without changing the surface itself, and wished to notify some other process of the change. Most applications, however, never need to change the uniqueness value.


Using Non-local Video Memory Surfaces

DirectDraw supports the Accelerated Graphics Port (AGP) architecture for creating surfaces in non-local video memory. On AGP-equipped systems, DirectDraw will use non-local video memory if local video memory is exhausted or if non-local video memory is explicitly requested, depending on the type of AGP implementation that is in place.

[C++]

Currently, there are two implementations of the AGP architecture, known as the "execute model" and the "DMA model." In the execute model implementation, the display device supports the same features for non-local video memory surfaces and local video memory surfaces. As a result, when you retrieve hardware capabilities by calling the IDirectDraw7::GetCaps method, the blit-related flags in the dwNLVBCaps, dwNLVBCaps2, dwNLVBCKeyCaps, dwNLVBFXCaps, and dwNLVBRops members of the DDCAPS structure will be identical to those for local video memory. Under the execute model, if local video memory is exhausted, DirectDraw will automatically fall back on non-local video memory unless the caller specifically requests otherwise.

In the DMA model implementation, support for blitting and texturing from non-local video memory surfaces is limited. When the display device uses the DMA model, the DDCAPS2_NONLOCALVIDMEMCAPS flag will be set in the dwCaps2 member when you retrieve device capabilities. In the DMA model, the blit-related flags included in the dwNLVBCaps, dwNLVBCaps2, dwNLVBCKeyCaps, dwNLVBFXCaps, and dwNLVBRops members of the DDCAPS structure describe the features that are supported; these features will often be a smaller subset of those supported for local video memory surfaces. Under the DMA model, when local video memory is exhausted, DirectDraw will automatically fall back on non-local video memory for texture surfaces only, unless the caller had explicitly requested local video memory. Texture surfaces are the only types of surfaces that will be treated this way; all other types of surfaces cannot be created in non-local video memory unless the caller explicitly requests it.

DMA model implementations vary in support for texturing from non-local video memory surfaces. If the driver supports texturing from non-local video memory surfaces, the D3DDEVCAPS_TEXTURENONLOCALVIDMEM flag will be set when you retrieve the 3-D device's capabilities by calling the IDirect3DDevice7::GetCaps method.

[Visual Basic]

Currently, there are two implementations of the AGP architecture, known as the "execute model" and the "DMA model." In the execute model implementation, the display device supports the same features for non-local video memory surfaces and local video memory surfaces. As a result, when you retrieve hardware capabilities by calling the DirectDraw7.GetCaps method, the blit-related flags in the lNLVBCaps, lNLVBCaps2, lNLVBCKeyCaps, lNLVBFXCaps, and lNLVBRops members of the DDCAPS type will be identical to those for local video memory. Under the execute model, if local video memory is exhausted, DirectDraw will automatically fall back on non-local video memory unless the caller specifically requests otherwise.

In the DMA model implementation, support for blitting and texturing from non-local video memory surfaces is limited. When the display device uses the DMA model, the DDCAPS2_NONLOCALVIDMEMCAPS flag will be set in the lCaps2 member when you retrieve device capabilities. In the DMA model, the blit-related flags included in the lNLVBCaps, lNLVBCaps2, lNLVBCKeyCaps, lNLVBFXCaps, and lNLVBRops members of the DDCAPS type describe the features that are supported; these features will often be a smaller subset of those supported for local video memory surfaces. Under the DMA model, when local video memory is exhausted, DirectDraw will automatically fall back on non-local video memory for texture surfaces only, unless the caller had explicitly requested local video memory. Texture surfaces are the only types of surfaces that will be treated this way; all other types of surfaces cannot be created in non-local video memory unless the caller explicitly requests it.

DMA model implementations vary in support for texturing from non-local video memory surfaces. If the driver supports texturing from non-local video memory surfaces, the D3DDEVCAPS_TEXTURENONLOCALVIDMEM flag will be set when you retrieve the 3-D device's capabilities by calling the Direct3DDevice7.GetCaps method.


Surfaces and Device Contexts

It is often convenient to mix-and-match DirectDraw and GDI services to manipulate the contents of DirectDraw surfaces. DirectDraw offers methods to enable GDI to access DirectDraw surfaces through device contexts, and to retrieve a surface given the surface's device context. This section contains the follows topics that describe these features in detail:

  • Retrieving the Device Context for a Surface
  • Finding a Surface with a Device Context


Retrieving the Device Context for a Surface

[C++]

If you want to modify the contents of a DirectDraw surface object by using GDI functions, you must retrieve a GDI-compatible device context handle. This could be useful if you wanted to display text in a DirectDraw surface by calling the DrawText Win32 function, which accepts a handle to a device context as a parameter. It is possible to retrieve a GDI-compatible device context for a surface by calling the IDirectDrawSurface7::GetDC method for that surface. The following example shows how this might be done:

// For this example the lpDDS7 variable is a valid pointer
// to an IDirectDrawSurface7 interface.

  HDC     hdc;
  HRESULT HR;

  hr = lpDDS7->GetDC(&hdc);
  if(FAILED(hr))
      return hr;

  // Call DrawText, or some other GDI
  // function here.

  lpDDS7->ReleaseDC(hdc);

Note that the code calls the IDirectDrawSurface7::ReleaseDC method when the surface's device context is no longer needed. This step is required, because the IDirectDrawSurface7::GetDC method uses an internal version of the IDirectDrawSurface7::Lock method to lock the surface. The surface remains locked until the IDirectDrawSurface7::ReleaseDC method is called.

[Visual Basic]

If you want to modify the contents of a DirectDraw surface object by using GDI functions, you must retrieve a GDI-compatible device context handle. It is possible to retrieve a GDI-compatible device context for a surface by calling the DirectDrawSurface7.GetDC method for that surface.

Note that the code calls the DirectDrawSurface7.ReleaseDC method when the surface's device context is no longer needed. This step is required, because the DirectDrawSurface7.GetDC method uses an internal version of the DirectDrawSurface7.Lock method to lock the surface. The surface remains locked until the DirectDrawSurface7.ReleaseDC method is called.


Finding a Surface with a Device Context

[Visual Basic]

The information in this topic pertains only to applications written in C++.

[C++]

You can retrieve a pointer to a surface's IDirectDrawSurface7 interface from the device context for the surface by calling the IDirectDraw7::GetSurfaceFromDC method. This feature might be very useful for component applications or ActiveX® controls, that are commonly given a device context to draw into at run time, but could benefit by exploiting the features exposed by the IDirectDrawSurface7 interface.

A device context might identify memory that isn't associated with a DirectDraw object, or the device context might identify a surface for another DirectDraw object entirely. The latter case is most likely to occur on a system with multiple monitors. If the device context doesn't identify a surface that wasn't created by that DirectDraw object, the method fails, returning DDERR_NOTFOUND.

The following sample code shows what a very simple scenario might look like:

// For this example, the hdc variable is a valid
// handle to a video memory device context, and the
// lpDD variable is a valid IDirectDraw7 interface pointer.

LPDIRECTDRAWSURFACE7 lpDDS;
HRESULT hr;

hr = lpDD->GetSurfaceFromDC(hdc, &lpDDS);
if(SUCCEEDED(hr)) {
    // Use the surface interface.
}
else if(DDERR_NOTFOUND == hr) {
    OutputDebugString("HDC not from this DirectDraw surface\n");
 }


Palettes

This section contains information about DirectDrawPalette objects. The following topics are discussed:

  • What Are Palettes?
  • Palette Types
  • Setting Palettes on Nonprimary Surfaces
  • Sharing Palettes
  • Palette Animation


What Are Palettes?

Palettized surfaces need palettes to be meaningfully displayed. A palettized surface, also known as a color-indexed surface, is simply a collection of numbers where each number represents a pixel. The value of the number is an index into a color table that tells DirectDraw what color to use when displaying that pixel. DirectDrawPalette objects, casually referred to as palettes, provide you with an easy way to manage a color table. Surfaces that use a 16-bit or greater pixel format do not use palettes.

A DirectDrawPalette object represents an indexed color table that has 2, 4, 16 or 256 entries to be used with a color indexed surface. Each entry in the palette is an RGB triplet that describes the color to be used when displaying pixels within the surface. The color table can contain 16- or 24-bit RGB triplets representing the colors to be used. For 16-color palettes, the table can also contain indexes to another 256-color palette. Palettes are supported for textures, off-screen surfaces, and overlay surfaces, none of which is required to have the same palette as the primary surface.

[C++]

You can create a palette by calling the IDirectDraw7::CreatePalette method. This method retrieves a pointer to the palette object's IDirectDrawPalette interface. You can use the methods of this interface to manipulate palette entries, retrieve information about the object's capabilities, or initialize the object (if you used the CoCreateInstance COM function to create it).

You apply a palette to a surface by calling the surface's IDirectDrawSurface7::SetPalette method. A single palette can be applied to multiple surfaces.

DirectDrawPalette objects reserve entry 0 and entry 255 for 8-bit palettes, unless you specify the DDPCAPS_ALLOW256 flag to request that these entries be made available to you.

You can retrieve palette entries by using the IDirectDrawPalette::GetEntries method, and you can change entries by using the IDirectDrawPalette::SetEntries method.

The Ddutil.cpp source file included with the SDK contains some handy application-defined functions for working with palettes. For more information, see the DDLoadPalette functions in that source file.

[Visual Basic]

You can create a palette by calling the DirectDraw7.CreatePalette method. This method returns a DirectDrawPalette object. You can use the methods of this object to manipulate palette entries and retrieve information about the object's capabilities.

You apply a palette to a surface by calling the surface's DirectDrawSurface7.SetPalette method. A single palette can be applied to multiple surfaces.

DirectDrawPalette objects reserve entry 0 and entry 255 for 8-bit palettes, unless you specify the DDPCAPS_ALLOW256 flag to request that these entries be made available to you.

You can retrieve palette entries by using the DirectDrawPalette.GetEntries method, and you can change entries by using the DirectDrawPalette.SetEntries method.


Palette Types

DirectDraw supports 1-bit (2 entry), 2-bit (4 entry), 4-bit (16 entry), and 8-bit (256 entry) palettes. A palette can only be attached to a surface that has a matching pixel format. For example, a 2-entry palette created with the DDPCAPS_1BIT flag can be attached only to a 1-bit surface created with the DDPF_PALETTEINDEXED1 flag.

Additionally, you can create palettes that don't contain a color table at all, known as index palettes. Instead of a color table, an index palette contains index values that represent locations in another palette's color table.

[C++]

To create an indexed palette, specify the DDPCAPS_8BITENTRIES flag when calling the IDirectDraw7::CreatePalette method. For example, to create a 4-bit indexed palette, specify both the DDPCAPS_4BIT and DDPCAPS_8BITENTRIES flags. When you create an indexed palette, you pass a pointer to an array of bytes rather than a pointer to an array of PALETTEENTRY structures. You must cast the pointer to the array of bytes to an LPPALETTEENTRY type when you use the IDirectDraw7::CreatePalette method.

Note that DirectDraw does not dereference index palette entries during blit operations.

[Visual Basic]

To create an indexed palette, specify the DDPCAPS_8BITENTRIES flag when calling the DirectDraw7.CreatePalette method. For example, to create a 4-bit indexed palette, specify both the DDPCAPS_4BIT and DDPCAPS_8BITENTRIES flags. When you create an indexed palette, you pass an array of bytes rather than an array of PALETTEENTRY types.


Setting Palettes on Nonprimary Surfaces

Palettes can be attached to any palettized surface (primary, back buffer, off-screen plain, or texture map). Only those palettes attached to primary surfaces will have any effect on the system palette. It is important to note that DirectDraw blits never perform color conversion; any palettes attached to the source or destination surface of a blit are ignored.

Nonprimary surface palettes are intended for use by Direct3D applications.


Sharing Palettes

[C++]

Palettes can be shared among multiple surfaces. The same palette can be set on the front buffer and the back buffer of a flipping chain or shared among multiple texture surfaces. When an application attaches a palette to a surface by using the IDirectDrawSurface7::SetPalette method, the surface increments the reference count of that palette. When the reference count of the surface reaches 0, the surface will decrement the reference count of the attached palette. In addition, if a palette is detached from a surface by using IDirectDrawSurface7::SetPalette with a NULL palette interface pointer, the reference count of the surface's palette will be decremented.

Note If IDirectDrawSurface7::SetPalette is called several times consecutively on the same surface with the same palette, the reference count for the palette is incremented only once. Subsequent calls do not affect the palette's reference count.

[Visual Basic]

Palettes can be shared among multiple surfaces. The same palette can be set on the front buffer and the back buffer of a flipping chain or shared among multiple texture surfaces.


Palette Animation

Palette animation refers to the process of modifying a surface's palette to change how the surface itself looks when displayed. By repeatedly changing the palette, the surface appears to change without actually modifying the contents of the surface. To this end, palette animation gives you a way to modify the appearance of a surface without changing its contents and with very little overhead.

There are two methods for providing straightforward palette animation:

  • Modifying palette entries within a single palette
  • Switching between multiple palettes
[C++]

Using the first method, you change individual palette entries that correspond to the colors you want to animate, then reset the entries with a single call to the IDirectDrawPalette::SetEntries method.

The second method requires two or more DirectDrawPalette objects. When using this method, you perform the animation by attaching one palette object after another to the surface object by calling the IDirectDrawSurface7::SetPalette method.

Neither method is hardware intensive, so use whichever technique works best for your application.

For specific information and an example of how to implement palette animation, see Tutorial 5: Dynamically Modifying Palettes.

[Visual Basic]

Using the first method, you change individual palette entries that correspond to the colors you want to animate, then reset the entries with a single call to the DirectDrawPalette.SetEntries method.

The second method requires two or more DirectDrawPalette objects. When using this method, you perform the animation by attaching one palette object after another to the surface object by calling the DirectDrawSurface7.SetPalette method.

Neither method is hardware intensive, so use whichever technique works best for your application.


Clippers

This section contains information about DirectDrawClipper objects. The following topics are discussed:

  • What Are Clippers?
  • Clip Lists
  • Sharing DirectDrawClipper Objects
  • Independent DirectDrawClipper Objects
  • Creating DirectDrawClipper Objects with CoCreateInstance
  • Using a Clipper with the System Cursor
  • Using a Clipper with Multiple Windows


What Are Clippers?

Clippers, or DirectDrawClipper objects, allow you to blit to selected parts of a surface represented by a bounding rectangle or a list of several bounding rectangles. (See Clip Lists.)

One common use for a clipper is to define the boundaries of the screen or window. For example, imagine that you want to display a sprite as it enters the screen from an edge. You don't want to make the sprite pop suddenly onto the screen; you want it to appear as though it is smoothly moving into view. Without a clipper object, DirectDraw does not allow you to blit the entire sprite, because part of it would fall outside the destination surface. A straight copy of the pixel values in the sprite to the destination surface buffer would result in an incorrect display and even memory access violations. With a clipper that has the screen rectangle as its clip list, DirectDraw knows how to trim the sprite as it performs the blit so that only the visible portion is copied.

The following illustration shows this type of clipping.

You can also use clipper objects to designate certain areas within a destination surface as writable. DirectDraw clips blit operations in these areas, protecting the pixels outside the specified clipping rectangle.

The following illustration shows this use of a clipper.


Clip Lists

[C++]

A clip list consists of one or more RECT structures, in pixel coordinates. DirectDraw manages clip lists by using a DirectDrawClipper object, which can be attached to any surface.

The IDirectDrawSurface7::Blt method copies data only to rectangles in the clip list. For instance, if the upper-right quarter of a surface was excluded by the rectangles in the clip list, and an application blitted to the entire area of the clipped surface, DirectDraw would effectively perform two blits, the first being to the upper-left corner of the surface, and the second being to the bottom half of the surface, as shown in the following diagram.

[Visual Basic]

A clip list consists of one or more RECT types, in pixel coordinates. DirectDraw manages clip lists by using a DirectDrawClipper object, which can be attached to any surface.

The DirectDrawSurface7.Blt method copies data only to rectangles in the clip list. For instance, if the upper-right quarter of a surface was excluded by the rectangles in the clip list, and an application blitted to the entire area of the clipped surface, DirectDraw would effectively perform two blits, the first being to the upper-left corner of the surface, and the second being to the bottom half of the surface, as shown in the following diagram.

You can manage a surface's clip list manually or, for a primary surface, have it done automatically by DirectDraw.

[C++]

To manage the clip list yourself, create a list of rectangles in the form of a RGNDATA structure and pass this to the IDirectDrawClipper::SetClipList method.

To have DirectDraw manage the clip list for a primary surface, you attach the clipper to a window (even a full-screen window) by calling the IDirectDrawClipper::SetHWnd method, specifying the target window's handle. This has the effect of setting the clipping region to the client area of the window and ensuring that the clip list is automatically updated as the window is resized, covered, or uncovered.

[Visual Basic]

To manage the clip list yourself, create a list of rectangles in the form of an array of RECT types and pass this to the DirectDrawClipper.SetClipList method.

To have DirectDraw manage the clip list for a primary surface, you attach the clipper to a window (even a full-screen window) by calling the DirectDrawClipper.SetHWnd method, specifying the target window's handle. This has the effect of setting the clipping region to the client area of the window and ensuring that the clip list is automatically updated as the window is resized, covered, or uncovered.

If you set a clipper using a window handle, you cannot set additional rectangles.

Clipping for overlay surfaces is supported only if the overlay hardware can support clipping and if destination color keying is not active.


Sharing DirectDrawClipper Objects

[C++]

DirectDrawClipper objects can be shared between multiple surfaces. For example, the same DirectDrawClipper object can be set on both the front buffer and the back buffer of a flipping chain. When an application attaches a DirectDrawClipper object to a surface by using the IDirectDrawSurface7::SetClipper method, the surface increments the reference count of that object. When the reference count of the surface reaches 0, the surface will decrement the reference count of the attached DirectDrawClipper object. In addition, if a DirectDrawClipper object is detached from a surface by calling IDirectDrawSurface7::SetClipper with a NULL clipper interface pointer, the reference count of the surface's DirectDrawClipper object will be decremented.

Note If IDirectDrawSurface7::SetClipper is called several times consecutively on the same surface for the same DirectDrawClipper object, the reference count for the object is incremented only once. Subsequent calls do not affect the object's reference count.

[Visual Basic]

DirectDrawClipper objects can be shared between multiple surfaces. For example, the same DirectDrawClipper object can be set on both the front buffer and the back buffer of a flipping chain. When an application attaches a DirectDrawClipper object to a surface by using the DirectDrawSurface7.SetClipper method.


Independent DirectDrawClipper Objects

[Visual Basic]

The information in this topic pertains only to applications written in C++.

[C++]

You can create DirectDrawClipper objects that are not directly owned by any particular DirectDraw object. These DirectDrawClipper objects can be shared across multiple DirectDraw objects. Driver-independent DirectDrawClipper objects are created by using the new DirectDrawCreateClipper DirectDraw function. An application can call this function before any DirectDraw objects are created.

Because DirectDraw objects do not own these DirectDrawClipper objects, they are not automatically released when your application's objects are released. If the application does not explicitly release these DirectDrawClipper objects, DirectDraw will release them when the application closes.

You can still create DirectDrawClipper objects by using the IDirectDraw7::CreateClipper method. These DirectDrawClipper objects are automatically released when the DirectDraw object from which they were created is released.


Creating DirectDrawClipper Objects with CoCreateInstance

[Visual Basic]

The information in this topic pertains only to applications written in C++.

[C++]

DirectDrawClipper objects have full class-factory support for COM compliance. In addition to using the standard DirectDrawCreateClipper function and IDirectDraw7::CreateClipper method, you can also create a DirectDrawClipper object either by using the CoGetClassObject function to obtain a class factory and then calling the CoCreateInstance function, or by calling CoCreateInstance directly. The following example shows how to create a DirectDrawClipper object by using CoCreateInstance and the IDirectDrawClipper::Initialize method.

ddrval = CoCreateInstance(&CLSID_DirectDrawClipper,
    NULL, CLSCTX_ALL, &IID_IDirectDrawClipper, &lpClipper);
if (!FAILED(ddrval))
    ddrval = IDirectDrawClipper_Initialize(lpClipper,
        lpDD, 0UL);

In this call to CoCreateInstance, the first parameter, CLSID_DirectDrawClipper, is the class identifier of the DirectDrawClipper object class, the IID_IDirectDrawClipper parameter identifies the currently supported interface, and the lpClipper parameter points to the DirectDrawClipper object that is retrieved.

An application must use the IDirectDrawClipper::Initialize method to initialize DirectDrawClipper objects that were created by the class-factory mechanism before it can use the object. The value 0UL is the dwFlags parameter, which in this case has a value of 0 because no flags are currently supported. In the example shown here, lpDD is the DirectDraw object that owns the DirectDrawClipper object. However, you could supply a NULL value instead, which would create an independent DirectDrawClipper object. (This is equivalent to creating a DirectDrawClipper object by using the DirectDrawCreateClipper function.)

Before you close the application, close the COM library by using the CoUninitialize function.


Using a Clipper with the System Cursor

DirectDraw applications often need to provide a way for users to navigate using the mouse. For full-screen exclusive mode applications that use page-flipping, the only option is to implement a mouse cursor manually with a sprite, moving the sprite based on data retrieved from the device by DirectInput® or by responding to Windows mouse messages. However, any application that doesn't use page-flipping can still use the system's mouse cursor support.

When you use the system mouse cursor, you will sometimes fall victim to graphic artifacts that occur when you blit to parts of the primary surface. These artifacts appear as portions of the mouse cursor seemingly left behind by the system.

[C++]

A DirectDrawClipper object can prevent these artifacts from appearing by preventing the mouse cursor image from "being in the way" during a blit operation. It's a relatively simple matter to implement, as well. To do so, create a DirectDrawClipper object by calling the IDirectDraw7::CreateClipper method. Then, assign your application's window handle to the clipper with the IDirectDrawClipper::SetHWnd method. Once a clipper is attached, any subsequent blits you perform on the primary surface with the IDirectDrawSurface7::Blt method will not exhibit the artifact.

Note that the IDirectDrawSurface7::BltFast method, and its counterparts in the IDirectDrawSurface, IDirectDrawSurface2, and IDirectDrawSurface3 interfaces, will not work on surfaces with attached clippers.

[Visual Basic]

A DirectDrawClipper object can prevent these artifacts from appearing by preventing the mouse cursor image from "being in the way" during a blit operation. It's a relatively simple matter to implement, as well. To do so, create a DirectDrawClipper object by calling the DirectDraw7.CreateClipper method. Then, assign your application's window handle to the clipper with the DirectDrawClipper.SetHWnd method. Once a clipper is attached, any subsequent blits you perform on the primary surface with the DirectDrawSurface7.Blt method will not exhibit the artifact.


Using a Clipper with Multiple Windows

You can use a DirectDrawClipper object to blit to multiple windows created by an application running at the normal cooperative level.

[C++]

To do this, create a single DirectDraw object with a primary surface. Then, create a DirectDrawClipper object and assign it to your primary surface by calling the IDirectDrawSurface7::SetClipper method. To blit only to the client area of a window, set the clipper to that window's client area by calling the IDirectDrawClipper::SetHWnd method before blitting to the primary surface. Whenever you need to blit to another window's client area, call the IDirectDrawClipper::SetHWnd method again with the new target window handle.

[Visual Basic]

To do this, create a single DirectDraw object with a primary surface. Then, create a DirectDrawClipper object and assign it to your primary surface by calling the DirectDrawSurface7.SetClipper method. To blit only to the client area of a window, set the clipper to that window's client area by calling the DirectDrawClipper.SetHWnd method before blitting to the primary surface. Whenever you need to blit to another window's client area, call the DirectDrawClipper.SetHWnd method again with the new target window handle.

Creating multiple DirectDraw objects that blit to each others' primary surface is not recommended. The technique just described provides an efficient and reliable way to blit to multiple client areas with a single DirectDraw object.


Multiple-Monitor Systems

[Visual Basic]

The information in this topic pertains only to applications written in C++.

[C++]

Windows 98 and Windows 2000 support multiple display devices and monitors on a single system. The multiple-monitor architecture (sometimes referred to as MultiMon) enables the operating system to use the display area from two or more display devices and monitors to create a single logical desktop. For example, in a MultiMon system with two monitors, the user could display applications on either monitor, or even drag windows from one monitor to another. DirectDraw supports this architecture, allowing applications to directly access hardware on multiple display devices in a MultiMon system.

Note As long as it is created on the null device and is not rendering directly to the primary surface, a non-full-screen DirectDraw application will work automatically with MultiMon, and the user will be able to drag the window from one monitor to another. However, DirectDraw will take advantage of hardware acceleration only when the window is entirely within the primary display. It is recommended that windowed DirectDraw applications be specifically designed for MultiMon by maintaining separate DirectDraw objects and surfaces for each monitor. For more information, see Devices and Acceleration in MultiMon Systems.

This section contains information about using DirectDraw on systems with multiple-monitor support. The following topics are discussed:

  • Enumerating Devices on MultiMon Systems
  • DirectDraw Objects on Multiple Monitors
  • Focus and Device Windows
  • Devices and Acceleration in MultiMon Systems
  • Debugging Full-Screen DirectDraw Applications with MultiMon

The Multimon.h header file included with the DirectX SDK makes it possible for code written around Windows 98 multiple-monitor functions to compile and run successfully on operating systems that do not support MultiMon.

The following sample application demonstrates the implementation of MultiMon in DirectDraw:

  • Multimon Sample


Enumerating Devices on MultiMon Systems

[Visual Basic]

The information in this topic pertains only to applications written in C++.

[C++]

Use the DirectDrawEnumerateEx function to enumerate devices on systems with multiple monitors, specifying flags to determine what types of DirectDraw devices should be enumerated. The function calls an application-defined DDEnumCallbackEx function for each enumerated device.

The DirectDrawEnumerateEx function is supported on Windows 98 and Windows 2000 operating systems. It is available in Ddraw.lib for applications compiled under DirectX 6.0 and later versions. Applications that statically link to the function will always run under DirectX 6.0 and later, and will always run under any version of DirectX on Windows 98 and Windows 2000. Such applications will fail if run on previous versions of DirectX under Windows 95.

If your application needs to run on versions of DirectX older than DirectX 5.0, it should use GetProcAddress to see if DirectDrawEnumerateEx is available. The following example shows one way you can do this:

    HINSTANCE h = LoadLibrary("ddraw.dll");

    // If ddraw.dll doesn't exist in the search path,
    // then DirectX probably isn't installed, so fail.
    if (!h)
        return FALSE;

    // Note that you must know which version of the
    // function to retrieve (see the following text).
    // For this example, we use the ANSI version.
    LPDIRECTDRAWENUMERATEEX lpDDEnumEx;
    lpDDEnumEx = (LPDIRECTDRAWENUMERATEEX) GetProcAddress(h,"DirectDrawEnumerateExA");

    // If the function is there, call it to enumerate all display
    // devices attached to the desktop, and any non-display DirectDraw
    // devices.
    if (lpDDEnumEx)
        lpDDEnumEx(Callback, NULL,
            DDENUM_ATTACHEDSECONDARYDEVICES |
            DDENUM_NONDISPLAYDEVICES
            );
    else
    {
        /*
         * We must be running on an old version of DirectDraw.
         * Therefore MultiMon isn't supported. Fall back on
         * DirectDrawEnumerate to enumerate standard devices on a
         * single-monitor system.
         */
        DirectDrawEnumerate(OldCallback,NULL);

        /* Note that it could be handy to let the OldCallback function
         * be a wrapper for a DDEnumCallbackEx.
         *
         * Such a function would look like:
         *    BOOL FAR PASCAL OldCallback(GUID FAR *lpGUID,
         *                                LPSTR pDesc,
         *                                LPSTR pName,
         *                                LPVOID pContext)
         *    {
         *         return Callback(lpGUID,pDesc,pName,pContext,NULL);
         *    }
         */
    }

    // If the library was loaded by calling LoadLibrary(),
    // then you must use FreeLibrary() to let go of it.
    FreeLibrary(h);

The previous example will work for applications that link to Ddraw.dll at run time or load time.

Note that you must retrieve the address of either the ANSI or Unicode version of the DirectDrawEnumerateEx function, depending of the type of strings your application uses. When declaring the corresponding callback function, use the LPTSTR data type for the string parameters. The LPTSTR data type compiles to use Unicode strings if you declare the _UNICODE symbol, and ANSI strings otherwise. By using the LPTSTR data type, the function should compile properly regardless of the string type you use in your application.


DirectDraw Objects on Multiple Monitors

[Visual Basic]

The information in this topic pertains only to applications written in C++.

[C++]

Windowed DirectDraw applications written for the null or default display driver will work on MultiMon systems, but in applications optimized for MultiMon you will want to create a separate DirectDraw object for each device, using the GUID returned in the enumeration callback. (See Enumerating Devices on MultiMon Systems.)

There are some MultiMon behaviors that will vary depending on whether the application specfies a GUID or NULL during DirectDraw object creation. The most noteable one being that if the application specifies NULL, DirectDraw always clips the cursor to the primary monitor.

Avoid setting the cooperative level multiple times on a MultiMon system. If you need to switch from full-screen to normal mode, it is best to create a new DirectDraw object.

To make an application respond to a user pressing the ALT + TAB keys, the application should not use the default window procedure. To enable this functionality, the device window must change the focus to the parent window each time a SETFOCUS message is recieved.

It is good practice to release all DirectDraw objects at the same time. If you release only the secondary device or devices, the primary device goes back to its original desktop mode, but only the task bar is redrawn and the DirectDraw primary surface is still present. You cannot draw to this surface without first releasing the DirectDraw object and then re-creating it.


Focus and Device Windows

[Visual Basic]

The information in this topic pertains only to applications written in C++.

[C++]

Each DirectDraw application that uses one or more monitors in full-screen exclusive mode must have a single focus window, which is the window that receives keyboard input.

Each device that is to hold a full-screen DirectDraw surface must be represented by a DirectDraw object and a device window. The device window is the one that is sized to fit the window and is put on top of all other windows.

For single-monitor applications, there is no distinction between the device and focus window. They are one and the same. For multiple-monitor applications, however, you need to set a device window for each monitor, and you have to let each DirectDraw object know about the application's focus window. The focus window can also serve as the device window for one of the monitors. Other device windows should be children of the focus window so that the application does not minimize when the user clicks on one of them.

Note: make sure your input focus window is specified as the devices parent window when creating multiple exclusive windows for a multimon application or your application will fail to get proper input.

See also:

  • Setting the Focus Window
  • Setting Device Windows


Setting the Focus Window

[Visual Basic]

The information in this topic pertains only to applications written in C++.

[C++]

To set the focus window, you call the IDirectDraw7::SetCooperativeLevel method for each of the DirectDraw objects. You pass in a window handle (normally the application window handle) and set the DDSCL_SETFOCUSWINDOW flag, as in the following example:

/* It is presumed that lpDD is a valid IDirectDraw interface pointer,
   and that hWnd is a valid window handle. */

HRESULT ddrval = lpDD->SetCooperativeLevel( hWnd,
        DDSCL_SETFOCUSWINDOW );

The focus window must be the same for all devices.


Setting Device Windows

[Visual Basic]

The information in this topic pertains only to applications written in C++.

[C++]

There are two ways to set a device window:

  • Create a window yourself and pass its handle to the IDirectDraw7::SetCooperativeLevel method of the DirectDraw object representing the monitor, setting the DDSCL_SETDEVICEWINDOW, DDSCL_FULLSCREEN, and DDSCL_EXCLUSIVE flags. This creates a full-screen window and sets it as the device window for the monitor. Your application will receive mouse messages for the window, and you are responsible for destroying the window at the appropriate time. The window you pass to SetCooperativeLevel should be either the focus window (possible only if it is on the same device) or a child of the focus window.
  • Let DirectDraw create the window. You pass the focus window handle to SetCooperativeLevel and set the DDSCL_CREATEDEVICEWINDOW, DDSCL_FULLSCREEN, and DDSCL_EXCLUSIVE flags. DirectDraw creates a default device window that is a child of the focus window. It manages this window and will destroy it at the appropriate time. Your application will not receive any mouse messages for the window.

The following example sets an existing device window for the DirectDraw object represented by lpDD.

/* It is presumed that lpDD is a valid IDirectDraw interface pointer,
   and that hWnd is the handle to an appropriate device window. */

HRESULT hr = lpDD->SetCooperativeLevel( hWnd,
        DDSCL_SETDEVICEWINDOW | DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN );

The following example sets a default device window created by DirectDraw. In this case, hWnd is the handle to the existing focus window.

HRESULT hr = lpDD->SetCooperativeLevel( hWnd,
        DDSCL_CREATEDEVICEWINDOW | DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN );

Although a focus window can be a device window, you cannot set a window as both the focus window and a device window with a single call to SetCooperativeLevel. You must first set it as the focus window and then set it as a device window. However, it is possible to set a focus window and a default device window on the same device with a single call to SetCooperativeLevel. The following example shows how this can be done:

HRESULT hr = lpDD->SetCooperativeLevel(
        hwndFocus,
        DDSCL_SETFOCUSWINDOW | DDSCL_FULLSCREEN |
        DDSCL_EXCLUSIVE | DDSCL_CREATEDEVICEWINDOW);

In this example, an existing window (probably the application window) is set as the focus window, and DirectDraw creates a default device window.


Devices and Acceleration in MultiMon Systems

[Visual Basic]

The information in this topic pertains only to applications written in C++.

[C++]

Full-screen exclusive mode DirectDraw objects will take advantage of hardware acceleration regardless of whether they are running on the primary device or on a secondary device. However, they cannot use built-in support for spanning graphics operations across display devices. It is the application's responsibility to perform operations on the appropriate device.

When the normal cooperative level is set, DirectDraw uses hardware acceleration only when the window is wholly within the display area of the primary device. When a window straddles two or more monitors, all blits are done in emulation and performance can be significantly slower. This is necessarily the case, because hardware buffers cannot blit to a display surface controlled by another piece of hardware.

As long as you create the DirectDraw object for the null device—that is, pass NULL to DirectDrawCreate as the lpGUID parameter—DirectDraw will blit to the entire window regardless of where it is located. However, if the device is created by its actual GUID, this is not the case, and blit operations that cross an edge of the primary surface will be clipped (if you are using a clipper) or will fail, returning DDERR_INVALIDRECT.

Note When you are blitting to a window in a MultiMon application, negative coordinates are valid when the logical location of the secondary monitor is to the left of the primary monitor.

To get the best performance in a windowed MultiMon application, you need to create a DirectDraw object for each device, maintain off-screen surfaces in parallel on each device, keep track of which part of the window resides on each device, and perform separate blits to each device.


Debugging Full-Screen DirectDraw Applications with MultiMon

[Visual Basic]

The information in this topic pertains only to applications written in C++.

[C++]

It is possible to use a multimonitor system rather than remote debugging in order to step through code while debugging a full-screen DirectDraw application.

You should use the primary monitor for your development environment and the secondary monitor for the DirectDraw output. Also, you need to change a registry setting through the DirectX property sheet in Control Panel. On the DirectDraw page, click Advanced Settings and select the Enable Multi-Monitor Debugging checkbox. This setting will prevent DirectDraw from minimizing your application when it loses focus.

Under Windows 98, you cannot step through code when a surface is locked. For more information, see Accessing Surface Memory Directly.


Advanced DirectDraw Topics

This section supplements the DirectDraw overview, providing information about advanced DirectDraw issues. The following topics are discussed:

  • Mode 13 Support
  • Taking Advantage of DMA Support
  • Using DirectDraw Palettes in Windowed Mode
  • Video Ports
  • Getting the Flip and Blit Status
  • Determining the Capabilities of the Display Hardware
  • Storing Bitmaps in Display Memory
  • Triple Buffering
  • DirectDraw Applications and Window Styles
  • Matching True RGB Colors to the Frame Buffer's Color Space
  • Displaying a Window in Full-Screen Mode


Mode 13 Support

This section contains information about DirectDraw Mode 13 graphics mode support. The following topics are discussed:

  • About Mode 13
  • Setting Mode 13
  • Mode 13 and Surface Capabilities
  • Using Mode 13


About Mode 13

DirectDraw supports access to the linear unflippable 320x200 8 bits per pixel palettized mode known widely by the name Mode 13, its hexadecimal BIOS mode number. DirectDraw treats this mode like a Mode X mode, but with some important differences imposed by the physical nature of Mode 13.


Setting Mode 13

[C++]

Mode 13 has similar enumeration and mode-setting behavior as Mode X. DirectDraw will only enumerate Mode 13 if the DDSCL_ALLOWMODEX flag was passed to the IDirectDraw7::SetCooperativeLevel method.

You enumerate the Mode 13 display mode like all other modes, but you make a surface capabilities check before calling IDirectDraw7::EnumDisplayModes. To do this, call IDirectDraw7::GetCaps and check for the DDSCAPS_STANDARDVGAMODE flag in the DDSCAPS2 structure after the method returns. If this flag is not present, then Mode 13 is not supported, and attempts to enumerate with the DDEDM_STANDARDVGAMODES flag will fail, returning DDERR_INVALIDPARAMS.

The EnumDisplayModes method now supports a new enumeration flag, DDEDM_STANDARDVGAMODES, which causes DirectDraw to enumerate Mode 13 in addition to the 320x200x8 Mode X mode. There is also a new IDirectDraw7::SetDisplayMode flag, DDSDM_STANDARDVGAMODE, which you must pass in order to distinguish Mode 13 from 320x200x8 Mode X.

[Visual Basic]

Mode 13 has similar enumeration and mode-setting behavior as Mode X. DirectDraw will only enumerate Mode 13 if the DDSCL_ALLOWMODEX flag was passed to the DirectDraw7.SetCooperativeLevel method.

You enumerate the Mode 13 display mode like all other modes, but you make a surface capabilities check before calling DirectDraw7.GetDisplayModesEnum. To do this, call DirectDraw7.GetCaps and check for the DDSCAPS_STANDARDVGAMODE flag in the DDSCAPS2 type after the method returns. If this flag is not present, then Mode 13 is not supported, and attempts to enumerate with the DDEDM_STANDARDVGAMODES flag will fail, generating DDERR_INVALIDPARAMS.

The GetDisplayModesEnum method now supports an enumeration flag, DDEDM_STANDARDVGAMODES, which causes DirectDraw to enumerate Mode 13 in addition to the 320x200x8 Mode X mode. There is also a new DirectDraw7.SetDisplayMode flag, DDSDM_STANDARDVGAMODE, which you must pass in order to distinguish Mode 13 from 320x200x8 Mode X.

Note that some video cards offer linear accelerated 320x200x8 modes. On such cards DirectDraw will not enumerate Mode 13, enumerating the linear mode instead. In this case, if you attempt to set Mode 13 by passing the DDSDM_STANDARDVGAMODE flag to SetDisplayMode, the method will succeed, but the linear mode will be used. This is analogous to the way that linear low resolution modes override Mode X modes.


Mode 13 and Surface Capabilities

[C++]

When DirectDraw calls an application's EnumModesCallback callback function, the ddsCaps member of the associated DDSURFACEDESC or DDSURFACEDESC2 structure contains flags that reflect the mode being enumerated. You can expect DDSCAPS_MODEX for a Mode X mode or DDSCAPS_STANDARDVGAMODE for Mode 13. These flags are mutually exclusive. If neither of these bits is set, then the mode is a linear accelerated mode. This behavior also applies to the flags retrieved by the IDirectDraw7::GetDisplayMode method.

[Visual Basic]

When DirectDraw calls an application's DirectDraw7.GetDisplayModesEnum method, the ddsCaps member of the associated DDSURFACEDESC2 type contains flags that reflect the mode being enumerated. You can expect DDSCAPS_MODEX for a Mode X mode or DDSCAPS_STANDARDVGAMODE for Mode 13. These flags are mutually exclusive. If neither of these bits is set, then the mode is a linear accelerated mode. This behavior also applies to the flags retrieved by the DirectDraw7.GetDisplayMode method.


Using Mode 13

[C++]

Because Mode 13 is a linear mode, unlike the Mode X modes, DirectDraw can give an application direct access to the frame buffer.You can call the IDirectDrawSurface7::Lock, IDirectDrawSurface7::Blt, and IDirectDrawSurface7::BltFast methods to gain direct access to the primary surface.

When using Mode 13, DirectDraw supports an emulated IDirectDrawSurface7::Flip that is implemented as a straight copy of the contents of a back buffer to the primary surface. You can emulate this yourself by copying all or part of the back-buffer's contents to the primary surface using Blt or BltFast.

[Visual Basic]

Because Mode 13 is a linear mode, unlike the Mode X modes, DirectDraw can give an application direct access to the frame buffer.You can call the DirectDrawSurface7.Lock, IDirectDrawSurface7.Blt, and DirectDrawSurface7.BltFast methods to gain direct access to the primary surface.

When using Mode 13, DirectDraw supports an emulated DirectDrawSurface7.Flip that is implemented as a straight copy of the contents of a back buffer to the primary surface. You can emulate this yourself by copying all or part of the back-buffer's contents to the primary surface using Blt or BltFast.

There is one warning concerning Lock and Mode 13. Although DirectDraw allows direct linear access to the Mode 13 VGA frame buffer, do not assume that the buffer is always located at address 0xA0000, since DirectDraw can return an aliased virtual-memory pointer to the frame buffer which will not be 0xA0000. Similarly, do not assume that the pitch of a Mode 13 surface is 320, because display cards that support an accelerated 320x200x8 mode will very likely use a different pitch.


Taking Advantage of DMA Support

This section contains information about how you can take advantage of device support for Direct Memory Access (DMA) to increase performance in completing certain tasks. The following topics are discussed:

  • About DMA Device Support
  • Testing for DMA Support
  • Typical Scenarios for DMA
  • Using DMA


About DMA Device Support

Some display devices can perform blit operations (or other operations) on system memory surfaces. These operations are commonly referred to as Direct Memory Access (DMA) operations. You can exploit DMA support to accelerate certain combinations of operations. For example, on such a device, you could perform a blit from system memory to video memory while using the processor to prepare the next frame. In order to use such facilities, you must assume certain responsibilities. This section details these tasks.


Testing for DMA Support

[C++]

Before using DMA operations, you must test the device for DMA support and, if it does support DMA, how much support it provides. Begin by retrieving the driver capabilities by calling the IDirectDraw7::GetCaps method, then look for the DDCAPS_CANBLTSYSMEM flag in the dwCaps member of the associated DDCAPS structure. If the flag is set, the device supports DMA.

If you know that DMA is generally supported, you also need to find out how well the driver supports it. You do so by looking at some other structure members that provide information about system-to-video, video-to-system, and system-to-system blit operations. These capabilities are provided in 12 DDCAPS structure members that are named according to blit and capability type. The following table shows these new members.

System-to-video | Video-to-system | System-to-system
dwSVBCaps | dwVSBCaps | dwSSBCaps
dwSVBCKeyCaps | dwVSBCKeyCaps | dwSSBCKeyCaps
dwSVBFXCaps | dwVSBFXCaps | dwSSBFXCaps
dwSVBRops | dwVSBRops | dwSSBRops

For example, the system-to-video blit capability flags are provided in the dwSVBCaps, dwSVBCKeyCaps, dwSVBFXCaps and dwSVBRops members. Similarly, video-to-system blit capabilities are in the members whose names begin with "dwVSB," and system-to system capabilities are in the "dwSSB" members. Examine the flags present in these members to determine the level of hardware support for that blit category.

The flags in these members are parallel with the blit-related flags included in the dwCaps, dwCKeyCaps, and dwFXCaps members, with respect to that member's blit type. For example, the dwSVBCaps member contains general blit capabilities as specified by the same flags you might find in the dwCaps member. Likewise, the raster operation values in the dwSVBRops, dwVSBRops, and dwSSBRops members provide information about the raster operations supported for a given type of blit operation.

One of the key features to look for in these members is support for asynchronous DMA blit operations. If the driver supports asynchronous DMA blits between surfaces, the DDCAPS_BLTQUEUE flag will be set in the dwSVBCaps, dwVSBCaps, or dwSSBCaps member. (Generally, you'll see the best support for system-memory-to-video-memory surfaces.) If the flag isn't present, the driver isn't reporting support for asynchronous DMA blit operations.

[Visual Basic]

Before using DMA operations, you must test the device for DMA support and, if it does support DMA, how much support it provides. Begin by retrieving the driver capabilities by calling the DirectDraw7.GetCaps method, then look for the DDCAPS_CANBLTSYSMEM flag in the lCaps member of the associated DDCAPS type. If the flag is set, the device supports DMA.

If you know that DMA is generally supported, you also need to find out how well the driver supports it. You do so by looking at some other structure members that provide information about system-to-video, video-to-system, and system-to-system blit operations. These capabilities are provided in 12 DDCAPS structure members that are named according to blit and capability type. The following table shows these new members.

System-to-video | Video-to-system | System-to-system
lSVBCaps | lVSBCaps | lSSBCaps
lSVBCKeyCaps | lVSBCKeyCaps | lSSBCKeyCaps
lSVBFXCaps | lVSBFXCaps | lSSBFXCaps
lSVBRops | lVSBRops | lSSBRops

For example, the system-to-video blit capability flags are provided in the lSVBCaps, lSVBCKeyCaps, lSVBFXCaps and lSVBRops members. Similarly, video-to-system blit capabilities are in the members whose names begin with "lVSB," and system-to system capabilities are in the "lSSB" members. Examine the flags present in these members to determine the level of hardware support for that blit category.

The flags in these members are parallel with the blit-related flags included in the lCaps, lCKeyCaps, and lFXCaps members, with respect to that member's blit type. For example, the lSVBCaps member contains general blit capabilities as specified by the same flags you might find in the lCaps member. Likewise, the raster operation values in the lSVBRops, lVSBRops, and lSSBRops members provide information about the raster operations supported for a given type of blit operation.

One of the key features to look for in these members is support for asynchronous DMA blit operations. If the driver supports asynchronous DMA blits between surfaces, the DDCAPS_BLTQUEUE flag will be set in the lSVBCaps, lVSBCaps, or lSSBCaps member. (Generally, you'll see the best support for system-memory-to-video-memory surfaces.) If the flag isn't present, the driver isn't reporting support for asynchronous DMA blit operations.


Typical Scenarios for DMA

System memory to video memory transfers that use the SRCCOPY raster operation are the most common type of hardware-supported blit operation. (The SRCCOPY raster operation, which is documented in the Platform SDK, causes the data within the source rectangle to be copied directly to the destination rectangle.) The most typical use for such an operation is to move textures from a large collection of system memory surfaces to a surface in video memory in preparation for subsequent operations. System-to-video DMA transfers are about as fast as processor-controlled transfers (for example, HEL blits), but are of great utility since they can operate in parallel with the host processor.


Using DMA

[Visual Basic]

The information in this topic pertains only to applications written in C++.

[C++]

Hardware transfers use physical memory addresses, not the virtual addresses which are home to applications. Some device drivers require that you provide the surface's physical memory address. This mechanism is implemented by the IDirectDrawSurface7::PageLock method. If the device driver does not require page locking, the DDCAPS2_NOPAGELOCKREQUIRED flag will be set when you retrieve the hardware capabilities by calling the IDirectDraw7::GetCaps method.

Page locking a surface prevents the system from committing a surface's physical memory to other uses, and guarantees that the surface's physical address will remain constant until a corresponding IDirectDrawSurface7::PageUnlock call is made. If the device driver requires page locking, DirectDraw will allow asynchronous DMA operations only on system memory surfaces that the application has page locked. If you do not call IDirectDrawSurface7::PageLock in such a situation, DirectDraw will perform the transfers by using software emulation. Note that locking a large amount of system memory will make Windows run poorly. Therefore, it is highly recommended that only full-screen exclusive mode applications use IDirectDrawSurface7::PageLock for large amounts of system memory, and that such applications take care to unlock these surfaces when the application is minimized. Of course, when the application is restored, you should page lock the system memory surface again.

Responsibility for managing page locking is entirely in the hands of the application developer. DirectDraw will never page lock or page unlock a surface. Additionally, it is up to you to determine how much memory you can safely page lock without adversely affecting system performance.


Using DirectDraw Palettes in Windowed Mode

[C++]

IDirectDrawPalette interface methods write directly to the hardware when the display is in exclusive (full-screen) mode. However, when the display is in nonexclusive (windowed) mode, the IDirectDrawPalette interface methods call the GDIs palette handling functions to work cooperatively with other windowed applications.

[Visual Basic]

DirectDrawPalette class methods write directly to the hardware when the display is in exclusive (full-screen) mode. However, when the display is in nonexclusive (windowed) mode, the DirectDrawPalette class methods call the GDIs palette handling functions to work cooperatively with other windowed applications.

The discussion in the following topics assumes that the desktop is in an 8-bit palettized mode and that you have created a primary surface and a typical window.

  • Types of Palette Entries in Windowed Mode
  • Creating a Palette in Windowed Mode
  • Setting Palette Entries in Windowed Mode


Types of Palette Entries in Windowed Mode

[C++]

Unlike full-screen exclusive mode applications, windowed applications must share the desktop palette with other applications. This imposes several restrictions on which palette entries you can safely modify and how you can modify them. The PALETTEENTRY structure you use when working with DirectDrawPalette objects and GDI contains a peFlags member to carry information that describes how the system should interpret the PALETTEENTRY structure.

The peFlags member describes three types of palette entries, discussed in this topic:

[Visual Basic]

Unlike full-screen exclusive mode applications, windowed applications must share the desktop palette with other applications. This imposes several restrictions on which palette entries you can safely modify and how you can modify them. The PALETTEENTRY type you use when working with DirectDrawPalette objects and GDI contains a flags member to carry information that describes how the system should interpret the PALETTEENTRY type.

The flags member describes three types of palette entries, discussed in this topic:

  • Windows static entries
  • Animated entries
  • Nonanimated entries

Windows static entries

In normal mode, Windows reserves palette entries 0 through 9 and 246 through 255 for system colors that it uses to display menu bars, menu text, window borders, and so on. In order to maintain a consistent look for your application and avoid damaging the appearance of other applications, you need to protect these entries in the palette you set to the primary surface. Often, developers retrieve the system palette entries by calling the GetSystemPaletteEntries Win32® function, then explicitly set the identical entries in a custom palette to match before assigning it to the primary surface. Duplicating the system palette entries in a custom palette will work initially, but it becomes invalid if the user changes the desktop color scheme.

To avoid having your palette look bad when the user changes color schemes, you can protect the appropriate entries by providing a reference into the system palette instead specifying a color value. This way, no matter what color the system is using for a given entry, your palette will always match and you won't need to do any updating. The PC_EXPLICIT flag, used in the peFlags member, makes it possible for you to directly refer to a system palette entry. When you use this flag, the system no longer assumes that the other structure members include color information. Rather, when you use PC_EXPLICIT, you set the value in the peRed member to the desired system palette index and set the other colors to zero.

[C++]

For instance, if you want to ensure that the proper entries in your palette always match the system's color scheme, you could use the following code:

// Set the first and last 10 entries to match the system palette.
PALETTEENTRY pe[256];
ZeroMemory(pe, sizeof(pe));
for(int i=0;i<10;i++){
    pe[i].peFlags  = pe[i+246].peFlags = PC_EXPLICIT;
    pe[i].peRed = i;
    pe[i+246].peRed = i+246;
}

You can force Windows to use only the first and last palette entry (0 and 255) by calling the SetSystemPaletteUse Win32 function. In this case, you should set only entries 0 and 255 of your PALETTEENTRY structure to PC_EXPLICIT.

Animated entries

You specify palette entries that you will be animating by using the PC_RESERVED flag in the corresponding PALETTEENTRY structure. Windows will not allow any other application to map its logical palette entry to that physical entry, thereby preventing other applications from cycling their colors when your application animates the palette.

Nonanimated entries

You specify normal, nonanimated palette entries by using the PC_NOCOLLAPSE flag in the corresponding PALETTEENTRY structure. The PC_NOCOLLAPSE flag informs Windows not to substitute some other already-allocated physical palette entry for that entry.

[Visual Basic]

You can force Windows to use only the first and last palette entry (0 and 255) by calling the SetSystemPaletteUse Win32 function. In this case, you should set only entries 0 and 255 of your PALETTEENTRY type to PC_EXPLICIT.

Animated entries

You specify palette entries that you will be animating by using the PC_RESERVED flag in the corresponding PALETTEENTRY type. Windows will not allow any other application to map its logical palette entry to that physical entry, thereby preventing other applications from cycling their colors when your application animates the palette.

Nonanimated entries

You specify normal, nonanimated palette entries by using the PC_NOCOLLAPSE flag in the corresponding PALETTEENTRY type. The PC_NOCOLLAPSE flag informs Windows not to substitute some other already-allocated physical palette entry for that entry.


Creating a Palette in Windowed Mode

[C++]

The following example illustrates how to create a DirectDraw palette in nonexclusive (windowed) mode. In order for your palette to work correctly, it is vital that you set up every one of the 256 entries in the PALETTEENTRY structure that you submit to the IDirectDraw7::CreatePalette method.

LPDIRECTDRAW7        lpDD; // Assumed to be initialized previously
PALETTEENTRY         pPaletteEntry[256];
int                  index;
HRESULT              ddrval;
LPDIRECTDRAWPALETTE2 lpDDPal;

// First set up the Windows static entries.
for (index = 0; index < 10 ; index++)
{
    // The first 10 static entries:
    pPaletteEntry[index].peFlags = PC_EXPLICIT;
    pPaletteEntry[index].peRed = index;
    pPaletteEntry[index].peGreen = 0;
    pPaletteEntry[index].peBlue = 0;

    // The last 10 static entries:
    pPaletteEntry[index+246].peFlags = PC_EXPLICIT;
    pPaletteEntry[index+246].peRed = index+246;
    pPaletteEntry[index+246].peGreen = 0;
    pPaletteEntry[index+246].peBlue = 0;
}

// Now set up private entries. In this example, the first 16
// available entries are animated.
for (index = 10; index < 26; index ++)
{
    pPaletteEntry[index].peFlags = PC_NOCOLLAPSE|PC_RESERVED;
    pPaletteEntry[index].peRed = 255;
    pPaletteEntry[index].peGreen = 64;
    pPaletteEntry[index].peBlue = 32;
}

// Now set up the rest, the nonanimated entries.
for (; index < 246; index ++) // Index is set up by previous for loop
{
    pPaletteEntry[index].peFlags = PC_NOCOLLAPSE;
    pPaletteEntry[index].peRed = 25;
    pPaletteEntry[index].peGreen = 6;
    pPaletteEntry[index].peBlue = 63;
}

// All 256 entries are filled. Create the palette.
ddrval = lpDD->CreatePalette(DDPCAPS_8BIT, pPaletteEntry,
    &lpDDPal,NULL);
[Visual Basic]

The following example illustrates how to create a DirectDraw palette in nonexclusive (windowed) mode. In order for your palette to work correctly, it is vital that you set up every one of the 256 entries in the PALETTEENTRY type that you submit to the DirectDraw7.CreatePalette method.

Private Sub Form_Load()

    Dim pPaletteEntry(255) As PALETTEENTRY
    Dim index As Long
    Dim ddpal As DirectDrawPalette

    'First set up the windows static entries.
    For index = 0 To 9
        'The first 10 static entries.
        pPaletteEntry(index).flags = PC_EXPLICIT
        pPaletteEntry(index).red = index
        pPaletteEntry(index).green = 0
        pPaletteEntry(index).blue = 0

        'The last 10 static entries
        pPaletteEntry(index + 246).flags = PC_EXPLICIT
        pPaletteEntry(index + 246).red = index + 246
        pPaletteEntry(index + 246).green = 0
        pPaletteEntry(index + 246).blue = 0
    Next

    'Now set up private entries. In this example, the first
    '16 available entried are animated.
    For index = 10 To 25
        pPaletteEntry(index).flags = PC_NOCOLLAPSE Or PC_RESERVED
        pPaletteEntry(index).red = 255
        pPaletteEntry(index).green = 64
        pPaletteEntry(index).blue = 32
    Next

    'Now set up the rest, the non-animated entries.
    For index = 26 To 246
        pPaletteEntry(index).flags = PC_NOCOLLAPSE
        pPaletteEntry(index).red = 25
        pPaletteEntry(index).green = 6
        pPaletteEntry(index).blue = 63
    Next

    'All 256 entries are filled. Create the palette.
    Set ddpal = dd.CreatePalette(DDPCAPS_8BIT, pPaletteEntry())


Setting Palette Entries in Windowed Mode

[C++]

The rules that apply to the PALETTEENTRY structure used with the IDirectDraw7::CreatePalette method also apply to the IDirectDrawPalette::SetEntries method. Typically, you maintain your own array of PALETTEENTRY structures, so you do not need to rebuild it. When necessary, you can modify the array, and then call IDirectDrawPalette::SetEntries when it is time to update the palette.

In most circumstances, you should not attempt to set any of the Windows static entries when in nonexclusive (windowed) mode or you will get unpredictable results. The only exception is when you reset the 256 entries.

For palette animation, you typically change only a small subset of entries in your PALETTEENTRY array. You submit only those entries to IDirectDrawPalette::SetEntries. If you are resetting such a small subset, you must reset only those entries marked with the PC_NOCOLLAPSE and PC_RESERVED flags. Attempting to animate other entries can have unpredictable results.

The following example illustrates palette animation in nonexclusive mode:

LPDIRECTDRAW        lpDD;        // Already initialized
PALETTEENTRY pPaletteEntry[256]; // Already initialized
LPDIRECTDRAWPALETTE lpDDPal;     // Already initialized
int                 index;
HRESULT             ddrval;
PALETTEENTRY        temp;

// Animate some entries. Cycle the first 16 available entries.
// They were already animated.
temp = pPaletteEntry[10];
for (index = 10; index < 25; index ++)
{
    pPaletteEntry[index] = pPaletteEntry[index+1];
}
pPaletteEntry[25] = temp;

// Set the values. Do not pass a pointer to the entire palette entry
// structure, but only to the changed entries.
ddrval = lpDDPal->SetEntries(
    0,                      // Flags must be zero
    10,                     // First entry
    16,                     // Number of entries
    & (pPaletteEntry[10])); // Where to get the data
[Visual Basic]

The rules that apply to the PALETTEENTRY type used with the DirectDraw7.CreatePalette method also apply to the DirectDrawPalette.SetEntries method. Typically, you maintain your own array of PALETTEENTRY types, so you do not need to rebuild it. When necessary, you can modify the array, and then call DirectDrawPalette.SetEntries when it is time to update the palette.

In most circumstances, you should not attempt to set any of the Windows static entries when in nonexclusive (windowed) mode or you will get unpredictable results. The only exception is when you reset the 256 entries.

For palette animation, you typically change only a small subset of entries in your PALETTEENTRY array. You submit only those entries to DirectDrawPalette.SetEntries. If you are resetting such a small subset, you must reset only those entries marked with the PC_NOCOLLAPSE and PC_RESERVED flags. Attempting to animate other entries can have unpredictable results.


Video Ports

[Visual Basic]

The information in this topic pertains only to applications written in C++. Visual Basic for DirectX 7.0 does not support video ports.

[C++]

DirectDraw video-port extensions are a low-level programming interface, not intended for mainstream multimedia programmers. The target customer is the video-streaming software industry, which creates products like DirectShow®. Developers who want to include video playback in their software can make use of video-port extensions. However, for most software, a high-level programming interface like the one provided by DirectShow is recommended for greater ease of use.

This section contains information about DirectDrawVideoPort objects. The following topics are discussed:

  • What Are Video Ports?
  • Video-Port Technology Overview
  • About DirectDraw Video-Port Extensions
  • Video Frames and Fields
  • HREF, VREF, and Connections
  • Vertical Blanking Interval Data
  • Autoflipping
  • Solutions to Common Video Artifacts
  • Solving Problems Caused by Half-Lines
  • Exploiting Hardware Features


What Are Video Ports?

[Visual Basic]

The information in this topic pertains only to applications written in C++. Visual Basic for DirectX 7.0 does not support Video Ports.

[C++]

A DirectDrawVideoPort object represents the video-port hardware found on some display adapters. Generally, a video-port object controls how the video-port hardware applies a video signal it receives from a video decoder directly to the frame buffer.

More than one channel of video can be controlled by creating as many DirectDrawVideoPort objects as is required. Because each channel can be separately enumerated and configured, the video hardware for each channel does not need to be identical.

For more information, see Video-Port Technology Overview.


Video-Port Technology Overview

[Visual Basic]

The information in this topic pertains only to applications written in C++. Visual Basic for DirectX 7.0 does not support Video Ports.

[C++]

A video port is hardware on a display device that enables direct access to a surface within the frame buffer, bypassing the CPU and PCI bus. Direct frame buffer access makes it possible to efficiently play live or recorded video without creating noticeable load on the CPU. Once in a surface, an image can be displayed on the screen as an overlay, used as a Direct3D texture, or accessed by the CPU for capture or other processing. The following paragraphs provide general information about the components that make up the technology and how they work.

Data Flow

In a machine equipped with a video port, data in a video stream can flow directly from a video source through a video decoder and the video port to the frame buffer. These components often exist together on a display adapter, but can be on separate hardware components that are physically connected to one another. An example of this data flow is provided in the following illustration.

Video source

In the scope of video-port technology, a video source is strictly a hardware video input device, such as a Zoom Video port, MPEG codec, or other hardware source. These sources broadcast signals in a variety of formats, including NTSC, PAL, and SECAM through a physical connection to a video decoder.

Video Decoder

A video decoder is also a hardware component. The video decoder's job is to decipher the information provided by the video source and send it to the video port in an agreed upon connection format. The decoder possesses a physical connection to the video port, and exposes its services through a stream class minidriver. The decoder is responsible for sending video data and clock and sync information to the video port.

Video port

Like the other components in the data flow path, the video port is a piece of hardware. The video port exists on the display adapter's VGA chip and has direct access to the frame buffer. It receives information sent from the decoder, processes it, and places it in the frame buffer to be displayed. During processing, the video port can manipulate image data to provide scaling, shrinking, color control, or cropping services.

Frame Buffer

The frame buffer accepts video data as provided by the video port. Once received, applications can programmatically manipulate the image data, blit it to other locations, or show it on the display using an overlay (the most common use).


About DirectDraw Video-Port Extensions

[Visual Basic]

The information in this topic pertains only to applications written in C++. Visual Basic for DirectX 7.0 does not support Video Ports.

[C++]

DirectDraw has been extended to include the DirectDrawVideoPort object, which takes advantage of video-port technology and provides its services through the IDDVideoPortContainer and IDirectDrawVideoPort interfaces.

DirectDrawVideoPort objects do not control the video decoder, because it provides services of its own, nor does DirectDraw control the video source; it is beyond the scope of the video port. Rather, a DirectDrawVideoPort object represents the video port itself. It monitors the incoming signal and passes image data to the frame buffer, using parameters set though its interface methods to modify the image, perform flipping, or carry out other services.

The IDDVideoPortContainer interface, which you can retrieve by calling the IDirectDraw7::QueryInterface method, provides methods to query the hardware for its capabilities and create video-port objects. You create a video-port object by calling the IDDVideoPortContainer::CreateVideoPort method. Video-port objects expose their functionality through the IDirectDrawVideoPort interface, enabling you to manipulate the video-port hardware itself. Using these interfaces, you can examine the video-port's capabilities, assign an overlay surface to receive image data, start and stop video playback, and set hardware parameters to manipulate image data for cropping, color control, scaling, or shrinking effects.

DirectDraw video-port extensions provide for multiple video ports on the same machine by allowing you to create multiple DirectDrawVideoPort objects. There is no requirement that multiple video ports on a machine be identical—each port is separately enumerated and configured separately, regardless of any hardware differences that might exist.

In keeping with the general philosophy of DirectX, this technology gives programmers low-level access to hardware features while insulating them from specific hardware implementation details. It is not a high-level API.


Video Frames and Fields

[Visual Basic]

The information in this topic pertains only to applications written in C++. Visual Basic for DirectX 7.0 does not support Video Ports.

[C++]

Video can be interlaced or non-interlaced. When a video signal is interlaced, each video frame is made of two fields of image data. Each field is a collection of every other scan line in an image, starting with the first or second scan line. The first field, referred to as the odd field (or field 1), contains the data for the first scan line and skips every other scan line to the end of the image. Similarly, the even field (or field 2), carries every other scan line starting with the second. The "even-ness" or "odd-ness" of a field is referred to as its field polarity.

When video is not interlaced, each field contains all of a frame's scan lines. Typically, video signals are sent at a rate of 30 frames per second; in the case of interleaved video, this means the rate is 60 fields per second.

The fields that make up a frame do not always reflect the same moment in time. For example, if the frames are separated by 1/30 of a second then the two fields of a frame may be separated by 1/60 of a second. Because a television displays each field individually, no two fields are simultaneously visible, and the difference between fields adds to the illusion of movement.


HREF, VREF, and Connections

[Visual Basic]

The information in this topic pertains only to applications written in C++. Visual Basic for DirectX 7.0 does not support Video Ports.

[C++]

When a monitor or other display device is displaying an image, it typically scans down the screen, creating an image from left to right, top to bottom. (Sometimes, the device makes two passes down the screen to create a single image; this type of display is called an interlaced display.) The video stream contains signals that instruct the display device when a new line or new screen is to be drawn.

The terms HREF and VREF, also known as hsync and vsync, are the signals within the video stream that tell a display device what to do and when to do it. The HREF signals that a new line is to be drawn and the VREF signals a new screen.

For instance, imagine you're working with a video signal intended for the world's smallest monitor. The monitor only has 4 scan lines. (This is not at all realistic, of course, but it's simple.) On an oscilloscope, the HREF and VREF signals would look somewhat like the following illustration.

In the preceding illustration, both HREF and VREF signals are "active high," meaning that they are considered active when in a heightened state (when the waves go up). There is no standard for these signals. In some cases, places where the waves go down ("low" states) might signal an active HREF or VREF, or sometimes one will be active high and the other active low. Although the preceding illustration is only an imaginary example, note that there are lots of HREF signals for each VREF. This is because for each new screen, there are several scan lines. Of course, in a real video signal for a real broadcast, you would see hundreds of HREFs for a single VREF.

HREF signals, VREF signals, and video data are carried across physical data lines from the decoder to the video port. In many cases, a number of lines are reserved for video data, and others are dedicated to carrying HREF and VREF signals. However, there is no standard for how these data lines are used.

A connection is a protocol that a video port or decoder uses to define how it uses these data lines. Video ports and video decoders will support a variety of connections. DirectDraw video-port extensions use globally-unique identifiers (GUIDs) to identify each type of connection. You can query for the connections that the video port supports by calling the IDDVideoPortContainer::GetVideoPortConnectInfo method. You create a DirectDrawVideoPort object that supports a given connection by calling the IDDVideoPortContainer::CreateVideoPort method.

Keep in mind that the video decoder is outside the scope of DirectDraw video-port extensions, and exposes its supported connections through an interface of its own. By enumerating the connections that the video-port supports and comparing the results with the connections supported by the decoder, you can negotiate a common connection (or "language") that both components understand.


Vertical Blanking Interval Data

[Visual Basic]

The information in this topic pertains only to applications written in C++. Visual Basic for DirectX 7.0 does not support Video Ports.

[C++]

In broadcast video, a small period of time elapses between video frames, during which a display device refreshes its display for the next frame. This period of time is called the Vertical Blanking Interval (VBI). Instead of sitting idle during the VBI, broadcast video encodes data in the first twenty-one scan lines of a video frame and sends these lines during the VBI. This data is often used for closed captioning or time-stamping, but can be used for other purposes.

DirectDraw video-port extensions enable you to divert data contained with the VBI to a surface, bypass scaling of VBI data, and automatically flip between VBI surfaces in a flipping chain. Once data is in a surface, you can directly access the surface's memory as needed.

For more information, see Autoflipping.


Autoflipping

[Visual Basic]

The information in this topic pertains only to applications written in C++. Visual Basic for DirectX 7.0 does not support Video Ports.

[C++]

To avoid tearing images when refreshing the screen between frames, DirectDrawVideoPort objects can automatically flip their target overlay surfaces in response to VREF signals. To use this service, the target surface you set to the video-port object with the IDirectDrawVideoPort::SetTargetSurface method must be the first surface in a flipping chain of overlay surfaces. Then, to begin playing the video sequence, call the IDirectDrawVideoPort::StartVideo method, specifying the DDVP_AUTOFLIP flag in the dwVPFlags member of the associated DDVIDEOPORTINFO structure. The video-port object will flip to the next surface in the flipping chain for each VREF signal it receives. If the video port is interleaving fields, it will flip once for every two VREF signals it receives.

If you are using autoflipping and want to direct VBI data to separate auto-flipped surfaces, you must have the same number of VBI surfaces as you do standard video surfaces.


Solutions to Common Video Artifacts

[Visual Basic]

The information in this topic pertains only to applications written in C++. Visual Basic for DirectX 7.0 does not support Video Ports.

[C++]

Several problems are inherent in displaying broadcast video on display devices other than televisions. This section briefly discusses some common problems, then describes how DirectDraw video-port extensions tries to solve them.

NTSC Interlaced Display and Interleaved Memory

An NTSC signal broadcasts video at an approximate rate of 30 frames, or 60 fields, per second. Like a frame, a field in an NTSC signal is independent of the other field in a frame and can contain different image data. For more information on this behavior, see Video Frames and Fields.

The problems caused by the independence of fields within a frame become apparent when two fields are interleaved for display. In video with a lot of movement, the two fields of a single frame will contain images that don't match each other, resulting in motion artifacts.

One way that developers have tried to work around this behavior is by discarding one of the fields. This solution causes a loss in image quality by roughly one-half, but provides acceptable results for some purposes. Another method frequently used is to display fields individually, stretching each vertically by a factor of two when it is displayed. This provides better image quality, but because fields are offset by one pixel in the y-direction, the result is an animation that "jitters" up and down as it plays.

DirectDraw video-port extensions can employ two, more advanced, techniques for improving image quality, known as "Bob" and "Weave." Both are supported by the DirectDraw overlay surfaces that are used with video-port extensions.

The first algorithm, Bob, is very similar to the method of displaying each field in a frame individually. However, for each field, the overlay's source rectangle is adjusted to accommodate for any jittering effects. Effectively, the source rectangle bounces up and down in time with the fields, negating the jittering on the screen. The following illustration depicts this process.

The Weave algorithm provides the best image quality for material that originates from film by exploiting a common technique used in the video industry for converting motion pictures to television. Unlike Bob, a video-port object does not Weave by itself; you must combine the default overlay behavior of displaying both fields simultaneously with kernel mode video transport (provided with Windows 2000 and Windows 98) to implement the algorithm.

Here is a synopsis of the algorithm, provided for completeness. Motion pictures capture video at a rate of 24 frames per second. When converting a motion picture for television, technicians use a technique called 3:2 pulldown to convert the frame rate to the 30 frames per second required for television broadcasts. This technique involves inserting a redundant field for every four true fields in the video stream to come up with the required number of fields.

When you weave, you are reversing this process. You detect when 3:2 pulldown is being used, removing any redundant fields to restore the original motion-picture frames. The fields that make up the restored frames can then be interleaved in memory without risk of motion artifacts. Occasionally, the pattern of redundant frames will change due to edits within the original film or reel breaks. You must monitor when these changes occur and update the behavior to adjust for the new pattern.

By default, an overlay surface displays both fields simultaneously. This works well if you're implementing the Weave algorithm, but prevents the video port from using the Bob algorithm. You can programmatically change how the overlay treats video data by calling the IDirectDrawSurface7::UpdateOverlay method. The flags you include in the dwFlags parameter determine the overlay's behavior: if you include the DDOVER_BOB flag, the video port will use the Bob algorithm; if you don't, it displays both fields. Note that by simply displaying both fields simultaneously, the resulting video will show motion artifacts.


Solving Problems Caused by Half-Lines

[Visual Basic]

The information in this topic pertains only to applications written in C++. Visual Basic for DirectX 7.0 does not support Video Ports.

[C++]

Some video decoders output a half line of meaningless data at the beginning of the even field. If this extra line is written to the frame buffer, the resulting image will appear garbled. In some cases, the video-port hardware is capable of sensing and discarding this data before writing it to the frame buffer.

You can determine if a video port is capable of discarding this data when retrieving connection information with the IDDVideoPortContainer::GetVideoPortConnectInfo method. If the video port cannot discard half-lines, the DDVPCONNECT_HALFLINE flag will be specified in the dwFlags member of the associated DDVIDEOPORTCONNECT structure for each supported connection.

If the video port is unable to discard half-lines, you have two options: you can discard one of the fields, or you can work around the hardware's limitations by making some adjustments in how you create the video-port object and display images with the target overlay surface

Here's how to work around the problem. When creating the video-port object by calling the IDDVideoPortContainer::CreateVideoPort method, include the DDVPCONNECT_INVERTPOLARITY flag in the dwFlags member of the associated DDVIDEOPORTCONNECT structure. This causes the video port to invert the polarity of the fields in the video stream, treating even fields like odd fields and vice versa. Once reversed, the half-line preceding even fields will be written to the frame buffer as the first scan line of each frame. To remove the unwanted data, adjust the source rectangle of the overlay surface used to display the image down one pixel by calling the IDirectDrawVideoPort::StartVideo method with the necessary coordinates. Note that this technique requires that you allocate one extra line in the surface containing the even field.


Exploiting Hardware Features

[Visual Basic]

The information in this topic pertains only to applications written in C++. Visual Basic for DirectX 7.0 does not support Video Ports.

[C++]

Video-port hardware often supports special features for adjusting color, shrinking or zooming images, handling VBI data, or skipping fields. The HAL provides information about these features by using flags in the DDVIDEOPORTCAPS structure. You retrieve the capabilities of a machine's video-port hardware by calling the IDDVideoPortContainer::EnumVideoPorts method.

To exploit these features for playback, you use the IDirectDrawVideoPort::StartVideo method, which uses a DDVIDEOPORTINFO structure to request that hardware features be used to modify image data before placing it in the frame buffer or for display. By setting values and flags in this structure, you can specify the source rectangle used with the overlay surface, indicate cropping regions, request hardware scaling, and set pixel formats.

DirectDrawVideoPort objects do not emulate video-port hardware services.


Getting the Flip and Blit Status

[C++]

When the IDirectDrawSurface7::Flip method is called, the primary surface and back buffer are exchanged. However, the exchange may not occur immediately. For example, if a previous flip has not finished, or if it did not succeed, this method returns DDERR_WASSTILLDRAWING. In the samples included with the SDK, the IDirectDrawSurface7::Flip call continues to loop until it returns DD_OK. Also, a IDirectDrawSurface7::Flip call does not complete immediately. It schedules a flip for the next time a vertical blank occurs on the system.

An application that waits until the DDERR_WASSTILLDRAWING value is not returned is very inefficient. Instead, you could create a function in your application that calls the IDirectDrawSurface7::GetFlipStatus method on the back buffer to determine if the previous flip has finished.

If the previous flip has not finished and the call returns DDERR_WASSTILLDRAWING, your application can use the time to perform another task before it checks the status again. Otherwise, you can perform the next flip. The following example demonstrates this concept:

while(lpDDSBack->GetFlipStatus(DDGFS_ISFLIPDONE) ==
    DDERR_WASSTILLDRAWING);

    // Waiting for the previous flip to finish. The application can
    // perform another task here.

ddrval = lpDDSPrimary->Flip(NULL, 0);

You can use the IDirectDrawSurface7::GetBltStatus method in much the same way to determine whether a blit has finished. Because IDirectDrawSurface7::GetFlipStatus and IDirectDrawSurface7::GetBltStatus return immediately, you can use them periodically in your application with little loss in speed.

[Visual Basic]

When the DirectDrawSurface7.Flip method is called, the primary surface and back buffer are exchanged. However, the exchange may not occur immediately. For example, if a previous flip has not finished, or if it did not succeed, this method raises a DDERR_WASSTILLDRAWING error.

An application that waits until the DDERR_WASSTILLDRAWING error value is not raised is very inefficient. Instead, you could create a function in your application that calls the DirectDrawSurface7.GetFlipStatus method on the back buffer to determine if the previous flip has finished.

If the previous flip has not finished and the call returns DDERR_WASSTILLDRAWING, your application can use the time to perform another task before it checks the status again. Otherwise, you can perform the next flip. The following example demonstrates this concept:

while(DDSBack.GetFlipStatus(DDGFS_ISFLIPDONE) =
    DDERR_WASSTILLDRAWING)

    ' Waiting for the previous flip to finish. The application can
    ' perform another task here.

DDSPrimary->Flip(NOTHING, 0)

You can use the DirectDrawSurface7.GetBltStatus method in much the same way to determine whether a blit has finished. Because DirectDrawSurface7.GetFlipStatus and DirectDrawSurface7.GetBltStatus return immediately, you can use them periodically in your application with little loss in speed.


Determining the Capabilities of the Display Hardware

DirectDraw uses software emulation to perform the DirectDraw functions not supported by the user's hardware. To accelerate performance of your DirectDraw applications, you should determine the capabilities of the user's display hardware after you have created a DirectDraw object, then structure your program to take advantage of these capabilities when possible.

[C++]

You can determine these capabilities by using the IDirectDraw7::GetCaps method. Not all hardware features are supported in emulation. If you want to use a feature only supported by some hardware, you must also be prepared to supply some alternative for systems with hardware that lacks that feature.

[Visual Basic]

You can determine these capabilities by using the DirectDraw7.GetCaps method. Not all hardware features are supported in emulation. If you want to use a feature only supported by some hardware, you must also be prepared to supply some alternative for systems with hardware that lacks that feature.


Storing Bitmaps in Display Memory

Blitting from display memory to display memory is usually much more efficient than blitting from system memory to display memory. As a result, you should store as many of the sprites your application uses as possible in display memory.

[C++]

Most display adapter hardware contains enough extra memory to store more than the primary surface and the back buffer. Call the IDirectDraw7::GetAvailableVidMem method to determine the amount of total and available memory for storing bitmaps in the display adapter's memory. After the call, the lpdwTotal parameter contains the total amount of display memory, minus the primary surface and any private caches held by driver, and lpdwFree contains the amount of display memory currently free that can be allocated for a surface that matches the capabilities specified by the structure at lpDDSCaps2.

[Visual Basic]

Most display adapter hardware contains enough extra memory to store more than the primary surface and the back buffer. Call the DirectDraw7.GetAvailableTotalMem method to determine the amount of total and available memory for storing bitmaps in the display adapter's memory. This method returns the total amount of display memory, minus the primary surface and any private caches held by driver, for a surface that matches the capabilities specified by the DDSCAPS2 type.


Triple Buffering

[C++]

In some cases, that is, when the display adapter has enough memory, it may be possible to speed up the process of displaying your application by using triple buffering. Triple buffering uses one primary surface and two back buffers. The following example shows how to initialize a triple-buffering scheme:

// The lpDDSPrimary and lpDDSBack variables are globally
// declared, uninitialized LPDIRECTDRAWSURFACE7 variables.
//
// The lpDD variable is a pointer to an IDirectDraw7 interface

DDSURFACEDESC2 ddsd;
ZeroMemory (&ddsd, sizeof(ddsd));

// Create the primary surface with two back buffers.
ddsd.dwSize = sizeof(ddsd);
ddsd.dwFlags = DDSD_CAPS | DDSD_BACKBUFFERCOUNT;
ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE |
    DDSCAPS_FLIP | DDSCAPS_COMPLEX;
ddsd.dwBackBufferCount = 2;
ddrval = lpDD->CreateSurface(&ddsd, &lpDDSPrimary, NULL);

// If we successfully created the flipping chain,
// retrieve pointers to the surfaces we need for
// flipping and blitting.
if(ddrval == DD_OK)
{
    // Get the surface directly attached to the primary (the back buffer).
    ddsd.ddsCaps.dwCaps = DDSCAPS_BACKBUFFER;
    ddrval = lpDDSPrimary->GetAttachedSurface(&ddsd.ddsCaps,
        &lpDDSBack);
    if(ddrval != DD_OK) ;
        // Display an error message here.
}

You do not need to keep track of all surfaces in a triple buffered flipping chain. The only surfaces you must keep pointers to are the primary surface and the back-buffer surface. You need a pointer to the primary surface in order to flip the surfaces in the flipping chain, and you need a pointer to the back buffer for blitting. For more information, see Flipping Surfaces.

Triple buffering allows your application to continue blitting to the back buffer even if a flip has not completed and the back buffer's blit has already finished. Performing a flip is not a synchronous event; one flip can take longer than another. Therefore, if your application uses only one back buffer, it may spend some time idling while waiting for the IDirectDrawSurface7::Flip method to return with DD_OK.

[Visual Basic]

In some cases, that is, when the display adapter has enough memory, it may be possible to speed up the process of displaying your application by using triple buffering. Triple buffering uses one primary surface and two back buffers. The following example shows how to initialize a triple-buffering scheme:

' The DDSPrimary and DDSBack variables are globally
' declared DIRECTDRAWSURFACE7 variables.
'
' The DD variable is a DirectDraw7 object

Dim ddsd As DDSURFACEDESC2

' Create the primary surface with two back buffers.
ddsd.lFlags = DDSD_CAPS Or DDSD_BACKBUFFERCOUNT
ddsd.ddsCaps.lCaps = DDSCAPS_PRIMARYSURFACE Or
    DDSCAPS_FLIP Or DDSCAPS_COMPLEX
ddsd.lBackBufferCount = 2
DDSPrimary = DD.CreateSurface(ddsd)

' If we successfully created the flipping chain,
' retrieve the surfaces we need for flipping and blitting.
' Get the surface directly attached to the primary (the back buffer).
ddsd.ddsCaps.lCaps = DDSCAPS_BACKBUFFER
DDSBack = DDSPrimary.GetAttachedSurface(ddsd.ddsCaps)

You do not need to keep track of all surfaces in a triple buffered flipping chain. The only surfaces you must keep pointers to are the primary surface and the back-buffer surface. You need a pointer to the primary surface in order to flip the surfaces in the flipping chain, and you need a pointer to the back buffer for blitting. For more information, see Flipping Surfaces.

Triple buffering allows your application to continue blitting to the back buffer even if a flip has not completed and the back buffer's blit has already finished. Performing a flip is not a synchronous event; one flip can take longer than another. Therefore, if your application uses only one back buffer, it may spend some time idling while waiting for the DirectDrawSurface7.Flip method to succeed.


DirectDraw Applications and Window Styles

[Visual Basic]

The information in this topic pertains only to applications written in C++.

[C++]

If your application uses DirectDraw in windowed mode, you can create windows with any window style. However, full-screen exclusive mode applications cannot be created with the WS_EX_TOOLWINDOW style without risk of unpredictable behavior. The WS_EX_TOOLWINDOW style prevents a window from being the top most window, which is required for a DirectDraw full-screen, exclusive mode application.

Full-screen exclusive mode applications should use the WS_EX_TOPMOST extended window style and the WS_VISIBLE window style to display properly. These styles keep the application at the front of the window z-order and prevent GDI from drawing on the primary surface.

The following example shows one way to safely prepare a window to be used in a full-screen, exclusive mode application.

////////////////////////////////////////////////////////
// Register the window class and display the window.
////////////////////////////////////////////////////////
BOOL WINAPI InitApp(INT nWinMode)
{
    WNDCLASSEX wcex;

    wcex.cbSize           =    sizeof(WNDCLASSEX);
    wcex.hInstance        =    g_hinst;
    wcex.lpszClassName    =    g_szWinName;
    wcex.lpfnWndProc      =    WndProc;
    wcex.style            =    CS_VREDRAW|CS_HREDRAW|CS_DBLCLKS;
    wcex.hIcon            =    LoadIcon (NULL, IDI_APPLICATION);
    wcex.hIconSm          =    LoadIcon (NULL, IDI_WINLOGO);
    wcex.hCursor          =    LoadCursor (NULL, IDC_ARROW);
    wcex.lpszMenuName     =    MAKEINTRESOURCE(IDR_APPMENU);
    wcex.cbClsExtra       =    0 ;
    wcex.cbWndExtra       =    0 ;
    wcex.hbrBackground    =    GetStockObject (NULL_BRUSH);

    RegisterClassEx(&wcex);

    g_hwndMain = CreateWindowEx(
                        WS_EX_TOPMOST,
                        g_szWinName,
                        g_szWinCaption,
                        WS_VISIBLE|WS_POPUP,
                        0,0,0,0,
                        NULL,
                        NULL,
                        g_hinst,
                        NULL);

    if(!g_hwndMain)
        return(FALSE);

    SetFocus(g_hwndMain);
    ShowWindow(g_hwndMain, nWinMode);
    UpdateWindow(g_hwndMain);

    return TRUE;
}


Matching True RGB Colors to the Frame Buffer's Color Space

[Visual Basic]

The information in this topic pertains only to applications written in C++.

[C++]

Applications often need to find out how a true RGB color (RGB 888) will be mapped into a frame buffer's color space when the display device is not in RGB 888 mode. For example, imagine you're working on an application that will run in 16- and 24-bit RGB display modes. You know that when the art was created, a color was reserved for use as a transparent blitting color key; for the sake of argument, it is a 24-bit color such as RGB(128,64,255). Because your application will also run in a 16-bit RGB mode, you need a way to find out how this 24-bit color key maps into the color space that the frame buffer uses when it's running in a 16-bit RGB mode.

Although DirectDraw does not perform color matching services for you, there are ways to calculate how your color key will be mapped in the frame buffer. These methods can be pretty complicated. For most purposes, you can use the GDI built-in color matching services, combined with the DirectDraw direct frame buffer access, to determine how a color value maps into a different color space. In fact, the Ddutil.cpp source file included in the DirectX examples of the Platform SDK includes a sample function called DDColorMatch that performs this task. The DDColorMatch sample function performs the following main tasks:

  1. Retrieves the color value of a pixel in a surface at 0,0.
  2. Calls the Win32 SetPixel function, using a COLORREF structure that describes your 24-bit RGB color.
  3. Uses DirectDraw to lock the surface, getting a pointer to the frame buffer memory.
  4. Retrieves the actual color value from the frame buffer (set by GDI in Step 2) and unlocks the surface
  5. Resets the pixel at 0,0 to its original color using SetPixel.

The process used by the DDColorMatch sample function is not fast; it isn't intended to be. However, it provides a reliable way to determine how a color will be mapped across different RGB color spaces. For more information, see the source code for DDColorMatch in the Ddutil.cpp source file.

Note Because the SetPixel GDI function only accepts a COLORREF structure on input, this technique only works for matching RGB 888 colors to the frame buffer's pixel format. If your application needs to match colors of another pixel format, you should translate them to RGB 888 before using this technique or query the primary surface for its pixel format and match colors manually.


Displaying a Window in Full-Screen Mode

[Visual Basic]

The information in this topic pertains only to applications written in C++.

[C++]

In full-screen mode, DirectDraw has exclusive control over the display. As a result, dialog boxes and other windows created through GDI are not normally visible. However, by using special techniques you can incorporate a Windows dialog box, HTML Help, or any other kind of window in your application.

The FSWindow Sample illustrates how a dialog box can be displayed and updated in a full-screen application, and how mouse clicks and keystrokes work just as if the dialog box were being displayed by GDI.

In FSWindow, the dialog box is created and "shown" as an ordinary dialog window:

hWndDlg = CreateDialog(g_hInstance,
        MAKEINTRESOURCE(IDD_DIALOG_SAMPLE),
        hWnd, (DLGPROC) SampleDlgProc);
ShowWindow(hWndDlg, SW_SHOWNORMAL);

Of course, at this point the dialog box is shown only on the hidden GDI surface. It does not appear on the primary surface, which is controlled by DirectDraw.

If the hardware capabilities include DDCAPS2_CANRENDERWINDOWED (see DDCAPS), displaying and updating the dialog box is easy. The application simply calls the IDirectDraw7::FlipToGDISurface method, which makes the GDI surface the primary surface. From now on, all updates to the dialog box will be displayed automatically, because GDI is now rendering directly to the front buffer. The application continues rendering to the back buffer, and on each pass through the rendering loop the contents of the back buffer are blitted to the front buffer by DirectDraw. The dialog box is not overwritten because the front buffer is clipped to the application window, and the dialog box is obscuring part of that window.

The following code, from the FSWindow_Init function, creates the clipper, associates it with the application window, and brings the GDI surface to the front:

if (ddObject->CreateClipper(0, &ddClipper, NULL) == DD_OK)
    ddClipper->SetHWnd(0, hwndAppWindow);
ddObject->FlipToGDISurface();

Then, in the FSWindow_Update function, the following code blits the rendered contents of the back buffer to the clipping region:

ddFrontBuffer->SetClipper(ddClipper);
ddFrontBuffer->Blt(NULL, ddBackBuffer, NULL, DDBLT_WAIT, NULL);

Note that because the GDI surface is the primary surface, Windows continues displaying the mouse cursor. (This would not be the case, however, if the application were using DirectInput with the mouse device at the exclusive cooperative level.)

For hardware that does not have the DDCAPS2_CANRENDERWINDOWED capability, the process of displaying and updating a window in full-screen mode is somewhat more complicated. In this case, the application is responsible for obtaining the image of the window created by GDI and blitting it to the back buffer after the full-screen rendering has been done. The entire back buffer is then flipped to the front in the usual way.

The FSWindow sample provides two different methods for accessing the display memory of the window, depending on whether the content is static or dynamic. The method for static content is faster because it involves blitting from a memory device context rather than a screen device context. This method should be used for windows that do not change, such as informational dialog boxes. (Remember, though, that unless you manually update the bitmap in response to events, even basic animation such as a button press will not be visible to the user.)

If the content is static, FSWindow calls the CreateBMPFromWindow function when the window is initialized. This function creates a bitmap and blits the contents of the window into it. The bitmap handle is stored in the global variable hwndFSWindowBMP. Whenever the primary surface is about to be updated, this bitmap is blitted to the back buffer, as follows:

if (FSWindow_IsStatic)
{
    hdcMemory = CreateCompatibleDC(NULL);
    SelectObject(hdcMemory, hwndFSWindowBMP);
    BitBlt(hdcBackBuffer, x, y, cx, cy, hdcMemory, 0, 0, SRCCOPY);
    DeleteDC(hdcMemory);
}

If, on the other hand, the content of the window is dynamic, the following code is executed. It blits the image directly from the GDI surface (represented by the hdcScreen device context) to the back buffer.

BitBlt(hdcBackBuffer, x, y, cx, cy, hdcScreen, x, y, SRCCOPY);

The coordinates represent the position and dimensions of the window on the GDI surface, as retrieved through a call to GetWindowRect.

When the FSWindow application is running on hardware that does not have the DDCAPS2_CANRENDERWINDOWED capability, it does not use the GDI surface, so Windows cannot display the mouse cursor. The application takes over this task by obtaining information about the cursor and displaying it on the back buffer just before the flip.


DirectDraw Tutorials

This section contains a series of tutorials, each providing step-by-step instructions for implementing the basics of DirectDraw in a C/C++ or Visual Basic application. The tutorials are written parallel to a set of sample files that are provided with this SDK in the \Samples\Multimedia\DDraw\Tutorials directory, following their code path and providing explanations along the way. Readers are encouraged to follow along in the sample code as they move through these tutorials.

  • DirectDraw C/C++ Tutorials
  • DirectDraw Visual Basic Tutorials


DirectDraw C/C++ Tutorials

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

This section contains a series of tutorials, each of which provides step-by-step instructions for implementing a simple DirectDraw application. These tutorials use many of the DirectDraw sample files that are provided with this SDK. These samples demonstrate how to set up DirectDraw, and how to use the DirectDraw methods to perform common tasks:

  • Tutorial 1: The Basics of DirectDraw
  • Tutorial 2: Loading Bitmaps on the Back Buffer
  • Tutorial 3: Blitting from an Off-Screen Surface
  • Tutorial 4: Color Keys and Bitmap Animation
  • Tutorial 5: Dynamically Modifying Palettes
  • Tutorial 6: Using Overlay Surfaces

Note The sample files in these tutorials are written in C++. If you are using a C compiler, you must make the appropriate changes to the files for them to successfully compile. At the very least, you need to add the vtable and this pointers to the interface methods.


Tutorial 1: The Basics of DirectDraw

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

To use DirectDraw, you first create an instance of the DirectDraw object, which represents the display adapter on the computer. You then use the interface methods to manipulate the object. In addition, you need to create one or more instances of a DirectDrawSurface object to be able to display your application on a graphics surface.

To demonstrate this, the DDEx1 sample included with this SDK performs the following steps:

  • Step 1: Create a DirectDraw Object
  • Step 2: Determine the Application's Behavior
  • Step 3: Change the Display Mode
  • Step 4: Create Flipping Surfaces
  • Step 5: Render to the Surfaces
  • Step 6: Write to the Surface
  • Step 7: Flip the Surfaces
  • Step 8: Deallocate the DirectDraw Objects

Note To use GUIDs successfully in your applications, you must either define INITGUID prior to all other include and define statements, or you must link to the Dxguid.lib library. You should define INITGUID in only one of your source modules.


Step 1: Create a DirectDraw Object

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

To create an instance of a DirectDraw object, your application should use the DirectDrawCreateEx function as shown in the doInit sample function of the DDEx1 program. DirectDrawCreateEx contains four parameters. The first parameter takes a globally unique identifier (GUID) that represents the display device. The GUID, in most cases, is set to NULL, which means DirectDraw uses the default display driver for the system. The second parameter contains the address of a pointer that identifies the location of the DirectDraw object if it is created. The third parameter is the reference identification for the IDirectDraw7 interface, this parameter must be set to IID_IDirectDraw7. The fourth parameter is always set to NULL and is included for future expansion.

The following example shows how to create the DirectDraw object and how to determine if the creation was successful or not:

ddrval = DirectDrawCreateEx(NULL, &lpDD, IID_IDirectDraw7, NULL);
if(ddrval == DD_OK)
{
    // lpDD is a valid DirectDraw object.
}
else
{
    // The DirectDraw object could not be created.
}

Next: Step 2: Determine the Application's Behavior


Step 2: Determine the Application's Behavior

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

Before you can change the resolution of the display, you must at a minimum specify the DDSCL_EXCLUSIVE and DDSCL_FULLSCREEN flags in the dwFlags parameter of the IDirectDraw7::SetCooperativeLevel method. This gives your application complete control over the display device, and no other application will be able to share it. In addition, the DDSCL_FULLSCREEN flag sets the application in exclusive (full-screen) mode. Your application covers the entire desktop, and only your application can write to the screen. The desktop is still available, however. (To see the desktop in an application running in exclusive mode, start DDEx1 and press ALT + TAB.)

The following example demonstrates the use of the SetCooperativeLevel method:

HRESULT      ddrval;
LPDIRECTDRAW7 lpDD;     // Already created by DirectDrawCreateEx

ddrval = lpDD->SetCooperativeLevel(hwnd, DDSCL_EXCLUSIVE |
    DDSCL_FULLSCREEN);
if(ddrval == DD_OK)
{
    // Exclusive mode was successful.
}
else
{
    // Exclusive mode was not successful.
    // The application can still run, however.
}

If SetCooperativeLevel does not return DD_OK, you can still run your application. The application will not be in exclusive mode, however, and it might not be capable of the performance your application requires. In this case, you might want to display a message that allows the user to decide whether or not to continue.

If you are setting the full-screen, exclusive cooperative level, you must pass your application's window handle to SetCooperativeLevel to allow Windows to determine if your application terminates abnormally. For example, if a general protection (GP) fault occurs and GDI is flipped to the back buffer, the user will not be able to return to the Windows screen. To prevent this from occurring, DirectDraw provides a process running in the background that traps messages that are sent to that window. DirectDraw uses these messages to determine when the application terminates. This feature imposes some restrictions, however. You have to specify the window handle that is retrieving messages for your application—that is, if you create another window, you must ensure that you specify the window that is active. Otherwise, you might experience problems, including unpredictable behavior from GDI, or no response when you press ALT + TAB.

Next: Step 3: Change the Display Mode


Step 3: Change the Display Mode

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

After you have set the application's behavior, you can use the IDirectDraw7::SetDisplayMode method to change the resolution of the display. The following example shows how to set the display mode to 640×480×8 bpp:

HRESULT      ddrval;
LPDIRECTDRAW7 lpDD;  // Already created

ddrval = lpDD->SetDisplayMode(640, 480, 8);
if(ddrval == DD_OK)
{
    // The display mode changed successfully.
}
else
{
    // The display mode cannot be changed.
    // The mode is either not supported or
    // another application has exclusive mode.
}

When you set the display mode, you should ensure that if the user's hardware cannot support higher resolutions, your application reverts to a standard mode that is supported by a majority of display adapters. For example, your application could be designed to run on all systems that support 640×480×8 as a standard backup resolution.

Note IDirectDraw7::SetDisplayMode returns a DDERR_INVALIDMODE error value if the display adapter could not be set to the desired resolution. Therefore, you should use the IDirectDraw7::EnumDisplayModes method to determine the capabilities of the user's display adapter before trying to set the display mode.

Next: Step 4: Create Flipping Surfaces


Step 4: Create Flipping Surfaces

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

After you have set the display mode, you must create the surfaces on which to place your application. Because the DDEx1 example is using the IDirectDraw7::SetCooperativeLevel method to set the mode to exclusive (full-screen) mode, you can create surfaces that flip between the surfaces. If you were using SetCooperativeLevel to set the mode to DDSCL_NORMAL, you could create only surfaces that blit between the surfaces. Creating flipping surfaces requires the following steps, also discussed in this topic:

  • Step 4.1: Define the Surface Requirements
  • Step 4.2: Create the Surfaces


Step 4.1: Define the Surface Requirements

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

The first step in creating flipping surfaces is to define the surface requirements in a DDSURFACEDESC2 structure. The following example shows the structure definitions and flags needed to create a flipping surface.

// Create the primary surface with one back buffer.
ddsd.dwSize = sizeof(ddsd);
ddsd.dwFlags = DDSD_CAPS | DDSD_BACKBUFFERCOUNT;
ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE |
    DDSCAPS_FLIP | DDSCAPS_COMPLEX;

ddsd.dwBackBufferCount = 1;

In this example, the dwSize member is set to the size of the DDSURFACEDESC2 structure. This is to prevent any DirectDraw method call you use from returning with an invalid member error. (The dwSize member was provided for future expansion of the DDSURFACEDESC2 structure.)

The dwFlags member determines which members in the DDSURFACEDESC2 structure will be filled with valid information. For the DDEx1 example, dwFlags is set to specify that you want to use the DDSCAPS structure (DDSD_CAPS) and that you want to create a back buffer (DDSD_BACKBUFFERCOUNT).

The dwCaps member in the example indicates the flags that will be used in the DDSCAPS structure. In this case, it specifies a primary surface (DDSCAPS_PRIMARYSURFACE), a flipping surface (DDSCAPS_FLIP), and a complex surface (DDSCAPS_COMPLEX).

Finally, the example specifies one back buffer. The back buffer is where the backgrounds and sprites will actually be written. The back buffer is then flipped to the primary surface. In the DDEx1 example, the number of back buffers is set to 1. You can, however, create as many back buffers as the amount of display memory allows. For more information on creating more than one back buffer, see Triple Buffering.

Surface memory can be either display memory or system memory. DirectDraw uses system memory if the application runs out of display memory (for example, if you specify more than one back buffer on a display adapter with only 1 MB of RAM). You can also specify whether to use only system memory or only display memory by setting the dwCaps member in the DDSCAPS structure to DDSCAPS_SYSTEMMEMORY or DDSCAPS_VIDEOMEMORY. (If you specify DDSCAPS_VIDEOMEMORY, but not enough memory is available to create the surface, IDirectDraw7::CreateSurface returns with a DDERR_OUTOFVIDEOMEMORY error.)

Next: Step 4.2: Create the Surfaces


Step 4.2: Create the Surfaces

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

After the DDSURFACEDESC2 structure is filled, you can use it and lpDD, the pointer to the DirectDraw object that was created by the DirectDrawCreateEx function, to call the IDirectDraw7::CreateSurface method, as shown in the following example:

ddrval = lpDD->CreateSurface(&ddsd, &lpDDSPrimary, NULL);
if(ddrval == DD_OK)
{
    // lpDDSPrimary points to the new surface.
}
else
{
    // The surface was not created.
    return FALSE;
}

The lpDDSPrimary parameter will point to the primary surface returned by CreateSurface if the call succeeds.

After the pointer to the primary surface is available, you can use the IDirectDrawSurface7::GetAttachedSurface method to retrieve a pointer to the back buffer, as shown in the following example:

ddscaps.dwCaps = DDSCAPS_BACKBUFFER;
ddrval = lpDDSPrimary->GetAttachedSurface(&ddcaps, &lpDDSBack);
if(ddrval == DD_OK)
{
    // lpDDSBack points to the back buffer.
}
else
{
    return FALSE;
}

By supplying the address of the surface's primary surface and by setting the capabilities value with the DDSCAPS_BACKBUFFER flag, the lpDDSBack parameter will point to the back buffer if the IDirectDrawSurface7::GetAttachedSurface call succeeds.

Next: Step 5: Render to the Surfaces


Step 5: Render to the Surfaces

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

After the primary surface and a back buffer have been created, the DDEx1 example renders some text on the primary surface and back buffer surface by using standard Windows GDI functions, as shown in the following example:

if (lpDDSPrimary->GetDC(&hdc) == DD_OK)
{
    SetBkColor(hdc, RGB(0, 0, 255));
    SetTextColor(hdc, RGB(255, 255, 0));
    TextOut(hdc, 0, 0, szFrontMsg, lstrlen(szFrontMsg));
    lpDDSPrimary->ReleaseDC(hdc);
}

if (lpDDSBack->GetDC(&hdc) == DD_OK)
{
    SetBkColor(hdc, RGB(0, 0, 255));
    SetTextColor(hdc, RGB(255, 255, 0));
    TextOut(hdc, 0, 0, szBackMsg, lstrlen(szBackMsg));
    lpDDSBack->ReleaseDC(hdc);
}

The example uses the IDirectDrawSurface7::GetDC method to retrieve the handle of the device context, and it internally locks the surface. If you are not going to use Windows functions that require a handle of a device context, you could use the IDirectDrawSurface7::Lock and IDirectDrawSurface7::Unlock methods to lock and unlock the back buffer.

Locking the surface memory (whether the whole surface or part of a surface) ensures that your application and the system blitter cannot obtain access to the surface memory at the same time. This prevents errors from occurring while your application is writing to surface memory. In addition, your application cannot page flip until the surface memory is unlocked.

After the surface is locked, the example uses standard Windows GDI functions: SetBkColor to set the background color, SetTextColor to select the color of the text to be placed on the background, and TextOut to print the text and background color on the surfaces.

After the text has been written to the buffer, the example uses the IDirectDrawSurface7::ReleaseDC method to unlock the surface and release the handle. Whenever your application finishes writing to the back buffer, you must call either IDirectDrawSurface7::ReleaseDC or IDirectDrawSurface7::Unlock, depending on your application. Your application cannot flip the surface until the surface is unlocked.

Typically, you write to a back buffer, which you then flip to the primary surface to be displayed. In the case of DDEx1, there is a significant delay before the first flip, so DDEx1 writes to the primary buffer in the initialization function to prevent a delay before displaying the surface. As you will see in a subsequent step of this tutorial, the DDEx1 example writes only to the back buffer during WM_TIMER. An initialization function or title page may be the only place where you might want to write to the primary surface.

Note After the surface is unlocked by using IDirectDrawSurface7::Unlock, the pointer to the surface memory is invalid. You must use IDirectDrawSurface7::Lock again to obtain a valid pointer to the surface memory.

Next: Step 6: Write to the Surface


Step 6: Write to the Surface

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

The first half of the WM_TIMER message in DDEx1 is devoted to writing to the back buffer, as shown in the following example:

case WM_TIMER:
    // Flip surfaces.
    if(bActive)
    {
        if (lpDDSBack->GetDC(&hdc) == DD_OK)
        {
            SetBkColor(hdc, RGB(0, 0, 255));
            SetTextColor(hdc, RGB(255, 255, 0));
            if(phase)
            {
                TextOut(hdc, 0, 0, szFrontMsg, lstrlen(szFrontMsg));
                phase = 0;
            }
            else
            {
                TextOut(hdc, 0, 0, szBackMsg, lstrlen(szBackMsg));
                phase = 1;
            }
            lpDDSBack->ReleaseDC(hdc);
        }

The line of code that calls the IDirectDrawSurface7::GetDC method locks the back buffer in preparation for writing. The SetBkColor and SetTextColor functions set the colors of the background and text.

Next, the phase variable determines whether the primary buffer message or the back buffer message should be written. If phase equals 1, the primary surface message is written, and phase is set to 0. If phase equals 0, the back buffer message is written, and phase is set to 1. Note, however, that in both cases the messages are written to the back buffer.

After the message is written to the back buffer, the back buffer is unlocked by using the IDirectDrawSurface7::ReleaseDC method.

Next: Step 7: Flip the Surfaces


Step 7: Flip the Surfaces

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

After the surface memory is unlocked, you can use the IDirectDrawSurface7::Flip method to flip the back buffer to the primary surface, as shown in the following example:

while(1)
{
    HRESULT ddrval;
    ddrval = lpDDSPrimary->Flip(NULL, 0);
    if(ddrval == DD_OK)
    {
        break;
    }
    if(ddrval == DDERR_SURFACELOST)
    {
        ddrval = lpDDSPrimary->Restore();
        if(ddrval != DD_OK)
        {
            break;
        }
    }
    if(ddrval != DDERR_WASSTILLDRAWING)
    {
        break;
    }
}

In the example, lpDDSPrimary parameter designates the primary surface and its associated back buffer. When IDirectDrawSurface7::Flip is called, the front and back surfaces are exchanged (only the pointers to the surfaces are changed; no data is actually moved). If the flip is successful and returns DD_OK, the application breaks from the while loop.

If the flip returns with a DDERR_SURFACELOST value, an attempt is made to restore the surface by using the IDirectDrawSurface7::Restore method. If the restore is successful, the application loops back to the IDirectDrawSurface7::Flip call and tries again. If the restore is unsuccessful, the application breaks from the while loop, and returns with an error.

Note When you call IDirectDrawSurface7::Flip, the flip does not complete immediately. Rather, a flip is scheduled for the next time a vertical blank occurs on the system. If, for example, the previous flip has not occurred, IDirectDrawSurface7::Flip returns DDERR_WASSTILLDRAWING. In the example, the IDirectDrawSurface7::Flip call continues to loop until it returns DD_OK.

Next: Step 8: Deallocate the DirectDraw Objects


Step 8: Deallocate the DirectDraw Objects

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

When you press the F12 key, the DDEx1 application processes the WM_DESTROY message before exiting the application. This message calls the finiObjects sample function, which contains all of the IUnknown::Release calls, as shown in the following example:

static void finiObjects(void)
{
    if(lpDD != NULL)
    {
        if(lpDDSPrimary != NULL)
        {
            lpDDSPrimary->Release();
            lpDDSPrimary = NULL;
        }
        lpDD->Release();
        lpDD = NULL;
    }
} // finiObjects

The application checks if the pointers to the DirectDraw object (lpDD) and the DirectDrawSurface object (lpDDSPrimary) are not equal to NULL. Then DDEx1 calls the IDirectDrawSurface7::Release method to decrease the reference count of the DirectDrawSurface object by 1. Because this brings the reference count to 0, the DirectDrawSurface object is deallocated. The DirectDrawSurface pointer is then destroyed by setting its value to NULL. Next, the application calls IDirectDraw7::Release to decrease the reference count of the DirectDraw object to 0, deallocating the DirectDraw object. This pointer is then also destroyed by setting its value to NULL.


Tutorial 2: Loading Bitmaps on the Back Buffer

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

The sample discussed in this tutorial (DDEx2) expands on the DDEx1 sample that was discussed in Tutorial 1. DDEx2 includes functionality to load a bitmap file on the back buffer. This new functionality is demonstrated in the following steps:

  • Step 1: Create the Palette
  • Step 2: Set the Palette
  • Step 3: Load a Bitmap on the Back Buffer
  • Step 4: Flip the Surfaces

As in DDEx1, doInit is the initialization function for the DDEx2 application. Although the code for the DirectDraw initialization does not look quite the same in DDEx2 as it did in DDEx1, it is essentially the same, except for the following section:

lpDDPal = DDLoadPalette(lpDD, szBackground);

if (lpDDPal == NULL)
    goto error;

ddrval = lpDDSPrimary->SetPalette(lpDDPal);

if(ddrval != DD_OK)
    goto error;

// Load a bitmap into the back buffer.
ddrval = DDReLoadBitmap(lpDDSBack, szBackground);

if(ddrval != DD_OK)
    goto error;


Step 1: Create the Palette

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

The DDEx2 sample first loads the palette into a structure by using the following code:

lpDDPal = DDLoadPalette(lpDD, szBackground);

if (lpDDPal == NULL)
    goto error;

The sample function DDLoadPalette is part of the common DirectDraw functions found in the Ddutil.cpp file located in the \Dxsdk\Sdk\Samples\Misc directory. Most of the DirectDraw sample files in this SDK use this file. Essentially, it contains the functions for loading bitmaps and palettes from either files or resources. To avoid having to repeat code in the example files, these functions were placed in a file that could be reused. Make sure you include Ddutil.cpp in the list of files to be compiled with the rest of the DDExn samples.

For DDEx2, the DDLoadPalette sample function creates a DirectDrawPalette object from the Back.bmp file. The DDLoadPalette sample function determines if a file or resource for creating a palette exists. If one does not, it creates a default palette. For DDEx2, it extracts the palette information from the bitmap file and stores it in a structure pointed to by ape.

DDEx2 then creates the DirectDrawPalette object, as shown in the following example:

pdd->CreatePalette(DDPCAPS_8BIT, ape, &ddpal, NULL);
return ddpal;

When the IDirectDraw7::CreatePalette method returns, the ddpal parameter points to the DirectDrawPalette object, which is then returned from the DDLoadPalette call.

The ape parameter is a pointer to a structure that can contain either 2, 4, 16, or 256 entries, organized linearly. The number of entries depends on the dwFlags parameter in the CreatePalette method. In this case, the dwFlags parameter is set to DDPCAPS_8BIT, which indicates that there are 256 entries in this structure. Each entry contains 4 bytes (a red channel, a green channel, a blue channel, and a flags byte).

Next: Step 2: Set the Palette


Step 2: Set the Palette

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

After you create the palette, you pass the pointer to the DirectDrawPalette object (ddpal) to the primary surface by calling the IDirectDrawSurface7::SetPalette method, as shown in the following example:

ddrval = lpDDSPrimary->SetPalette(lpDDPal);

if(ddrval != DD_OK)
    // SetPalette failed.

After you have called IDirectDrawSurface7::SetPalette, the DirectDrawPalette object is associated with the DirectDrawSurface object. Any time you need to change the palette, you simply create a new palette and set the palette again. (Although this tutorial uses these steps, there are other ways of changing the palette, as will be shown in later examples.)

Next: Step 3: Load a Bitmap on the Back Buffer


Step 3: Load a Bitmap on the Back Buffer

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

After the DirectDrawPalette object is associated with the DirectDrawSurface object, DDEx2 loads the Back.bmp bitmap on the back buffer by using the following code:

// Load a bitmap into the back buffer.
ddrval = DDReLoadBitmap(lpDDSBack, szBackground);

if(ddrval != DD_OK)
    // Load failed.

DDReLoadBitmap is another sample function found in Ddutil.cpp. It loads a bitmap from a file or resource into an already existing DirectDraw surface. (You could also use DDLoadBitmap to create a surface and load the bitmap into that surface. For more information, see Tutorial 5: Dynamically Modifying Palettes.) For DDEx2, it loads the Back.bmp file pointed to by szBackground onto the back buffer pointed to by lpDDSBack. The DDReLoadBitmap function calls the DDCopyBitmap function to copy the file onto the back buffer and stretch it to the proper size.

The DDCopyBitmap function copies the bitmap into memory, and it uses the GetObject function to retrieve the size of the bitmap. It then uses the following code to retrieve the size of the back buffer onto which it will place the bitmap:

// Get the size of the surface.
ddsd.dwSize = sizeof(ddsd);
ddsd.dwFlags = DDSD_HEIGHT | DDSD_WIDTH;
pdds->GetSurfaceDesc(&ddsd);

The ddsd value is a pointer to the DDSURFACEDESC2 structure. This structure stores the current description of the DirectDraw surface. In this case, the DDSURFACEDESC2 members describe the height and width of the surface, which are indicated by DDSD_HEIGHT and DDSD_WIDTH. The call to the IDirectDrawSurface7::GetSurfaceDesc method then loads the structure with the proper values. For DDEx2, the values will be 480 for the height and 640 for the width.

The DDCopyBitmap sample function locks the surface and copies the bitmap to the back buffer, stretching or compressing it as applicable by using the StretchBlt function, as shown in the following example:

if ((hr = pdds->GetDC(&hdc)) == DD_OK)
{
    StretchBlt(hdc, 0, 0, ddsd.dwWidth, ddsd.dwHeight, hdcImage, x, y,
        dx, dy, SRCCOPY);
    pdds->ReleaseDC(hdc);
}

Next: Step 4: Flip the Surfaces


Step 4: Flip the Surfaces

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

Flipping surfaces in the DDEx2 sample is essentially the same process as that in the DDEx1 tutorial (see Tutorial 1: The Basics of DirectDraw) except that if the surface is lost (DDERR_SURFACELOST), the bitmap must be reloaded on the back buffer by using the DDReLoadBitmap function after the surface is restored.


Tutorial 3: Blitting from an Off-Screen Surface

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

The sample in Tutorial 2 (DDEx2) takes a bitmap and puts it in the back buffer, and then it flips between the back buffer and the primary buffer. This is not a very realistic approach to displaying bitmaps. The sample in this tutorial (DDEx3) expands on the capabilities of DDEx2 by including two off-screen buffers in which the two bitmaps—one for the even screen and one for the odd screen—are stored. It uses the IDirectDrawSurface7::BltFast method to copy the contents of an off-screen surface to the back buffer, and then it flips the buffers and copies the next off-screen surface to the back buffer.

The new functionality demonstrated in DDEx3 is shown in the following steps:

  • Step 1: Create the Off-Screen Surfaces
  • Step 2: Load the Bitmaps to the Off-Screen Surfaces
  • Step 3: Blit the Off-Screen Surfaces to the Back Buffer


Step 1: Create the Off-Screen Surfaces

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

The following code is added to the doInit sample function in DDEx3 to create the two off-screen buffers:

// Create an offscreen bitmap.
ddsd.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH;
ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN;
ddsd.dwHeight = 480;
ddsd.dwWidth = 640;
ddrval = lpDD->CreateSurface(&ddsd, &lpDDSOne, NULL);
if(ddrval != DD_OK)
{
    return initFail(hwnd);
}

// Create another offscreen bitmap.
ddrval = lpDD->CreateSurface(&ddsd, &lpDDSTwo, NULL);
if(ddrval != DD_OK)
{
    return initFail(hwnd);
}

The dwFlags member specifies that the application will use the DDSCAPS structure, and it will set the height and width of the buffer. The surface will be an off-screen plain buffer, as indicated by the DDSCAPS_OFFSCREEN flag set in the DDSCAPS structure. The height and the width are set as 480 and 640, respectively, in the DDSURFACEDESC2 structure. The surface is then created by using the IDirectDraw7::CreateSurface method.

Because both of the off-screen plain buffers are the same size, the only requirement for creating the second buffer is to call IDirectDraw7::CreateSurface again with a different pointer name.

You can also specifically request that the off-screen buffer be placed in system memory or display memory by setting either the DDSCAPS_SYSTEMMEMORY or DDSCAPS_VIDEOMEMORY capability in the DDSCAPS structure. By saving the bitmaps in display memory, you can increase the speed of the transfers between the off-screen surfaces and the back buffer. This will become more important when using bitmap animation. However, if you specify DDSCAPS_VIDEOMEMORY for the off-screen buffer and not enough display memory is available to hold the entire bitmap, a DDERR_OUTOFVIDEOMEMORY error value will be returned when you attempt to create the surface.

Next: Step 2: Load the Bitmaps to the Off-Screen Surfaces


Step 2: Load the Bitmaps to the Off-Screen Surfaces

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

After the two off-screen surfaces are created, DDEx3 uses the InitSurfaces sample function to load the bitmaps from the Frntback.bmp file onto the surfaces. The InitSurfaces function uses the DDCopyBitmap sample function located in Ddutil.cpp to load both of the bitmaps, as shown in the following example:

// Load the bitmap resource.
hbm = (HBITMAP)LoadImage(GetModuleHandle(NULL), szBitmap,
    IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION);

if (hbm == NULL)
    return FALSE;

DDCopyBitmap(lpDDSOne, hbm, 0, 0,   640, 480);
DDCopyBitmap(lpDDSTwo, hbm, 0, 480, 640, 480);
DeleteObject(hbm);

return TRUE;

If you look at the Frntback.bmp file in Microsoft® Paint or another drawing application, you can see that the bitmap consists of two screens, one on top of the other. The DDCopyBitmap function breaks the bitmap in two at the point where the screens meet. In addition, it loads the first bitmap into the first off-screen surface (lpDDSOne) and the second bitmap into the second off-screen surface (lpDDSTwo).

Next: Step 3: Blit the Off-Screen Surfaces to the Back Buffer


Step 3: Blit the Off-Screen Surfaces to the Back Buffer

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

The WM_TIMER message contains the code for writing to surfaces and flipping surfaces. In the case of DDEx3, it contains the following code to select the proper off-screen surface and to blit it to the back buffer:

rcRect.left = 0;
rcRect.top = 0;
rcRect.right = 640;
rcRect.bottom = 480;
if(phase)
{
    pdds = lpDDSTwo;
    phase = 0;
}
else
{
    pdds = lpDDSOne;
    phase = 1;
}
while(1)
{
    ddrval = lpDDSBack->BltFast(0, 0, pdds, &rcRect, FALSE);
    if(ddrval == DD_OK)
    {
        break;
    }
}

The phase variable determines which off-screen surface will be blitted to the back buffer. The IDirectDrawSurface7::BltFast method is then called to blit the selected off-screen surface onto the back buffer, starting at position (0, 0), the upper-left corner. The rcRect parameter points to the RECT structure that defines the upper-left and lower-right corners of the off-screen surface that will be blitted from. The last parameter is set to FALSE (or 0), indicating that no specific transfer flags are used.

Depending on the requirements of your application, you could use either the IDirectDrawSurface7::Blt method or the IDirectDrawSurface7::BltFast method to blit from the off-screen buffer. If you are performing a blit from an off-screen plain buffer that is in display memory, you should use IDirectDrawSurface7::BltFast. Although you will not gain speed on systems that use hardware blitter on their display adapters, the blit will take about 10 percent less time on systems that use hardware emulation to perform the blit. Because of this, you should use IDirectDrawSurface7::BltFast for all display operations that blit from display memory to display memory. If you are blitting from system memory or require special hardware flags, however, you have to use IDirectDrawSurface7::Blt.

After the off-screen surface is loaded in the back buffer, the back buffer and the primary surface are flipped in much the same way as shown in the previous tutorials.


Tutorial 4: Color Keys and Bitmap Animation

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

The sample in Tutorial 3 (DDEx3) shows one simple method of placing bitmaps into an off-screen buffer before they are blitted to the back buffer. The sample in this tutorial (DDEx4) uses the techniques described in the previous tutorials to load a background and a series of sprites into an off-screen surface. Then it uses the IDirectDrawSurface7::BltFast method to copy portions of the off-screen surface to the back buffer, thereby generating a simple bitmap animation.

The bitmap file that DDEx4 uses, All.bmp, contains the background and 60 iterations of a rotating red donut with a black background. The DDEx4 sample contains new functions that set the color key for the rotating donut sprites. Then, the sample copies the appropriate sprite to the back buffer from the off-screen surface.

The new functionality demonstrated in DDEx4 is shown in the following steps:

  • Step 1: Set the Color Key
  • Step 2: Create a Simple Animation


Step 1: Set the Color Key

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

In addition to the other functions found in the doInit sample function of some of the other DirectDraw samples, the DDEx4 sample contains the code to set the color key for the sprites. Color keys are used for setting a color value that will be used for transparency. When the system contains a hardware blitter, all the pixels of a rectangle are blitted except the value that was set as the color key, thereby creating nonrectangular sprites on a surface. The following code shows how to set the color key in DDEx4:

// Set the color key for this bitmap (black).
DDSetColorKey(lpDDSOne, RGB(0,0,0));

return TRUE;

You can select the color key by setting the RGB values for the color you want in the call to the DDSetColorKey sample function. The RGB value for black is (0, 0, 0). The DDSetColorKey function calls the DDColorMatch function. (Both functions are in Ddutil.cpp.) The DDColorMatch function stores the current color value of the pixel at location (0, 0) on the bitmap located in the lpDDSOne surface. Then it takes the RGB values you supplied and sets the pixel at location (0, 0) to that color. Finally, it masks the value of the color with the number of bits per pixel that are available. After that is done, the original color is put back in location (0, 0), and the call returns to DDSetColorKey with the actual color key value. After it is returned, the color key value is placed in the dwColorSpaceLowValue member of the DDCOLORKEY structure. It is also copied to the dwColorSpaceHighValue member. The call to IDirectDrawSurface7::SetColorKey then sets the color key.

You may have noticed the reference to CLR_INVALID in DDSetColorKey and DDColorMatch. If you pass CLR_INVALID as the color key in the DDSetColorKey call in DDEx4, the pixel in the upper-left corner (0, 0) of the bitmap will be used as the color key. As the DDEx4 bitmap is delivered, that does not mean much because the color of the pixel at (0, 0) is a shade of gray. If, however, you would like to see how to use the pixel at (0, 0) as the color key for the DDEx4 sample, open the All.bmp bitmap file in a drawing application and then change the single pixel at (0, 0) to black. Be sure to save the change (it's hard to see). Then change the DDEx4 line that calls DDSetColorKey to the following:

DDSetColorKey(lpDDSOne, CLR_INVALID);

Recompile the DDEx4 sample, and ensure that the resource definition file is also recompiled so that the new bitmap is included. (To do this, you can simply add and then delete a space in the Ddex4.rc file.) The DDEx4 sample will then use the pixel at (0, 0), which is now set to black, as the color key.

Next: Step 2: Create a Simple Animation


Step 2: Create a Simple Animation

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

The DDEx4 sample uses the updateFrame sample function to create a simple animation using the red donuts included in the All.bmp file. The animation consists of three red donuts positioned in a triangle and rotating at various speeds. This sample compares the Win32 GetTickCount function with the number of milliseconds since the last call to GetTickCount to determine whether to redraw any of the sprites. It subsequently uses the IDirectDrawSurface7::BltFast method first to blit the background from the off-screen surface (lpDDSOne) to the back buffer, and then to blit the sprites to the back buffer using the color key that you set earlier to determine which pixels are transparent. After the sprites are blitted to the back buffer, DDEx4 calls the IDirectDrawSurface7::Flip method to flip the back buffer and the primary surface.

Note that when you use IDirectDrawSurface7::BltFast to blit the background from the off-screen surface, the dwTrans parameter that specifies the type of transfer is set to DDBLTFAST_NOCOLORKEY. This indicates that a normal blit will occur with no transparency bits. Later, when the red donuts are blitted to the back buffer, the dwTrans parameter is set to DDBLTFAST_SRCCOLORKEY. This indicates that a blit will occur with the color key for transparency as it is defined, in this case, in the lpDDSOne buffer.

In this sample, the entire background is redrawn each time through the updateFrame function. One way of optimizing this sample would be to redraw only that portion of the background that changes while rotating the red donuts. Because the location and size of the rectangles that make up the donut sprites never change, you should be able to easily modify the DDEx4 sample with this optimization.


Tutorial 5: Dynamically Modifying Palettes

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

The sample described in this tutorial (DDEx5) is a modification of the sample described in Tutorial 4 (DDEx4) example. DDEx5 demonstrates how to dynamically change the palette entries while an application is running. The new functionality demonstrated in DDEx5 is shown in the following steps:

  • Step 1: Load the Palette Entries
  • Step 2: Rotate the Palettes


Step 1: Load the Palette Entries

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

The following code in DDEx5 loads the palette entries with the values in the lower half of the All.bmp file (the part of the bitmap that contains the red donuts):

// First, set all colors as unused.
for(i=0; i<256; i++)
{
    torusColors[i] = 0;
}

// Lock the surface and scan the lower part (the torus area),
// and keep track of all the indexes found.
ddsd.dwSize = sizeof(ddsd);
while (lpDDSOne->Lock(NULL, &ddsd, 0, NULL) == DDERR_WASSTILLDRAWING)
    ;

// Search through the torus frames and mark used colors.
for(y=480; y<480+384; y++)
{
    for(x=0; x<640; x++)
    {
        torusColors[((BYTE *)ddsd.lpSurface)[y*ddsd.lPitch+x]] = 1;
    }
}

lpDDSOne->Unlock(NULL);

The torusColors array is used as an indicator of the color index of the palette used in the lower half of the All.bmp file. Before it is used, all of the values in the torusColors array are reset to 0. The off-screen buffer is then locked in preparation for determining if a color index value is used.

The torusColors array is set to start at row 480 and column 0 of the bitmap. The color index value in the array is determined by the byte of data at the location in memory where the bitmap surface is located. This location is determined by the lpSurface member of the DDSURFACEDESC2 structure, which is pointing to the memory location corresponding to row 480 and column 0 of the bitmap (y × lPitch + x). The location of the specific color index value is then set to 1. The y-value (row) is multiplied by the lPitch value (found in the DDSURFACEDESC2 structure) to get the actual location of the pixel in linear memory.

The color index values that are set in torusColors will be used later to determine which colors in the palette are rotated. Because there are no common colors between the background and the red donuts, only those colors associated with the red donuts are rotated. If you want to check whether this is true or not, just remove the "*ddsd.lPitch" from the array and see what happens when you recompile and run the program. (Without multiplying y × lPitch, the red donuts are never reached and only the colors found in the background are indexed and later rotated.) For more information about width and pitch, see Width vs. Pitch.

Next: Step 2: Rotate the Palettes


Step 2: Rotate the Palettes

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

The updateFrame sample function in DDEx5 works in much the same way as it did in Tutorial 4 (DDEx4). It first blits the background into the back buffer, and then it blits the three donuts in the foreground. However, before it flips the surfaces, updateFrame changes the palette of the primary surface from the palette index that was created in the doInit function, as shown in the following code:

// Change the palette.
if(lpDDPal->GetEntries(0, 0, 256, pe) != DD_OK)
{
    return;
}

for(i=1; i<256; i++)
{
    if(!torusColors[i])
    {
       continue;
    }
    pe[i].peRed = (pe[i].peRed+2) % 256;
    pe[i].peGreen = (pe[i].peGreen+1) % 256;
    pe[i].peBlue = (pe[i].peBlue+3) % 256;
}

if(lpDDPal->SetEntries(0, 0, 256, pe) != DD_OK)
{
    return;
}

The IDirectDrawPalette::GetEntries method in the first line queries palette values from a DirectDrawPalette object. Because the palette entry values pointed to by pe should be valid, the method will return DD_OK and continue. The loop that follows checks torusColors to determine if the color index was set to 1 during its initialization. If so, the red, green, and blue values in the palette entry pointed to by pe are rotated.

After all of the marked palette entries are rotated, the IDirectDrawPalette::SetEntries method is called to change the entries in the DirectDrawPalette object. This change takes place immediately if you are working with a palette set to the primary surface.

With this done, the surfaces are subsequently flipped.


Tutorial 6: Using Overlay Surfaces

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

This tutorial shows you, step by step, how to use DirectDraw and hardware supported overlay surfaces in your applications. The tutorial is written around the Mosquito sample application included with the DirectX SDK samples. Mosquito is a simple application that uses a flipping chain of overlay surfaces to display an animated bitmap on the desktop without blitting to the primary surface. The sample adjusts the characteristics of the overlay surface as needed to accommodate for hardware limitations.

The Mosquito sample application performs the following steps (complex tasks are divided into smaller sub-steps):

  • Step 1: Create a Primary Surface
  • Step 2: Test for Hardware Overlay Support
  • Step 3: Create an Overlay Surface
  • Step 4: Display the Overlay Surface
  • Step 5: Update the Overlay Display Position
  • Step 6: Hide the Overlay Surface


Step 1: Create a Primary Surface

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

To prepare for using overlay surfaces, you must first initialize DirectDraw and create a primary surface over which the overlay surface will be displayed. Mosquito creates a primary surface with the following code:

    // Zero-out the structure and set the dwSize member.
    ZeroMemory(&ddsd, sizeof(ddsd));
    ddsd.dwSize = sizeof(ddsd);

    // Set flags and create a primary surface.
    ddsd.dwFlags = DDSD_CAPS;
    ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
    ddrval = g_lpdd->CreateSurface(&ddsd, &g_lpddsPrimary, NULL );

The preceding example begins by initializing the DDSURFACEDESC2 structure it will use. It then sets the flags appropriate to create a primary surface and creates it by calling the IDirectDraw7::CreateSurface method. For the call, the first parameter is a pointer to a DDSURFACEDESC2 structure that describes the surface to be created. The second parameter is a pointer to a variable that will receive an IDirectDrawSurface7 interface pointer if the call succeeds. The last parameter is set to NULL to indicate that no COM aggregation is taking place.

Next: Step 2: Test for Hardware Overlay Support


Step 2: Test for Hardware Overlay Support

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

After initializing DirectDraw, you need to verify that the device supports overlay surfaces. Because DirectDraw doesn't emulate overlays, if the hardware device driver doesn't support them, you can't continue. You can test for overlay support by retrieving the device driver capabilities with the IDirectDraw7::GetCaps method. After the call, look for the presence of the DDCAPS_OVERLAY flag in the dwFlags member of the associated DDCAPS structure. If the flag is present, then the display hardware supports overlays; if not, you can't use overlay surfaces with that device.

The following example, taken from the Mosquito sample application, shows how to test for hardware overlay support:

BOOL AreOverlaysSupported()
{
    DDCAPS  capsDrv;
    HRESULT ddrval;

    // Get driver capabilities to determine Overlay support.
    ZeroMemory(&capsDrv, sizeof(capsDrv));
    capsDrv.dwSize = sizeof(capsDrv);

    ddrval = g_lpdd->GetCaps(&capsDrv, NULL);
    if (FAILED(ddrval))
        return FALSE;

    // Does the driver support overlays in the current mode?
    // (Currently the DirectDraw emulation layer does not support overlays.
    // Overlay related APIs will fail without hardware support).
    if (!(capsDrv.dwCaps & DDCAPS_OVERLAY))
        return FALSE;

    return TRUE;
}

The preceding example calls the IDirectDraw7::GetCaps method to retrieve device driver capabilities. The first parameter for the call is the address of a DDCAPS that will be filled with information describing the device driver's capabilities. Because the application doesn't need information about emulation capabilities, the second parameter is set to NULL.

After retrieving the driver capabilities, the example checks the dwCaps member for the presence of the DDCAPS_OVERLAY flag using a logical AND operation. If the flag isn't present, the example returns FALSE to indicate failure. Otherwise, the example returns TRUE to indicate that the device driver supports overlay surfaces.

In your code, this might be a good time for you to check the dwMaxVisibleOverlays and dwCurrVisibleOverlays members in the DDCAPS structure to ensure that no other overlay surfaces are in use by other applications.

Next: Step 3: Create an Overlay Surface


Step 3: Create an Overlay Surface

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

Now that you know that the driver supports overlay surfaces, you can try to create one. Because there is no standard dictating how devices must support overlay surfaces, you can't count on being able to create overlays of any particular size or pixel format. Additionally, you can't expect to succeed in creating an overlay surface on the first try. Therefore, be prepared to attempt creation multiple times starting with the most desirable characteristics, falling back on less desirable (but possibly less hardware intensive) configurations until one works.

Note You can call the IDirectDraw7::GetFourCCCodes method to retrieve a list of FOURCC codes that describe non-RGB pixel formats that the driver will likely support for overlay surfaces. However, in you want to try using RGB overlay surfaces, it is recommended that you attempt to create surfaces in various common RGB formats, falling back on another format if you fail.

The Mosquito sample follows a "best case to worst case" philosophy when creating an overlay surface. Mosquito first tries to create a triple-buffered page flipping complex overlay surface. If the creation attempt fails, the sample tries the configuration with other common pixel formats. The following code fragment shows how this can be done:

    ZeroMemory(&ddsdOverlay, sizeof(ddsdOverlay));
    ddsdOverlay.dwSize = sizeof(ddsdOverlay);

    ddsdOverlay.dwFlags= DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH |
                         DDSD_BACKBUFFERCOUNT| DDSD_PIXELFORMAT;
    ddsdOverlay.ddsCaps.dwCaps = DDSCAPS_OVERLAY | DDSCAPS_FLIP |
                                 DDSCAPS_COMPLEX | DDSCAPS_VIDEOMEMORY;
    ddsdOverlay.dwWidth  =320;
    ddsdOverlay.dwHeight =240;
    ddsdOverlay.dwBackBufferCount=2;

    // Try to create an overlay surface using one of the pixel formats in our
    // global list.
    i=0;
    do{
    ddsdOverlay.ddpfPixelFormat=g_ddpfOverlayFormats[i];
       // Try to create the overlay surface
       ddrval = g_lpdd->CreateSurface(&ddsdOverlay, &g_lpddsOverlay, NULL);
    } while( FAILED(ddrval) && (++i < NUM_OVERLAY_FORMATS) );

The preceding example sets the flags and values within a DDSURFACEDESC2 structure to reflect a triple-buffered page flipping complex overlay surface. Then, the sample performs a loop during which it attempts to create the requested surface in a variety of common pixel formats, in order of most desirable to least desirable pixel formats. If the attempt succeeds, the loop ends. If all the attempts fail, it's likely that the display hardware doesn't have enough memory to support a triple-buffered scheme or that it doesn't support flipping overlay surfaces. In this case, the sample falls back on a less desirable configuration using a single non-flipping overlay surface, as shown in the following example:

    // If we failed to create a triple buffered complex overlay surface, try
    // again with a single non-flippable buffer.
    if(FAILED(ddrval))
    {
        ddsdOverlay.dwBackBufferCount=0;
        ddsdOverlay.ddsCaps.dwCaps=DDSCAPS_OVERLAY | DDSCAPS_VIDEOMEMORY;
        ddsdOverlay.dwFlags= DDSD_CAPS|DDSD_HEIGHT|DDSD_WIDTH|DDSD_PIXELFORMAT;

        // Try to create the overlay surface
        ddrval = g_lpdd->CreateSurface(&ddsdOverlay, &g_lpddsOverlay, NULL);
        i=0;
        do{
            ddsdOverlay.ddpfPixelFormat=g_ddpfOverlayFormats[i];
            ddrval = g_lpdd->CreateSurface(&ddsdOverlay, &g_lpddsOverlay, NULL);
        } while( FAILED(ddrval) && (++i < NUM_OVERLAY_FORMATS) );

        // We couldn't create an overlay surface.  Exit, returning failure.
        if (FAILED(ddrval))
            return FALSE;
    }

The previous code resets the flags and values in the DDSURFACEDESC2 structure to reflect a single non-flipping overlay surface. Again, the example loops through pixel formats attempting to create the surfaces, stopping the loop if an attempt succeeded. If the attempts still didn't work, the sample returns FALSE to indicate failure.

After you've successfully created your overlay surface or surfaces, you can load bitmaps onto them in preparation for display.

Next: Step 4: Display the Overlay Surface


Step 4: Display the Overlay Surface

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

After creating your overlay surface, you can display it. Often, display hardware imposes alignment restrictions on the position and pixel width of the rectangles you use to display the overlay. Additionally, you will often need to account for a minimum required stretch factor by adjusting the width of the destination rectangle in order to successfully display the overlay surface. The Mosquito sample performs the following tasks to prepare and display the overlay surface:

  • Step 4.1: Determine the Minimum Display Requirements
  • Step 4.2: Set Up the Source and Destination Rectangles
  • Step 4.3: Display the Overlay Surface

Next: Step 4.1: Determine the Minimum Display Requirements


Step 4.1: Determine the Minimum Display Requirements

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

Most display hardware imposes restrictions on displaying overlay surfaces. You must carefully meet these restrictions in order to successfully display an overlay surface. You can retrieve information about these restrictions by calling the IDirectDraw7::GetCaps method. The DDCAPS structure that the method fills contains information about overlay capabilities and their usage restrictions. Hardware restrictions vary, so always look at the flags included in the dwFlags member to determine which restrictions apply to you.

The Mosquito sample starts by retrieving the hardware capabilities, then takes action based upon the minimum stretch factor, as shown in the following code fragment:

    // Get driver capabilities
    ddrval = g_lpdd->GetCaps(&capsDrv, NULL);
    if (FAILED(ddrval))
        return FALSE;

    // Check the minimum stretch and set the local variable accordingly.
    if(capsDrv.dwCaps & DDCAPS_OVERLAYSTRETCH)
        uStretchFactor1000 = (capsDrv.dwMinOverlayStretch>1000) ? capsDrv.dwMinOverlayStretch : 1000;
    else
        uStretchFactor1000 = 1000;

The preceding code calls GetCaps to retrieve only the hardware capabilities. For this call, the first parameter is a pointer the DDCAPS structure that will be filled with the capability information for the device driver, and the second parameter is NULL to indicate that emulation information is not to be retrieved.

The example retains the minimum stretch factor in a temporary variable for use later. (Keep in mind that stretch factors are reported multiplied by 1000, so 1300 really means 1.3.) If the driver reports a value greater than 1000, it means that the driver requires that all destination rectangles must be stretched along the x-axis by a ratio of the reported value. For example, if the driver reports a stretch factor 1.3 and the source rectangle is 320 pixels wide, the destination rectangle must be at least 416 pixels wide. If the driver reports a stretch factor less than 1000, it means that the driver can display overlays smaller than the source rectangle, but can also stretch the overlay if desired.

Next, the sample examines values describing the driver's size alignment restrictions, as shown in the following example:

    // Grab any alignment restrictions and set the local variables acordingly.
    uSrcSizeAlign = (capsDrv.dwCaps & DDCAPS_ALIGNSIZESRC)?capsDrv.dwAlignSizeSrc:0;
    uDestSizeAlign= (capsDrv.dwCaps & DDCAPS_ALIGNSIZESRC)?capsDrv.dwAlignSizeDest:0;

The sample uses more temporary variables to hold the reported size alignment restrictions taken from the dwAlignSizeSrc and dwAlignSizeDest members. These values provide information about pixel width alignment restrictions and are needed when setting the dimensions of the source and destination rectangles to reflect these restrictions later. Source and destination rectangles must have a pixel width that is a multiple of the values in these members.

Last, the sample examines the value that describes the destination rectangle boundary alignment:

    // Set the "destination position alignment" global so we won't have to
    // keep calling GetCaps() every time we move the overlay surface.
    if (capsDrv.dwCaps & DDCAPS_ALIGNBOUNDARYDEST)
        g_dwOverlayXPositionAlignment = capsDrv.dwAlignBoundaryDest;
    else
        g_dwOverlayXPositionAlignment = 0;

The preceding code uses a global variable to hold the value for the destination rectangle's boundary alignment, as taken from the dwAlignBoundaryDest member. This value will be used when the program repositions the overlay later. (For details, see Step 5: Update the Overlay Display Position) You must set the x-coordinate of the destination rectangle's top left corner to be aligned with this value, in pixels. That is, if the value specified is 4, you can only specify destination rectangles whose top-left corner has an x-coordinate at pixels 0, 4, 8, 12, and so on. The Mosquito application initially displays the overlay at 0,0, so alignment compliance is assumed and the sample doesn't need to retrieve the restriction information until after displaying the overlay the first time. Your implementation might vary, so you will probably need to check this information and adjust the destination rectangle before displaying the overlay.

Next: Step 4.2: Set Up the Source and Destination Rectangles


Step 4.2: Set Up the Source and Destination Rectangles

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

After retrieving the driver's overlay restrictions you should set the values for your source and destination rectangles accordingly, assuring that you will be able to successfully display the overlay. The following sample from the Mosquito sample application starts by setting the characteristics of the source rectangle:

    // Set initial values in the source RECT.
    rs.left=0; rs.top=0;
    rs.right = 320;
    rs.bottom = 240;

    // Apply size alignment restrictions, if necessary.
    if (capsDrv.dwCaps & DDCAPS_ALIGNSIZESRC && uSrcSizeAlign)
        rs.right -= rs.right % uSrcSizeAlign;

The preceding code sets initial values for the surface to include the dimensions of the entire surface. If the device driver requires size alignment for the source rectangle, the example adjusts the source rectangle to conform. The example adjusts the width of the source rectangle to be narrower than the original size because the width cannot be expanded without completely recreating the surface. However, your code could just as easily start with a smaller rectangle and widen the rectangle to meet driver restrictions.

After the dimensions of the source rectangle are set and conform with hardware restrictions, you need to set and adjust the dimensions of the destination rectangle. This process requires a little more work because the rectangle might need to be stretched first, then adjusted to meet size alignment restrictions. The following code performs the task of accounting for the minimum stretch factor:

    // Set up the destination RECT, starting with the source RECT values.
    // We use the source RECT dimensions instead of the surface dimensions in
    // case they differ.
    rd.left=0; rd.top=0;
    rd.right  = (rs.right*uStretchFactor1000+999)/1000;
    // (Adding 999 avoids integer truncation problems.)

    // (This isn't required by DDraw, but we'll stretch the
    //  height, too, to maintain aspect ratio).
    rd.bottom = rs.bottom*uStretchFactor1000/1000;

The preceding code sets the top left corner of the destination rectangle to the top left corner of the screen, then sets the width to account for the minimum stretch factor. While adjusting for the stretch factor, note that the example adds 999 to the product of the width and stretch factor. This is done to prevent integer truncation that could result in a rectangle that isn't as wide as the minimum stretch factor requires. For more information, see Minimum and Maximum Stretch Factors. Also, after the example stretches the width, it stretches the height. Stretching the height isn't required, but was done to preserve the bitmap's aspect ratio and avoid a distorted appearance.

After stretching the destination rectangle, the example continues by adjusting it to conform to size alignment restrictions as follows:

    // Adjust the destination RECT's width to comply with any imposed
    // alignment restrictions.
    if (capsDrv.dwCaps & DDCAPS_ALIGNSIZEDEST && uDestSizeAlign)
        rd.right = (int)((rd.right+uDestSizeAlign-1)/uDestSizeAlign)*uDestSizeAlign;

The example checks the capabilities flags to see if the driver imposes destination size alignment restrictions. If so, the destination rectangle's width is increased by enough pixels to meet alignment restrictions. Note that the rectangle is adjusted by expanding the width, not by decreasing it. This is done because decreasing the width could cause the destination rectangle to be smaller than is required by the minimum stretch factor, consequently causing attempts to display the overlay surface to fail.

Next: Step 4.3: Display the Overlay Surface


Step 4.3: Display the Overlay Surface

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

After you've set up the source and destination rectangles, you can display the overlay for the first time. If you've prepared correctly, this will be simple. The Mosquito sample uses the following code to initially display the overlay:

    // Set the flags we'll send to UpdateOverlay
    dwUpdateFlags = DDOVER_SHOW | DDOVER_DDFX;

    // Does the overlay hardware support source color keying?
    // If so, we can hide the black background around the image.
    // This probably won't work with YUV formats
    if (capsDrv.dwCKeyCaps & DDCKEYCAPS_SRCOVERLAY)
        dwUpdateFlags |= DDOVER_KEYSRCOVERRIDE;

    // Create an overlay FX structure so we can specify a source color key.
    // This information is ignored if the DDOVER_SRCKEYOVERRIDE flag isn't set.
    ZeroMemory(&ovfx, sizeof(ovfx));
    ovfx.dwSize = sizeof(ovfx);

    ovfx.dckSrcColorkey.dwColorSpaceLowValue=0; // Specify black as the color key
    ovfx.dckSrcColorkey.dwColorSpaceHighValue=0;

    // Call UpdateOverlay() to displays the overlay on the screen.
    ddrval = g_lpddsOverlay->UpdateOverlay(&rs, g_lpddsPrimary, &rd, dwUpdateFlags, &ovfx);
    if(FAILED(ddrval))
        return FALSE;

The preceding example starts by setting the DDOVER_SHOW and DDOVER_DDFX flags in the dwUpdateFlags temporary variable, indicating that the overlay is to be displayed for the first time, and that the hardware should use the effects information included in an associated DDOVERLAYFX structure to do so. Next, the example checks a previously existing DDCAPS structure to determine if overlay source color keying is supported. If it is, the DDOVER_KEYSRCOVERRIDE is included in the dwUpdateFlags variable to take advantage of source color keying and the example sets color key values accordingly.

After preparation is complete, the example calls the IDirectDrawSurface7::UpdateOverlay method to display the overlay. For the call, the first and third parameters are the addresses of the adjusted source and destination rectangles. The second parameter is the address of the primary surface over which the overlay will be displayed. The fourth parameter consists of the flags placed in the previously prepared dwUpdateFlags variable, and the fifth parameter is the address of DDOVERLAYFX structure whose members were set to match those flags.

If the hardware only supports one overlay surface and that surface is in use, the UpdateOverlay method fails, returning DDERR_OUTOFCAPS. Additionally, if UpdateOverlay fails, you might try increasing the width of the destination rectangle to accommodate for the possibility that the hardware incorrectly reported a minimum stretch factor that was too small. However, this rarely occurs and Mosquito simply fails if UpdateOverlay doesn't succeed.

Next: Step 5: Update the Overlay Display Position


Step 5: Update the Overlay Display Position

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

After displaying the overlay surface, you might not need to do anything else. However, some software might need to reposition the overlay surface. The Mosquito sample uses the IDirectDrawSurface7::SetOverlayPosition method to reposition the overlay, as shown in the following example:

    // Set x- and y-coordinates
    .
    .
    .
    // We need to check for any alignment restrictions on the x-position
    // and align it if necessary.
    if (g_dwOverlayXPositionAlignment)
        dwXAligned = g_nOverlayXPos - g_nOverlayXPos % g_dwOverlayXPositionAlignment;
    else
        dwXAligned = g_nOverlayXPos;

    // Set the overlay to its new position.
    ddrval = g_lpddsOverlay->SetOverlayPosition(dwXAligned, g_nOverlayYPos);
    if (ddrval == DDERR_SURFACELOST)
    {
        if (!RestoreAllSurfaces())
            return;
    }

The preceding example starts by aligning the rectangle to meet any destination rectangle boundary alignment restrictions that might exist. The global variable that it checks, g_dwOverlayXPositionAlignment, was set earlier to equal the value reported in the dwAlignBoundaryDest member of the DDCAPS structure when the application previously called the IDirectDraw7::GetCaps method. (For details, see Step 4.1: Determine the Minimum Display Requirements). If destination alignment restrictions exist, the example adjusts the new x-coordinate to be pixel-aligned accordingly. Failing to meet this requirement will cause the overlay surface not to be displayed.

After making any requisite adjustments to the new x-coordinate, the example calls IDirectDrawSurface7::SetOverlayPosition method to reposition the overlay. For the call, the first parameter is the aligned x-coordinate, and the second parameter is the new y-coordinate. These values represent the new location of the overlay's top-left corner. Width and height information are not accepted, nor are they needed because DirectDraw already knows the dimensions of the surface from the IDirectDrawSurface7::UpdateOverlay method made to initially display the overlay. If the call fails because one or more surfaces were lost, the example calls an application-defined function to restore them and reload their bitmaps.

Note Take care not to use coordinates too close to the bottom or right edge of the target surface. The IDirectDraw7::SetOverlayPosition method does not perform clipping for you; using coordinates that would potentially make the overlay run off the edge of the target surface will cause the method to fail, returning DDERR_INVALIDPOSITION.

Next: Step 6: Hide the Overlay Surface


Step 6: Hide the Overlay Surface

[Visual Basic]

The information in this section pertains only to applications written in C and C++. See DirectDraw Visual Basic Tutorials.

[C++]

When you do not need the overlay surface anymore, or if you simply want to remove it from view, you can hide the surface by calling the IDirectDrawSurface7::UpdateOverlay method with the appropriate flags. Mosquito hides the overlay in preparation for closing the application using the following code:

void DestroyOverlay()
{
    if (g_lpddsOverlay){
        // Use UpdateOverlay() with the DDOVER_HIDE flag to remove an overlay
        // from the display.
        g_lpddsOverlay->UpdateOverlay(NULL, g_lpddsPrimary, NULL, DDOVER_HIDE, NULL);
        g_lpddsOverlay->Release();
        g_lpddsOverlay=NULL;
    }
}

When the preceding example calls IDirectDrawSurface7::UpdateOverlay, it specifies NULL for the source and destination rectangles, because they are irrelevant when hiding the overlay. Similarly, the example uses NULL in the fifth parameter because overlay effects aren't being used. The second parameter is a pointer to the target surface. Lastly, the example uses the DDOVER_HIDE flag in the fourth parameter to indicate that the overlay will be removed from view.

After the example hides the overlay, the example releases its IDirectDrawSurface7 interface and invalidates its global variable by setting it to NULL. For the purposes of the Mosquito sample application, the overlay surface is no longer needed. If you still need the overlay surface for later, you could simply hide the overlay without releasing it, then redisplay it whenever you require.


DirectDraw Visual Basic Tutorials

[C++]

This section pertains only to application development in Visual Basic. See DirectDraw C/C++ Tutorials.

[Visual Basic]

This section contains a series of tutorials, each of which provides step-by-step instructions for implementing a simple DirectDraw application. These tutorials use many of the DirectDraw sample files that are provided with this SDK. These samples demonstrate how to set up DirectDraw, and how to use the DirectDraw methods to perform common tasks:

  • Tutorial 1: Blitting to the Screen
  • Tutorial 2: Using Transparency
  • Tutorial 3: Using Full-Screen Features
  • Tutorial 4: Blitting to Areas of the Screen
  • Tutorial 5: Enumerating DirectDraw Devices


Tutorial 1: Blitting to the Screen

[C++]

This section pertains only to application development in Visual Basic. See DirectDraw C/C++ Tutorials.

[Visual Basic]

This first tutorial deals with blitting a bitmap to the display adapter. The term blit is shorthand for "bit block transfer," which is the process of transferring blocks of data from one place in memory to another. Graphics programmers use blitting to transfer graphics from one place in memory to another. Blits are often used to perform sprite animation.

To use DirectDraw, you first create an instance of the DirectDraw object, which represents the display adapter on the computer. You then use methods to manipulate the object. In addition, you need to create one or more instances of a DirectDrawSurface object to be able to display your application on a graphics surface.

To demonstrate this, the Tutorial 1: Blitting to the Screen sample included in this SDK performs the following steps:

  • Step 1: Create the Form
  • Step 2: Declare Module Level Variables
  • Step 2: Initialize Variables


Step 1: Create the Form

[C++]

This section pertains only to application development in Visual Basic. See DirectDraw C/C++ Tutorials.

[Visual Basic]

The Tutorial 1 blitting sample is a standard .exe project with a picture box control placed on the form. The picture box control is placed with the top left corner of the picture box with the top left corner of the form. This picture box is used to display the bitmap image of the application and is named Picture1.

Next: Step 2: Declare Module Level Variables


Step 2: Declare Module Level Variables

[C++]

This section pertains only to application development in Visual Basic. See DirectDraw C/C++ Tutorials.

[Visual Basic]

The first step of coding DirectX application written in Visual Basic is to create an instance of the DirectX7 class. This object contains the methods necessary to create the starting objects of all the DirectX components including DirectDraw, DirectSound, Direct3D Immediate Mode, Direct3D Retained Mode, DirectInput, DirectPlay, and DirectMusic. Information on Direct3D Retained Mode can be found in the Appendix node of this documentation.

The DirectX7 class is the top level class of the DxVBLib type library and an object of this class is created with the statement:

Dim objDX As New DirectX7

Additional module level variables declarations found in the Tutorial 1 blitting sample are for a DirectDraw object, DirectDrawSurface objects, DirectDrawClipper object, DirectDraw surface description types, and a Boolean variable used to hold initialization information.

Next: Step 3: Initialize Variables


Step 3: Initialize Variables

[C++]

This section pertains only to application development in Visual Basic. See DirectDraw C/C++ Tutorials.

[Visual Basic]

The first procedure called from the Form_Load event is the init procedure. This procedure creates the DirectDraw object. This is accomplished by invoking the DirectX7.DirectDrawCreate method of the DirectX7 object and setting the returned object to DirectDraw which we declared as an object variable of class DirectDraw7. In the Tutorial 1 blitting sample, this is done with the statement:

Set objDD = objDX.DirectDrawCreate("")

This method takes only one string argument and passing an empty string specifies the active display driver.

Next you must specify the behavior of the application by calling the DirectDraw7.SetCooperativeLevel method of the DirectDraw object. The Tutorial 1 blitting sample is run as a regular windowed application and this is done with the statement:

Call objDD.SetCooperativeLevel (Me.hwnd, DDSCL_NORMAL)

You are now ready to start creating surfaces. Before you actually create the surface object, you need to create a surface description by setting the members of the DDSURFACEDESC2 type. One of the members of this type is ddscaps, a nested type, and by setting the lFlags member of the DDSURFACEDESC2 to DDSD_CAPS, you are stating that the ddscaps member is valid in this type. This is done with the statement:

ddsd1.lFlags = DDSD_CAPS

Next you need to specify that this type description is for a primary surface, which is done with the statement:

ddsd1.ddsCaps.lCaps = DDSCAPS_PRIMARYSURFACE

After creating the surface description, you actually create the surface object by invoking the CreateSurface method from the DirectDraw object with the set surface description as an argument. This is done in the Tutorial 1 blitting sample with the statement:

Set objDDPrimSurf = objDD.CreateSurface(ddsd1)

The surface object creation steps are repeated for a second surface which has the DDSCAPS_OFFSCREENPLAIN flag set to specify that this surface is any off-screen surface that is not an overlay, texture, z-buffer, front-buffer, back-buffer, or alpha surface. It is used to identify plain surfaces. Then the CreateSurfaceFromFile method is invoked from the DirectDraw object. This method creates the surface object and loads a bitmap onto the surface. The location of the bitmap is specified through the FindMediaDir procedure. These steps are shown with the statements:

FindMediaDir "lake.bmp"

ddsd2.lFlags = DDSD_CAPS
ddsd2.ddsCaps.lCaps = DDSCAPS_OFFSCREENPLAIN
Set objDDSurf = objDD.CreateSurfaceFromFile("lake.bmp", ddsd2)

A DirectDrawClipper object is then created by calling the DirectDraw7.CreateClipper method. Clippers, or DirectDrawClipper objects, allow you to blit to selected parts of a surface represented by a bounding rectangle. In Tutorial 1, we want to contain the blit to the Picture1 picture box control. This is done with the following statements:

Set ddClipper = objDD.CreateClipper(0)
ddClipper.SetHWnd Picture1.hWnd
objDDPrimSurf.SetClipper ddClipper

After initializing all the variables and objects we set the bInit variable to True and call the blt subroutine.

Next: Step 4: Blit the Surface


Step 4: Blit the Surface

[C++]

This section pertains only to application development in Visual Basic. See DirectDraw C/C++ Tutorials.

[Visual Basic]

So far in the Tutorial 1: Blitting to the Screen sample you have created a primary surface and a off-screen surface which has a loaded bitmap. To display the bitmap on the screen, you must blit the off-screen surface to the primary surface. The blit method of the DirectDraw surface object takes four arguments and returns a Long indicating the success or failure of the blit. Two of the arguments of are type RECT which specify the bounding rectangles of the destination surface and the source surface.

The coordinates of the source rectangle are obtained from the lHeight and the lWidth members of the off-screen surface description. There are a few extra steps in obtaining the destination rectangle. First of all, since Visual Basic uses twips for screen measurement and DirectX uses pixels, the dimensions of the Visual Basic picture box control must be converted to pixels before setting the destination rectangle. This is accomplished by setting the ScaleMode property of the form to Pixels and then making the width and height of the picture box equal to the ScaleWidth and ScaleHeight of the form. Note: the width and height of the form stay in twips after you change the ScaleMode, but the ScaleWidth and the ScaleHeight are now in pixels. In the Tutorial 1 blitting sample, this is done with the statements:

Picture1.Width = Me.ScaleWidth
Picture1.Height = Me.ScaleHeight

These statements are in the Form_Resize event and are executed when the form is initially displayed and resized.

Furthermore, the destination RECT type is filled when the DirectX7.GetWindowRect is called.

Lastly the blit is perform with the blt method of the primary surface object:

ddrval = objDDPrimSurf.blt(r1, objDDSurf, r2, DDBLT_WAIT)

The result of the method is a Long that is stored in ddrval. You can check this variable for success or failure. The last argument of the method is the DDBLT_WAIT flag which tells DirectDraw to wait if the blitter is busy and blit the surface when it becomes available.


Tutorial 2: Using Transparency

[C++]

This section pertains only to application development in Visual Basic. See DirectDraw C/C++ Tutorials.

[Visual Basic]

This second tutorial expands on the concepts learned in the first tutorial by introducing transparent blitting. Transparent blitting enables you to create the illusion of nonrectangular blits when animating sprites. A sprite image is usually nonrectangular, but blits are always rectangular, so every pixel within the sprite's bounding rectangle becomes part of the data transfer. With transparent blitting, each pixel that is not part of the sprite image is treated as transparent when the blitter is moving the image to its destination, so that it does not overwrite the color in that pixel on the background image.

The artist creating the sprite chooses an arbitrary color or range of colors to be used as the transparency color key. This tutorial uses a source color key on the sprite image to give the illusion of a nonrectangular blit.

The first steps of this tutorial are identical to the first tutorial to the point of creating the primary surface in Step 3: Initialize Variables. Therefore, to avoid redundancy, the first step in this tutorial will be to create the back buffer surface.

To demonstrate transparent blitting, the Tutorial 2 sample included in this SDK performs the following steps:

  • Step 1: Create the Back Buffer
  • Step 2: Initialize the Surfaces
  • Step 3: Blit to the Primary Surface


Step 1: Create the Back Buffer

[C++]

This section pertains only to application development in Visual Basic. See DirectDraw C/C++ Tutorials.

[Visual Basic]

The Tutorial 2 sample uses an off-screen surface as a composing surface. An off-screen surface is a conceptually rectangular area in memory that is generally used to store bitmaps to be blitted to the primary surface. This back buffer will be used to store the images of the lake and the sprite before displaying the composited image to the screen. This surface is created with the following statements:

'Create an invisible surface to draw to be used
'as a compositing surface in system memory

'Indicate that we want to specify the height and width
'The format of the surface (bits per pixel) will be the same
'as the primary surface
ddsdBackBuffer.lFlags = DDSD_CAPS Or DDSD_HEIGHT Or DDSD_WIDTH

'Indicate that we want a surface that is not visible and that
'we want it in system memory as opposed to video memory
ddsdBackBuffer.ddsCaps.lCaps = DDSCAPS_OFFSCREENPLAIN Or DDSCAPS_SYSTEMMEMORY

'Specify the height and width of the surface to be the same
'as the picture box (note unit are in pixels)
ddsdBackBuffer.lWidth = Picture1.Width
ddsdBackBuffer.lHeight = Picture1.Height

'Create the requested surface
Set objDDBackBuffer = objDD.CreateSurface(ddsdBackBuffer)

Next: Step 2: Initialize the Surfaces


Step 2: Initialize the Surfaces

[C++]

This section pertains only to application development in Visual Basic. See DirectDraw C/C++ Tutorials.

[Visual Basic]

This step involves creating and initializing two more surfaces, one for the background image and one for the sprite image. Additionally, we will specify the transparent color key to the sprite surface.

Both surfaces are off-screen surfaces created with a call to the DirectDraw7.CreateSurfaceFromFile method. The first surface created, objDDLakeSurf, is for the background image and has the same height and width as the Picture1 picture box control on the form. The second surface, objDDSpriteSurf, contains the sprite image which will eventually be composed with the background image on the back buffer. These surfaces are created with the following statements:

'Load a background image of the lake

'Indicate that we want to create an off-screen surface
'An off-screen surface is one that is available in memory
'(video or system memory) but is not visible to the user
ddsdLake.lFlags = DDSD_CAPS Or DDSD_WIDTH Or DDSD_HEIGHT
ddsdLake.ddsCaps.lCaps = DDSCAPS_OFFSCREENPLAIN
ddsdLake.lWidth = Picture1.Width
ddsdLake.lHeight = Picture1.Height

'Create the surface and load lake.bmp onto the surface
Set objDDLakeSurf = objDD.CreateSurfaceFromFile("lake.bmp", ddsdLake)

'Copy the background to the compositing surface
RepaintEntireBackground

'Load a sprite image of a flying dog

ddsdSprite.lFlags = DDSD_CAPS Or DDSD_WIDTH Or DDSD_HEIGHT
ddsdSprite.lWidth = 64
ddsdSprite.lHeight = 64
ddsdSprite.ddsCaps.lCaps = DDSCAPS_OFFSCREENPLAIN

Set objDDSpriteSurf = objDD.CreateSurfaceFromFile("disk1.bmp", ddsdSprite)

Next we set the transparent color key for the sprite surface. The color key is specified through a DDCOLORKEY type variable. This type has two members, low and high, both Longs. You can specify a range of values to be used as the color key or a single color by passing the same values to both members. In the Tutorial 2 sample both the high and low values are 0, indicating that we want solid black to be the color key. The color key is set on a surface by calling the DirectDrawSurface7.SetColorKey method.

There are two types of color keys you can specify on a surface. A source color key is a color that (in the case of blitting) is not copied to, or (in the case of overlays) not visible on, the destination surface. A destination color key is a color that (in the case of blitting) is replaced or (in the case of overlays) is covered on the destination surface. The Tutorial 2 sample uses a source color key. The steps in setting a color key are as follows:

'Set the transparent color of the sprite

Dim key As DDCOLORKEY

key.low = 0
key.high = 0

'Assign the transparent color to the sprite object
'DDCKEY_SRCBLT specifies that when a blt is done the
'transparent color is associated with the surface being
'blitted and not the one being blitted to
objDDSpriteSurf.SetColorKey DDCKEY_SRCBLT, key

Next: Step 3: Blit to the Primary Surface


Step 3: Blit to the Primary Surface

[C++]

This section pertains only to application development in Visual Basic. See DirectDraw C/C++ Tutorials.

[Visual Basic]

There are several steps involved before the simple sprite animation is displayed on the screen. Both the sprite surface and the background image are composed to the back buffer and then the back buffer is blitted to the primary surface. The animation is achieved by constantly moving the location of the destination rectangle when blitting the sprite surface to the back buffer. In Tutorial 2, the DoFrame procedure updates the location of the sprite surface and repaints the background image while the application is running. Additionally, there is some code to display the frames per second (fps) of the animation.

First a simple timer loop is implemented to calculate the angle of where to place the sprite:

t2 = Timer
If t1 <> 0 Then
    a = a + (t2 - t1) * 100
    If a > 360 Then a = a - 360
End If
t1 = t2

Next we make sure that we still retain control of the created surfaces. Surfaces can be lost and will need to be restored if another application takes control of the display adapter. The Tutorial 2 sample contains a simple function, ExModeActive, that tests the cooperative level of the DirectDraw object to determine whether or not we will have to restore the surfaces. This is shown in the following code:

Dim bRestore As Boolean
bRestore = False
Do Until ExModeActive
    DoEvents
    bRestore = True
Loop

DoEvents
If bRestore Then
    bRestore = False
    objDD.RestoreAllSurfaces
End If

Next, a small bit of code is implemented to display the frames per second of the sprite animation. This can be useful to help streamline your application and to find potential bottlenecks in your application.

'calculate FPS
i = i + 1
If i = 30 Then
    tNow = Timer
    If tNow <> tLast Then
       fps = 30 / (Timer - tLast)
       tLast = Timer
       i = 0
       Me.Caption = "DD Transparency    Frames per Second =" + Format$(fps, "#.0")
    End If
End If

Next we calculate the x and y coordinates of where to place the sprite:

x = Cos((a / 360) * 2 * 3.141) * Picture1.Width / 8
y = Sin((a / 360) * 2 * 3.141) * Picture1.Height / 8
x = x + Picture1.Width / 2
y = y + Picture1.Height / 2

The previous position of the sprite is held in a RECT type so we can repaint only the affected portion of the background surface. This increases the performance of the application because we do not have to constantly blit the entire surface. Then we determine the new position of the sprite and blit the sprite surface to the back buffer.

'Clean up background from last frame
'by only repainting the background where it needs to
Dim rClean As RECT
If lastX <> 0 Then
    rClean.Left = lastX
    rClean.Top = lastY
    rClean.Right = lastX + ddsdSprite.lWidth
    rClean.Bottom = lastY + ddsdSprite.lHeight
    Call objDDBackBuffer.BltFast(lastX, lastY, objDDLakeSurf, rClean, DDBLTFAST_WAIT)
End If

lastX = x
lastY = y

'Blit the sprite to the backbuffer
'using the color key on the source
'wait for the blt to finish before moving one
Dim rtemp As RECT
rtemp.Left = x
rtemp.Top = y
rtemp.Right = x + ddsdSprite.lWidth
rtemp.Bottom = y + ddsdSprite.lHeight

objDDBackBuffer.Blt rtemp, objDDSpriteSurf, rSprite, DDBLT_KEYSRC Or DDBLT_WAIT

Finally, we obtain the rectangle coordinates of the picture box control by calling the DirectX7.GetWindowRect method and call the DirectDrawSurface7.Blt method to blit the back buffer to the primary surface.

Call objDX.GetWindowRect(Picture1.hWnd, rPrim)

Call objDDScreen.Blt(rPrim, objDDBackBuffer, rBackBuffer, DDBLT_WAIT)


Tutorial 3: Using Full-Screen Features

[C++]

This section pertains only to application development in Visual Basic. See DirectDraw C/C++ Tutorials.

[Visual Basic]

This section demonstrates creating a full-screen DirectDraw application. This tutorial is very similar the Tutorial 2: Using Transparency but because it runs in full-screen, the implementation is slightly different. Mainly, instead of re-blitting the back buffer to the primary surface, this tutorial introduces the concept of a complex surface and a flipping chain. The steps to creating a full-screen application are:

  • Step 1: Set the Cooperative Level and the Display Mode
  • Step 2: Create a Complex Surface
  • Step 3: Initialize the Surfaces
  • Step 4: Update the Display with Page Flipping


Step 1: Set the Cooperative Level and the Display Mode

[C++]

This section pertains only to application development in Visual Basic. See DirectDraw C/C++ Tutorials.

[Visual Basic]

The first step in creating a full-screen application in DirectDraw is to set the cooperative level and the display mode for the DirectDraw object. Setting the cooperative level determines the top-level behavior of the application. We want this application to have exclusive access to the primary display and run in the full screen. Note: to run in full-screen mode you must also have exclusive access. Additionally, we want the enable the Mode X which is derived from the standard VGA Mode 13. The cooperative level is set through the following calls:

Set dd = dx.DirectDrawCreate("")
Me.Show
Call dd.SetCooperativeLevel(Me.hWnd, DDSCL_FULLSCREEN Or DDSCL_ALLOWMODEX Or DDSCL_EXCLUSIVE)

After setting the cooperative level, we must set the display mode for this application by calling the DirectDraw7.SetDisplayMode method:

dd.SetDisplayMode 640, 480, 16, 0, DDSDM_DEFAULT

The first two parameters are the height and width of the mode. The third is the bits per pixel (bpp). Next is the refresh rate, specifying 0 requests the default refresh rate for the driver. The last parameter is additional options, DDSDM_DEFAULT sets the mode without substituting Mode 13 for Mode X.

Next: Step 2: Create a Complex Surface


Step 2: Create a Complex Surface

[C++]

This section pertains only to application development in Visual Basic. See DirectDraw C/C++ Tutorials.

[Visual Basic]

In Tutorial 2, the off-screen, back buffer surface was used as a composing surface for the background image and the sprite image. This tutorial again uses a back buffer, but it is part of a complex surface. A complex surface is a set of surfaces created with a single call to the DirectDraw7.CreateSurface method. If the DDSCAPS_COMPLEX flag is set when you call CreateSurface call, DirectDraw implicitly creates one or more surfaces in addition to the surface explicitly specified.

One of the most useful complex surfaces you can create is a flipping chain. Usually, a flipping chain is made of a primary surface and one or more back buffers. The DDSCAPS_FLIP flag indicates that a surface is part of a flipping chain. Creating a flipping chain this way requires that you also include the DDSCAPS_COMPLEX flag.

The Tutorial 2 sample creates a flipping chain with one back buffer with the statements:

ddsd1.lFlags = DDSD_CAPS Or DDSD_BACKBUFFERCOUNT
ddsd1.ddsCaps.lCaps = DDSCAPS_PRIMARYSURFACE Or DDSCAPS_FLIP Or DDSCAPS_COMPLEX
ddsd1.lBackBufferCount = 1
Set primary = dd.CreateSurface(ddsd1)

Next we create a DDSCAPS2 type variable and set the DDSCAPS_BACKBUFFER flag to specify this is surface description for a back buffer. Then we obtain the created back buffer by using the DirectDrawSurface7.GetAttachedSurface method:

Dim caps As DDSCAPS2
caps.lCaps = DDSCAPS_BACKBUFFER
Set backbuffer = primary.GetAttachedSurface(caps)

Next: Step 3: Initialize the Surfaces


Step 3: Initialize the Surfaces

[C++]

This section pertains only to application development in Visual Basic. See DirectDraw C/C++ Tutorials.

[Visual Basic]

Initializing the off-screen surface buffers for the background image and the sprite image is essentially identical to the Step 2: Initialize the Surfaces topic found in Tutorial 2. The only difference is that we create the background surface with the surface description of the back buffer. This is easily obtained by calling the DirectDrawSurface7.GetSurfaceDesc method. This is shown in the statements:

backbuffer.GetSurfaceDesc ddsd4
ddsd2.lFlags = DDSD_CAPS Or DDSD_HEIGHT Or DDSD_WIDTH
ddsd2.ddsCaps.lCaps = DDSCAPS_OFFSCREENPLAIN
ddsd2.lWidth = ddsd4.lWidth
ddsd2.lHeight = ddsd4.lHeight
Set lakesurf = dd.CreateSurfaceFromFile("lake.bmp", ddsd2)

Next: Step 4: Update the Display with Page Flipping


Step 4: Update the Display with Page Flipping

[C++]

This section pertains only to application development in Visual Basic. See DirectDraw C/C++ Tutorials.

[Visual Basic]

This step is very similar to the Step 3: Blit to the Primary Surface step in Tutorial 2. In fact, the results are identical, except that this tutorial is done in full-screen. However, since we created the back buffer as part of a flipping chain, instead of constantly re-blitting the entire back buffer to the primary surface we can use page flipping.

Page flipping is key in multimedia, animation, and game software. Software page flipping is analogous to the way animation can be done with a pad of paper. On each page the artist changes the figure slightly, so that when you flip between sheets rapidly the drawing appears animated.

This application writes to the back buffer, then flips the primary surface so that the back buffer appears on screen. While the system is displaying the image, we are again writing to the back buffer. The process continues as long as the application is running, allowing us to animate images quickly and efficiently.

After blitting the background image and the sprite to the back buffer, we can flip the surface by calling the DirectDrawSurface7.Flip method as seen in the code:

primary.Flip Nothing, DDFLIP_WAIT


Tutorial 4: Blitting to Areas of the Screen

[C++]

This section pertains only to application development in Visual Basic. See DirectDraw C/C++ Tutorials.

[Visual Basic]

The Tutorial 4 application in the SDK is very similar to Tutorial 3: Using Full Screen Features with additional sprite animation. In fact, the only difference between the two applications is that this Tutorial uses a bitmap with many frames of animation. If you open donut.bmp file in an image viewer, you will notice that although it is a single bitmap, there are numerous images of the donut shape from slightly different viewpoints. Animation is accomplished by changing the location of the destination rectangle for the sprite on the back buffer. In addition, the different views of the donut are cycled to be blit, making the sprite rotate.

Since this tutorial is so similar to the previous one, only the step showing how to animate the sprite is discussed:

  • Step 1: Animate the Sprite


Step 1: Animate the Sprite

[C++]

This section pertains only to application development in Visual Basic. See DirectDraw C/C++ Tutorials.

[Visual Basic]

Since we know the height and width of each instance of the donut in the donut.bmp image, we can separate the bitmap into columns and rows with each cell being a single image of the donut:

ddsd3.lFlags = DDSD_CAPS
ddsd3.ddsCaps.lCaps = DDSCAPS_OFFSCREENPLAIN
Set spritesurf = dd.CreateSurfaceFromFile("donut.bmp ", ddsd3)
spriteWidth = 64
spriteHeight = 64
cols = ddsd3.lWidth / spriteWidth
rows = ddsd3.lHeight / spriteHeight

Taking a closer look at the DirectDrawSurface7.BltFast method, we see that srcRect parameter is a RECT type that defines the upper-left and lower-right points of the rectangle to blit from on the source surface. Therefore by randomly specifying a portion or cell of the sprite surface we give the sprite animation:

col = currentFrame Mod cols
row = Int(currentFrame / cols)
rSprite.Left = col * spriteWidth
rSprite.Top = row * spriteHeight
rSprite.Right = rSprite.Left + spriteWidth
rSprite.Bottom = rSprite.Top + spriteHeight

'blt to the backbuffer our animated sprite
ddrval = backbuffer.BltFast(rSprite2.Left, rSprite2.Top, spritesurf, _
         rSprite, DDBLTFAST_SRCCOLORKEY Or DDBLTFAST_WAIT)


Tutorial 5: Enumerating DirectDraw Devices

[C++]

This section pertains only to application development in Visual Basic. See DirectDraw C/C++ Tutorials.

[Visual Basic]

The Tutorial 5 sample application illustrates using the enumeration objects in DirectX for Visual Basic to obtain DirectDraw device information. This application reports the hardware and software capabilities, 3-D hardware and software capabilities, and the available display modes for each DirectDraw device installed on the system.

This tutorial is divided into the following steps:

  • Step 1: Obtain Installed DirectDraw Devices
  • Step 2: Display DirectDraw Device Capabilities
  • Step 3: Display DirectDraw Device 3-D Capabilities
  • Step 4: Report Available Display Modes


Step 1: Obtain Installed DirectDraw Devices

[C++]

This section pertains only to application development in Visual Basic. See DirectDraw C/C++ Tutorials.

[Visual Basic]

DirectX for Visual Basic enables you to query the display hardware's capabilities at run time, then provide the best performance possible given the host computer's hardware capabilities. This is easily accomplished through the use of the many enumeration objects in the DxVBLib type library.

The first step is to obtain all DirectDraw devices installed on the system. In addition to the primary display adapter, some systems have multiple display cards. A common scenario is a secondary 3-D graphics card. All the installed devices are obtained by calling the DirectX7.GetDDEnum method. This method returns a DirectDrawEnum object which you then query for information. Through the methods of the DirectDrawEnum object, you can retrieve the number of installed devices and the name, description, GUID and monitor handle for each individual device.

In the Tutorial 5 sample application this is done with the following code:

Dim ddEnum As DirectDrawEnum
Dim strGuid As String

Set ddEnum = m_dx.GetDDEnum()
OutList.AddItem "Display Cards"
For i = 1 To ddEnum.GetCount()
    OutList.AddItem " Index        " + Str(i)
    OutList.AddItem " Description  " + ddEnum.GetDescription(i)
    OutList.AddItem " Name         " + ddEnum.GetName(i)
    OutList.AddItem " GUID         " + ddEnum.GetGuid(i)
    OutList.AddItem ""

    strGuid = ddEnum.GetGuid(i)
    GetDDCaps strGuid
    GetD3DDevices strGuid
    GetDisplayModes strGuid

Next

Notice that GetDDCaps, GetD3DDevices and GetDisplayModes procedures are called for each device found installed on the system.

The information is displayed by populating a List box control.

Next: Step 2: Display DirectDraw Device Capabilities


Step 2: Display DirectDraw Device Capabilities

[C++]

This section pertains only to application development in Visual Basic. See DirectDraw C/C++ Tutorials.

[Visual Basic]

To obtain the DirectDraw hardware and software capabilities for the device you must first create the DirectDraw object, set the cooperative level of the application and call the DirectDraw7.GetCaps method. This method takes two parameters both DDCAPS type variables. Calling this method fills the first parameter, hwCaps, with the capabilities of the hardware. The second parameter, helCaps, is filled with the capabilities of the hardware emulation layer (HEL). For more information on software and hardware capabilities, see the Architectural Overview for DirectDraw topic.

After the GetCaps method is called, displaying the capabilities is done by checking the flags returned in the DDCAPS variables:

Dim dd As DirectDraw7
Dim hwCaps As DDCAPS   'HARDWARE
Dim helCaps As DDCAPS  'SOFTWARE EMULATION

Set dd = m_dx.DirectDrawCreate(sGuid)
dd.SetCooperativeLevel Me.hWnd, DDSCL_NORMAL

'Its always a good idea to figure out if the HW
'supports a feature
'Unsupported features however are emulated via
'software but are much slower
dd.GetCaps hwCaps, helCaps

'how much video memory is available
OutList.AddItem "  HW CAPS"
OutList.AddItem "   total video memory " + Str(hwCaps.lVidMemTotal)
OutList.AddItem "   free video memory " + Str(hwCaps.lVidMemFree)

'Palette Support
'Most apps don't use palettes since
'all cards support 16bpp
'Some apps use 8bpp for speed

lVal = hwCaps.lPalCaps
If (lVal = 0) Then
    OutList.AddItem "   no hw palette support"
End If
If (lVal And DDPCAPS_1BIT) Then
    OutList.AddItem "   palette support 1bpp "
End If
If (lVal And DDPCAPS_2BIT) Then
    OutList.AddItem "   palette support 2bit "
End If

'do we support the gamma ramp interface?
lVal = hwCaps.ddsCaps.lCaps2
If lVal And DDCAPS2_CANCALIBRATEGAMMA Then
    OutList.AddItem "   supports gamma correction"
Else
    OutList.AddItem "   no support for gamma correction"
End If

Set dd = Nothing

Next: Step 3: Display DirectDraw Device 3-D Capabilities


Step 3: Display DirectDraw Device 3-D Capabilities

[C++]

This section pertains only to application development in Visual Basic. See DirectDraw C/C++ Tutorials.

[Visual Basic]

Retrieving the 3-D capabilities of a DirectDraw device is very similar to the previous step of this tutorial. First a Direct3D7 object must be created from the DirectDraw7 object. Next, the Direct3D7.GetDevicesEnum method is called to create and fill a Direct3DEnumDevices enumeration object. The methods of the enumeration object are then called to retrieve information about the Direct3D devices present on a system.

In the Tutorial 5 sample, the Direct3DEnumDevices.GetDesc method is called on each Direct3D device to obtain the capabilities. Then capability flags are checked in the D3DDEVICEDESC7 type and the results are reported in the List box. This is shown in the following statements:

Set dd = m_dx.DirectDrawCreate(sGuid)
Set d3d = dd.GetDirect3D()

OutList.AddItem "   D3D devices"

Set d3denum = d3d.GetDevicesEnum()

OutList.AddItem ""

For i = 1 To d3denum.GetCount()

    d3denum.GetDesc i, hwDesc
    OutList.AddItem "     Guid        " + d3denum.GetGuid(i)
    OutList.AddItem "     Description " + d3denum.GetDescription(i)
    OutList.AddItem "     Name        " + d3denum.GetName(i)
    OutList.AddItem "     Device "
    With hwDesc
        OutList.AddItem "     Max Texture Height  " + Str(.lMaxTextureHeight)
        OutList.AddItem "     Max Texture Width   " + Str(.lMaxTextureWidth)
        If (.lDeviceRenderBitDepth And DDBD_8) Then
            OutList.AddItem "     Supports rendering to 8 bit"
        End If
        If (.lDeviceZBufferBitDepth And DDBD_8) Then
            OutList.AddItem "     Supports  8 bit z buffer"
        End If
        If (.lDevCaps And D3DDEVCAPS_TEXTURENONLOCALVIDMEM) Then
            OutList.AddItem "     Supports AGP textures"
        End If
    End With

Next: Step 4: Report Available Display Modes


Step 4: Report Available Display Modes

[C++]

This section pertains only to application development in Visual Basic. See DirectDraw C/C++ Tutorials.

[Visual Basic]

A display mode is a hardware setting that describes the dimensions and bit-depth of graphics that the display hardware sends to the monitor from the primary surface. Display modes are described by their defining characteristics: width, height, and bit-depth. For instance, most display adapters can display graphics 640 pixels wide and 480 pixels tall, where each pixel is 8 bits of data. In shorthand, this display mode is called 640×480×8. As the dimensions of a display mode get larger or as the bit-depth increases, more display memory is required.

Support for display modes varies depending on the display adapter. To ensure a particular display mode is supported on the system, you should enumerate all the valid display modes using the DirectDraw7.GetDisplayModesEnum method. This method creates and fills a DirectDrawEnumModes enumeration object called DisplayModesEnum which is then used to retrieve the descriptions of individual display modes.

In the Tutorial 5 sample the methods of the DisplayModesEnum object are called for each supported display mode:

Dim DisplayModesEnum As DirectDrawEnumModes
Dim ddsd2 As DDSURFACEDESC2
Dim dd As DirectDraw7
Set dd = m_dx.DirectDrawCreate(sGuid)
dd.SetCooperativeLevel Me.hWnd, DDSCL_NORMAL
Set DisplayModesEnum = dd.GetDisplayModesEnum(0, ddsd2)
OutList.AddItem " Display Modes"
For i = 1 To DisplayModesEnum.GetCount()
    DisplayModesEnum.GetItem i, ddsd2
    OutList.AddItem "  Index          " + Str(i)
    OutList.AddItem "  Width          " + Str(ddsd2.lWidth)
    OutList.AddItem "  Height         " + Str(ddsd2.lHeight)
    OutList.AddItem "  Bits Per Pixel" + Str(ddsd2.ddpfPixelFormat.lRGBBitCount)
    OutList.AddItem "  Refresh Rate   " + Str(ddsd2.lRefreshRate)
    OutList.AddItem ""
Next


DirectDraw Reference

This section contains reference information for the application programming interface (API) elements provided by Microsoft® DirectDraw® in C/C++ and Microsoft® Visual Basic®. Reference material is organized by language:

  • DirectDraw C/C++ Reference
  • DirectDraw Visual Basic Reference


DirectDraw C/C++ Reference

This section contains reference information for the API elements that DirectDraw provides. Reference material is divided into the following categories:

  • Interfaces
  • Functions
  • Callback Functions
  • Structures
  • Return Values
  • Pixel Format Masks
  • Four-Character Codes (FOURCC)


Interfaces

This section contains reference information about the interfaces used with the DirectDraw component. The following interfaces are covered:

  • IDDVideoPortContainer
  • IDirectDraw7
  • IDirectDrawClipper
  • IDirectDrawColorControl
  • IDirectDrawGammaControl
  • IDirectDrawPalette
  • IDirectDrawSurface7
  • IDirectDrawVideoPort


IDDVideoPortContainer

Applications use the methods of the IDDVideoPortContainer interface to create and manipulate DirectDrawVideoPort objects. Retrieve a pointer to this interface by calling the IUnknown::QueryInterface method of a DirectDraw object, specifying the IID_IDDVideoPortContainer reference identifier.

The methods of the IDDVideoPortContainer interface can be organized into the following groups:

Creating objects | CreateVideoPort
Video ports | EnumVideoPorts
 | QueryVideoPortStatus
Connections | GetVideoPortConnectInfo

The IDDVideoPortContainer interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

You can use the LPDDVIDEOPORTCONTAINER data type to declare a variable that contains a pointer to an IDDVideoPortContainer interface. The Dvp.h header file declares the LPDDVIDEOPORTCONTAINER with the following code:

typedef struct IDDVideoPortContainer    FAR *LPDDVIDEOPORTCONTAINER;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dvp.h.
Import Library: Use ddraw.lib.


IDDVideoPortContainer::CreateVideoPort

The IDDVideoPortContainer::CreateVideoPort method creates a DirectDrawVideoPort object.

HRESULT CreateVideoPort(
  DWORD dwFlags,
  LPDDVIDEOPORTDESC lpDDVideoPortDesc,
  LPDIRECTDRAWVIDEOPORT FAR *lplpDDVideoPort,
  IUnknown FAR *pUnkOuter
);

Parameters

dwFlags
Flags specifying video-port control options. This parameter can be one of the following flags, or NULL if control options are not needed:
DDVPCREATE_VBIONLY
The process wants to control only the VBI portion of the video stream.
DDVPCREATE_VIDEOONLY
The process wants to control only the non-VBI (video) portion of the video stream.
lpDDVideoPortDesc
Address of a DDVIDEOPORTDESC structure that describes the DirectDrawVideoPort object to be created.
lplpDDVideoPort
Address of a variable to be filled with a pointer to the new DirectDrawVideoPort object's IDirectDrawVideoPort interface if the call succeeds.
pUnkOuter
Allows for future compatibility with COM aggregation features. Presently, however, this method returns an error if this parameter is anything but NULL.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_CURRENTLYNOTAVAIL
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOCOOPERATIVELEVELSET
DDERR_OUTOFCAPS
DDERR_OUTOFMEMORY

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dvp.h.
Import Library: Use ddraw.lib.


IDDVideoPortContainer::EnumVideoPorts

The IDDVideoPortContainer::EnumVideoPorts method enumerates all the video ports that the hardware exposes that are compatible with a provided video-port description.

HRESULT EnumVideoPorts(
  DWORD dwFlags,
  LPDDVIDEOPORTCAPS lpDDVideoPortCaps,
  LPVOID lpContext,
  LPENUMVIDEOCALLBACK lpEnumVideoCallback
);

Parameters

dwFlags
Reserved for future use. This parameter must be 0.
lpDDVideoPortCaps
Address of a DDVIDEOPORTCAPS structure to be checked against the available video ports. If this parameter is NULL, all video ports are enumerated.
lpContext
Address of a caller-defined structure to be passed to each enumeration member.
lpEnumVideoCallback
Address of the EnumVideoCallback function to be called each time that a match is found.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dvp.h.
Import Library: Use ddraw.lib.


IDDVideoPortContainer::GetVideoPortConnectInfo

The IDDVideoPortContainer::GetVideoPortConnectInfo method retrieves the connection information supported by all video ports.

HRESULT GetVideoPortConnectInfo(
  DWORD dwPortId,
  LPDWORD lpNumEntries,
  LPDDVIDEOPORTCONNECT lpConnectInfo
);

Parameters

dwPortId
Identifier of the video port for which the connection information is to be retrieved.
lpNumEntries
Address of a variable that contains the number of entries that the array at lpConnectInfo can hold. If this number is less than the total number of connections, the method fills the array with all the entries that fit, sets the value at lpNumEntries to indicate the total number of connections, and returns DDERR_MOREDATA.
lpConnectInfo
Address of an array of DDVIDEOPORTCONNECT structures to be filled with the connection options supported by the specified video port. If this parameter is NULL, the method sets lpNumEntries to indicate the total number of connections that the video port supports, then returns DD_OK.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_MOREDATA

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dvp.h.
Import Library: Use ddraw.lib.


IDDVideoPortContainer::QueryVideoPortStatus

The IDDVideoPortContainer::QueryVideoPortStatus method retrieves the status of a DirectDrawVideoPort object.

HRESULT QueryVideoPortStatus(
  DWORD dwPortId,
  LPDDVIDEOPORTSTATUS lpVPStatus
);

Parameters

dwPortId
Identifier of the video port for which the status information is to be retrieved.
lpVPStatus
Address of a DDVIDEOPORTSTATUS structure to be filled with information about the status of the specified video port.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_CURRENTLYNOTAVAIL
DDERR_EXCEPTION
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_UNSUPPORTED

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dvp.h.
Import Library: Use ddraw.lib.


IDirectDraw7

Applications use the methods of the IDirectDraw7 interface to create DirectDraw objects and work with system-level variables. This section is a reference to the methods of this interface. For a conceptual overview, see The DirectDraw Object.

The methods of the IDirectDraw7 interface can be organized into the following groups:

Allocating memory | Compact
 | Initialize
Cooperative levels | SetCooperativeLevel
 | TestCooperativeLevel
Creating objects | CreateClipper
 | CreatePalette
 | CreateSurface
Device capabilities | GetCaps
Display modes | EnumDisplayModes
 | GetDisplayMode
 | GetMonitorFrequency
 | RestoreDisplayMode
 | SetDisplayMode
 | WaitForVerticalBlank
Display status | GetScanLine
 | GetVerticalBlankStatus
Miscellaneous | EvaluateMode
 | GetAvailableVidMem
 | GetDeviceIdentifier
 | GetFourCCCodes
 | StartModeTest
Surface management | DuplicateSurface
 | EnumSurfaces
 | FlipToGDISurface
 | GetGDISurface
 | GetSurfaceFromDC
 | RestoreAllSurfaces

The IDirectDraw7 interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The IDirectDraw7 interface extends the features of previous versions of the interface by offering methods enabling more flexible surface management than previous versions. All the surface-related methods in the IDirectDraw7 interface accept slightly different parameters than their counterparts in the IDirectDraw2 interface. Wherever an IDirectDraw2 interface method might accept a DDSURFACEDESC structure and retrieve an IDirectDrawSurface3 interface, the methods in IDirectDraw7 accept a DDSURFACEDESC2 structure and retrieve an IDirectDrawSurface7 interface, instead.

IDirectDraw7 introduces improved compliance with COM rules dictating the lifetime of child objects. For more information, see Parent and Child Object Lifetimes.

Use the LPDIRECTDRAW, LPDIRECTDRAW2, LPDIRECTDRAW4 or LPDIRECTDRAW7 data types to declare a variable that contains a pointer to an IDirectDraw, IDirectDraw2, IDirectDraw4 or IDirectDraw7 interface. The Ddraw.h header file declares these data types with the following code:

typedef struct IDirectDraw     FAR *LPDIRECTDRAW;
typedef struct IDirectDraw2    FAR *LPDIRECTDRAW2;
typedef struct IDirectDraw4    FAR *LPDIRECTDRAW4;
typedef struct IDirectDraw7    FAR *LPDIRECTDRAW7;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.


IDirectDraw7::Compact

The IDirectDraw7::Compact method is not currently implemented.

HRESULT Compact();

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOEXCLUSIVEMODE
DDERR_SURFACEBUSY

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.


IDirectDraw7::CreateClipper

The IDirectDraw7::CreateClipper method creates a DirectDrawClipper object.

HRESULT CreateClipper(
  DWORD dwFlags,
  LPDIRECTDRAWCLIPPER FAR *lplpDDClipper,
  IUnknown FAR *pUnkOuter
);

Parameters

dwFlags
Currently not used and must be set to 0.
lplpDDClipper
Address of a variable to be set to a valid IDirectDrawClipper interface pointer if the call succeeds.
pUnkOuter
Allows for future compatibility with COM aggregation features. Presently, however, this method returns an error if this parameter is anything but NULL.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOCOOPERATIVELEVELSET
DDERR_OUTOFMEMORY

Remarks

The DirectDrawClipper object can be attached to a DirectDrawSurface and used during IDirectDrawSurface7::Blt, IDirectDrawSurface7::BltBatch, and IDirectDrawSurface7::UpdateOverlay operations.

To create a DirectDrawClipper object that is not owned by a specific DirectDraw object, use the DirectDrawCreateClipper function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDrawSurface7::GetClipper, IDirectDrawSurface7::SetClipper


IDirectDraw7::CreatePalette

The IDirectDraw7::CreatePalette method creates a DirectDrawPalette object for this DirectDraw object.

HRESULT CreatePalette(
  DWORD dwFlags,
  LPPALETTEENTRY lpDDColorArray,
  LPDIRECTDRAWPALETTE FAR *lplpDDPalette,
  IUnknown FAR *pUnkOuter
);

Parameters

dwFlags
One or more of the following flags:
DDPCAPS_1BIT
The index is 1 bit. There are two entries in the color table.
DDPCAPS_2BIT
The index is 2 bits. There are four entries in the color table.
DDPCAPS_4BIT
The index is 4 bits. There are 16 entries in the color table.
DDPCAPS_8BIT
The index is 8 bits. There are 256 entries in the color table.
DDPCAPS_8BITENTRIES
The index refers to an 8-bit color index. This flag is valid only when used with the DDPCAPS_1BIT, DDPCAPS_2BIT, or DDPCAPS_4BIT flag, and when the target surface is 8 bpp. Each color entry is 1 byte long and is an index to a destination surface's 8-bpp palette.
DDPCAPS_ALPHA
The peFlags member of the associated PALETTEENTRY structure is to be interpreted as a single 8-bit alpha value (in addition to the peRed, peGreen, and peBlue members). A palette created with this flag can only be attached to a texture: a surface created with the DDSCAPS_TEXTURE capability flag.
DDPCAPS_ALLOW256
This palette can have all 256 entries defined.
DDPCAPS_INITIALIZE
Obsolete. DirectDraw always initializes this palette with the colors in the color array passed at lpDDColorArray.
DDPCAPS_PRIMARYSURFACE
This palette is attached to the primary surface. Changing this palette's color table immediately affects the display unless DDPSETPAL_VSYNC is specified and supported.
DDPCAPS_PRIMARYSURFACELEFT
This palette is the one attached to the left-eye primary surface. Changing this palette's color table immediately affects the left-eye display unless DDPSETPAL_VSYNC is specified and supported.
DDPCAPS_VSYNC
This palette can have modifications to it synchronized with the monitor's refresh rate.
lpDDColorArray
Address of an array of 2, 4, 16, or 256 PALETTEENTRY structures to initialize this DirectDrawPalette object.
lplpDDPalette
Address of a variable to be set to a valid IDirectDrawPalette interface pointer if the call succeeds.
pUnkOuter
Allows for future compatibility with COM aggregation features. Presently, however, this method returns an error if this parameter is anything but NULL.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOCOOPERATIVELEVELSET
DDERR_OUTOFMEMORY
DDERR_UNSUPPORTED

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.


IDirectDraw7::CreateSurface

The IDirectDraw7::CreateSurface method creates a DirectDrawSurface object for this DirectDraw object.

HRESULT CreateSurface(
  LPDDSURFACEDESC2 lpDDSurfaceDesc2,
  LPDIRECTDRAWSURFACE7 FAR *lplpDDSurface,
  IUnknown FAR *pUnkOuter
);

Parameters

lpDDSurfaceDesc2
Address of a DDSURFACEDESC2 structure that describes the requested surface. Set any unused members of the DDSURFACEDESC2 structure to 0 before calling this method. A DDSCAPS2 structure is a member of DDSURFACEDESC2.
lplpDDSurface
Address of a variable to be set to a valid IDirectDrawSurface7 interface pointer if the call succeeds.
pUnkOuter
Allows for future compatibility with COM aggregation features. Presently, however, this method returns an error if this parameter is anything but NULL.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INCOMPATIBLEPRIMARY
DDERR_INVALIDCAPS
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDPIXELFORMAT
DDERR_NOALPHAHW
DDERR_NOCOOPERATIVELEVELSET
DDERR_NODIRECTDRAWHW
DDERR_NOEMULATION
DDERR_NOEXCLUSIVEMODE
DDERR_NOFLIPHW
DDERR_NOMIPMAPHW
DDERR_NOOVERLAYHW
DDERR_NOZBUFFERHW
DDERR_OUTOFMEMORY
DDERR_OUTOFVIDEOMEMORY
DDERR_PRIMARYSURFACEALREADYEXISTS
DDERR_UNSUPPORTEDMODE

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.


IDirectDraw7::DuplicateSurface

The IDirectDraw7::DuplicateSurface method duplicates a DirectDrawSurface object.

HRESULT DuplicateSurface(
  LPDIRECTDRAWSURFACE7 lpDDSurface,
  LPLPDIRECTDRAWSURFACE7 FAR *lplpDupDDSurface
);

Parameters

lpDDSurface
Address of the IDirectDrawSurface7 interface for the surface to be duplicated.
lplpDupDDSurface
Address of a variable to be filled with an IDirectDrawSurface7 interface pointer for the newly duplicated DirectDrawSurface object.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_CANTDUPLICATE
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY
DDERR_SURFACELOST

Remarks

This method creates a new DirectDrawSurface object that points to the same surface memory as an existing DirectDrawSurface object. This duplicate can be used just like the original object. The surface memory is released after the last object referring to it is released. A primary surface, 3-D surface, or implicitly created surface cannot be duplicated.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.


IDirectDraw7::EnumDisplayModes

The IDirectDraw7::EnumDisplayModes method enumerates all the display modes that the hardware exposes through the DirectDraw object that are compatible with a provided surface description.

HRESULT EnumDisplayModes(
  DWORD dwFlags,
  LPDDSURFACEDESC2 lpDDSurfaceDesc2,
  LPVOID lpContext,
  LPDDENUMMODESCALLBACK2 lpEnumModesCallback
);

Parameters

dwFlags
DDEDM_REFRESHRATES
Enumerates modes with different refresh rates. IDirectDraw7::EnumDisplayModes guarantees that a particular mode is enumerated only once. This flag specifies whether the refresh rate is taken into account when determining whether a mode is unique.
DDEDM_STANDARDVGAMODES
Enumerates Mode 13 in addition to the 320x200x8 Mode X mode.
lpDDSurfaceDesc2
Address of a DDSURFACEDESC2 structure to be checked against available modes. If the value of this parameter is NULL, all modes are enumerated.
lpContext
Address of an application-defined structure to be passed to each enumeration member.
lpEnumModesCallback
Address of the EnumModesCallback2 function that the enumeration procedure calls every time a match is found.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

This method enumerates the dwRefreshRate member of the DDSURFACEDESC2 structure; the IDirectDraw::EnumDisplayModes method does not contain this capability. If you use the IDirectDraw7::SetDisplayMode method to set the refresh rate of a new mode, use IDirectDraw7::EnumDisplayModes to enumerate the dwRefreshRate member.

This method differs from its counterparts in former interfaces in that it accepts the address of an EnumModesCallback2 function as a parameter, rather than an EnumModesCallback function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDraw7::GetDisplayMode, IDirectDraw7::SetDisplayMode, IDirectDraw7::RestoreDisplayMode


IDirectDraw7::EnumSurfaces

The IDirectDraw7::EnumSurfaces method enumerates all the existing or possible surfaces that meet the specified surface description.

HRESULT EnumSurfaces(
  DWORD dwFlags,
  LPDDSURFACEDESC2 lpDDSD2,
  LPVOID lpContext,
  LPDDENUMSURFACESCALLBACK2 lpEnumSurfacesCallback
);

Parameters

dwFlags
A combination of one search type flag and one matching flag. The search type flag determines how the method searches for matching surfaces; you can search for surfaces that can be created using the description in the lpDDSD2 parameter or for existing surfaces that already match that description. The matching flag determines whether the method enumerates all surfaces, only those that match, or only those that do not match the description in the lpDDSD2 parameter.
Search type flags
DDENUMSURFACES_CANBECREATED
Enumerates the first surface that can be created and meets the search criterion. This flag can be used only with the DDENUMSURFACES_MATCH flag.
DDENUMSURFACES_DOESEXIST
Enumerates the already existing surfaces that meet the search criterion.
Matching flags
DDENUMSURFACES_ALL
Enumerates all surfaces that meet the search criterion. This flag can be used only with the DDENUMSURFACES_DOESEXIST search type flag.
DDENUMSURFACES_MATCH
Searches for any surface that matches the surface description.
DDENUMSURFACES_NOMATCH
Searches for any surface that does not match the surface description.
lpDDSD2
Address of a DDSURFACEDESC2 structure that defines the surface of interest. This parameter can be NULL if dwFlags includes the DDENUMSURFACES_ALL flag.
lpContext
Address of an application-defined structure to be passed to each enumeration member.
lpEnumSurfacesCallback
Address of the EnumSurfacesCallback2 function that the enumeration procedure calls every time a match is found.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

If the DDENUMSURFACES_CANBECREATED flag is set, this method attempts to temporarily create a surface that meets the search criterion.

When using the DDENUMSURFACES_DOESEXIST flag, an enumerated surface's reference count is incremented—if you are not going to use the surface, be sure to use IDirectDrawSurface7::Release to release it after each enumeration. If you will be using the surface, release it when it is no longer needed.

This method differs from its counterparts in previous interface versions in that it accepts a pointer to an EnumSurfacesCallback2 function, rather than an EnumSurfacesCallback function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

Enumerating Surfaces


IDirectDraw7::EvaluateMode

The IDirectDraw7::EvaluateMode method is used after a call to IDirectDraw7::StartModeTest to pass or fail each mode presented by the test and to step through the modes until the test is complete.

HRESULT EvaluateMode(
  DWORD  dwFlags,
  DWORD  *pSecondsUntilTimeout
);

Parameters

dwFlags
Flags indicating the status of the mode being tested.
DDEM_MODEPASSED
The mode being tested has passed.
DDEM_MODEFAILED
The mode being tested has failed.
pSecondsUntilTimeout
A pointer to the DWORD that will receive a value denoting the seconds remaining before the current mode will be failed automatically unless it is explicitly passed or failed.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails or on completion, the method can return one of the following error values:

DDERR_TESTFINISHED
DDERR_NEWMODE
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOTFOUND

Remarks

The IDirectDraw7::EvaluateMode method can be used in conjunction with the IDirectDraw7::StartModeTest method to determine the maximum refresh rate that an EDID monitor and display adapter combination can support for each screen resolution.

Specifically, a call to IDirectDraw7::StartModeTest directs DirectDraw to establish a set of testable resolutions and to display a mode based on the first resolution in the set. Subsequent calls to IDirectDraw7::EvaluateMode can be used to pass or fail each mode and to advance the test to the next display mode. The method steps through the testable resolutions starting with the highest refresh rate supported for a given resolution. Once a refresh rate for a given resolution passes, testing of lower refresh rates for that resolution is skipped.

When the test is initiated, or whenever a mode is passed or failed, DirectDraw will begin a 15 second timeout. An application can monitor the time remaining without passing or failing the current mode by calling IDirectDraw7::EvaluateMode with a value of 0 for the dwFlags argument. Note that DirectDraw will only change modes or terminate the test when IDirectDraw7::EvaluateMode is called. However, if the method is called after the timeout period has elapsed, the current mode will be failed, regardless of the value provided for the dwFlags argument.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDraw7::StartModeTest


IDirectDraw7::FlipToGDISurface

The IDirectDraw7::FlipToGDISurface method makes the surface that the GDI writes to the primary surface.

HRESULT FlipToGDISurface();

Parameters

None.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOTFOUND

Remarks

This method can be called at the end of a page-flipping application to ensure that the display memory that the GDI is writing to is visible.

The method can also be used to make the GDI surface the primary surface so that normal windows such as dialog boxes can be displayed in full-screen mode. The hardware must have the DDCAPS2_CANRENDERWINDOWED capability. For more information, see Displaying a Window in Full-Screen Mode

This method disables stereo autoflipping.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDraw7::GetGDISurface


IDirectDraw7::GetAvailableVidMem

The IDirectDraw7::GetAvailableVidMem method retrieves the total amount of display memory available and the amount of display memory currently free for a given type of surface.

HRESULT GetAvailableVidMem(
  LPDDSCAPS2 lpDDSCaps2,
  LPDWORD    lpdwTotal,
  LPDWORD    lpdwFree
);

Parameters

lpDDSCaps2
Address of a DDSCAPS2 structure that indicates the hardware capabilities of the proposed surface.
lpdwTotal
Address of a variable to be filled with the total amount of display memory available, in bytes. The value retrieved reflects the total video memory, minus the video memory required for the primary surface and any private caches that the display driver reserves.
lpdwFree
Address of a variable to be filled with the amount of display memory currently free that can be allocated for a surface that matches the capabilities specified by the structure at lpDDSCaps2.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDCAPS
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NODIRECTDRAWHW

If NULL is passed to either lpdwTotal or lpdwFree, the value for that parameter is not returned.

Remarks

The following C++ example demonstrates how to use IDirectDraw7::GetAvailableVidMem to determine both the total and free display memory available for texture-map surfaces:

// For this example, the lpDD variable is a valid
// pointer to an IDirectDraw interface.
LPDIRECTDRAW7 lpDD;
DDSCAPS2      ddsCaps2;
DWORD         dwTotal;
DWORD         dwFree;
HRESULT       hr;

hr = lpDD->QueryInterface(IID_IDirectDraw7, &lpDD);
if (FAILED(hr))
    return hr;

// Initialize the structure.
ZeroMemory(&ddsCaps2, sizeof(ddsCaps2));

ddsCaps2.dwCaps = DDSCAPS_TEXTURE;
hr = lpDD->GetAvailableVidMem(&ddsCaps2, &dwTotal, &dwFree);
if (FAILED(hr))
    return hr;

If the surface has the DDSCAPS_VIDEOMEMORY flag set, this method will return different amounts of video memory depending on whether or not the surface can be used as a 3-D texture. If the surface can be used for 3-D textures, the GetAvailableVidMem method will return the sum of the local video memory and the non-local video memory on AGP systems.

This method provides only a snapshot of the current display-memory state. The amount of free display memory is subject to change as surfaces are created and released. Therefore, you should use the free memory value only as an approximation. In addition, a particular display adapter card might make no distinction between two different memory types. For example, the adapter might use the same portion of display memory to store z-buffers and textures. So, allocating one type of surface (for example, a z-buffer) can affect the amount of display memory available for another type of surface (textures). Therefore, it is best to first allocate an application's fixed resources (such as front and back buffers and z-buffers) before determining how much memory is available for dynamic use (such as texture mapping).

This method was not implemented in the IDirectDraw interface.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.


IDirectDraw7::GetCaps

The IDirectDraw7::GetCaps method fills in the capabilities of the device driver for the hardware and the hardware emulation layer (HEL).

HRESULT GetCaps(
  LPDDCAPS lpDDDriverCaps,
  LPDDCAPS lpDDHELCaps
);

Parameters

lpDDDriverCaps
Address of a DDCAPS structure to be filled with the capabilities of the hardware, as reported by the device driver. Set this parameter to NULL if device driver capabilities are not to be retrieved.
lpDDHELCaps
Address of a DDCAPS structure to be filled with the capabilities of the HEL. Set this parameter to NULL if HEL capabilities are not to be retrieved.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

You can set only one of the two parameters to NULL to exclude it. If you set both to NULL, the method fails, returning DDERR_INVALIDPARAMS.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.


IDirectDraw7::GetDeviceIdentifier

The IDirectDraw7::GetDeviceIdentifier method obtains information about the driver. This method can be used, with caution, to recognize specific hardware installations to implement workarounds for poor driver or chipset behavior.

HRESULT GetDeviceIdentifier(
  LPDDDEVICEIDENTIFIER2 lpdddi,
  DWORD dwFlags
);

Parameters

lpdddi
Address of a DDDEVICEIDENTIFIER2 structure to receive information about the driver.
dwFlags
Flags specifying options. The following flag is defined:
DDGDI_GETHOSTIDENTIFIER
Causes the method to return information about the host (typically 2-D) adapter in a system equipped with a stacked secondary 3-D adapter. Such an adapter appears to the application as if it were part of the host adapter, but is typically located on a separate card. When the dwFlags parameter is 0, information on the stacked secondary is returned because this most accurately reflects the qualities of the DirectDraw object involved.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return DDERR_INVALIDPARAMS.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.


IDirectDraw7::GetDisplayMode

The IDirectDraw7::GetDisplayMode method retrieves the current display mode.

HRESULT GetDisplayMode(
  LPDDSURFACEDESC2 lpDDSurfaceDesc2
);

Parameters

lpDDSurfaceDesc2
Address of a DDSURFACEDESC2 structure to be filled with a description of the surface.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_UNSUPPORTEDMODE

Remarks

An application should not save the information returned by this method to restore the display mode on clean-up. The application should use the IDirectDraw7::RestoreDisplayMode method to restore the mode on clean-up, thus avoiding mode-setting conflicts that could arise in a multiprocess environment.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDraw7::SetDisplayMode, IDirectDraw7::RestoreDisplayMode, IDirectDraw7::EnumDisplayModes


IDirectDraw7::GetFourCCCodes

The IDirectDraw7::GetFourCCCodes method retrieves the FOURCC codes supported by the DirectDraw object. This method can also retrieve the number of codes supported.

HRESULT GetFourCCCodes(
  LPDWORD lpNumCodes,
  LPDWORD lpCodes
);

Parameters

lpNumCodes
Address of a variable that contains the number of entries that the array pointed to by lpCodes can hold. If the number of entries is too small to accommodate all the codes, lpNumCodes is set to the required number, and the array pointed to by lpCodes is filled with all that fits.
lpCodes
Address of an array of variables to be filled with FOURCC codes supported by this DirectDraw object. If you specify NULL, lpNumCodes is set to the number of supported FOURCC codes, and the method returns.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.


IDirectDraw7::GetGDISurface

The IDirectDraw7::GetGDISurface method retrieves the DirectDrawSurface object that currently represents the surface memory that GDI is treating as the primary surface.

HRESULT GetGDISurface(
  LPDIRECTDRAWSURFACE7 FAR *lplpGDIDDSSurface
);

Parameters

lplpGDIDDSSurface
Address of a variable to be filled with a pointer to the IDirectDrawSurface7 interface for the surface that currently controls the GDI's primary surface memory.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOTFOUND

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDraw7::FlipToGDISurface


IDirectDraw7::GetMonitorFrequency

The IDirectDraw7::GetMonitorFrequency method retrieves the frequency of the monitor being driven by the DirectDraw object.

HRESULT GetMonitorFrequency(
  LPDWORD lpdwFrequency
);

Parameters

lpdwFrequency
Address of a variable to be filled with the monitor frequency, in Hz.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_UNSUPPORTED

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.


IDirectDraw7::GetScanLine

The IDirectDraw7::GetScanLine method retrieves the scan line that is currently being drawn on the monitor.

HRESULT GetScanLine(
  LPDWORD lpdwScanLine
);

Parameters

lpdwScanLine
Address of a variable to contain the scan line that the display is currently drawing.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_UNSUPPORTED
DDERR_VERTICALBLANKINPROGRESS

Remarks

Scan lines are reported as zero-based integers. The returned scan line value is in the range from 0 through n, where 0 is the first visible scan line on the screen and n is the last visible scan line, plus any scan lines that occur during the vertical blank period. So, in a case where an application is running at a resolution of 640×480 and there are 12 scan lines during vblank, the values returned by this method range from 0 through 491.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDraw7::GetVerticalBlankStatus, IDirectDraw7::WaitForVerticalBlank


IDirectDraw7::GetSurfaceFromDC

The IDirectDraw7::GetSurfaceFromDC method retrieves the IDirectDrawSurface7 interface for a surface, based on its GDI device context handle.

HRESULT GetSurfaceFromDC(
  HDC hdc,
  LPDIRECTDRAWSURFACE7 * lpDDS
);

Parameters

hdc
Handle of a display device context.
lpDDS
Address of a variable to be filled with a valid IDirectDrawSurface7 interface pointer if the call succeeds.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_GENERIC
DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY
DDERR_NOTFOUND

Remarks

This method succeeds only for device context handles that identify surfaces already associated with the DirectDraw object.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

Surfaces and Device Contexts


IDirectDraw7::GetVerticalBlankStatus

The IDirectDraw7::GetVerticalBlankStatus method retrieves the status of the vertical blank.

HRESULT GetVerticalBlankStatus(
  LPBOOL lpbIsInVB
);

Parameters

lpbIsInVB
Address of a variable to be filled with the status of the vertical blank. This parameter is TRUE if a vertical blank is occurring, and FALSE otherwise.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

To synchronize with the vertical blank, use the IDirectDraw7::WaitForVerticalBlank method.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDraw7::GetScanLine, IDirectDraw7::WaitForVerticalBlank


IDirectDraw7::Initialize

The IDirectDraw7::Initialize method initializes a DirectDraw object that was created by using the CoCreateInstance COM function.

HRESULT Initialize(
  GUID FAR *lpGUID
);

Parameters

lpGUID
Address of the globally unique identifier (GUID) used as the interface identifier.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_ALREADYINITIALIZED
DDERR_DIRECTDRAWALREADYCREATED
DDERR_GENERIC
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NODIRECTDRAWHW
DDERR_NODIRECTDRAWSUPPORT
DDERR_OUTOFMEMORY

This method is provided for compliance with the Component Object Model (COM). If the DirectDrawCreate function was used to create a DirectDraw object, this method returns DDERR_ALREADYINITIALIZED. If IDirectDraw7::Initialize is not called when using CoCreateInstance to create a DirectDraw object, any method that is called afterward returns DDERR_NOTINITIALIZED.

Remarks

For more information about using IDirectDraw7::Initialize with CoCreateInstance, see Creating DirectDraw Objects by Using CoCreateInstance.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.


IDirectDraw7::RestoreAllSurfaces

The IDirectDraw7::RestoreAllSurfaces method restores all the surfaces created for the DirectDraw object, in the order that they were created.

HRESULT RestoreAllSurfaces();

Parameters

None.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

This method is provided for convenience. Effectively, this method calls the IDirectDrawSurface7::Restore method for each surface created by this DirectDraw object.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDrawSurface7::Restore, Losing and Restoring Surfaces


IDirectDraw7::RestoreDisplayMode

The IDirectDraw7::RestoreDisplayMode method resets the mode of the display device hardware for the primary surface to what it was before the IDirectDraw7::SetDisplayMode method was called. Exclusive-level access is required to use this method.

HRESULT RestoreDisplayMode();

Parameters

None.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_GENERIC
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_LOCKEDSURFACES
DDERR_NOEXCLUSIVEMODE

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDraw7::SetDisplayMode, IDirectDraw7::EnumDisplayModes, IDirectDraw7::SetCooperativeLevel


IDirectDraw7::SetCooperativeLevel

The IDirectDraw7::SetCooperativeLevel method determines the top-level behavior of the application.

HRESULT SetCooperativeLevel(
  HWND hWnd,
  DWORD dwFlags
);

Parameters

hWnd
Window handle used for the application. Set to the calling application's top-level window handle (not a handle for any child windows created by the top-level window). This parameter can be NULL when the DDSCL_NORMAL flag is specified in the dwFlags parameter.
dwFlags
One or more of the following flags:
DDSCL_ALLOWMODEX
Allows the use of Mode X display modes. This flag can only be used if the DDSCL_EXCLUSIVE and DDSCL_FULLSCREEN flags are present.
DDSCL_ALLOWREBOOT
Allows CTRL+ALT+DEL to function while in exclusive (full-screen) mode.
DDSCL_CREATEDEVICEWINDOW
This flag is supported in Microsoft® Windows® 98 and Microsoft® Windows® 2000 only. Indicates that DirectDraw is to create and manage a default device window for this DirectDraw object. For more information, see Focus and Device Windows.
DDSCL_EXCLUSIVE
Requests the exclusive level. This flag must be used with the DDSCL_FULLSCREEN flag.
DDSCL_FPUPRESERVE
The calling application cares about the FPU state and does not want Direct3D to modify it in ways visible to the application. In this mode, Direct3D saves and restores the FPU state every time that it needs to modify the FPU state. For more information, see DirectDraw Cooperative Levels and FPU Precision.
DDSCL_FPUSETUP
The calling application is likely to keep the FPU set up for optimal Direct3D performance (single precision and exceptions disabled), so Direct3D does not need to explicitly set the FPU each time. This is the default state. For more information, see DirectDraw Cooperative Levels and FPU Precision.
DDSCL_FULLSCREEN
The exclusive-mode owner is responsible for the entire primary surface. The GDI can be ignored. This flag must be used with the DDSCL_EXCLUSIVE flag.
DDSCL_MULTITHREADED
Requests multithread-safe DirectDraw behavior. This causes Direct3D to take the global critical section more frequently.
DDSCL_NORMAL
The application functions as a regular Microsoft® Windows® application. This flag cannot be used with the DDSCL_ALLOWMODEX, DDSCL_EXCLUSIVE, or DDSCL_FULLSCREEN flags.
DDSCL_NOWINDOWCHANGES
DirectDraw is not allowed to minimize or restore the application window on activation.
DDSCL_SETDEVICEWINDOW
This flag is supported in Windows 98 and Windows 2000 only. Indicates that the hWnd parameter is the window handle of the device window for this DirectDraw object. This flag cannot be used with the DDSCL_SETFOCUSWINDOW flag.
DDSCL_SETFOCUSWINDOW
This flag is supported in Windows 98 and Windows 2000 only. Indicates that the hWnd parameter is the window handle of the focus window for this DirectDraw object. This flag cannot be used with the DDSCL_SETDEVICEWINDOW flag.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_EXCLUSIVEMODEALREADYSET
DDERR_HWNDALREADYSET
DDERR_HWNDSUBCLASSED
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY

Remarks

This method must be called by the same thread that created the application window.

An application must set either the DDSCL_EXCLUSIVE or the DDSCL_NORMAL flag.

The DDSCL_EXCLUSIVE flag must be set to call functions that can have drastic performance consequences for other applications. For more information, see Cooperative Levels.

Interaction between this method and the IDirectDraw7::SetDisplayMode method differs from their IDirectDraw counterparts. For more information, see Restoring Display Modes.

If you use Microsoft Foundation Classes (MFC), the window handle passed to this method should identify the application's top-level window, not a derived child window. To retrieve your MFC application's top-level window handle, you could use the following code:

    HWND hwndTop = AfxGetMainWnd()->GetSafeHwnd();

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDraw7::SetDisplayMode, IDirectDraw7::Compact, IDirectDraw7::EnumDisplayModes, Mode X and Mode 13 Display Modes, Focus and Device Windows


IDirectDraw7::SetDisplayMode

The IDirectDraw7::SetDisplayMode method sets the mode of the display-device hardware.

HRESULT SetDisplayMode(
  DWORD dwWidth,
  DWORD dwHeight,
  DWORD dwBPP,
  DWORD dwRefreshRate,
  DWORD dwFlags
);

Parameters

dwWidth and dwHeight
Width and height of the new mode.
dwBPP
Bits per pixel (bpp) of the new mode.
dwRefreshRate
Refresh rate of the new mode. Set this value to 0 to request the default refresh rate for the driver.
dwFlags
Flags describing additional options. Currently, the only valid flag is DDSDM_STANDARDVGAMODE, which causes the method to set Mode 13, instead of Mode X 320x200x8 mode. If you are setting another resolution, bit depth, or a Mode X mode, do not use this flag; instead, set the parameter to 0.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_GENERIC
DDERR_INVALIDMODE
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_LOCKEDSURFACES
DDERR_NOEXCLUSIVEMODE
DDERR_SURFACEBUSY
DDERR_UNSUPPORTED
DDERR_UNSUPPORTEDMODE
DDERR_WASSTILLDRAWING

Remarks

This method must be called by the same thread that created the application window.

If another application changes the display mode, the primary surface is lost, and the method returns DDERR_SURFACELOST until the primary surface is recreated to match the new display mode.

As part of the IDirectDraw interface, this method did not include the dwRefreshRate and dwFlags parameters.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDraw7::RestoreDisplayMode, IDirectDraw7::GetDisplayMode, IDirectDraw7::EnumDisplayModes, IDirectDraw7::SetCooperativeLevel, Setting Display Modes, Restoring Display Modes


IDirectDraw7::StartModeTest

The IDirectDraw7::StartModeTest method initiates a test to update the system registry with refresh rate information for the current display adapter and monitor combination. A call to this method is typically followed by calls to IDirectDraw7::EvaluateMode to pass or fail modes displayed by the test.

HRESULT StartModeTest(
  LPSIZE   lpModesToTest,
  DWORD    dwNumEntries,
  DWORD    dwFlags
);

Parameters

lpModesToTest
A pointer to an array of SIZE elements describing, in terms of screen resolutions, the modes that should be tested.
dwNumEntries
The number of elements in the array pointed to by lpModesToTest.
dwFlags
The only flag value that is valid at present is DDSMT_ISTESTREQUIRED. When this flag is specified, IDirectDraw7::StartModeTest will not initiate a test, but will instead return a value indicating whether it is possible or necessary to test the resolutions identified by lpModesToTest and dwNumEntries.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_CURRENTLYNOTAVAIL
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOEXCLUSIVEMODE
DDERR_NOTFOUND
DDERR_TESTFINISHED

When the method is called with the DDSMT_ISTESTREQUIRED flag, it can return one of the following values:

DDERR_NEWMODE
DDERR_NODRIVERSUPPORT
DDERR_NOMONITORINFORMATION
DDERR_TESTFINISHED

Remarks

The IDirectDraw7::StartModeTest method can be used in conjunction with the IDirectDraw7::EvaluateMode method to determine the maximum refresh rate that an EDID monitor and display adapter combination can support for each screen resolution. The results of the testing are stored in the system registry and affect the operation of IDirectDraw7::EnumDisplayModes when that method is called with the DDEDM_REFRESHRATES flag set.

Specifically, a call to IDirectDraw7::StartModeTest directs DirectDraw to establish a set of testable resolutions and to display a mode based on the first resolution in the set. Subsequent calls to IDirectDraw7::EvaluateMode can be used to pass or fail each mode and to advance the test to the next display mode.

This method will only succeed with monitors that contain EDID data. If the monitor is not EDID-compliant, then the method will return DDERR_TESTFINISHED without testing any modes. If the EDID table does not contain values higher than 60 Hz, no modes will be tested. Refresh rates higher than 100 Hz will only be tested if the EDID table contains values higher than 85 Hz.

Calling the method with an argument list of (NULL, 0, 0) will clear existing refresh rate information from the registry.

The test will not guarantee to display only the resolutions in the array described by the lpModesToTest and dwNumEntries parameters. For example, the 640×480 resolution is used to obtain a maximum viewable refresh rate for the 320×200 resolution.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDraw7::EvaluateMode


IDirectDraw7::TestCooperativeLevel

The IDirectDraw7::TestCooperativeLevel method reports the current cooperative-level status of the DirectDraw device for a windowed or full-screen application.

HRESULT TestCooperativeLevel(void);

Parameters

None.

Return Values

If the method succeeds, the return value is DD_OK, indicating that the calling application can continue.

If it fails, the method can return one of the following error values (see Remarks):

DDERR_INVALIDOBJECT
DDERR_EXCLUSIVEMODEALREADYSET
DDERR_NOEXCLUSIVEMODE
DDERR_WRONGMODE

Remarks

This method is particularly useful to applications that use the WM_ACTIVATEAPP and WM_DISPLAYCHANGE system messages as a notification to restore surfaces or recreate DirectDraw objects. The DD_OK return value always indicates that the application can continue, but the error codes are interpreted differently, depending on the cooperative level that the application uses. For more information, see Testing Cooperative Levels.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.


IDirectDraw7::WaitForVerticalBlank

The IDirectDraw7::WaitForVerticalBlank method helps the application synchronize itself with the vertical-blank interval.

HRESULT WaitForVerticalBlank(
  DWORD dwFlags,
  HANDLE hEvent
);

Parameters

dwFlags
Determines how long to wait for the vertical blank. One of the following flags:
DDWAITVB_BLOCKBEGIN
Returns when the vertical-blank interval begins.
DDWAITVB_BLOCKBEGINEVENT
Triggers an event when the vertical blank begins. This value is not currently supported.
DDWAITVB_BLOCKEND
Returns when the vertical-blank interval ends and the display begins.
hEvent
Handle of the event to be triggered when the vertical blank begins. This parameter is not currently used.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_UNSUPPORTED
DDERR_WASSTILLDRAWING

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDraw7::GetVerticalBlankStatus, IDirectDraw7::GetScanLine


IDirectDrawClipper

Applications use the methods of the IDirectDrawClipper interface to manage clip lists. This section is a reference to the methods of this interface. For a conceptual overview, see Clippers.

The methods of the IDirectDrawClipper interface can be organized into the following groups:

Allocating memory | Initialize
Clip list | GetClipList
 | IsClipListChanged
 | SetClipList
 | SetHWnd
Handles | GetHWnd

The IDirectDrawClipper interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

You can use the LPDIRECTDRAWCLIPPER data type to declare a variable that contains a pointer to an IDirectDrawClipper interface. The Ddraw.h header file declares these data types with the following code:

typedef struct IDirectDrawClipper    FAR *LPDIRECTDRAWCLIPPER;

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.
Import Library: Use ddraw.lib.


IDirectDrawClipper::GetClipList

The IDirectDrawClipper::GetClipList method retrieves a copy of the clip list associated with a DirectDrawClipper object. A subset of the clip list can be selected by passing a rectangle that clips the clip list.

HRESULT GetClipList(
  LPRECT lpRect,
  LPRGNDATA lpClipList,
  LPDWORD lpdwSize
);

Parameters

lpRect
Address of a rectangle to be used to clip the clip list. This parameter can be NULL to retrieve the entire clip list.
lpClipList
Address of an RGNDATA structure to receive the resulting copy of the clip list. If this parameter is NULL, the method fills the variable at lpdwSize to the number of bytes necessary to hold the entire clip list.
lpdwSize
Address of a variable to receive the size of the resulting clip list. When retrieving the clip list, this parameter is the size of the buffer at lpClipList. When lpClipList is NULL, the variable at lpdwSize receives the required size of the buffer, in bytes.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_GENERIC
DDERR_INVALIDCLIPLIST
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOCLIPLIST
DDERR_REGIONTOOSMALL

Remarks

The RGNDATA structure used with this method has the following syntax:

typedef struct _RGNDATA {
    RGNDATAHEADER rdh;
    char          Buffer[1];
} RGNDATA;

The rdh member of the RGNDATA structure is an RGNDATAHEADER structure that has the following syntax:

typedef struct _RGNDATAHEADER {
    DWORD dwSize;
    DWORD iType;
    DWORD nCount;
    DWORD nRgnSize;
    RECT  rcBound;
} RGNDATAHEADER;

For more information about these structures, see the Platform SDK.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.
Import Library: Use ddraw.lib.

See Also

IDirectDrawClipper::SetClipList


IDirectDrawClipper::GetHWnd

The IDirectDrawClipper::GetHWnd method retrieves the window handle previously associated with this DirectDrawClipper object by the IDirectDrawClipper::SetHWnd method.

HRESULT GetHWnd(
  HWND FAR *lphWnd
);

Parameters

lphWnd
Address of the window handle previously associated with this DirectDrawClipper object by the IDirectDrawClipper::SetHWnd method.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.
Import Library: Use ddraw.lib.

See Also

IDirectDrawClipper::SetHWnd


IDirectDrawClipper::Initialize

The IDirectDrawClipper::Initialize method initializes a DirectDrawClipper object that was created by using the CoCreateInstance COM function.

HRESULT Initialize(
  LPDIRECTDRAW lpDD,
  DWORD dwFlags
);

Parameters

lpDD
Address of the DirectDraw structure that represents the DirectDraw object. If this parameter is set to NULL, an independent DirectDrawClipper object is created (the equivalent of using the DirectDrawCreateClipper function).
dwFlags
Currently not used and must be set to 0.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_ALREADYINITIALIZED
DDERR_INVALIDPARAMS

This method is provided for compliance with the Component Object Model (COM). If DirectDrawCreateClipper or the IDirectDraw7::CreateClipper method was used to create the DirectDrawClipper object, this method returns DDERR_ALREADYINITIALIZED.

Remarks

For more information about using IDirectDrawClipper::Initialize with CoCreateInstance, see Creating DirectDrawClipper Objects with CoCreateInstance.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.
Import Library: Use ddraw.lib.

See Also

IUnknown::AddRef, IUnknown::QueryInterface, IUnknown::Release, IDirectDraw7::CreateClipper


IDirectDrawClipper::IsClipListChanged

The IDirectDrawClipper::IsClipListChanged method monitors the status of the clip list if a window handle is associated with a DirectDrawClipper object.

HRESULT IsClipListChanged(
  BOOL FAR *lpbChanged
);

Parameters

lpbChanged
Address of a variable that is set to TRUE if the clip list has changed.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.
Import Library: Use ddraw.lib.


IDirectDrawClipper::SetClipList

The IDirectDrawClipper::SetClipList method sets or deletes the clip list used by the IDirectDrawSurface7::Blt, IDirectDrawSurface7::BltBatch, and IDirectDrawSurface7::UpdateOverlay methods on surfaces to which the parent DirectDrawClipper object is attached.

HRESULT SetClipList(
  LPRGNDATA lpClipList,
  DWORD dwFlags
);

Parameters

lpClipList
Address of a valid RGNDATA structure or NULL. If there is an existing clip list associated with the DirectDrawClipper object and this value is NULL, the clip list is deleted.
dwFlags
Currently not used and must be set to 0.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_CLIPPERISUSINGHWND
DDERR_INVALIDCLIPLIST
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY

Remarks

The clip list cannot be set if a window handle is already associated with the DirectDrawClipper object. The BltFast method cannot clip.

The RGNDATA structure used with this method has the following syntax:

typedef struct _RGNDATA {
    RGNDATAHEADER rdh;
    char          Buffer[1];
} RGNDATA;

The rdh member of the RGNDATA structure is an RGNDATAHEADER structure that has the following syntax:

typedef struct _RGNDATAHEADER {
    DWORD dwSize;
    DWORD iType;
    DWORD nCount;
    DWORD nRgnSize;
    RECT  rcBound;
} RGNDATAHEADER;

For more information about these structures, see the Platform SDK.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.
Import Library: Use ddraw.lib.

See Also

IDirectDrawClipper::GetClipList, IDirectDrawSurface7::Blt, IDirectDrawSurface7::BltFast, IDirectDrawSurface7::BltBatch, IDirectDrawSurface7::UpdateOverlay


IDirectDrawClipper::SetHWnd

The IDirectDrawClipper::SetHWnd method sets the window handle that the clipper object uses to obtain clipping information.

HRESULT SetHWnd(
  DWORD dwFlags,
  HWND hWnd
);

Parameters

dwFlags
Currently not used and must be set to 0.
hWnd
Window handle that obtains the clipping information.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDCLIPLIST
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.
Import Library: Use ddraw.lib.

See Also

IDirectDrawClipper::GetHWnd


IDirectDrawColorControl

The IDirectDrawColorControl interface allows you to get and set color controls. It has the following methods:

Color controls | GetColorControls
 | SetColorControls

The IDirectDrawColorControl interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

You can use the LPDIRECTDRAWCOLORCONTROL data type to declare a variable that contains a pointer to an IDirectDrawColorControl interface. The Ddraw.h header file declares these data types with the following code:

typedef struct IDirectDrawColorControl    FAR *LPDIRECTDRAWCOLORCONTROL;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.
Import Library: Use ddraw.lib.


IDirectDrawColorControl::GetColorControls

The IDirectDrawColorControl::GetColorControls method returns the current color-control settings associated with the specified overlay or primary surface. The dwFlags member of the DDCOLORCONTROL structure indicates which of the color-control options are supported.

HRESULT GetColorControls(
  LPDDCOLORCONTROL lpColorControl
);

Parameters

lpColorControl
Address of the DDCOLORCONTROL structure to receive the current control settings of the specified surface.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_UNSUPPORTED

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.
Import Library: Use ddraw.lib.

See Also

IDirectDrawColorControl::SetColorControls, Using Color Controls, Gamma and Color Controls


IDirectDrawColorControl::SetColorControls

The IDirectDrawColorControl::SetColorControls method sets the color-control settings associated with the specified overlay or primary surface.

HRESULT SetColorControls(
  LPDDCOLORCONTROL lpColorControl
);

Parameters

lpColorControl
Address of the DDCOLORCONTROL structure that contains the new values to be applied to the specified surface.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_UNSUPPORTED

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.
Import Library: Use ddraw.lib.

See Also

IDirectDrawColorControl::GetColorControls, Using Color Controls, Gamma and Color Controls


IDirectDrawGammaControl

Applications use the methods of the IDirectDrawGammaControl interface to adjust the red, green, and blue gamma ramp levels of the primary surface. This section is a reference to the methods of this interface. This interface is supported by DirectDrawSurface objects; you can retrieve a pointer to this interface by calling the IUnknown::QueryInterface method of a DirectDrawSurface object, specifying the IID_IDirectDrawGammaControl reference identifier.

For a conceptual overview, see Gamma and Color Controls.

The interface has the following methods:

Gamma ramps | GetGammaRamp
 | SetGammaRamp

The IDirectDrawGammaControl interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

You can use the LPDIRECTDRAWGAMMACONTROL data type to declare a variable that contains a pointer to an IDirectDrawGammaControl interface. The Ddraw.h header file declares the data type with the following code:

typedef struct IDirectDrawGammaControl    FAR *LPDIRECTDRAWGAMMACONTROL;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.
Import Library: Use ddraw.lib.


IDirectDrawGammaControl::GetGammaRamp

The IDirectDrawGammaControl::GetGammaRamp method retrieves the red, green, and blue gamma ramps for the primary surface.

HRESULT GetGammaRamp(
  DWORD  dwFlags,
  LPGAMMARAMP lpRampData
);

Parameters

dwFlags
Not currently used; set to 0.
lpRampData
Address of a DDGAMMARAMP structure to be filled with the current red, green, and blue gamma ramps. Each array maps color values in the frame buffer to the color values to be passed to the digital-to-analog converter (DAC).

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_EXCEPTION
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.
Import Library: Use ddraw.lib.

See Also

IDirectDrawGammaControl::SetGammaRamp, Gamma and Color Controls


IDirectDrawGammaControl::SetGammaRamp

The IDirectDrawGammaControl::SetGammaRamp method retrieves the red, green, and blue gamma ramps for the primary surface.

HRESULT SetGammaRamp(
  DWORD  dwFlags,
  LPGAMMARAMP lpRampData
);

Parameters

dwFlags
Flag indicating whether gamma calibration is desired. Set this parameter to DDSGR_CALIBRATE to request that the calibrator adjust the gamma ramp according to the physical properties of the display, making the result identical on all systems. If calibration is not needed, set this parameter to 0.
lpRampData
Address of a DDGAMMARAMP structure that contains the new red, green, and blue gamma ramp entries. Each array maps color values in the frame buffer to the color values to be passed to the digital-to-analog converter (DAC).

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_EXCEPTION
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY

Remarks

Not all systems support gamma calibration. To determine whether gamma calibration is supported, call IDirectDraw7::GetCaps, and examine the dwCaps2 member of the associated DDCAPS structure after the method returns. If the DDCAPS2_CANCALIBRATEGAMMA capability flag is present, gamma calibration is supported.

Calibrating gamma ramps incurs some processing overhead and should not be used frequently.

Including the DDSGR_CALIBRATE flag in the dwFlags parameter when running on systems that do not support gamma calibration does not cause this method to fail. The method succeeds, setting new gamma ramp values without calibration.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.
Import Library: Use ddraw.lib.

See Also

IDirectDrawGammaControl::GetGammaRamp, Gamma and Color Controls


IDirectDrawPalette

Applications use the methods of the IDirectDrawPalette interface to create DirectDrawPalette objects and work with system-level variables. This section is a reference to the methods of this interface. For a conceptual overview, see Palettes.

The methods of the IDirectDrawPalette interface can be organized into the following groups:

Allocating memory | Initialize
Palette capabilities | GetCaps
Palette entries | GetEntries
 | SetEntries

The IDirectDrawPalette interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

You can use the LPDIRECTDRAWPALETTE data type to declare a variable that contains a pointer to an IDirectDrawPalette interface. The Ddraw.h header file declares the data type with the following code:

typedef struct IDirectDrawPalette    FAR *LPDIRECTDRAWPALETTE;

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.
Import Library: Use ddraw.lib.


IDirectDrawPalette::GetCaps

The IDirectDrawPalette::GetCaps method retrieves the capabilities of this palette object.

HRESULT GetCaps(
  LPDWORD lpdwCaps
);

Parameters

lpdwCaps
One of the following flags from the dwPalCaps member of the DDCAPS structure that defines palette capabilities:
DDPCAPS_1BIT
DDPCAPS_2BIT
DDPCAPS_4BIT
DDPCAPS_8BIT
DDPCAPS_8BITENTRIES
DDPCAPS_ALPHA
DDPCAPS_ALLOW256
DDPCAPS_PRIMARYSURFACE
DDPCAPS_PRIMARYSURFACELEFT
DDPCAPS_VSYNC

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.
Import Library: Use ddraw.lib.


IDirectDrawPalette::GetEntries

The IDirectDrawPalette::GetEntries method queries palette values from a DirectDrawPalette object.

HRESULT GetEntries(
  DWORD dwFlags,
  DWORD dwBase,
  DWORD dwNumEntries,
  LPPALETTEENTRY lpEntries
);

Parameters

dwFlags
Currently not used and must be set to 0.
dwBase
Start of the entries to be retrieved sequentially.
dwNumEntries
Number of palette entries that can fit in the address specified in lpEntries. The colors of the palette entry are returned in sequence, from the value of the dwStartingEntry parameter through the value of the dwCount parameter minus 1. (These parameters are set by IDirectDrawPalette::SetEntries.)
lpEntries
Address of the palette entries. The palette entries are 1 byte each if the DDPCAPS_8BITENTRIES flag is set, and 4 bytes otherwise. Each field is a color description.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOTPALETTIZED

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.
Import Library: Use ddraw.lib.

See Also

IDirectDrawPalette::SetEntries


IDirectDrawPalette::Initialize

The IDirectDrawPalette::Initialize method initializes the DirectDrawPalette object.

HRESULT Initialize(
  LPDIRECTDRAW lpDD,
  DWORD dwFlags,
  LPPALETTEENTRY lpDDColorTable
);

Parameters

lpDD
Address of the DirectDraw structure that represents the DirectDraw object.
dwFlags and lpDDColorTable
Currently not used and must be set to 0.

Return Values

This method returns DDERR_ALREADYINITIALIZED.

This method is provided for compliance with the Component Object Model (COM). Because the DirectDrawPalette object is initialized when it is created, this method always returns DDERR_ALREADYINITIALIZED.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.
Import Library: Use ddraw.lib.

See Also

IUnknown::AddRef, IUnknown::QueryInterface, IUnknown::Release


IDirectDrawPalette::SetEntries

The IDirectDrawPalette::SetEntries method changes entries in a DirectDrawPalette object immediately.

HRESULT SetEntries(
  DWORD dwFlags,
  DWORD dwStartingEntry,
  DWORD dwCount,
  LPPALETTEENTRY lpEntries
);

Parameters

dwFlags
Currently not used and must be set to 0.
dwStartingEntry
First entry to be set.
dwCount
Number of palette entries to be changed.
lpEntries
Address of the palette entries. The palette entries are 1 byte each if the DDPCAPS_8BITENTRIES flag is set, and 4 bytes otherwise. Each field is a color description.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOPALETTEATTACHED
DDERR_NOTPALETTIZED
DDERR_UNSUPPORTED

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.
Import Library: Use ddraw.lib.

See Also

IDirectDrawPalette::GetEntries, IDirectDrawSurface7::SetPalette


IDirectDrawSurface7

Applications use the methods of the IDirectDrawSurface7 interface to create DirectDrawSurface objects and work with system-level variables. This section is a reference to the methods of this interface. For a conceptual overview, see Surfaces.

The methods of the IDirectDrawSurface7 interface can be organized into the following groups:

Allocating memory | Initialize
 | IsLost
 | Restore
Attaching surfaces | AddAttachedSurface
 | DeleteAttachedSurface
 | EnumAttachedSurfaces
 | GetAttachedSurface
Blitting | Blt
 | BltBatch
 | BltFast
 | GetBltStatus
Color keying | GetColorKey
 | SetColorKey
Device contexts | GetDC
 | ReleaseDC
Flipping | Flip
 | GetFlipStatus
Locking surfaces | Lock
 | PageLock
 | PageUnlock
 | Unlock
Miscellaneous | GetDDInterface
Overlays | AddOverlayDirtyRect
 | EnumOverlayZOrders
 | GetOverlayPosition
 | SetOverlayPosition
 | UpdateOverlay
 | UpdateOverlayDisplay
 | UpdateOverlayZOrder
Private surface data | FreePrivateData
 | GetPrivateData
 | SetPrivateData
Surface capabilities | GetCaps
Surface clipper | GetClipper
 | SetClipper
Surface characteristics | ChangeUniquenessValue
 | GetPixelFormat
 | GetSurfaceDesc
 | GetUniquenessValue
 | SetSurfaceDesc
Surface palettes | GetPalette
 | SetPalette
Textures | GetLOD
 | GetPriority
 | SetLOD
 | SetPriority

The IDirectDrawSurface7 interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The IDirectDrawSurface7 interface extends the features of previous versions of the interface by offering methods that offer better surface management and ease of use. Many methods in this interface accept slightly different parameters than their counterparts in former versions of the interface. Wherever an IDirectDrawSurface3 interface method might accept a DDSURFACEDESC structure or an IDirectDrawSurface3 interface, the methods in IDirectDrawSurface7 accept a DDSURFACEDESC2 structure or an IDirectDrawSurface7 interface, instead.

You can use the LPDIRECTDRAWSURFACE, LPDIRECTDRAWSURFACE2, LPDIRECTDRAWSURFACE3, LPDIRECTDRAWSURFACE4, or LPDIRECTDRAWSURFACE7 data types to declare variables that point to various DirectDrawSurface object interfaces. The Ddraw.h header file declares these data types with the following code:

typedef struct IDirectDrawSurface     FAR *LPDIRECTDRAWSURFACE;
typedef struct IDirectDrawSurface2    FAR *LPDIRECTDRAWSURFACE2;
typedef struct IDirectDrawSurface3    FAR *LPDIRECTDRAWSURFACE3;
typedef struct IDirectDrawSurface4    FAR *LPDIRECTDRAWSURFACE4;
typedef struct IDirectDrawSurface7    FAR *LPDIRECTDRAWSURFACE7;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.


IDirectDrawSurface7::AddAttachedSurface

The IDirectDrawSurface7::AddAttachedSurface method attaches the specified z-buffer surface to this surface.

HRESULT AddAttachedSurface(
  LPDIRECTDRAWSURFACE7 lpDDSAttachedSurface
);

Parameters

lpDDSAttachedSurface
Address of an IDirectDrawSurface7 interface that the surface is to be attached to.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_CANNOTATTACHSURFACE
DDERR_GENERIC
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_SURFACEALREADYATTACHED
DDERR_SURFACELOST
DDERR_WASSTILLDRAWING

Remarks

This method increments the reference count of the surface being attached. You can explicitly unattach the surface and decrement its reference count by using the IDirectDrawSurface7::DeleteAttachedSurface method. Unlike complex surfaces that you create with a single call to IDirectDraw7::CreateSurface, surfaces attached with this method are not automatically released. It is the application's responsibility to release such surfaces.

You can attach only z-buffer surfaces with this method.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDrawSurface7::DeleteAttachedSurface, IDirectDrawSurface7::EnumAttachedSurfaces


IDirectDrawSurface7::AddOverlayDirtyRect

The IDirectDrawSurface7::AddOverlayDirtyRect method is not currently implemented.

HRESULT AddOverlayDirtyRect(
  LPRECT lpRect
);

Parameters

lpRect
Address of the RECT structure that needs to be updated.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDSURFACETYPE
DDERR_UNSUPPORTED

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDrawSurface7::UpdateOverlayDisplay


IDirectDrawSurface7::Blt

The IDirectDrawSurface7::Blt method performs a bit block transfer (blit). This method does not support z-buffering or alpha blending (see alpha channel) during blit operations.

HRESULT Blt(
  LPRECT lpDestRect,
  LPDIRECTDRAWSURFACE7 lpDDSrcSurface,
  LPRECT lpSrcRect,
  DWORD dwFlags,
  LPDDBLTFX lpDDBltFx
);

Parameters

lpDestRect
Address of a RECT structure that defines the upper-left and lower-right points of the rectangle to blit to on the destination surface. If this parameter is NULL, the entire destination surface is used.
lpDDSrcSurface
Address of an IDirectDrawSurface7 interface for the DirectDrawSurface object that is the source of the blit.
lpSrcRect
Address of a RECT structure that defines the upper-left and lower-right points of the rectangle to blit from on the source surface. If this parameter is NULL, the entire source surface is used.
dwFlags
A combination of flags that determine the valid members of the associated DDBLTFX structure, specify color-key information, or request special behavior from the method. The following flags are defined:
Validation flags
DDBLT_COLORFILL
Uses the dwFillColor member of the DDBLTFX structure as the RGB color that fills the destination rectangle on the destination surface.
DDBLT_DDFX
Uses the dwDDFX member of the DDBLTFX structure to specify the effects to use for this blit.
DDBLT_DDROPS
Uses the dwDDROP member of the DDBLTFX structure to specify the raster operations (ROPS) that are not part of the Microsoft® Win32® API.
DDBLT_DEPTHFILL
Uses the dwFillDepth member of the DDBLTFX structure as the depth value with which to fill the destination rectangle on the destination z-buffer surface.
DDBLT_KEYDESTOVERRIDE
Uses the ddckDestColorkey member of the DDBLTFX structure as the color key for the destination surface.
DDBLT_KEYSRCOVERRIDE
Uses the ddckSrcColorkey member of the DDBLTFX structure as the color key for the source surface.
DDBLT_ROP
Uses the dwROP member of the DDBLTFX structure for the ROP for this blit. These ROPs are the same as those defined in the Win32 API.
DDBLT_ROTATIONANGLE
Uses the dwRotationAngle member of the DDBLTFX structure as the rotation angle (specified in 1/100s of a degree) for the surface.
Color key flags
DDBLT_KEYDEST
Uses the color key associated with the destination surface.
DDBLT_KEYSRC
Uses the color key associated with the source surface.
Behavior flags
DDBLT_ASYNC
Performs this blit asynchronously through the first in, first out (FIFO) hardware in the order received. If no room is available in the FIFO hardware, the call fails.
DDBLT_DONOTWAIT
New for DirectX 7.0. Returns without blitting and also returns DDERR_WASSTILLDRAWING if the blitter is busy.
DDBLT_WAIT
Postpones the DDERR_WASSTILLDRAWING return value if the blitter is busy, and returns as soon as the blit can be set up or another error occurs.
Obsolete and unsupported flags
All DDBLT_ALPHA flag values.
Not currently implemented.
All DDBLT_ZBUFFER flag values
This method does not currently support z-aware blit operations. None of the flags beginning with "DDBLT_ZBUFFER" are supported in this release of DirectX.
lpDDBltFx
Address of the DDBLTFX structure.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_GENERIC
DDERR_INVALIDCLIPLIST
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDRECT
DDERR_NOALPHAHW
DDERR_NOBLTHW
DDERR_NOCLIPLIST
DDERR_NODDROPSHW
DDERR_NOMIRRORHW
DDERR_NORASTEROPHW
DDERR_NOROTATIONHW
DDERR_NOSTRETCHHW
DDERR_NOZBUFFERHW
DDERR_SURFACEBUSY
DDERR_SURFACELOST
DDERR_UNSUPPORTED
DDERR_WASSTILLDRAWING

Remarks

This method is capable of synchronous or asynchronous blits (the latter is the default behavior), either display memory to display memory, display memory to system memory, system memory to display memory, or system memory to system memory. The blits can be performed by using source color keys and destination color keys. Arbitrary stretching or shrinking is performed if the source and destination rectangles are not the same size.

Typically, IDirectDrawSurface7::Blt returns immediately with an error if the blitter is busy and the blit could not be set up. Specify the DDBLT_WAIT flag to request a synchronous blit. When you include the DDBLT_WAIT flag, the method waits until the blit can be set up or another error occurs before it returns.

RECT structures are defined so that the right and bottom members are exclusive—therefore, right minus left equals the width of the rectangle, not 1 less than the width.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.


IDirectDrawSurface7::BltBatch

The IDirectDrawSurface7::BltBatch method is not currently implemented.

HRESULT BltBatch(
  LPDDBLTBATCH lpDDBltBatch,
  DWORD dwCount,
  DWORD dwFlags
);

Parameters

lpDDBltBatch
Address of the first DDBLTBATCH structure that defines the parameters for the blit operations.
dwCount
Number of blit operations to be performed.
dwFlags
Currently not used and must be set to 0.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_GENERIC
DDERR_INVALIDCLIPLIST
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDRECT
DDERR_NOALPHAHW
DDERR_NOBLTHW
DDERR_NOCLIPLIST
DDERR_NODDROPSHW
DDERR_NOMIRRORHW
DDERR_NORASTEROPHW
DDERR_NOROTATIONHW
DDERR_NOSTRETCHHW
DDERR_NOZBUFFERHW
DDERR_SURFACEBUSY
DDERR_SURFACELOST
DDERR_UNSUPPORTED

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.


IDirectDrawSurface7::BltFast

The IDirectDrawSurface7::BltFast method performs a source copy blit or transparent blit by using a source color key or destination color key.

HRESULT BltFast(
  DWORD dwX,
  DWORD dwY,
  LPDIRECTDRAWSURFACE7 lpDDSrcSurface,
  LPRECT lpSrcRect,
  DWORD dwTrans
);

Parameters

dwX and dwY
The x- and y-coordinates to blit to on the destination surface.
lpDDSrcSurface
Address of an IDirectDrawSurface7 interface for the DirectDrawSurface object that is the source of the blit.
lpSrcRect
Address of a RECT structure that defines the upper-left and lower-right corners of the rectangle to blit from on the source surface.
dwTrans
Type of transfer. The following transfers are defined:
DDBLTFAST_DESTCOLORKEY
A transparent blit that uses the destination color key.
DDBLTFAST_NOCOLORKEY
A normal copy blit with no transparency.
DDBLTFAST_SRCCOLORKEY
A transparent blit that uses the source color key.
DDBLTFAST_WAIT
Postpones the DDERR_WASSTILLDRAWING message if the blitter is busy, and returns as soon as the blit can be set up or another error occurs.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_EXCEPTION
DDERR_GENERIC
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDRECT
DDERR_NOBLTHW
DDERR_SURFACEBUSY
DDERR_SURFACELOST
DDERR_UNSUPPORTED
DDERR_WASSTILLDRAWING

Remarks

This method always attempts an asynchronous blit if it is supported by the hardware.

This method works only on display memory surfaces and cannot clip when blitting. If you use this method on a surface with an attached clipper, the call fails, and the method returns DDERR_UNSUPPORTED.

The software implementation of IDirectDrawSurface7::BltFast is 10 percent faster than the IDirectDrawSurface7::Blt method. However, there is no speed difference between the two if display hardware is used.

Typically, IDirectDrawSurface7::BltFast returns immediately with an error if the blitter is busy and the blit cannot be set up. You can use the DDBLTFAST_WAIT flag, however, if you want this method not to return until either the blit can be set up or another error occurs.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.


IDirectDrawSurface7::ChangeUniquenessValue

The IDirectDrawSurface7::ChangeUniquenessValue method manually updates the uniqueness value for this surface.

HRESULT ChangeUniquenessValue();

Parameters

None.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_EXCEPTION
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

DirectDraw automatically updates uniqueness values whenever the contents of a surface change.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDrawSurface7::GetUniquenessValue, Surface Uniqueness Values


IDirectDrawSurface7::DeleteAttachedSurface

The IDirectDrawSurface7::DeleteAttachedSurface method detaches two attached surfaces.

HRESULT DeleteAttachedSurface(
  DWORD dwFlags,
  LPDIRECTDRAWSURFACE7 lpDDSAttachedSurface
);

Parameters

dwFlags
Currently not used and must be set to 0.
lpDDSAttachedSurface
Address of the IDirectDrawSurface7 interface for the DirectDrawSurface object to be detached. If this parameter is NULL, all attached surfaces are detached.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_CANNOTDETACHSURFACE
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_SURFACELOST
DDERR_SURFACENOTATTACHED

Remarks

This method decrements the reference count of the surface to be detached. If the reference count of the surface to be detached reaches 0, it is lost and removed from memory.

Implicit attachments, those formed by DirectDraw rather than the IDirectDrawSurface7::AddAttachedSurface method, cannot be detached. Detaching surfaces from a flipping chain can alter other surfaces in the chain. If a front buffer is detached from a flipping chain, the next surface in the chain becomes the front buffer, and the following surface becomes the back buffer. If a back buffer is detached from a chain, the following surface becomes a back buffer. If a plain surface is detached from a chain, the chain simply becomes shorter. If a flipping chain has only two surfaces and they are detached, the chain is destroyed, and both surfaces return to their previous designations.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDrawSurface7::Flip


IDirectDrawSurface7::EnumAttachedSurfaces

The IDirectDrawSurface7::EnumAttachedSurfaces method enumerates all the surfaces attached to a given surface.

HRESULT EnumAttachedSurfaces(
  LPVOID lpContext,
  LPDDENUMSURFACESCALLBACK2 lpEnumSurfacesCallback
);

Parameters

lpContext
Address of the application-defined structure that is passed to the enumeration member every time that it is called.
lpEnumSurfacesCallback
Address of the EnumSurfacesCallback2 function to be called for each surface that is attached to this surface.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_SURFACELOST

Remarks

This method enumerates only those surfaces that are directly attached to this surface. For example, in a flipping chain of three or more surfaces, only one surface is enumerated because each surface is attached only to the next surface in the flipping chain. In such a configuration, you can call EnumAttachedSurfaces on each successive surface to walk the entire flipping chain.

This method differs from its counterparts in previous interface versions in that it accepts a pointer to an EnumSurfacesCallback2 function, rather than an EnumSurfacesCallback function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.


IDirectDrawSurface7::EnumOverlayZOrders

The IDirectDrawSurface7::EnumOverlayZOrders method enumerates the overlay surfaces on the specified destination. The overlays can be enumerated in front-to-back or back-to-front order.

HRESULT EnumOverlayZOrders(
  DWORD dwFlags,
  LPVOID lpContext,
  LPDDENUMSURFACESCALLBACK2 lpfnCallback
);

Parameters

dwFlags
One of the following flags:
DDENUMOVERLAYZ_BACKTOFRONT
Enumerates overlays back to front.
DDENUMOVERLAYZ_FRONTTOBACK
Enumerates overlays front to back.
lpContext
Address of the user-defined context to be passed to the callback function for each overlay surface.
lpfnCallback
Address of the EnumSurfacesCallback2 callback function to be called for each surface to be overlaid on this surface.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

This method differs from its counterparts in previous interface versions in that it accepts a pointer to an EnumSurfacesCallback2 function, rather than an EnumSurfacesCallback function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.


IDirectDrawSurface7::Flip

The IDirectDrawSurface7::Flip method makes the surface memory associated with the DDSCAPS_BACKBUFFER surface become associated with the front-buffer surface.

HRESULT Flip(
  LPDIRECTDRAWSURFACE7 lpDDSurfaceTargetOverride,
  DWORD dwFlags
);

Parameters

lpDDSurfaceTargetOverride
Address of the IDirectDrawSurface7 interface for an arbitrary surface in the flipping chain. The default for this parameter is NULL, in which case DirectDraw cycles through the buffers in the order that they are attached to each other. If this parameter is not NULL, DirectDraw flips to the specified surface, instead of the next surface in the flipping chain. The method fails if the specified surface is not a member of the flipping chain.
dwFlags
Flags specifying flip options.
DDFLIP_DONOTWAIT
On IDirectDrawSurface7 interfaces, the default is DDFLIP_WAIT. If you want to override the default and use time when the accelerator is busy (as denoted by the DDERR_WASSTILLDRAWING return value), use DDFLIP_DONOTWAIT.
DDFLIP_EVEN
For use only when displaying video in an overlay surface. The new surface contains data from the even field of a video signal. This flag cannot be used with the DDFLIP_ODD flag.
DDFLIP_STEREO
DirectDraw flips and displays a main stereo surface. When this flag is set, stereo autoflipping is enabled. The hardware automatically flips between the left and right buffers during each screen refresh.
DDFLIP_INTERVAL2
DDFLIP_INTERVAL3
DDFLIP_INTERVAL4
These flags indicate how many vertical retraces to wait between each flip. The default is 1. DirectDraw returns DERR_WASSTILLDRAWING for each surface involved in the flip until the specified number of vertical retraces has occurred. If DDFLIP_INTERVAL2 is set, DirectDraw flips on every second vertical sync; if DDFLIP_INTERVAL3, on every third sync; and if DDFLIP_INTERVAL4, on every fourth sync.

These flags are effective only if DDCAPS2_FLIPINTERVAL is set in the DDCAPS structure returned for the device.

DDFLIP_NOVSYNC
Causes DirectDraw to perform the physical flip as close as possible to the next scan line. Subsequent operations involving the two flipped surfaces do not check whether the physical flip has finished—that is, they do not return DDERR_WASSTILLDRAWING for that reason (but might for other reasons). This allows an application to perform flips at a higher frequency than the monitor refresh rate, but might introduce visible artifacts.

If DDCAPS2_FLIPNOVSYNC is not set in the DDCAPS structure returned for the device, DDFLIP_NOVSYNC has no effect.

DDFLIP_ODD
For use only when displaying video in an overlay surface. The new surface contains data from the odd field of a video signal. This flag cannot be used with the DDFLIP_EVEN flag.
DDFLIP_WAIT
Typically, if the flip cannot be set up because the state of the display hardware is not appropriate, the DDERR_WASSTILLDRAWING error returns immediately, and no flip occurs. Setting this flag causes the method to continue trying to flip if it receives the DDERR_WASSTILLDRAWING error from the hardware abstraction layer (HAL). The method does not return until the flipping operation has been successfully set up or another error, such as DDERR_SURFACEBUSY, is returned.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_GENERIC
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOFLIPHW
DDERR_NOTFLIPPABLE
DDERR_SURFACEBUSY
DDERR_SURFACELOST
DDERR_UNSUPPORTED
DDERR_WASSTILLDRAWING

Remarks

With IDirectDrawSurface7, the default behavior of this method is to wait for the accelator to finish. Therefore, under default conditions, this method never returns DDERR_WASSTILLDRAWING. If you want to see the error codes and not wait until the flip operation succeeds, use the DDFLIP_DONOTWAIT flag.

This method can be called only for a surface that has the DDSCAPS_FLIP and DDSCAPS_FRONTBUFFER capabilities. The display memory previously associated with the front buffer is associated with the back buffer.

The lpDDSurfaceTargetOverride parameter is used in rare cases in which the back buffer is not the buffer that should become the front buffer. Typically, this parameter is NULL.

The IDirectDrawSurface7::Flip method is always synchronized with the vertical blank. If the surface has been assigned to a video port, this method updates the visible overlay surface and the target surface of the video port.

For more information, see Flipping Surfaces.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDrawSurface7::GetFlipStatus


IDirectDrawSurface7::FreePrivateData

The IDirectDrawSurface7::FreePrivateData method frees the specified private data associated with this surface.

HRESULT FreePrivateData(
  REFGUID guidTag
);

Parameters

guidTag
Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to be freed.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOTFOUND

Remarks

DirectDraw calls this method automatically when a surface is released.

If the private data was set by using the DDSPD_IUNKNOWNPOINTER flag, this method calls the IUnknown::Release method on the associated interface.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDrawSurface7::GetPrivateData, IDirectDrawSurface7::SetPrivateData


IDirectDrawSurface7::GetAttachedSurface

The IDirectDrawSurface7::GetAttachedSurface method obtains the attached surface that has the specified capabilities and increments the reference count of the retrieved interface.

HRESULT GetAttachedSurface(
  LPDDSCAPS2 lpDDSCaps,
  LPDIRECTDRAWSURFACE7 FAR *lplpDDAttachedSurface
);

Parameters

lpDDSCaps
Address of a DDSCAPS2 structure that contains the hardware capabilities of the surface.
lplpDDAttachedSurface
Address of a variable to receive a pointer to the retrieved surface's IDirectDrawSurface7 interface. The retrieved surface is the one that matches the description, according to the lpDDSCaps parameter.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOTFOUND
DDERR_SURFACELOST

Remarks

Attachments are used to connect multiple DirectDrawSurface objects into complex structures, like the ones needed to support 3-D page flipping with z-buffers. This method fails if more than one surface is attached that matches the capabilities requested. In this case, the application must use the IDirectDrawSurface7::EnumAttachedSurfaces method to obtain the attached surfaces.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.


IDirectDrawSurface7::GetBltStatus

The IDirectDrawSurface7::GetBltStatus method obtains the blitter status.

HRESULT GetBltStatus(
  DWORD dwFlags
);

Parameters

dwFlags
One of the following flags:
DDGBS_CANBLT
Inquires whether a blit involving this surface can occur immediately, and returns DD_OK if the blit can be completed.
DDGBS_ISBLTDONE
Inquires whether the blit is done, and returns DD_OK if the last blit on this surface has completed.

Return Values

If the method succeeds, a blitter is present, and the return value is DD_OK.

If it fails, the method returns DDERR_WASSTILLDRAWING if the blitter is busy, DDERR_NOBLTHW if there is no blitter, or one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOBLTHW
DDERR_SURFACEBUSY
DDERR_SURFACELOST
DDERR_UNSUPPORTED
DDERR_WASSTILLDRAWING

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.


IDirectDrawSurface7::GetCaps

The IDirectDrawSurface7::GetCaps method retrieves the capabilities of the surface. These capabilities are not necessarily related to the capabilities of the display device.

HRESULT GetCaps(
  LPDDSCAPS2 lpDDSCaps
);

Parameters

lpDDSCaps
Address of a DDSCAPS2 structure to be filled with the hardware capabilities of the surface.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

This method differs from its counterpart in the IDirectDrawSurface3 interface in that it accepts a pointer to a DDSCAPS2 structure, rather than the legacy DDSCAPS structure.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.


IDirectDrawSurface7::GetClipper

The IDirectDrawSurface7::GetClipper method retrieves the DirectDrawClipper object associated with this surface and increments the reference count of the returned clipper.

HRESULT GetClipper(
  LPDIRECTDRAWCLIPPER FAR *lplpDDClipper
);

Parameters

lplpDDClipper
Address of a pointer to the DirectDrawClipper object associated with the surface.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOCLIPPERATTACHED

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDrawSurface7::SetClipper


IDirectDrawSurface7::GetColorKey

The IDirectDrawSurface7::GetColorKey method retrieves the color key value for the DirectDrawSurface object.

HRESULT GetColorKey(
  DWORD dwFlags,
  LPDDCOLORKEY lpDDColorKey
);

Parameters

dwFlags
One of the following flags determines which color key is requested:
DDCKEY_DESTBLT
A color key or color space to be used as a destination color key for blit operations.
DDCKEY_DESTOVERLAY
A color key or color space to be used as a destination color key for overlay operations.
DDCKEY_SRCBLT
A color key or color space to be used as a source color key for blit operations.
DDCKEY_SRCOVERLAY
A color key or color space to be used as a source color key for overlay operations.
lpDDColorKey
Address of the DDCOLORKEY structure to be filled with the current values for the specified color key of the DirectDrawSurface object.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOCOLORKEY
DDERR_NOCOLORKEYHW
DDERR_SURFACELOST
DDERR_UNSUPPORTED

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDrawSurface7::SetColorKey


IDirectDrawSurface7::GetDC

The IDirectDrawSurface7::GetDC method creates a GDI-compatible handle of a device context for the surface.

HRESULT GetDC(
  HDC FAR *lphDC
);

Parameters

lphDC
Address for the returned handle of a device context.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_DCALREADYCREATED
DDERR_GENERIC
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDSURFACETYPE
DDERR_SURFACELOST
DDERR_UNSUPPORTED
DDERR_WASSTILLDRAWING

Remarks

This method uses an internal version of the IDirectDrawSurface7::Lock method to lock the surface. The surface remains locked until the IDirectDrawSurface7::ReleaseDC method is called.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDrawSurface7::Lock


IDirectDrawSurface7::GetDDInterface

The IDirectDrawSurface7::GetDDInterface method retrieves an interface to the DirectDraw object that was used to create the surface.

HRESULT GetDDInterface(
  LPVOID FAR *lplpDD
);

Parameters

lplpDD
Address of a variable to be filled with a valid interface pointer if the call succeeds. Cast this pointer to an IUnknown interface pointer; then query for the desired DirectDraw interface.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

This method was not implemented in the IDirectDraw interface.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.


IDirectDrawSurface7::GetFlipStatus

The IDirectDrawSurface7::GetFlipStatus method indicates whether the surface has finished its flipping process.

HRESULT GetFlipStatus(
  DWORD dwFlags
);

Parameters

dwFlags
One of the following flags:
DDGFS_CANFLIP
Inquires whether this surface can be flipped immediately, and returns DD_OK if the flip can be completed.
DDGFS_ISFLIPDONE
Inquires whether the flip has finished, and returns DD_OK if the last flip on this surface has completed.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return DDERR_WASSTILLDRAWING if the surface has not finished its flipping process, or one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDSURFACETYPE
DDERR_SURFACEBUSY
DDERR_SURFACELOST
DDERR_UNSUPPORTED

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDrawSurface7::Flip


IDirectDrawSurface7::GetLOD

The IDirectDrawSurface7::GetLOD method retrieves the maximum level of detail currently set for a managed mipmap surface. This method succeeds only on managed textures (see Remarks).

HRESULT GetLOD(
    LPDWORD lpdwMaxLOD
);

Parameters

lpdwMaxLOD
Address of a variable to contain the maximum level-of-detail value if the call succeeds.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

Applications can call this method only for managed textures (those that were created with the DDSCAPS2_TEXTUREMANAGE flag). Calling this method on a nonmanaged texture causes the method to fail and return DDERR_INVALIDOBJECT.

This method communicates to the Direct3D texture manager the most detailed mipmap in this chain that it should load into local video memory. For example, in a five-level mipmap chain, a value of 2 in the variable at lpdwMaxLOD indicates that the texture manager loads only mipmap levels 2 through 4 into local video memory at any given time. Likewise, if the most detailed mipmap in the chain has the dimensions 256×256, a value of 2 in lpdwMaxLOD means that the largest mipmap ever present in video memory has dimensions 64×64.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDrawSurface7::SetLOD, Texture Filtering With Mipmaps, Automatic Texture Management, Textures


IDirectDrawSurface7::GetOverlayPosition

Given a visible, active overlay surface (DDSCAPS_OVERLAY flag set), the IDirectDrawSurface7::GetOverlayPosition method returns the display coordinates of the surface.

HRESULT GetOverlayPosition(
  LPLONG lplX,
  LPLONG lplY
);

Parameters

lplX and lplY
Addresses of the x- and y-display coordinates.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_GENERIC
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDPOSITION
DDERR_NOOVERLAYDEST
DDERR_NOTAOVERLAYSURFACE
DDERR_OVERLAYNOTVISIBLE
DDERR_SURFACELOST

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDrawSurface7::SetOverlayPosition, IDirectDrawSurface7::UpdateOverlay


IDirectDrawSurface7::GetPalette

The IDirectDrawSurface7::GetPalette method retrieves the DirectDrawPalette object associated with this surface and increments the reference count of the returned palette.

HRESULT GetPalette(
  LPDIRECTDRAWPALETTE FAR *lplpDDPalette
);

Parameters

lplpDDPalette
Address of a variable to be filled with a pointer to the palette object's IDirectDrawPalette interface.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_GENERIC
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOEXCLUSIVEMODE
DDERR_NOPALETTEATTACHED
DDERR_SURFACELOST
DDERR_UNSUPPORTED

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDrawSurface7::SetPalette


IDirectDrawSurface7::GetPixelFormat

The IDirectDrawSurface7::GetPixelFormat method retrieves the color and pixel format of the surface.

HRESULT GetPixelFormat(
  LPDDPIXELFORMAT lpDDPixelFormat
);

Parameters

lpDDPixelFormat
Address of the DDPIXELFORMAT structure to be filled with a detailed description of the current pixel and color space format of the surface.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDSURFACETYPE

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.


IDirectDrawSurface7::GetPriority

The IDirectDrawSurface7::GetPriority method retrieves the texture-management priority for this texture. This method succeeds only on managed textures (see Remarks).

HRESULT GetPriority(
  LPDWORD lpdwPriority
);

Parameters

lpdwPriority
Address of a variable to be filled with the texture priority if the call succeeds.

Return Values

If the method succeeds, the return value is D3D_OK.

If it fails, the return value is an error. The method returns DDERR_INVALIDOBJECT if the parameter is invalid or if the texture is not managed by Direct3D.

Remarks

Priorities are used to determine when managed textures are to be removed from memory. A texture assigned a low priority is removed before a texture with a high priority. If two textures have the same priority, the texture that was used more recently is kept in memory; the other texture is removed.

Applications can set and retrieve priorities only for managed textures (those that were created with the DDSCAPS2_TEXTUREMANAGE flag). Calling this method on a nonmanaged texture causes the method to fail and return DDERR_INVALIDOBJECT.

This method was introduced with the IDirectDrawSurface7 interface.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDrawSurface7::SetPriority, Automatic Texture Management, Textures


IDirectDrawSurface7::GetPrivateData

The IDirectDrawSurface7::GetPrivateData method copies the private data associated with the surface to a provided buffer.

HRESULT GetPrivateData(
  REFGUID guidTag,
  LPVOID  lpBuffer,
  LPDWORD lpcbBufferSize
);

Parameters

guidTag
Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to be retrieved.
lpBuffer
Address of a previously allocated buffer to be filled with the requested private data if the call succeeds. The application calling this method is responsible for allocating and releasing this buffer.
lpcbBufferSize
Size of the buffer at lpBuffer, in bytes. If this value is less than the actual size of the private data (such as 0), the method sets this parameter to the required buffer size, and the method returns DDERR_MOREDATA.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_EXPIRED
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_MOREDATA
DDERR_NOTFOUND
DDERR_OUTOFMEMORY

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDrawSurface7::SetPrivateData, IDirectDrawSurface7::FreePrivateData


IDirectDrawSurface7::GetSurfaceDesc

The IDirectDrawSurface7::GetSurfaceDesc method retrieves a description of the surface in its current condition.

HRESULT GetSurfaceDesc(
  LPDDSURFACEDESC2 lpDDSurfaceDesc
);

Parameters

lpDDSurfaceDesc
Address of a DDSURFACEDESC2 structure to be filled with the current description of this surface. You need only initialize this structure's dwSize member to the size, in bytes, of the structure prior to the call; no other preparation is required.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

DDSURFACEDESC, DDSURFACEDESC2


IDirectDrawSurface7::GetUniquenessValue

The IDirectDrawSurface7::GetUniquenessValue method retrieves the current uniqueness value for this surface.

HRESULT GetUniquenessValue(
  LPDWORD lpValue
);

Parameters

lpValue
Address of a variable to be filled with the surface's current uniqueness value if the call succeeds.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

The only defined uniqueness value is 0, indicating that the surface is likely to be changing beyond the control of DirectDraw. Other uniqueness values are only significant if they differ from a previously cached uniqueness value. If the current value is different from a cached value, the contents of the surface have changed.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDrawSurface7::ChangeUniquenessValue, Surface Uniqueness Values


IDirectDrawSurface7::Initialize

The IDirectDrawSurface7::Initialize method initializes a DirectDrawSurface object.

HRESULT Initialize(
  LPDIRECTDRAW lpDD,
  LPDDSURFACEDESC2 lpDDSurfaceDesc
);

Parameters

lpDD
Address of the DirectDraw structure that represents the DirectDraw object.
lpDDSurfaceDesc
Address of a DDSURFACEDESC2 structure to be filled with the relevant details about the surface.

Return Values

The method returns DDERR_ALREADYINITIALIZED.

Remarks

This method is provided for compliance with the Component Object Model (COM). Because the DirectDrawSurface object is initialized when it is created, this method always returns DDERR_ALREADYINITIALIZED.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IUnknown::AddRef, IUnknown::QueryInterface, IUnknown::Release


IDirectDrawSurface7::IsLost

The IDirectDrawSurface7::IsLost method determines whether the surface memory associated with a DirectDrawSurface object has been freed.

HRESULT IsLost();

Parameters

None.

Return Values

If the method succeeds, the return value is DD_OK because the memory has not been freed.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_SURFACELOST

You can use this method to determine when you need to reallocate surface memory. When a DirectDrawSurface object loses its surface memory, most methods return DDERR_SURFACELOST and perform no other action.

Remarks

Surfaces can lose their memory when the mode of the display card is changed or when an application receives exclusive access to the display card and frees all surface memory currently allocated on the display card.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDrawSurface7::Restore, Losing and Restoring Surfaces


IDirectDrawSurface7::Lock

The IDirectDrawSurface7::Lock method obtains a pointer to the surface memory.

HRESULT Lock(
  LPRECT lpDestRect,
  LPDDSURFACEDESC2 lpDDSurfaceDesc,
  DWORD dwFlags,
  HANDLE hEvent
);

Parameters

lpDestRect
Address of a RECT structure that identifies the region of the surface that is being locked. If NULL, the entire surface is locked.
lpDDSurfaceDesc
Address of a DDSURFACEDESC2 structure to be filled with the relevant details about the surface.
dwFlags
The following flags are defined:
DDLOCK_DONOTWAIT
On IDirectDrawSurface7 interfaces, the default is DDLOCK_WAIT. If you want to override the default and use time when the accelerator is busy (as denoted by the DDERR_WASSTILLDRAWING return value). use DDLOCK_DONOTWAIT.
DDLOCK_EVENT
Not currently implemented.
DDLOCK_NOOVERWRITE
New for DirectX 7.0. Used only with Direct3D vertex-buffer locks. Indicates that no vertices that were referred to in Draw*PrimitiveVB calls since the start of the frame (or the last lock without this flag) are modified during the lock. This can be useful when you want only to append data to the vertex buffer.
DDLOCK_NOSYSLOCK
Do not take the Win16Mutex (also known as Win16Lock). This flag is ignored when locking the primary surface.
DDLOCK_DISCARDCONTENTS
New for DirectX 7.0. Used only with Direct3D vertex-buffer locks. Indicates that no assumptions are made about the contents of the vertex buffer during this lock. This enables Direct3D or the driver to provide an alternative memory area as the vertex buffer. This is useful when you plan to clear the contents of the vertex buffer and fill in new data.
DDLOCK_OKTOSWAP
This flag is obsolete and was replaced by the DDLOCK_DISCARDCONTENTS flag.
DDLOCK_READONLY
Indicates that the surface being locked can only be read.
DDLOCK_SURFACEMEMORYPTR
Indicates that a valid memory pointer to the top of the specified rectangle should be returned. If no rectangle is specified, a pointer to the top of the surface is returned. This is the default.
DDLOCK_WAIT
If a lock cannot be obtained because a blit operation is in progress, the method retries until a lock is obtained or another error occurs, such as DDERR_SURFACEBUSY.
DDLOCK_WRITEONLY
Indicates that the surface being locked is write-enabled.
hEvent
Not used and must be set to NULL.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY
DDERR_SURFACEBUSY
DDERR_SURFACELOST
DDERR_WASSTILLDRAWING

Remarks

For more information on using this method, see Accessing Surface Memory Directly.

In IDirectDrawSurface7, the default behavior of this method is to wait for the accelator to finish. Therefore, under default conditions, this method never returns DDERR_WASSTILLDRAWING. If you want to see the error codes and not wait until the blit operation succeeds, use the DDLOCK_DONOTWAIT flag.

After retrieving a surface memory pointer, you can access the surface memory until a corresponding IDirectDrawSurface7::Unlock method is called. When the surface is unlocked, the pointer to the surface memory is invalid.

Do not call DirectDraw blit functions to blit from a locked region of a surface. If you do, the blit returns either DDERR_SURFACEBUSY or DDERR_LOCKEDSURFACES. GDI blit functions also silently fail when used on a locked video memory surface.

Unless you include the DDLOCK_NOSYSLOCK flag, this method causes DirectDraw to hold the Win16Mutex (also known as Win16Lock) until you call the IDirectDrawSurface7::Unlock method. GUI debuggers cannot operate while the Win16Mutex is held.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDrawSurface7::Unlock, IDirectDrawSurface7::GetDC, IDirectDrawSurface7::ReleaseDC


IDirectDrawSurface7::PageLock

The IDirectDrawSurface7::PageLock method prevents a system-memory surface from being paged out while a blit operation that uses direct memory access (DMA) transfers to or from system memory is in progress.

HRESULT PageLock(
  DWORD dwFlags
);

Parameters

dwFlags
Currently not used and must be set to 0.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_CANTPAGELOCK
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_SURFACELOST

Remarks

You must call this method to make use of DMA support. If you do not, the blit occurs using software emulation. For more information, see Using DMA.

The performance of the operating system can be negatively affected if too much memory is locked.

A lock count is maintained for each surface and is incremented each time that IDirectDrawSurface7::PageLock is called for that surface. The count is decremented when IDirectDrawSurface7::PageUnlock is called. When the count reaches 0, the memory is unlocked, and can then be paged by the operating system.

This method works only on system-memory surfaces; it does not page-lock a display-memory surface or an emulated primary surface. If an application calls this method on a display memory surface, the method does nothing except return DD_OK.

This method was not implemented in the IDirectDraw interface.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDrawSurface7::PageUnlock


IDirectDrawSurface7::PageUnlock

The IDirectDrawSurface7::PageUnlock method unlocks a system-memory surface, allowing it to be paged out.

HRESULT PageUnlock(
  DWORD dwFlags
);

Parameters

dwFlags
Currently not used and must be set to 0.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_CANTPAGEUNLOCK
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOTPAGELOCKED
DDERR_SURFACELOST

Remarks

A lock count is maintained for each surface and is incremented each time that IDirectDrawSurface7::PageLock is called for that surface. The count is decremented when IDirectDrawSurface7::PageUnlock is called. When the count reaches 0, the memory is unlocked, and can then be paged by the operating system.

This method works only on system-memory surfaces; it does not page-unlock a display-memory surface or an emulated primary surface. If an application calls this method on a display-memory surface, this method does nothing except return DD_OK.

This method was not implemented in the IDirectDraw interface.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDrawSurface7::PageLock


IDirectDrawSurface7::ReleaseDC

The IDirectDrawSurface7::ReleaseDC method releases the handle of a device context previously obtained by using the IDirectDrawSurface7::GetDC method.

HRESULT ReleaseDC(
  HDC hDC
);

Parameters

hDC
Handle of a device context previously obtained by IDirectDrawSurface7::GetDC.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_GENERIC
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_SURFACELOST
DDERR_UNSUPPORTED

Remarks

This method also unlocks the surface previously locked when the IDirectDrawSurface7::GetDC method was called.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDrawSurface7::GetDC


IDirectDrawSurface7::Restore

The IDirectDrawSurface7::Restore method restores a surface that has been lost. This occurs when the surface memory associated with the DirectDrawSurface object has been freed.

HRESULT Restore();

Parameters

None.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_GENERIC
DDERR_IMPLICITLYCREATED
DDERR_INCOMPATIBLEPRIMARY
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOEXCLUSIVEMODE
DDERR_OUTOFMEMORY
DDERR_UNSUPPORTED
DDERR_WRONGMODE

Remarks

This method restores the memory allocated for a surface, but does not reload any bitmaps that might have existed in the surface before it was lost. For more information, see Losing and Restoring Surfaces.

Surfaces can be lost because the mode of the display card was changed or because an application received exclusive access to the display card and freed all surface memory currently allocated on the card. When a DirectDrawSurface object loses its surface memory, many methods return DDERR_SURFACELOST and perform no other function. The IDirectDrawSurface7::Restore method reallocates surface memory and reattaches it to the DirectDrawSurface object.

A single call to this method restores a DirectDrawSurface object's associated implicit surfaces (back buffers, and so on). An attempt to restore an implicitly created surface results in an error. IDirectDrawSurface7::Restore does not work across explicit attachments created by using the IDirectDrawSurface7::AddAttachedSurface method—each of these surfaces must be restored individually.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDrawSurface7::IsLost


IDirectDrawSurface7::SetClipper

The IDirectDrawSurface7::SetClipper method attaches a clipper object to, or deletes one from, a surface.

HRESULT SetClipper(
  LPDIRECTDRAWCLIPPER lpDDClipper
);

Parameters

lpDDClipper
Address of the IDirectDrawClipper interface for the DirectDrawClipper object to be attached to the DirectDrawSurface object. If NULL, the current DirectDrawClipper object is detached.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDSURFACETYPE
DDERR_NOCLIPPERATTACHED

Remarks

When setting a clipper to a surface for the first time, this method increments the clipper's reference count; subsequent calls do not affect the clipper's reference count. If you pass NULL as the lpDDClipper parameter, the clipper is removed from the surface, and the clipper's reference count is decremented. If you do not delete the clipper, the surface automatically releases its reference to the clipper when the surface itself is released. According to COM rules, your application is responsible for releasing any references that it holds to the clipper when the object is no longer needed.

This method is primarily used by surfaces that are being overlaid on, or blitted to, the primary surface. However, it can be used on any surface. After a DirectDrawClipper object has been attached and a clip list is associated with it, the DirectDrawClipper object is used for the IDirectDrawSurface7::Blt, IDirectDrawSurface7::BltBatch, and IDirectDrawSurface7::UpdateOverlay operations involving the parent DirectDrawSurface object. This method can also detach the current DirectDrawClipper object of a DirectDrawSurface object.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDrawSurface7::GetClipper


IDirectDrawSurface7::SetColorKey

The IDirectDrawSurface7::SetColorKey method sets the color key value for the DirectDrawSurface object if the hardware supports color keys on a per-surface basis.

HRESULT SetColorKey(
  DWORD dwFlags,
  LPDDCOLORKEY lpDDColorKey
);

Parameters

dwFlags
Determines which color key is requested. The following flags are defined:
DDCKEY_COLORSPACE
The structure contains a color space. Not set if the structure contains a single color key.
DDCKEY_DESTBLT
A color key or color space to be used as a destination color key for blit operations.
DDCKEY_DESTOVERLAY
A color key or color space to be used as a destination color key for overlay operations.
DDCKEY_SRCBLT
A color key or color space to be used as a source color key for blit operations.
DDCKEY_SRCOVERLAY
A color key or color space to be used as a source color key for overlay operations.
lpDDColorKey
Address of the DDCOLORKEY structure that contains the new color key values for the DirectDrawSurface object. This value can be NULL to remove a previously set color key.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_GENERIC
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDSURFACETYPE
DDERR_NOOVERLAYHW
DDERR_NOTAOVERLAYSURFACE
DDERR_SURFACELOST
DDERR_UNSUPPORTED
DDERR_WASSTILLDRAWING

Remarks

For transparent blits and overlays, set destination color on the destination surface and source color on the source surface.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDrawSurface7::GetColorKey


IDirectDrawSurface7::SetLOD

The IDirectDrawSurface7::SetLOD method sets the maximum level of detail for a managed mipmap surface. This method succeeds only on managed textures (see Remarks).

HRESULT SetLOD(
    DWORD dwMaxLOD
);
dwMaxLOD
Maximum level-of-detail value to be set for the mipmap chain if the call succeeds.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

Applications can call this method only for managed textures (those that were created with the DDSCAPS2_TEXTUREMANAGE flag). Calling this method on a nonmanaged texture causes the method to fail and return DDERR_INVALIDOBJECT.

This method communicates to the Direct3D texture manager the most detailed mipmap in this chain that it should load into local video memory. For example, in a five-level mipmap chain, setting dwMaxLOD to 2 indicates that the texture manager should load only mipmap levels 2 through 4 into local video memory at any given time. Likewise, if the most detailed mipmap in the chain has the dimensions 256×256, setting the maximum level to 2 means that the largest mipmap ever present in video memory has dimensions 64×64.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDrawSurface7::GetLOD, Texture Filtering With Mipmaps, Automatic Texture Management, Textures


IDirectDrawSurface7::SetOverlayPosition

The IDirectDrawSurface7::SetOverlayPosition method changes the display coordinates of an overlay surface.

HRESULT SetOverlayPosition(
  LONG lX,
  LONG lY
);

Parameters

lX and lY
New x- and y-display coordinates.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_GENERIC
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDPOSITION
DDERR_NOOVERLAYDEST
DDERR_NOTAOVERLAYSURFACE
DDERR_OVERLAYNOTVISIBLE
DDERR_SURFACELOST
DDERR_UNSUPPORTED

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDrawSurface7::GetOverlayPosition, IDirectDrawSurface7::UpdateOverlay


IDirectDrawSurface7::SetPalette

The IDirectDrawSurface7::SetPalette method attaches a palette object to (or detaches one from) a surface. The surface uses this palette for all subsequent operations. The palette change takes place immediately, without regard to refresh timing.

HRESULT SetPalette(
  LPDIRECTDRAWPALETTE lpDDPalette
);

Parameters

lpDDPalette
Address of the IDirectDrawPalette interface for the palette object to be used with this surface. If NULL, the current palette is detached.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_GENERIC
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDPIXELFORMAT
DDERR_INVALIDSURFACETYPE
DDERR_NOEXCLUSIVEMODE
DDERR_NOPALETTEATTACHED
DDERR_NOPALETTEHW
DDERR_NOT8BITCOLOR
DDERR_SURFACELOST
DDERR_UNSUPPORTED

Remarks

When setting a palette to a surface for the first time, this method increments the palette's reference count; subsequent calls do not affect the palette's reference count. If you pass NULL as the lpDDPalette parameter, the palette is removed from the surface, and the palette's reference count is decremented. If you do not delete the palette, the surface automatically releases its reference to the palette when the surface itself is released. According to COM rules, your application is responsible for releasing any references that it holds to the palette when the object is no longer needed.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDrawSurface7::GetPalette, IDirectDraw7::CreatePalette


IDirectDrawSurface7::SetPriority

The IDirectDrawSurface7::GetPriority method assigns the texture-management priority for this texture. This method succeeds only on managed textures (see Remarks).

HRESULT SetPriority(
  DWORD dwPriority
);

Parameters

dwPriority
Value specifying the new texture-management priority for the texture.

Return Values

If the method succeeds, the return value is D3D_OK.

If it fails, the method returns an error. It returns DDERR_INVALIDOBJECT if the parameter is invalid or if the texture is not managed by Direct3D.

Remarks

This method was introduced with the IDirectDrawSurface7 interface.

Priorities are used to determine when managed textures are to be removed from memory. A texture with a low priority is removed before a texture with a high priority. If two textures have the same priority, the texture that was used more recently is kept in memory; the other texture is removed.

Applications can set and retrieve priorities only for managed textures (those that were created with the DDSCAPS2_TEXTUREMANAGE flag). Calling this method on a nonmanaged texture causes the method to fail and return DDERR_INVALIDOBJECT.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDrawSurface7::GetPriority, Automatic Texture Management, Textures


IDirectDrawSurface7::SetPrivateData

The IDirectDrawSurface7::SetPrivateData method associates data with the surface that is intended for use by the application, not by DirectDraw. Data is passed by value, and multiple sets of data can be associated with a single surface.

HRESULT SetPrivateData(
  REFGUID guidTag,
  LPVOID  lpData,
  DWORD   cbSize,
  DWORD   dwFlags
);

Parameters

guidTag
Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to be set.
lpData
Address of a buffer that contains the data to be associated with the surface.
cbSize
Size of the buffer at lpData, in bytes.
dwFlags
Flags describing the type of data being passed or requesting that the data be invalidated when the surface changes. The following flags are defined:
(none)
If no flags are specified, DirectDraw allocates memory to hold the data within the buffer and copies the data into the new buffer. The buffer allocated by DirectDraw is automatically freed, as appropriate.
DDSPD_IUNKNOWNPOINTER
The data at lpData is a pointer to an IUnknown interface. DirectDraw automatically calls the IUnknown::AddRef method of this interface. When this data is no longer needed, DirectDraw automatically calls the IUnknown::Release method of this interface.
DDSPD_VOLATILE
The buffer at lpData is only valid while the surface remains unchanged. If the surface's contents change, subsequent calls to the IDirectDrawSurface7::GetPrivateData method return DDERR_EXPIRED.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY

Remarks

DirectDraw does not manage the memory at lpData. If this buffer was dynamically allocated, it is the caller's responsibility to free the memory.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDrawSurface7::GetPrivateData, IDirectDrawSurface7::FreePrivateData


IDirectDrawSurface7::SetSurfaceDesc

The IDirectDrawSurface7::SetSurfaceDesc method sets the characteristics of an existing surface.

HRESULT SetSurfaceDesc(
  LPDDSURFACEDESC2 lpddsd2,
  DWORD dwFlags
);

Parameters

lpddsd2
Address of a DDSURFACEDESC2 structure that contains the new surface characteristics.
dwFlags
Currently not used and must be set to 0.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDPARAMS
DDERR_INVALIDOBJECT
DDERR_SURFACELOST
DDERR_SURFACEBUSY
DDERR_INVALIDSURFACETYPE
DDERR_INVALIDPIXELFORMAT
DDERR_INVALIDCAPS
DDERR_UNSUPPORTED
DDERR_GENERIC

Remarks

Currently, this method can be used only to set the surface data and pixel format used by an explicit system-memory surface. This is useful because it allows a surface to use data from a previously allocated buffer without copying. The new surface memory is allocated by the client application, and therefore the client application must also deallocate it. For more information, see Updating Surface Characteristics.

Using this method incorrectly causes unpredictable behavior. The DirectDrawSurface object does not deallocate surface memory that it did not allocate. Therefore, when the surface memory is no longer needed, it is your responsibility to deallocate it. However, when this method is called, DirectDraw frees the original surface memory that it implicitly allocated when creating the surface.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.


IDirectDrawSurface7::Unlock

The IDirectDrawSurface7::Unlock method notifies DirectDraw that the direct surface manipulations are complete.

HRESULT Unlock(
  LPRECT lpRect
);

Parameters

lpRect
Address of the RECT structure that was used to lock the surface in the corresponding call to the IDirectDrawSurface7::Lock method. This parameter can be NULL only if the entire surface was locked by passing NULL in the lpDestRect parameter of the corresponding call to the IDirectDrawSurface7::Lock method.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_GENERIC
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDRECT
DDERR_NOTLOCKED
DDERR_SURFACELOST

Remarks

Because it is possible to call IDirectDrawSurface7::Lock multiple times for the same surface with different destination rectangles, the pointer in lpRect links the calls to the IDirectDrawSurface7::Lock and IDirectDrawSurface7::Unlock methods.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDrawSurface7::Lock


IDirectDrawSurface7::UpdateOverlay

The IDirectDrawSurface7::UpdateOverlay method repositions or modifies the visual attributes of an overlay surface. These surfaces must have the DDSCAPS_OVERLAY flag set.

HRESULT UpdateOverlay(
  LPRECT lpSrcRect,
  LPDIRECTDRAWSURFACE7 lpDDDestSurface,
  LPRECT lpDestRect,
  DWORD dwFlags,
  LPDDOVERLAYFX lpDDOverlayFx
);

Parameters

lpSrcRect
Address of a RECT structure that defines the x, y, width, and height of the region on the source surface being used as the overlay. This parameter can be NULL when hiding an overlay or to indicate that the entire overlay surface is to be used and that the overlay surface conforms to any boundary and size-alignment restrictions imposed by the device driver.
lpDDDestSurface
Address of the IDirectDrawSurface7 interface for the surface that is being overlaid.
lpDestRect
Address of a RECT structure that defines the x, y, width, and height of the region on the destination surface that the overlay should be moved to. This parameter can be NULL when hiding the overlay.
dwFlags
The following flags are defined:
DDOVER_ADDDIRTYRECT
Adds a dirty rectangle to an emulated overlay surface.
DDOVER_ALPHADEST
Obsolete.
DDOVER_ALPHADESTCONSTOVERRIDE
Uses the dwAlphaDestConst member of the DDOVERLAYFX structure as the destination alpha channel for this overlay.
DDOVER_ALPHADESTNEG
Indicates that the destination surface becomes more transparent as the alpha value increases (0 is opaque).
DDOVER_ALPHADESTSURFACEOVERRIDE
Uses the lpDDSAlphaDest member of the DDOVERLAYFX structure as the alpha channel destination for this overlay.
DDOVER_ALPHAEDGEBLEND
Uses the dwAlphaEdgeBlend member of the DDOVERLAYFX structure as the alpha channel for the edges of the image that border the color key colors.
DDOVER_ALPHASRC
Uses either the alpha information in pixel format or the alpha channel surface attached to the source surface as the source alpha channel for this overlay.
DDOVER_ALPHASRCCONSTOVERRIDE
Uses the dwAlphaSrcConst member of the DDOVERLAYFX structure as the source alpha channel for this overlay.
DDOVER_ALPHASRCNEG
Indicates that the source surface becomes more transparent as the alpha value increases (0 is opaque).
DDOVER_ALPHASRCSURFACEOVERRIDE
Uses the lpDDSAlphaSrc member of the DDOVERLAYFX structure as the alpha channel source for this overlay.
DDOVER_ARGBSCALEFACTORS
New for DirectX 7.0. Indicates that the DDOVERLAYFX structure contains valid ARGB scaling factors.
DDOVER_AUTOFLIP
Automatically flips to the next surface in the flipping chain each time that a video port VSYNC occurs.
DDOVER_BOB
Displays each field of the interlaced video stream individually without causing any artifacts.
DDOVER_BOBHARDWARE
Bob operations are performed using hardware, rather than software or emulated. This flag must be used with the DDOVER_BOB flag.
DDOVER_DDFX
Uses the overlay FX flags in the lpDDOverlayFx parameter to define special overlay effects.
DDOVER_DEGRADEARGBSCALING
New for DirectX 7.0. ARGB scaling factors can be degraded to fit driver capabilities.
DDOVER_HIDE
Turns off this overlay.
DDOVER_INTERLEAVED
The surface memory is composed of interleaved fields.
DDOVER_KEYDEST
Uses the color key associated with the destination surface.
DDOVER_KEYDESTOVERRIDE
Uses the dckDestColorkey member of the DDOVERLAYFX structure as the color key for the destination surface.
DDOVER_KEYSRC
Uses the color key associated with the source surface.
DDOVER_KEYSRCOVERRIDE
Uses the dckSrcColorkey member of the DDOVERLAYFX structure as the color key for the source surface.
DDOVER_OVERRIDEBOBWEAVE
Bob and weave decisions should not be overridden by other interfaces.
DDOVER_REFRESHALL
Redraws the entire surface on an emulated overlayed surface.
DDOVER_REFRESHDIRTYRECTS
Redraws all dirty rectangles on an emulated overlayed surface.
DDOVER_SHOW
Turns on this overlay.
lpDDOverlayFx
Address of a DDOVERLAYFX structure that describes the effects to be used. Can be NULL if the DDOVER_DDFX flag is not specified.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_DEVICEDOESNTOWNSURFACE
DDERR_GENERIC
DDERR_HEIGHTALIGN
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDRECT
DDERR_INVALIDSURFACETYPE
DDERR_NOSTRETCHHW
DDERR_NOTAOVERLAYSURFACE
DDERR_OUTOFCAPS
DDERR_SURFACELOST
DDERR_UNSUPPORTED
DDERR_XALIGN

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.


IDirectDrawSurface7::UpdateOverlayDisplay

The IDirectDrawSurface7::UpdateOverlayDisplay method is not currently implemented.

HRESULT UpdateOverlayDisplay(
  DWORD dwFlags
);

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDrawSurface7::AddOverlayDirtyRect


IDirectDrawSurface7::UpdateOverlayZOrder

The IDirectDrawSurface7::UpdateOverlayZOrder method sets the z-order of an overlay.

HRESULT UpdateOverlayZOrder(
  DWORD dwFlags,
  LPDIRECTDRAWSURFACE7 lpDDSReference
);

Parameters

dwFlags
One of the following flags:
DDOVERZ_INSERTINBACKOF
Inserts this overlay in the overlay chain behind the reference overlay.
DDOVERZ_INSERTINFRONTOF
Inserts this overlay in the overlay chain in front of the reference overlay.
DDOVERZ_MOVEBACKWARD
Moves this overlay one position backward in the overlay chain.
DDOVERZ_MOVEFORWARD
Moves this overlay one position forward in the overlay chain.
DDOVERZ_SENDTOBACK
Moves this overlay to the back of the overlay chain.
DDOVERZ_SENDTOFRONT
Moves this overlay to the front of the overlay chain.
lpDDSReference
Address of the IDirectDrawSurface7 interface for the DirectDraw surface to be used as a relative position in the overlay chain. This parameter is needed only for DDOVERZ_INSERTINBACKOF and DDOVERZ_INSERTINFRONTOF.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOTAOVERLAYSURFACE

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.

See Also

IDirectDrawSurface7::EnumOverlayZOrders


IDirectDrawVideoPort

Applications use the methods of the IDirectDrawVideoPort interface to channel live video data from a hardware video port to a DirectDraw surface. This section is a reference to the methods of this interface. For a conceptual overview, see Video Ports.

The methods of the IDirectDrawVideoPort interface can be organized into the following groups:

Color controls | GetColorControls
 | SetColorControls
Fields and signals | GetFieldPolarity
 | GetVideoSignalStatus
Flipping | Flip
 | SetTargetSurface
Formats | GetInputFormats
 | GetOutputFormats
Timing and synchronization | GetVideoLine
 | WaitForSync
Video control | StartVideo
 | StopVideo
 | UpdateVideo
Zoom factors | GetBandwidthInfo

The IDirectDrawVideoPort interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

You can use the LPDIRECTDRAWVIDEOPORT data type to declare a variable that contains a pointer to an IDirectDrawVideoPort interface. The Dvp.h header file declares the LPDIRECTDRAWVIDEOPORT with the following code:

typedef struct IDirectDrawVideoPort    FAR *LPDIRECTDRAWVIDEOPORT;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dvp.h.
Import Library: Use ddraw.lib.


IDirectDrawVideoPort::Flip

The IDirectDrawVideoPort::Flip method instructs the DirectDrawVideoPort object to write the next frame of video to a new surface.

HRESULT Flip(
  LPDIRECTDRAWSURFACE lpDDSurface,
  DWORD dwFlags
);

Parameters

lpDDSurface
Address of the IDirectDrawSurface interface for the surface to receive the next frame of video. Setting this parameter to NULL causes DirectDraw to cycle through surfaces in the flipping chain in the order that they were attached.
dwFlags
Flip options flags. Can be one of the following values:
DDVPFLIP_VIDEO
The specified surface is to receive the normal video data.
DDVPFLIP_VBI
The specified surface is to receive only the data within the vertical blanking interval.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

This method can be used to prevent tearing. Calls to IDirectDrawVideoPort::Flip are asynchronous—the flip operation is always synchronized with the vertical blank of the video signal.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dvp.h.
Import Library: Use ddraw.lib.


IDirectDrawVideoPort::GetBandwidthInfo

The IDirectDrawVideoPort::GetBandwidthInfo method retrieves the minimum required overlay zoom factors and device limitations of a video port that uses the provided output pixel format.

HRESULT GetBandwidthInfo(
  LPDDPIXELFORMAT lpddpfFormat,
  DWORD dwWidth,
  DWORD dwHeight,
  DWORD dwFlags,
  LPDDVIDEOPORTBANDWIDTH lpBandwidth
);

Parameters

lpddpfFormat
Address of a DDPIXELFORMAT structure that describes the output pixel format for which bandwidth information is retrieved.
dwWidth and dwHeight
Dimensions of an overlay or video data. These parameters depend on the value specified in the dwFlags parameter.
dwFlags
Flags indicating how the method is to interpret the dwWidth and dwHeight parameters. Can be one of the following values:
DDVPB_OVERLAY
The dwWidth and dwHeight parameters indicate the size of the source overlay surface. Use this flag when the video port is dependent on the overlay source size.
DDVPB_TYPE
The dwWidth and dwHeight parameters are not set. The method retrieves the device's dependency type in the dwCaps member of the associated DDVIDEOPORTBANDWIDTH structure. Use this flag when you call this method the first time.
DDVPB_VIDEOPORT
The dwWidth and dwHeight parameters indicate the prescale size of the video data that the video port writes to the frame buffer. Use this flag when the video port is dependent on the overlay zoom factor.
lpBandwidth
Address of a DDVIDEOPORTBANDWIDTH structure to be filled with the retrieved bandwidth and device dependency information.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

This method is usually called twice. When you make the first call, specify the DDVPB_TYPE flag in the dwFlags parameter to retrieve information about the device's overlay dependency type. Subsequent calls using the DDVPB_VIDEOPORT or DDVPB_OVERLAY flags must be interpreted considering the device's dependency type.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dvp.h.
Import Library: Use ddraw.lib.


IDirectDrawVideoPort::GetColorControls

The IDirectDrawVideoPort::GetColorControls method returns the current color control settings associated with the video port.

HRESULT GetColorControls(
  LPDDCOLORCONTROL lpColorControl
);

Parameters

lpColorControl
Address of a DDCOLORCONTROL structure to be filled with the current settings of the video port's color control.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_UNSUPPORTED

Remarks

The dwFlags member of the DDCOLORCONTROL structure indicates which of the color control options are supported.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dvp.h.
Import Library: Use ddraw.lib.


IDirectDrawVideoPort::GetFieldPolarity

The IDirectDrawVideoPort::GetFieldPolarity method retrieves the polarity of a video field.

HRESULT GetFieldPolarity(
  LPBOOL lpbFieldPolarity
);

Parameters

lpbFieldPolarity
Address of a variable to be set to indicate the current field polarity. This value is set to TRUE if the current video field is the even field of an interlaced video signal, and FALSE otherwise.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_UNSUPPORTED
DDERR_VIDEONOTACTIVE

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dvp.h.
Import Library: Use ddraw.lib.


IDirectDrawVideoPort::GetInputFormats

The IDirectDrawVideoPort::GetInputFormats method retrieves the input formats supported by the DirectDrawVideoPort object.

HRESULT GetInputFormats(
  LPDWORD lpNumFormats,
  LPDDPIXELFORMAT lpFormats,
  DWORD dwFlags
);

Parameters

lpNumFormats
Address of a variable that contains the number of entries that the array at lpFormats can hold. If this number is less than the total number of codes, the method fills the array with all the codes that fit, sets the value at lpNumFormats to indicate the total number of codes, and returns DDERR_MOREDATA.
lpFormats
Address of an array of DDPIXELFORMAT structures to be filled in with the input formats supported by this DirectDrawVideoPort object. If NULL, the method sets lpNumFormats to the number of supported formats, and then returns DD_OK.
dwFlags
Flags specifying the part of the video signal for which formats are enumerated. One of the following values:
DDVPFORMAT_VIDEO
Returns formats for the video data.
DDVPFORMAT_VBI
Returns formats for the VBI data.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_MOREDATA

Remarks

This method can also be used to return the number of formats supported. To do this, set the lpFormats parameter to NULL. When the method returns, the variable at lpNumFormats contains the total number of supported input formats.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dvp.h.
Import Library: Use ddraw.lib.


IDirectDrawVideoPort::GetOutputFormats

The IDirectDrawVideoPort::GetOutputFormats method retrieves a list of output formats that the DirectDrawVideoPort object supports for a specified input format.

HRESULT GetOutputFormats(
  LPDDPIXELFORMAT lpInputFormat,
  LPDWORD lpNumFormats,
  LPDDPIXELFORMAT lpFormats,
  DWORD dwFlags
);

Parameters

lpInputFormat
Address of a DDPIXELFORMAT structure that describes the input format for which conversion information is requested.
lpNumFormats
Address of a variable that contains the number of entries that the array at lpFromats can hold. If this number is less than the total number of codes, the method fills the array with all the codes that fit, sets the value at lpNumFormats to indicate the total number of codes, and returns DDERR_MOREDATA.
lpFormats
Address of an array of DDPIXELFORMAT structures to be filled in with the output formats supported by this DirectDrawVideoPort object. If NULL, the method sets lpNumFormats to the number of supported formats, and then returns DD_OK.
dwFlags
Flags specifying the part of the video signal for which formats are enumerated. One of the following values:
DDVPFORMAT_VIDEO
Returns formats for the video data.
DDVPFORMAT_VBI
Returns formats for the VBI data.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_MOREDATA

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dvp.h.
Import Library: Use ddraw.lib.


IDirectDrawVideoPort::GetVideoLine

The IDirectDrawVideoPort::GetVideoLine method retrieves the line of video currently being written to the frame buffer.

HRESULT GetVideoLine(
  LPDWORD lpdwLine
);

Parameters

lpdwLine
Address of a variable to be filled with a value indicating the video line currently being written to the frame buffer.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_UNSUPPORTED
DDERR_VERTICALBLANKINPROGRESS
DDERR_VIDEONOTACTIVE

Remarks

The value that this method retrieves reflects the true video line being written, relative to the field height, before any prescaling occurs.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dvp.h.
Import Library: Use ddraw.lib.


IDirectDrawVideoPort::GetVideoSignalStatus

The IDirectDrawVideoPort::GetVideoSignalStatus method retrieves the status of the video signal currently being presented to the video port.

HRESULT GetVideoSignalStatus(
  LPDWORD lpdwStatus
);

Parameters

lpdwStatus
Address of a variable to contain a return value indicating the quality of the video signal at the video port. The value is set to one of the following codes:
DDVPSQ_NOSIGNAL
No video signal is present at the video port.
DDVPSQ_SIGNALOK
A valid video signal is present at the video port.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_UNSUPPORTED

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dvp.h.
Import Library: Use ddraw.lib.


IDirectDrawVideoPort::SetColorControls

The IDirectDrawVideoPort::SetColorControls method sets the color control settings associated with the video port.

HRESULT SetColorControls(
  LPDDCOLORCONTROL lpColorControl
);

Parameters

lpColorControl
Address of a DDCOLORCONTROL structure that contains the new color control settings to be applied to the video port.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_UNSUPPORTED

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dvp.h.
Import Library: Use ddraw.lib.


IDirectDrawVideoPort::SetTargetSurface

The IDirectDrawVideoPort::SetTargetSurface method sets the DirectDraw surface object to receive the stream of live video data and/or the vertical blank interval data.

HRESULT SetTargetSurface(
  LPDIRECTDRAWSURFACE lpDDSurface,
  DWORD dwFlags
);

Parameters

lpDDSurface
Address of the DirectDrawSurface object to receive the video data.
dwFlags
Value specifying the type of the target surface. One of the following flags:
DDVPTARGET_VIDEO
The specified surface should receive the normal video data and vertical interval data unless a separate surface was attached for this purpose.
DDVPTARGET_VBI
The specified surface should receive the data within the vertical blanking interval.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dvp.h.
Import Library: Use ddraw.lib.

See Also

IDirectDrawVideoPort::StartVideo, IDirectDrawVideoPort::StopVideo, IDirectDrawVideoPort::UpdateVideo


IDirectDrawVideoPort::StartVideo

The IDirectDrawVideoPort::StartVideo method enables the hardware video port and starts the flow of video data into the currently specified surface.

HRESULT StartVideo(
  LPDDVIDEOPORTINFO lpVideoInfo
);

Parameters

lpVideoInfo
Address of a pointer to a DDVIDEOPORTINFO structure.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_SURFACELOST

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dvp.h.
Import Library: Use ddraw.lib.

See Also

IDirectDrawVideoPort::SetTargetSurface, IDirectDrawVideoPort::StopVideo, IDirectDrawVideoPort::UpdateVideo


IDirectDrawVideoPort::StopVideo

The IDirectDrawVideoPort::StopVideo method stops the flow of video-port data into the frame buffer.

HRESULT StopVideo();

Parameters

None.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method returns DDERR_INVALIDOBJECT.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dvp.h.
Import Library: Use ddraw.lib.

See Also

IDirectDrawVideoPort::SetTargetSurface, IIDirectDrawVideoPort::StartVideo, IDirectDrawVideoPort::UpdateVideo


IDirectDrawVideoPort::UpdateVideo

The IDirectDrawVideoPort::UpdateVideo method updates parameters that govern the flow of video data from the video port to the DirectDrawSurface object.

HRESULT UpdateVideo(
  LPDDVIDEOPORTINFO lpVideoInfo
);

Parameters

lpVideoInfo
Address of a DDVIDEOPORTINFO structure that describes the video transfer parameters.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dvp.h.
Import Library: Use ddraw.lib.

See Also

IDirectDrawVideoPort::SetTargetSurface, IDirectDrawVideoPort::StartVideo, IDirectDrawVideoPort::StopVideo


IDirectDrawVideoPort::WaitForSync

The IDirectDrawVideoPort::WaitForSync method waits for VSYNC or until a given scan line is being drawn.

HRESULT WaitForSync(
  DWORD dwFlags,
  DWORD dwLine,
  DWORD dwTimeout
);

Parameters

dwFlags
Flag specifying how the method waits for the video VSYNC or the specified line number. One of the following values:
DDVPWAIT_BEGIN
Return at the start of the vertical blanking interval.
DDVPWAIT_END
Return at the end of the vertical blanking interval.
DDVPWAIT_LINE
Return when the video counter either reaches or passes the line specified by the dwLine parameter.
dwLine
Video line determining when the method returns, relative to the field height, before prescaling. This parameter is ignored if the dwFlags parameter is set to DDVPWAIT_BEGIN or DDVPWAIT_END.
dwTimeout
Amount of time, in milliseconds, that the method waits for the next video vertical blank before timing out. If this parameter is 0, the method waits 3 times the value specified in the dwMicrosecondsPerField member of the DDVIDEOPORTDESC.

Return Values

If the method succeeds, the return value is DD_OK.

If it fails, the method can return one of the following error values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_UNSUPPORTED
DDERR_VIDEONOTACTIVE
DDERR_WASSTILLDRAWING

Remarks

This method helps the caller synchronize with the video vertical blank interval or with an arbitrary line of video data. The method blocks the calling thread until either the video VSYNC occurs or the video line counter matches the specified line number.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dvp.h.
Import Library: Use ddraw.lib.


Functions

This section contains information about the following DirectDraw global functions:

  • DirectDrawCreate
  • DirectDrawCreateEx
  • DirectDrawCreateClipper
  • DirectDrawEnumerate
  • DirectDrawEnumerateEx


DirectDrawCreate

The DirectDrawCreate function creates an instance of a DirectDraw object. A DirectDraw object created with this function does not support the newest set of Direct3D interfaces. To create a DirectDraw object capable of exposing the new features of Direct3D, use the DirectDrawCreateEx function.

HRESULT WINAPI DirectDrawCreate(
  GUID FAR *lpGUID,
  LPDIRECTDRAW FAR *lplpDD,
  IUnknown FAR *pUnkOuter
);

Parameters

lpGUID
Address of the globally unique identifier (GUID) that represents the driver to be created. This can be NULL to indicate the active display driver, or you can pass one of the following flags to restrict the active display driver's behavior for debugging purposes:
DDCREATE_EMULATIONONLY
The DirectDraw object uses emulation for all features; it does not take advantage of any hardware-supported features.
DDCREATE_HARDWAREONLY
The DirectDraw object never emulates features not supported by the hardware. Attempts to call methods that require unsupported features fail, returning DDERR_UNSUPPORTED.
lplpDD
Address of a variable to be set to a valid IDirectDraw interface pointer if the call succeeds.
pUnkOuter
Allows for future compatibility with COM aggregation features. Presently, however, this method returns an error if this parameter is anything but NULL.

Return Values

If the function succeeds, the return value is DD_OK.

If it fails, the function can return one of the following error values:

DDERR_DIRECTDRAWALREADYCREATED
DDERR_GENERIC
DDERR_INVALIDDIRECTDRAWGUID
DDERR_INVALIDPARAMS
DDERR_NODIRECTDRAWHW
DDERR_OUTOFMEMORY

Remarks

This function attempts to initialize a DirectDraw object, and then sets a pointer to the object if the call succeeds.

On systems with multiple monitors, specifying NULL for lpGUID causes the DirectDraw object to run in emulation mode when the normal cooperative level is set. To make use of hardware acceleration on these systems, specify the device's GUID. For more information, see Devices and Acceleration in MultiMon Systems.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.
Import Library: Use ddraw.lib.


DirectDrawCreateEx

The DirectDrawCreateEx function creates an instance of a DirectDraw object that supports the newest set of Direct3D interfaces. To use the new features of Direct3D in DirectX 7.0, create a DirectDraw object with this function. For more information about the relationship between DirectDraw and Direct3D see The DirectDraw Object and Direct3D and Accessing Direct3D topics.

HRESULT WINAPI DirectDrawCreateEx(
  GUID FAR *lpGUID,
  LPVOID *lplpDD,
  REFIID iid,
  IUnknown FAR *pUnkOuter
);

Parameters

lpGUID
Address of the globally unique identifier (GUID) that represents the driver to be created. This can be NULL to indicate the active display driver, or you can pass one of the following flags to restrict the behavior of the active display driver for debugging purposes:
DDCREATE_EMULATIONONLY
The DirectDraw object uses emulation for all features; it does not take advantage of any hardware-supported features.
DDCREATE_HARDWAREONLY
The DirectDraw object never emulates features not supported by the hardware. Attempts to call methods that require unsupported features fail, returning DDERR_UNSUPPORTED.
lplpDD
Address of a variable to be set to a valid IDirectDraw7 interface pointer if the call succeeds.
iid
This parameter must be set to IID_IDirectDraw7. This function fails and returns DDERR_INVALIDPARAMS if any other interface is specified.
pUnkOuter
Allows for future compatibility with COM aggregation features. Presently, however, this method returns an error if this parameter is anything but NULL.

Return Values

If the function succeeds, the return value is DD_OK.

If it fails, the function can return one of the following error values:

DDERR_DIRECTDRAWALREADYCREATED
DDERR_GENERIC
DDERR_INVALIDDIRECTDRAWGUID
DDERR_INVALIDPARAMS
DDERR_NODIRECTDRAWHW
DDERR_OUTOFMEMORY

Remarks

This function attempts to initialize a DirectDraw object, and then sets a pointer to the object if the call succeeds.

On systems with multiple monitors, specifying NULL for lpGUID causes the DirectDraw object to run in emulation mode when the normal cooperative level is set. To make use of hardware acceleration on these systems, specify the device's GUID. For more information, see Devices and Acceleration in MultiMon Systems.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.
Import Library: Use ddraw.lib.


DirectDrawCreateClipper

The DirectDrawCreateClipper function creates an instance of a DirectDrawClipper object not associated with a DirectDraw object.

HRESULT WINAPI DirectDrawCreateClipper(
  DWORD dwFlags,
  LPDIRECTDRAWCLIPPER FAR *lplpDDClipper,
  IUnknown FAR *pUnkOuter
);

Parameters

dwFlags
Currently not used and must be set to 0.
lplpDDClipper
Address of a pointer to be filled with the address of the new DirectDrawClipper object.
pUnkOuter
Allows for future compatibility with COM aggregation features. Presently, however, this method returns an error if this parameter is anything but NULL.

Return Values

If the function succeeds, the return value is DD_OK.

If it fails, the function can return one of the following error values:

DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY

Remarks

This function can be called before any DirectDraw objects are created. Because these DirectDrawClipper objects are not owned by any DirectDraw object, they are not automatically released when an application's objects are released. If the application does not explicitly release the DirectDrawClipper objects, DirectDraw releases them when the application terminates.

To create a DirectDrawClipper object owned by a specific DirectDraw object, use the IDirectDraw7::CreateClipper method.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.
Import Library: Use ddraw.lib.

See Also

IDirectDraw7::CreateClipper


DirectDrawEnumerate

This function is superseded by the DirectDrawEnumerateEx function.

The DirectDrawEnumerate function enumerates the primary DirectDraw display device and a nondisplay device (such as a 3-D accelerator that has no 2-D capabilities), if one is installed. The NULL entry always identifies the primary display device shared with the GDI.

HRESULT WINAPI DirectDrawEnumerate(
  LPDDENUMCALLBACK lpCallback,
  LPVOID lpContext
);

Parameters

lpCallback
Address of a DDEnumCallback function to be called with a description of each enumerated DirectDraw-enabled hardware abstraction layer (HAL).
lpContext
Address of an application-defined context to be passed to the enumeration callback function each time that it is called.

Return Values

If the function succeeds, the return value is DD_OK.

If it fails, the function returns DDERR_INVALIDPARAMS.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.
Import Library: Use ddraw.lib.

See Also

DirectDrawEnumerateEx


DirectDrawEnumerateEx

The DirectDrawEnumerateEx function enumerates all DirectDraw devices installed on the system. The NULL entry always identifies the primary display device shared with GDI.

HRESULT WINAPI DirectDrawEnumerateEx(
  LPDDENUMCALLBACKEX lpCallback,
  LPVOID lpContext,
  DWORD  dwFlags
);

Parameters

lpCallback
Address of a DDEnumCallbackEx function to be called with a description of each enumerated DirectDraw-enabled hardware abstraction layer (HAL).
lpContext
Address of an application-defined value to be passed to the enumeration callback function each time that it is called.
dwFlags
Flags specifying the enumeration scope. This parameter can be 0 or a combination of the following flags. If the value is 0, the function enumerates only the primary display device.
DDENUM_ATTACHEDSECONDARYDEVICES
The function enumerates the primary device and any display devices that are attached to the desktop.
DDENUM_DETACHEDSECONDARYDEVICES
The function enumerates the primary device and any display devices that are not attached to the desktop.
DDENUM_NONDISPLAYDEVICES
The function enumerates the primary device and any nondisplay devices, such as 3-D accelerators that have no 2-D capabilities.

Return Values

If the function succeeds, the return value is DD_OK.

If it fails, the function returns DDERR_INVALIDPARAMS.

Remarks

On systems with multiple monitors, this method enumerates multiple display devices. For more information, see Multiple-Monitor Systems.

For Windows 98, this function is supported in DirectX 5.0 and later; for all other operating systems, DirectX 6.0 is required. Retrieve the address of the DirectDrawEnumerateEx function from the Ddraw.dll dynamic-link library by calling the GetProcAddress Win32 function with the "DirectDrawEnumerateExA" (ANSI) or "DirectDrawEnumerateExW" (Unicode) process name strings. If GetProcAddress fails, the installed version of the operating system does not support multiple monitors. For more information, see Enumerating Devices on MultiMon Systems.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.
Import Library: Use ddraw.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.


Callback Functions

This section contains information about the following callback functions used with DirectDraw:

  • DDEnumCallback
  • DDEnumCallbackEx
  • EnumModesCallback
  • EnumModesCallback2
  • EnumSurfacesCallback
  • EnumSurfacesCallback2
  • EnumSurfacesCallback7
  • EnumVideoCallback


DDEnumCallback

The DDEnumCallback function is an application-defined callback function for the DirectDrawEnumerate function.

BOOL WINAPI DDEnumCallback(
  GUID FAR *lpGUID,
  LPSTR  lpDriverDescription,
  LPSTR  lpDriverName,
  LPVOID lpContext
);

Parameters

lpGUID
Address of the unique identifier of the DirectDraw object.
lpDriverDescription
Address of a string that contains the driver description.
lpDriverName
Address of a string that contains the driver name.
lpContext
Address of an application-defined structure to be passed to the callback function each time that the function is called.

Return Values

The callback function returns nonzero to continue the enumeration.

It returns zero to stop the enumeration.

Remarks

You can use the LPDDENUMCALLBACK data type to declare a variable that can contain a pointer to this callback function.

If UNICODE is defined, the string values are returned as type LPWSTR, rather than LPSTR.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.
Import Library: User-defined.


DDEnumCallbackEx

The DDEnumCallbackEx function is an application-defined callback function for the DirectDrawEnumerateEx function.

BOOL WINAPI DDEnumCallbackEx(
  GUID FAR *lpGUID,
  LPSTR     lpDriverDescription,
  LPSTR     lpDriverName,
  LPVOID    lpContext,
  HMONITOR  hm
);

Parameters

lpGUID
Address of the unique identifier of the DirectDraw object.
lpDriverDescription
Address of a string that contains the driver description.
lpDriverName
Address of a string that contains the driver name.
lpContext
Address of an application-defined structure to be passed to the callback function each time that the function is called.
hm
Handle of the monitor associated with the enumerated DirectDraw object. This parameter is NULL when the enumerated DirectDraw object is for the primary device, a nondisplay device (such as a 3-D accelerator with no 2-D capabilities), or devices not attached to the desktop.

Return Values

The callback function returns nonzero to continue the enumeration.

It returns 0 to stop the enumeration.

Remarks

After the DirectDrawEnumerateEx function completes, the pointer to the GUID is no longer valid. You must save a copy of the GUID structure itself, not the pointer, or the DirectDrawCreate function fails.

You can use the LPDDENUMCALLBACKEX data type to declare a variable that can contain a pointer to this callback function.

If UNICODE is defined, the string values are returned as type LPWSTR, rather than LPSTR.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in ddraw.h.
Import Library: User-defined.

See Also

Enumerating Devices on MultiMon Systems, Multiple-Monitor Systems


EnumModesCallback

The EnumModesCallback function is an application-defined callback function for the IDirectDraw3::EnumDisplayModes method and its counterparts in earlier interfaces.

This callback function is superseded by the EnumModesCallback2 function that is used with the IDirectDraw7::EnumDisplayModes method.

HRESULT WINAPI EnumModesCallback(
  LPDDSURFACEDESC lpDDSurfaceDesc,
  LPVOID lpContext
);

Parameters

lpDDSurfaceDesc
Address of a read-only DDSURFACEDESC structure that provides the monitor frequency and the mode that can be created.
lpContext
Address of an application-defined structure to be passed to the callback function each time that the function is called.

Return Values

The callback function returns DDENUMRET_OK to continue the enumeration.

It returns DDENUMRET_CANCEL to stop the enumeration.

Remarks

You can use the LPDDENUMMODESCALLBACK data type to declare a variable that can contain a pointer to this callback function.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.
Import Library: User-defined.


EnumModesCallback2

The EnumModesCallback2 function is an application-defined callback function for the IDirectDraw7::EnumDisplayModes method.

HRESULT WINAPI EnumModesCallback2(
  LPDDSURFACEDESC2 lpDDSurfaceDesc,
  LPVOID lpContext
);

Parameters

lpDDSurfaceDesc
Address of a read-only DDSURFACEDESC2 structure that provides the monitor frequency and the mode that can be created.
lpContext
Address of an application-defined structure to be passed to the callback function each time that the function is called.

Return Values

The callback function returns DDENUMRET_OK to continue the enumeration.

It returns DDENUMRET_CANCEL to stop the enumeration.

Remarks

You can use the LPDDENUMMODESCALLBACK2 data type to declare a variable that can contain a pointer to this callback function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.
Import Library: User-defined.


EnumSurfacesCallback

The EnumSurfacesCallback function is an application-defined callback function for the IDirectDraw2::EnumSurfaces, IDirectDrawSurface3::EnumAttachedSurfaces, and IDirectDrawSurface3::EnumOverlayZOrders methods (and the versions from earlier interfaces).

HRESULT WINAPI EnumSurfacesCallback(
  LPDIRECTDRAWSURFACE lpDDSurface,
  LPDDSURFACEDESC lpDDSurfaceDesc,
  LPVOID lpContext
);

Parameters

lpDDSurface
Address of the IDirectDrawSurface interface for the attached surface.
lpDDSurfaceDesc
Address of a DDSURFACEDESC structure that describes the attached surface.
lpContext
Address of an application-defined structure to be passed to the callback function each time that the function is called.

Return Values

The callback function returns DDENUMRET_OK to continue the enumeration.

It returns DDENUMRET_CANCEL to stop the enumeration.

Remarks

You can use the LPDDENUMSURFACESCALLBACK data type to declare a variable that can contain a pointer to this callback function.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.
Import Library: User-defined.


EnumSurfacesCallback2

The EnumSurfacesCallback2 function is an application-defined callback function for the IDirectDrawSurface4::EnumAttachedSurfaces and IDirectDrawSurface4::EnumOverlayZOrders methods.

HRESULT WINAPI EnumSurfacesCallback2(
  LPDIRECTDRAWSURFACE7 lpDDSurface,
  LPDDSURFACEDESC2 lpDDSurfaceDesc,
  LPVOID lpContext
);

Parameters

lpDDSurface
Address of the IDirectDrawSurface4 interface of the attached surface.
lpDDSurfaceDesc
Address of a DDSURFACEDESC2 structure that describes the attached surface.
lpContext
Address of an application-defined structure to be passed to the callback function each time that the function is called.

Return Values

The callback function returns DDENUMRET_OK to continue the enumeration.

It returns DDENUMRET_CANCEL to stop the enumeration.

Remarks

You can use the LPDDENUMSURFACESCALLBACK2 data type to declare a variable that can contain a pointer to this callback function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.
Import Library: User-defined.


EnumSurfacesCallback7

The EnumSurfacesCallback7 function is an application-defined callback function for the IDirectDrawSurface7::EnumAttachedSurfaces and IDirectDrawSurface7::EnumOverlayZOrders methods.

HRESULT WINAPI EnumSurfacesCallback7(
  LPDIRECTDRAWSURFACE7 lpDDSurface,
  LPDDSURFACEDESC2 lpDDSurfaceDesc,
  LPVOID lpContext
);

Parameters

lpDDSurface
Address of the IDirectDrawSurface7 interface of the attached surface.
lpDDSurfaceDesc
Address of a DDSURFACEDESC2 structure that describes the attached surface.
lpContext
Address of an application-defined structure to be passed to the callback function each time that the function is called.

Return Values

The callback function returns DDENUMRET_OK to continue the enumeration.

It returns DDENUMRET_CANCEL to stop the enumeration.

Remarks

You can use the LPDDENUMSURFACESCALLBACK7 data type to declare a variable that can contain a pointer to this callback function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.
Import Library: User-defined.


EnumVideoCallback

The EnumVideoCallback function is an application-defined callback function for the IDDVideoPortContainer::EnumVideoPorts method.

HRESULT WINAPI EnumVideoCallback(
  LPDDVIDEOPORTCAPS lpDDVideoPortCaps,
  LPVOID lpContext
);

Parameters

lpDDVideoPortCaps
Address of the DDVIDEOPORTCAPS structure that contains the video port information, including the ID and capabilities. This data is read-only.
lpContext
Address of a caller-defined structure that is passed to the member every time that it is called.

Return Values

The callback function returns DDENUMRET_OK to continue the enumeration.

It returns DDENUMRET_CANCEL to stop the enumeration.

Remarks

Video-port-related functions cannot be called from inside the EnumVideoCallback function. Attempts to do so fail, returning DDERR_CURRENTLYNOTAVAIL.

You can use the LPDDENUMVIDEOCALLBACK data type to declare a variable that can contain a pointer to this callback function.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.
Import Library: User-defined.


Structures

This section contains information about the following structures used with DirectDraw:

  • DDBLTBATCH
  • DDBLTFX
  • DDCAPS
  • DDCOLORCONTROL
  • DDCOLORKEY
  • DDDEVICEIDENTIFIER2
  • DDGAMMARAMP
  • DDOVERLAYFX
  • DDPIXELFORMAT
  • DDSCAPS
  • DDSCAPS2
  • DDSURFACEDESC
  • DDSURFACEDESC2
  • DDVIDEOPORTBANDWIDTH
  • DDVIDEOPORTCAPS
  • DDVIDEOPORTCONNECT
  • DDVIDEOPORTDESC
  • DDVIDEOPORTINFO
  • DDVIDEOPORTSTATUS

Note The memory for all DirectX structures should be initialized to 0 before the structure is used. In addition, all structures that contain a dwSize member should set the member to the size of the structure, in bytes, before the structure is used. The following example performs these tasks on a common structure, DDCAPS:

DDCAPS ddcaps; // Can't use this yet.

ZeroMemory(&ddcaps, sizeof(DDCAPS));
ddcaps.dwSize = sizeof(DDCAPS);

// Now the structure can be used.
.
.


DDBLTBATCH

The DDBLTBATCH structure passes bilt block transfer (blit) operations to the IDirectDrawSurface7::BltBatch method.

typedef struct _DDBLTBATCH{
    LPRECT              lprDest;
    LPDIRECTDRAWSURFACE lpDDSSrc;
    LPRECT              lprSrc;
    DWORD               dwFlags;
    LPDDBLTFX           lpDDBltFx;
} DDBLTBATCH,FAR *LPDDBLTBATCH;

Members

lprDest
Address of a RECT structure that defines the destination for the blit.
lpDDSSrc
Address of a DirectDrawSurface object to be the source of the blit.
lprSrc
Address of a RECT structure that defines the source rectangle of the blit.
dwFlags
Optional control flags. The following values are defined:
DDBLT_ALPHADEST
Uses either the alpha information in pixel format or the alpha channel surface attached to the destination surface as the alpha channel for this blit.
DDBLT_ALPHADESTCONSTOVERRIDE
Uses the dwAlphaDestConst member of the DDBLTFX structure as the alpha channel for the destination surface for this blit.
DDBLT_ALPHADESTNEG
The destination surface becomes more transparent as the alpha value increases (0 is opaque).
DDBLT_ALPHADESTSURFACEOVERRIDE
Uses the lpDDSAlphaDest member of the DDBLTFX structure as the alpha channel for the destination surface for this blit.
DDBLT_ALPHAEDGEBLEND
Uses the dwAlphaEdgeBlend member of the DDBLTFX structure as the alpha channel for the edges of the image that border the color key colors.
DDBLT_ALPHASRC
Uses either the alpha information in pixel format or the alpha channel surface attached to the source surface as the alpha channel for this blit.
DDBLT_ALPHASRCCONSTOVERRIDE
Uses the dwAlphaSrcConst member of the DDBLTFX structure as the source alpha channel for this blit.
DDBLT_ALPHASRCNEG
The source surface becomes more transparent as the alpha value increases (0 is opaque).
DDBLT_ALPHASRCSURFACEOVERRIDE
Uses the lpDDSAlphaSrc member of the DDBLTFX structure as the alpha channel source for this blit.
DDBLT_ASYNC
Processes this blit asynchronously through the first in, first out (FIFO) hardware in the order received. If there is no room in the FIFO hardware, the call fails.
DDBLT_COLORFILL
Uses the dwFillColor member of the DDBLTFX structure as the RGB color that fills the destination rectangle on the destination surface.
DDBLT_DDFX
Uses the dwDDFX member of the DDBLTFX structure to specify the effects to be used for this blit.
DDBLT_DDROPS
Uses the dwDDROP member of the DDBLTFX structure to specify the raster operations (ROPs) that are not part of the Win32 API.
DDBLT_KEYDEST
Uses the color key associated with the destination surface.
DDBLT_KEYDESTOVERRIDE
Uses the ddckDestColorkey member of the DDBLTFX structure as the color key for the destination surface.
DDBLT_KEYSRC
Uses the color key associated with the source surface.
DDBLT_KEYSRCOVERRIDE
Uses the ddckSrcColorkey member of the DDBLTFX structure as the color key for the source surface.
DDBLT_ROP
Uses the dwROP member of the DDBLTFX structure for the ROP for this blit. The ROPs are the same as those defined in the Win32 API.
DDBLT_ROTATIONANGLE
Uses the dwRotationAngle member of the DDBLTFX structure as the rotation angle (specified in 1/100s of a degree) for the surface.
DDBLT_ZBUFFER
Performs a z-buffered blit, using the z-buffers attached to the source and destination surfaces and the dwZBufferOpCode member of the DDBLTFX structure as the z-buffer opcode.
DDBLT_ZBUFFERDESTCONSTOVERRIDE
Performs a z-buffered blit, using the dwZDestConst and dwZBufferOpCode members of the DDBLTFX structure as the z-buffer and z-buffer opcode, respectively, for the destination.
DDBLT_ZBUFFERDESTOVERRIDE
Performs a z-buffered blit, using the lpDDSZBufferDest and dwZBufferOpCode members of the DDBLTFX structure as the z-buffer and z-buffer opcode, respectively, for the destination.
DDBLT_ZBUFFERSRCCONSTOVERRIDE
Performs a z-buffered blit, using the dwZSrcConst and dwZBufferOpCode members of the DDBLTFX structure as the z-buffer and z-buffer opcode, respectively, for the source.
DDBLT_ZBUFFERSRCOVERRIDE
Performs a z-buffered blit, using the lpDDSZBufferSrc and dwZBufferOpCode members of the DDBLTFX structure as the z-buffer and z-buffer opcode, respectively, for the source.
lpDDBltFx
Address of a DDBLTFX structure specifying additional blit effects.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.


DDBLTFX

The DDBLTFX structure passes raster operations (ROPs), effects, and override information to the IDirectDrawSurface7::Blt method. This structure is also part of the DDBLTBATCH structure used with the IDirectDrawSurface7::BltBatch method.

typedef struct _DDBLTFX{
    DWORD dwSize;
    DWORD dwDDFX;
    DWORD dwROP;
    DWORD dwDDROP;
    DWORD dwRotationAngle;
    DWORD dwZBufferOpCode;
    DWORD dwZBufferLow;
    DWORD dwZBufferHigh;
    DWORD dwZBufferBaseDest;
    DWORD dwZDestConstBitDepth;
    union
    {
        DWORD               dwZDestConst;
        LPDIRECTDRAWSURFACE lpDDSZBufferDest;
    } DUMMYUNIONNAMEN(1);
    DWORD dwZSrcConstBitDepth;
    union
    {
        DWORD               dwZSrcConst;
        LPDIRECTDRAWSURFACE lpDDSZBufferSrc;
    } DUMMYUNIONNAMEN(2);
    DWORD dwAlphaEdgeBlendBitDepth;
    DWORD dwAlphaEdgeBlend;
    DWORD dwReserved;
    DWORD dwAlphaDestConstBitDepth;
    union
    {
        DWORD               dwAlphaDestConst;
        LPDIRECTDRAWSURFACE lpDDSAlphaDest;
    } DUMMYUNIONNAMEN(3);
    DWORD dwAlphaSrcConstBitDepth;
    union
    {
        DWORD               dwAlphaSrcConst;
        LPDIRECTDRAWSURFACE lpDDSAlphaSrc;
    } DUMMYUNIONNAMEN(4);
    union
    {
        DWORD               dwFillColor;
        DWORD               dwFillDepth;
        DWORD               dwFillPixel;
        LPDIRECTDRAWSURFACE lpDDSPattern;
    } DUMMYUNIONNAMEN(5);
    DDCOLORKEY ddckDestColorkey;
    DDCOLORKEY ddckSrcColorkey;
} DDBLTFX,FAR* LPDDBLTFX;

Members

dwSize
Size of the structure, in bytes. This member must be initialized before the structure is used.
dwDDFX
Type of FX operations. The following types are defined:
DDBLTFX_ARITHSTRETCHY
Uses arithmetic stretching along the y-axis for this blit.
DDBLTFX_MIRRORLEFTRIGHT
Turns the surface on its y-axis. This blit mirrors the surface from left to right.
DDBLTFX_MIRRORUPDOWN
Turns the surface on its x-axis. This blit mirrors the surface from top to bottom.
DDBLTFX_NOTEARING
Schedules this blit to avoid tearing.
DDBLTFX_ROTATE180
Rotates the surface 180 degrees clockwise during this blit.
DDBLTFX_ROTATE270
Rotates the surface 270 degrees clockwise during this blit.
DDBLTFX_ROTATE90
Rotates the surface 90 degrees clockwise during this blit.
DDBLTFX_ZBUFFERBASEDEST
Adds the dwZBufferBaseDest member to each of the source z-values before comparing them with the destination z-values during this z-blit.
DDBLTFX_ZBUFFERRANGE
Uses the dwZBufferLow and dwZBufferHigh members as range values to specify limits to the bits copied from a source surface during this z-blit.
dwROP
Win32 raster operations. You can retrieve a list of supported raster operations by calling the IDirectDraw7::GetCaps method.
dwDDROP
DirectDraw raster operations.
dwRotationAngle
Rotation angle for the blit.
dwZBufferOpCode
Z-buffer compares.
dwZBufferLow
Low limit of a z-buffer.
dwZBufferHigh
High limit of a z-buffer.
dwZBufferBaseDest
Destination base value of a z-buffer.
dwZDestConstBitDepth
Bit depth of the destination z-constant.
dwZDestConst
Constant used as the z-buffer destination.
lpDDSZBufferDest
Surface used as the z-buffer destination.
dwZSrcConstBitDepth
Bit depth of the source z-constant.
dwZSrcConst
Constant used as the z-buffer source.
lpDDSZBufferSrc
Surface used as the z-buffer source.
dwAlphaEdgeBlendBitDepth
Bit depth of the constant for an alpha edge blend.
dwAlphaEdgeBlend
Alpha constant used for edge blending.
dwReserved
Reserved for future use.
dwAlphaDestConstBitDepth
Bit depth of the destination alpha constant.
dwAlphaDestConst
Constant used as the alpha channel destination.
lpDDSAlphaDest
Surface used as the alpha channel destination.
dwAlphaSrcConstBitDepth
Bit depth of the source alpha constant.
dwAlphaSrcConst
Constant used as the alpha channel source.
lpDDSAlphaSrc
Surface used as the alpha channel source.
dwFillColor
Color used to fill a surface when DDBLT_COLORFILL is specified. This value must be a pixel appropriate to the pixel format of the destination surface. For a palettized surface, it would be a palette index, and for a 16-bit RGB surface, it would be a 16-bit pixel value.
dwFillDepth
Depth value for the z-buffer.
dwFillPixel
Pixel value for RGBA or RGBZ fills. Applications that use RGBZ fills should use this member, not dwFillColor or dwFillDepth.
lpDDSPattern
Surface to use as a pattern. The pattern can be used in certain blit operations that combine a source and a destination.
ddckDestColorkey
Destination color key override.
ddckSrcColorkey
Source color key override.

Remarks

The unions in this structure have been updated to work with compilers that do not support nameless unions. If your compiler does not support nameless unions, define the NONAMELESSUNION token before including the Ddraw.h header file.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.


DDCAPS

The DDCAPS structure represents the capabilities of the hardware exposed through the DirectDraw object. This structure contains a DDSCAPS structure used in this context to describe what kinds of DirectDrawSurface objects can be created. It might not be possible to create all the surfaces described by these capabilities simultaneously. This structure is used with the IDirectDraw7::GetCaps method.

The Ddraw.h header file contains multiple versions of this structure. For more information, see Remarks.

typedef struct _DDCAPS {
    DWORD    dwSize;
    DWORD    dwCaps;
    DWORD    dwCaps2;
    DWORD    dwCKeyCaps;
    DWORD    dwFXCaps;
    DWORD    dwFXAlphaCaps;
    DWORD    dwPalCaps;
    DWORD    dwSVCaps;
    DWORD    dwAlphaBltConstBitDepths;
    DWORD    dwAlphaBltPixelBitDepths;
    DWORD    dwAlphaBltSurfaceBitDepths;
    DWORD    dwAlphaOverlayConstBitDepths;
    DWORD    dwAlphaOverlayPixelBitDepths;
    DWORD    dwAlphaOverlaySurfaceBitDepths;
    DWORD    dwZBufferBitDepths;
    DWORD    dwVidMemTotal;
    DWORD    dwVidMemFree;
    DWORD    dwMaxVisibleOverlays;
    DWORD    dwCurrVisibleOverlays;
    DWORD    dwNumFourCCCodes;
    DWORD    dwAlignBoundarySrc;
    DWORD    dwAlignSizeSrc;
    DWORD    dwAlignBoundaryDest;
    DWORD    dwAlignSizeDest;
    DWORD    dwAlignStrideAlign;
    DWORD    dwRops[DD_ROP_SPACE];
    DDSCAPS  ddsOldCaps;
    DWORD    dwMinOverlayStretch;
    DWORD    dwMaxOverlayStretch;
    DWORD    dwMinLiveVideoStretch;
    DWORD    dwMaxLiveVideoStretch;
    DWORD    dwMinHwCodecStretch;
    DWORD    dwMaxHwCodecStretch;
    DWORD    dwReserved1;
    DWORD    dwReserved2;
    DWORD    dwReserved3;
    DWORD    dwSVBCaps;
    DWORD    dwSVBCKeyCaps;
    DWORD    dwSVBFXCaps;
    DWORD    dwSVBRops[DD_ROP_SPACE];
    DWORD    dwVSBCaps;
    DWORD    dwVSBCKeyCaps;
    DWORD    dwVSBFXCaps;
    DWORD    dwVSBRops[DD_ROP_SPACE];
    DWORD    dwSSBCaps;
    DWORD    dwSSBCKeyCaps;
    DWORD    dwSSBFXCaps;
    DWORD    dwSSBRops[DD_ROP_SPACE];
    DWORD    dwMaxVideoPorts;
    DWORD    dwCurrVideoPorts;
    DWORD    dwSVBCaps2;
    DWORD    dwNLVBCaps;
    DWORD    dwNLVBCaps2;
    DWORD    dwNLVBCKeyCaps;
    DWORD    dwNLVBFXCaps;
    DWORD    dwNLVBRops[DD_ROP_SPACE];
    DDSCAPS2 ddsCaps;
} DDCAPS,FAR* LPDDCAPS;

Members

dwSize
Size of the structure, in bytes. This member must be initialized before the structure is used.
dwCaps
The following driver-specific capabilities:
DDCAPS_3D
The display hardware has 3-D acceleration.
DDCAPS_ALIGNBOUNDARYDEST
DirectDraw supports only those overlay destination rectangles with the x-axis aligned to the dwAlignBoundaryDest boundaries of the surface.
DDCAPS_ALIGNBOUNDARYSRC
DirectDraw supports only those overlay source rectangles with the x-axis aligned to the dwAlignBoundarySrc boundaries of the surface.
DDCAPS_ALIGNSIZEDEST
DirectDraw supports only those overlay destination rectangles whose x-axis sizes, in pixels, are dwAlignSizeDest multiples.
DDCAPS_ALIGNSIZESRC
DirectDraw supports only those overlay source rectangles whose x-axis sizes, in pixels, are dwAlignSizeSrc multiples.
DDCAPS_ALIGNSTRIDE
DirectDraw creates display memory surfaces that have a stride alignment equal to the dwAlignStrideAlign value.
DDCAPS_ALPHA
The display hardware supports alpha-only surfaces. (See alpha channel)
DDCAPS_BANKSWITCHED
The display hardware is bank-switched and is potentially very slow at random access to display memory.
DDCAPS_BLT
Display hardware is capable of blit operations.
DDCAPS_BLTCOLORFILL
Display hardware is capable of color filling with a blitter.
DDCAPS_BLTDEPTHFILL
Display hardware is capable of depth filling z-buffers with a blitter.
DDCAPS_BLTFOURCC
Display hardware is capable of color-space conversions during blit operations.
DDCAPS_BLTQUEUE
Display hardware is capable of asynchronous blit operations.
DDCAPS_BLTSTRETCH
Display hardware is capable of stretching during blit operations.
DDCAPS_CANBLTSYSMEM
Display hardware is capable of blitting to or from system memory.
DDCAPS_CANCLIP
Display hardware is capable of clipping with blitting.
DDCAPS_CANCLIPSTRETCHED
Display hardware is capable of clipping while stretch blitting.
DDCAPS_COLORKEY
Supports some form of color key in either overlay or blit operations. More specific color-key capability information can be found in the dwCKeyCaps member.
DDCAPS_COLORKEYHWASSIST
The color key is partially hardware-assisted. This means that other resources (CPU or video memory) might be used. If this bit is not set, full hardware support is in place.
DDCAPS_GDI
Display hardware is shared with GDI.
DDCAPS_NOHARDWARE
There is no hardware support.
DDCAPS_OVERLAY
Display hardware supports overlays.
DDCAPS_OVERLAYCANTCLIP
Display hardware supports overlays but cannot clip them.
DDCAPS_OVERLAYFOURCC
Overlay hardware is capable of color-space conversions during overlay operations.
DDCAPS_OVERLAYSTRETCH
Overlay hardware is capable of stretching. The dwMinOverlayStretch and dwMaxOverlayStretch members contain valid data.
DDCAPS_PALETTE
DirectDraw is capable of creating and supporting DirectDrawPalette objects for surfaces other than the primary surface.
DDCAPS_PALETTEVSYNC
DirectDraw is capable of updating a palette synchronized with the vertical refresh.
DDCAPS_READSCANLINE
Display hardware is capable of returning the current scan line.
DDCAPS_VBI
Display hardware is capable of generating a vertical-blank interrupt.
DDCAPS_ZBLTS
Supports the use of z-buffers with blit operations.
DDCAPS_ZOVERLAYS
Supports the use of the IDirectDrawSurface7::UpdateOverlayZOrder method as a z-value for overlays to control their layering.
dwCaps2
The following driver-specific capabilities:
DDCAPS2_AUTOFLIPOVERLAY
The overlay can be automatically flipped to the next surface in the flipping chain each time that a video port VSYNC occurs, allowing the video port and the overlay to double-buffer the video without CPU overhead. This option is only valid when the surface is receiving data from a video port. If the video port data is noninterlaced or noninterleaved, it flips on every VSYNC. If the data is being interleaved in memory, it flips on every other VSYNC.
DDCAPS2_CANBOBHARDWARE
The overlay hardware can display each field of an interlaced video stream individually.
DDCAPS2_CANBOBINTERLEAVED
The overlay hardware can display each field of an interlaced video stream individually while it is interleaved in memory without causing any artifacts that might normally occur without special hardware support. This option is only valid when the surface is receiving data from a video port and the video is zoomed at least twice in the vertical direction.
DDCAPS2_CANBOBNONINTERLEAVED
The overlay hardware can display each field of an interlaced video stream individually while it is not interleaved in memory without causing any artifacts that might normally occur without special hardware support. This option is only valid when the surface is receiving data from a video port and the video is zoomed at least twice in the vertical direction.
DDCAPS2_CANCALIBRATEGAMMA
The system has a calibrator installed that can automatically adjust the gamma ramp so that the result is identical on all systems that have a calibrator. To invoke the calibrator when setting new gamma levels, use the DDSGR_CALIBRATE flag when calling the IDirectDrawGammaControl::SetGammaRamp method. Calibrating gamma ramps incurs some processing overhead and should not be used frequently.
DDCAPS2_CANDROPZ16BIT
Sixteen-bit RGBZ values can be converted into 16-bit RGB values. (The system does not support 8-bit conversions.)
DDCAPS2_CANFLIPODDEVEN
The driver is capable of performing odd and even flip operations, as specified by the DDFLIP_ODD and DDFLIP_EVEN flags used with the IDirectDrawSurface7::Flip method.
DDCAPS2_CANMANAGETEXTURE
The Direct3D texture manager uses this capability to decide whether to put managed surfaces in nonlocal video memory. If the capability is set, the texture manager puts managed surfaces in nonlocal video memory. Drivers that cannot texture from local video memory should not set this capability.
DDCAPS2_CANRENDERWINDOWED
The driver is capable of rendering in windowed mode.
DDCAPS2_CERTIFIED
Display hardware is certified.
DDCAPS2_COLORCONTROLPRIMARY
The primary surface contains color controls (for instance, gamma)
DDCAPS2_COLORCONTROLOVERLAY
The overlay surface contains color controls (such as brightness and sharpness)
DDCAPS2_COPYFOURCC
The driver supports blitting any FOURCC surface to another surface of the same FOURCC.
DDCAPS2_FLIPINTERVAL
The driver responds to the DDFLIP_INTERVAL* flags. (see IDirectDrawSurface7::Flip).
DDCAPS2_FLIPNOVSYNC
The driver responds to the DDFLIP_NOVSYNC flag (see IDirectDrawSurface7::Flip).
DDCAPS2_NO2DDURING3DSCENE
Two-dimensional operations such as IDirectDrawSurface7::Blt and IDirectDrawSurface7::Lock cannot be performed on any surfaces that Direct3D is using between calls to the IDirect3DDevice7::BeginScene and IDirect3DDevice7::EndScene methods.
DDCAPS2_NONLOCALVIDMEM
The display driver supports surfaces in nonlocal video memory.
DDCAPS2_NONLOCALVIDMEMCAPS
Blit capabilities for nonlocal video-memory surfaces differ from local video-memory surfaces. If this flag is present, the DDCAPS2_NONLOCALVIDMEM flag is also present.
DDCAPS2_NOPAGELOCKREQUIRED
DMA blit operations are supported on system-memory surfaces that are not page-locked.
DDCAPS2_PRIMARYGAMMA
Supports dynamic gamma ramps for the primary surface. For more information, see Gamma and Color Controls.
DDCAPS2_STEREO
New for DirectX 7.0. Turns on the ddcaps.dwSVCaps bit to support stereo mode. The driver can do stereo in at least one mode other than the current mode. The application can use IDirectDraw7::GetDisplayMode or IDirectDraw7::EnumDisplayModes to get per-mode stereo information.
DDCAPS2_TEXMANINNONLOCALVIDMEM
New for DirectX 7.0. The Direct3D texture manager uses this capability to decide whether to put managed surfaces in nonlocal video memory. If the capability is set, the texture manager puts managed surfaces in nonlocal video memory. Drivers that cannot texture from local video memory should not set this capability.
DDCAPS2_VIDEOPORT
Display hardware supports live video.
DDCAPS2_WIDESURFACES
The display surface supports surfaces wider than the primary surface.
dwCKeyCaps
The following color-key capabilities:
DDCKEYCAPS_DESTBLT
Supports transparent blitting with a color key that identifies the replaceable bits of the destination surface for RGB colors.
DDCKEYCAPS_DESTBLTCLRSPACE
Supports transparent blitting with a color space that identifies the replaceable bits of the destination surface for RGB colors.
DDCKEYCAPS_DESTBLTCLRSPACEYUV
Supports transparent blitting with a color space that identifies the replaceable bits of the destination surface for YUV colors.
DDCKEYCAPS_DESTBLTYUV
Supports transparent blitting with a color key that identifies the replaceable bits of the destination surface for YUV colors.
DDCKEYCAPS_DESTOVERLAY
Supports overlaying with color keying of the replaceable bits of the destination surface to be overlaid for RGB colors.
DDCKEYCAPS_DESTOVERLAYCLRSPACE
Supports a color space as the color key for the destination of RGB colors.
DDCKEYCAPS_DESTOVERLAYCLRSPACEYUV
Supports a color space as the color key for the destination of YUV colors.
DDCKEYCAPS_DESTOVERLAYONEACTIVE
Supports only one active destination color key value for visible overlay surfaces .
DDCKEYCAPS_DESTOVERLAYYUV
Supports overlaying, using color keying of the replaceable bits of the destination surface to be overlaid for YUV colors.
DDCKEYCAPS_NOCOSTOVERLAY
Indicates that there are no bandwidth trade-offs for using the color key with an overlay.
DDCKEYCAPS_SRCBLT
Supports transparent blitting, using the color key for the source with this surface for RGB colors.
DDCKEYCAPS_SRCBLTCLRSPACE
Supports transparent blitting, using a color space for the source with this surface for RGB colors.
DDCKEYCAPS_SRCBLTCLRSPACEYUV
Supports transparent blitting, using a color space for the source with this surface for YUV colors.
DDCKEYCAPS_SRCBLTYUV
Supports transparent blitting, using the color key for the source with this surface for YUV colors.
DDCKEYCAPS_SRCOVERLAY
Supports overlaying, using the color key for the source with this overlay surface for RGB colors.
DDCKEYCAPS_SRCOVERLAYCLRSPACE
Supports overlaying, using a color space as the source color key for the overlay surface for RGB colors.
DDCKEYCAPS_SRCOVERLAYCLRSPACEYUV
Supports overlaying, using a color space as the source color key for the overlay surface for YUV colors.
DDCKEYCAPS_SRCOVERLAYONEACTIVE
Supports only one active source color key value for visible overlay surfaces.
DDCKEYCAPS_SRCOVERLAYYUV
Supports overlaying, using the color key for the source with this overlay surface for YUV colors.
dwFXCaps
The following driver-specific stretching and effects capabilities:
DDFXCAPS_BLTALPHA
Supports alpha-blended blit operations.
DDFXCAPS_BLTARITHSTRETCHY
Uses arithmetic operations, rather than pixel-doubling techniques, to stretch and shrink surfaces during a blit operation. Occurs along the y-axis (vertically).
DDFXCAPS_BLTARITHSTRETCHYN
Uses arithmetic operations, rather than pixel-doubling techniques, to stretch and shrink surfaces during a blit operation. Occurs along the y-axis (vertically), and works only for integer stretching (×1, ×2, and so on).
DDFXCAPS_BLTFILTER
Driver can do surface-reconstruction filtering for warped blits.
DDFXCAPS_BLTMIRRORLEFTRIGHT
Supports mirroring left to right in a blit operation.
DDFXCAPS_BLTMIRRORUPDOWN
Supports mirroring top to bottom in a blit operation.
DDFXCAPS_BLTROTATION
Supports arbitrary rotation in a blit operation.
DDFXCAPS_BLTROTATION90
Supports 90-degree rotations in a blit operation.
DDFXCAPS_BLTSHRINKX
Supports arbitrary shrinking of a surface along the x-axis (horizontally). This flag is valid only for blit operations.
DDFXCAPS_BLTSHRINKXN
Supports integer shrinking (×1, ×2, and so on) of a surface along the x-axis (horizontally). This flag is valid only for blit operations.
DDFXCAPS_BLTSHRINKY
Supports arbitrary shrinking of a surface along the y-axis (vertically). This flag is valid only for blit operations.
DDFXCAPS_BLTSHRINKYN
Supports integer shrinking (×1, ×2, and so on) of a surface along the y-axis (vertically). This flag is valid only for blit operations.
DDFXCAPS_BLTSTRETCHX
Supports arbitrary stretching of a surface along the x-axis (horizontally). This flag is valid only for blit operations.
DDFXCAPS_BLTSTRETCHXN
Supports integer stretching (×1, ×2, and so on) of a surface along the x-axis (horizontally). This flag is valid only for blit operations.
DDFXCAPS_BLTSTRETCHY
Supports arbitrary stretching of a surface along the y-axis (vertically). This flag is valid only for blit operations.
DDFXCAPS_BLTSTRETCHYN
Supports integer stretching (×1, ×2, and so on) of a surface along the y-axis (vertically). This flag is valid only for blit operations.
DDFXCAPS_BLTTRANSFORM
Supports geometric transformations (or warps) for blitted sprites. Transformations are not currently supported for explicit blit operations.
DDFXCAPS_OVERLAYALPHA
Supports alpha blending for overlay surfaces.
DDFXCAPS_OVERLAYARITHSTRETCHY
Uses arithmetic operations, rather than pixel-doubling techniques, to stretch and shrink overlay surfaces. Occurs along the y-axis (vertically).
DDFXCAPS_OVERLAYARITHSTRETCHYN
Uses arithmetic operations, rather than pixel-doubling techniques, to stretch and shrink overlay surfaces. Occurs along the y-axis (vertically), and works only for integer stretching (×1, ×2, and so on).
DDFXCAPS_OVERLAYFILTER
Supports surface-reconstruction filtering for warped overlay sprites. Filtering is not currently supported for explicitly displayed overlay surfaces (those displayed with calls to IDirectDrawSurface7::UpdateOverlay).
DDFXCAPS_OVERLAYMIRRORLEFTRIGHT
Supports mirroring of overlays across the vertical axis.
DDFXCAPS_OVERLAYMIRRORUPDOWN
Supports mirroring of overlays across the horizontal axis.
DDFXCAPS_OVERLAYSHRINKX
Supports arbitrary shrinking of a surface along the x-axis (horizontally). This flag is valid only for DDSCAPS_OVERLAY surfaces. This flag indicates only the capabilities of a surface; it does not indicate that shrinking is available.
DDFXCAPS_OVERLAYSHRINKXN
Supports integer shrinking (×1, ×2, and so on) of a surface along the x-axis (horizontally). This flag is valid only for DDSCAPS_OVERLAY surfaces. This flag indicates only the capabilities of a surface; it does not indicate that shrinking is available.
DDFXCAPS_OVERLAYSHRINKY
Supports arbitrary shrinking of a surface along the y-axis (vertically). This flag is valid only for DDSCAPS_OVERLAY surfaces. This flag indicates only the capabilities of a surface; it does not indicate that shrinking is available.
DDFXCAPS_OVERLAYSHRINKYN
Supports integer shrinking (×1, ×2, and so on) of a surface along the y-axis (vertically). This flag is valid only for DDSCAPS_OVERLAY surfaces. This flag indicates only the capabilities of a surface; it does not indicate that shrinking is available.
DDFXCAPS_OVERLAYSTRETCHX
Supports arbitrary stretching of a surface along the x-axis (horizontally). This flag is valid only for DDSCAPS_OVERLAY surfaces. This flag indicates only the capabilities of a surface; it does not indicate that stretching is available.
DDFXCAPS_OVERLAYSTRETCHXN
Supports integer stretching (×1, ×2, and so on) of a surface along the x-axis (horizontally). This flag is valid only for DDSCAPS_OVERLAY surfaces. This flag indicates only the capabilities of a surface; it does not indicate that stretching is available.
DDFXCAPS_OVERLAYSTRETCHY
Supports arbitrary stretching of a surface along the y-axis (vertically). This flag is valid only for DDSCAPS_OVERLAY surfaces. This flag indicates only the capabilities of a surface; it does not indicate that stretching is available.
DDFXCAPS_OVERLAYSTRETCHYN
Supports integer stretching (×1, ×2, and so on) of a surface along the y-axis (vertically). This flag is valid only for DDSCAPS_OVERLAY surfaces. This flag indicates only the capabilities of a surface; it does not indicate that stretching is available.
DDFXCAPS_OVERLAYTRANSFORM
Supports geometric transformations (or warps) for overlay sprites. Transformations are not currently supported for explicitly displayed overlay surfaces (those displayed with calls to IDirectDrawSurface7::UpdateOverlay).
dwFXAlphaCaps
The following driver-specific alpha capabilities:
DDFXALPHACAPS_BLTALPHAEDGEBLEND
Supports alpha blending around the edge of a source color-keyed surface. Used for blit operations.
DDFXALPHACAPS_BLTALPHAPIXELS
Supports alpha information in pixel format. The bit depth of alpha information in the pixel format can be 1, 2, 4, or 8. The alpha value becomes more opaque as the alpha value increases. Regardless of the depth of the alpha information, 0 is always the fully transparent value. Used for blit operations.
DDFXALPHACAPS_BLTALPHAPIXELSNEG
Supports alpha information in pixel format. The bit depth of alpha information in the pixel format can be 1, 2, 4, or 8. The alpha value becomes more transparent as the alpha value increases. Regardless of the depth of the alpha information, 0 is always the fully opaque value. This flag can be used only if DDCAPS_ALPHA is set. Used for blit operations.
DDFXALPHACAPS_BLTALPHASURFACES
Supports alpha-only surfaces. The bit depth of an alpha-only surface can be 1, 2, 4, or 8. The alpha value becomes more opaque as the alpha value increases. Regardless of the depth of the alpha information, 0 is always the fully transparent value. Used for blit operations.
DDFXALPHACAPS_BLTALPHASURFACESNEG
Indicates that the alpha channel becomes more transparent as the alpha value increases. The depth of the alpha channel-data can be 1, 2, 4, or 8. Regardless of the depth of the alpha information, 0 is always the fully opaque value. This flag can be set only if DDCAPS_ALPHA has been set. Used for blit operations.
DDFXALPHACAPS_OVERLAYALPHAEDGEBLEND
Supports alpha blending around the edge of a source color-keyed surface. Used for overlays.
DDFXALPHACAPS_OVERLAYALPHAPIXELS
Supports alpha information in pixel format. The bit depth of alpha information in pixel format can be 1, 2, 4, or 8. The alpha value becomes more opaque as the alpha value increases. Regardless of the depth of the alpha information, 0 is always the fully transparent value. Used for overlays.
DDFXALPHACAPS_OVERLAYALPHAPIXELSNEG
Supports alpha information in pixel format. The bit depth of alpha information in pixel format can be 1, 2, 4, or 8. The alpha value becomes more transparent as the alpha value increases. Regardless of the depth of the alpha information, 0 is always the fully opaque value. This flag can be used only if DDCAPS_ALPHA has been set. Used for overlays.
DDFXALPHACAPS_OVERLAYALPHASURFACES
Supports alpha-only surfaces. The bit depth of an alpha-only surface can be 1, 2, 4, or 8. The alpha value becomes more opaque as the alpha value increases. Regardless of the depth of the alpha information, 0 is always the fully transparent value. Used for overlays.
DDFXALPHACAPS_OVERLAYALPHASURFACESNEG
Indicates that the alpha channel becomes more transparent as the alpha value increases. The depth of the alpha-channel data can be 1, 2, 4, or 8. Regardless of the depth of the alpha information, 0 is always the fully opaque value. This flag can be used only if DDCAPS_ALPHA has been set. Used for overlays.
dwPalCaps
The following palette capabilities:
DDPCAPS_1BIT
Supports palettes that contain 1-bit color entries (two colors).
DDPCAPS_2BIT
Supports palettes that contain 2-bit color entries (four colors).
DDPCAPS_4BIT
Supports palettes that contain 4-bit color entries (16 colors).
DDPCAPS_8BIT
Supports palettes that contain 8-bit color entries (256 colors).
DDPCAPS_8BITENTRIES
Specifies an index to an 8-bit color index. This field is valid only when used with the DDPCAPS_1BIT, DDPCAPS_2BIT, or DDPCAPS_4BIT capability and when the target surface is 8 bits per pixel (bpp). Each color entry is 1 byte long and is an index to an 8-bpp palette on the destination surface.
DDPCAPS_ALPHA
Supports palettes that include an alpha component. For alpha-capable palettes, the peFlags member of each PALETTEENTRY structure that the palette contains is to be interpreted as a single 8-bit alpha value (in addition to the color data in the peRed, peGreen, and peBlue members). A palette created with this flag can be attached only to a texture surface.
DDPCAPS_ALLOW256
Supports palettes that can have all 256 entries defined.
DDPCAPS_PRIMARYSURFACE
The palette is attached to the primary surface. Changing the palette has an immediate effect on the display unless the DDPCAPS_VSYNC capability is specified and supported.
DDPCAPS_PRIMARYSURFACELEFT
The palette is attached to the primary surface on the left. Changing the palette has an immediate effect on the display unless the DDPCAPS_VSYNC capability is specified and supported.
DDPCAPS_VSYNC
The palette can be modified synchronously with the monitor's refresh rate.
dwSVCaps
The following stereo-vision capabilities:
DDSVCAPS_RESERVED1, DDSVCAPS_RESERVED2, DDSVCAPS_RESERVED3, DDSVCAPS_RESERVED4
Reserved flags.
DDSVCAPS_STEREOSEQUENTIAL
New for DirectX 7.0. The driver can do stereo in at least one mode other than the current mode. The application can use IDirectDraw7::GetDisplayMode or IDirectDraw7::EnumDisplayModes to get per-mode stereo information.
dwAlphaBltConstBitDepths
DDBD_2, DDBD_4, or DDBD_8. (Indicate 2, 4, or 8 bits per pixel.)
dwAlphaBltPixelBitDepths
DDBD_1, DDBD_2, DDBD_4, or DDBD_8. (Indicate 1, 2, 4, or 8 bits per pixel.)
dwAlphaBltSurfaceBitDepths
DDBD_1, DDBD_2, DDBD_4, or DDBD_8. (Indicate 1, 2, 4, or 8 bits per pixel.)
dwAlphaOverlayConstBitDepths
DDBD_2, DDBD_4, or DDBD_8. (Indicate 2, 4, or 8 bits per pixel.)
dwAlphaOverlayPixelBitDepths
DDBD_1, DDBD_2, DDBD_4, or DDBD_8. (Indicate 1, 2, 4, or 8 bits per pixel.)
dwAlphaOverlaySurfaceBitDepths
DDBD_1, DDBD_2, DDBD_4, or DDBD_8. (Indicate 1, 2, 4, or 8 bits per pixel.)
dwZBufferBitDepths
DDBD_8, DDBD_16, DDBD_24, or DDBD_32. (Indicate 8, 16, 24, or 32 bits per pixel.) This member is obsolete for DirectX 6.0 and later. Use the IDirect3D7::EnumZBufferFormats to retrieve information about supported depth buffer formats.
dwVidMemTotal
Total amount of display memory on the device, in bytes, minus memory reserved for the primary surface and any private data structures reserved by the driver. (This value is the same as the total video memory reported by the IDirectDraw7::GetAvailableVidMem method.)
dwVidMemFree
Free display memory. This value equals the value in dwVidMemTotal, minus any memory currently allocated by the application for surfaces. Unlike the GetAvailableVidMem method, which reports the memory available for a particular type of surface (such as a texture), this value reflects the memory available for any type of surface.
dwMaxVisibleOverlays
Maximum number of visible overlays or overlay sprites.
dwCurrVisibleOverlays
Current number of visible overlays or overlay sprites.
dwNumFourCCCodes
Number of FourCC codes.
dwAlignBoundarySrc
Source-rectangle alignment for an overlay surface, in pixels.
dwAlignSizeSrc
Source-rectangle size alignment for an overlay surface, in pixels. Overlay source rectangles must have a pixel width that is a multiple of this value.
dwAlignBoundaryDest
Destination-rectangle alignment for an overlay surface, in pixels.
dwAlignSizeDest
Destination-rectangle size alignment for an overlay surface, in pixels. Overlay destination rectangles must have a pixel width that is a multiple of this value.
dwAlignStrideAlign
Stride alignment.
dwRops[DD_ROP_SPACE]
Raster operations supported.
ddsOldCaps
Obsolete. Prior to DirectX 6.0, this member contained general surface capabilities, which are now contained in the ddsCaps member (a DDSCAPS2 structure).
dwMinOverlayStretch and dwMaxOverlayStretch
Minimum and maximum overlay stretch factors, multiplied by 1000. For example, 1.3 = 1300.
dwMinLiveVideoStretch and dwMaxLiveVideoStretch
Obsolete; do not use.
dwMinHwCodecStretch and dwMaxHwCodecStretch
Obsolete; do not use.
dwReserved1, dwReserved2, and dwReserved3
Reserved for future use.
dwSVBCaps
Driver-specific capabilities for blits from system memory to display memory. Valid flags are identical to the blit-related flags used with the dwCaps member.
dwSVBCKeyCaps
Driver color-key capabilities for blits from system memory to display memory. Valid flags are identical to the blit-related flags used with the dwCKeyCaps member.
dwSVBFXCaps
Driver FX capabilities for blits from system memory to display memory. Valid flags are identical to the blit-related flags used with the dwFXCaps member.
dwSVBRops[DD_ROP_SPACE]
Raster operations supported for blits from system memory to display memory.
dwVSBCaps
Driver-specific capabilities for blits from display memory to system memory. Valid flags are identical to the blit-related flags used with the dwCaps member.
dwVSBCKeyCaps
Driver color-key capabilities for blits from display memory to system memory. Valid flags are identical to the blit-related flags used with the dwCKeyCaps member.
dwVSBFXCaps
Driver FX capabilities for blits from display memory to system memory. Valid flags are identical to the blit-related flags used with the dwFXCaps member.
dwVSBRops[DD_ROP_SPACE]
Raster operations supported for blits from display memory to system memory.
dwSSBCaps
Driver-specific capabilities for blits from system memory to system memory. Valid flags are identical to the blit-related flags used with the dwCaps member.
dwSSBCKeyCaps
Driver color-key capabilities for blits from system memory to system memory. Valid flags are identical to the blit-related flags used with the dwCKeyCaps member.
dwSSBFXCaps
Driver FX capabilities for blits from system memory to system memory. Valid flags are identical to the blit-related flags used with the dwFXCaps member.
dwSSBRops[DD_ROP_SPACE]
Raster operations supported for blits from system memory to system memory.
dwMaxVideoPorts
Maximum number of live video ports.
dwCurrVideoPorts
Current number of live video ports.
dwSVBCaps2
More driver-specific capabilities for blits from system memory to video memory. Valid flags are identical to the blit-related flags used with the dwCaps2 member.
dwNLVBCaps
Driver-specific capabilities for blits from nonlocal to local video memory. Valid flags are identical to the blit-related flags used with the dwCaps member.
dwNLVBCaps2
More driver-specific capabilities for blits from nonlocal to local video memory. Valid flags are identical to the blit-related flags used with the dwCaps2 member.
dwNLVBCKeyCaps
Driver color-key capabilities for blits form nonlocal to local video memory. Valid flags are identical to the blit-related flags used with the dwCKeyCaps member.
dwNLVBFXCaps
Driver FX capabilities for blits from nonlocal to local video memory. Valid flags are identical to the blit-related flags used with the dwFXCaps member.
dwNLVBRops[DD_ROP_SPACE]
Raster operations supported for blits from nonlocal to local video memory.
ddsCaps
DDSCAPS2 structure with general surface capabilities.

Remarks

For backward compatibility, the Ddraw.h header file contains multiple definitions of the DDCAPS structure. The version that passes the preprocessor is determined by the value of the DIRECTDRAW_VERSION constant. For details, see Component Version Constants.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.


DDCOLORCONTROL

The DDCOLORCONTROL structure defines the color controls associated with a DirectDrawVideoPortObject, an overlay surface, or a primary surface.

typedef struct _DDCOLORCONTROL {
    DWORD   dwSize;
    DWORD   dwFlags;
    LONG    lBrightness;
    LONG    lContrast;
    LONG    lHue;
    LONG    lSaturation;
    LONG    lSharpness;
    LONG    lGamma;
    LONG    lColorEnable;
    DWORD   dwReserved1;
} DDCOLORCONTROL, FAR *LPDDCOLORCONTROL;

Members

dwSize
Size of the structure, in bytes. This member must be initialized before the structure can be used.
dwFlags
The following flags specifying which structure members contain valid data . When the structure is returned by the IDirectDrawColorControl::GetColorControls method, it also indicates which options are supported by the device.
DDCOLOR_BRIGHTNESS
The lBrightness member contains valid data.
DDCOLOR_COLORENABLE
The lColorEnable member contains valid data.
DDCOLOR_CONTRAST
The lContrast member contains valid data.
DDCOLOR_GAMMA
The lGamma member contains valid data.
DDCOLOR_HUE
The lHue member contains valid data.
DDCOLOR_SATURATION
The lSaturation member contains valid data.
DDCOLOR_SHARPNESS
The lSharpness member contains valid data.
lBrightness
Luminance intensity, in IRE units times 100. The valid range is from 0 through 10,000. The default is 750, which translates to 7.5 IRE.
lContrast
Relative difference between higher and lower intensity luminance values in IRE units times 100. The valid range is from 0 through 20,000. The default value is 10,000 (100 IRE). Higher values of contrast cause darker luminance values to tend toward black and lighter luminance values to tend toward white. Lower values of contrast cause all luminance values to move toward the middle of the scale.
lHue
Phase relationship of the chrominance components. Hue is specified in degrees, and the valid range is from –180 through 180, with a default of 0.
lSaturation
Color intensity, in IRE units times 100. The valid range is from 0 through 20,000. The default value is 10,000, which translates to 100 IRE.
lSharpness
Sharpness, in arbitrary units. The valid range is from 0 through 10, with a default of 5.
lGamma
Controls the amount of gamma correction applied to the luminance values. The valid range is from 1 through 500 gamma units, with a default of 1.
lColorEnable
Flag indicating whether color is used. If this member is 0, color is not used; if it is 1, color is used. The default value is 1.
dwReserved1
Reserved.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.


DDCOLORKEY

The DDCOLORKEY structure describes a source color key, destination color key, or color space. A color key is specified if the low and high range values are the same. This structure is used with the IDirectDrawSurface7::GetColorKey and IDirectDrawSurface7::SetColorKey methods.

typedef struct _DDCOLORKEY{
    DWORD dwColorSpaceLowValue;
    DWORD dwColorSpaceHighValue;
} DDCOLORKEY,FAR* LPDDCOLORKEY;

Members

dwColorSpaceLowValue
Low value of the color range that is to be used as the color key.
dwColorSpaceHighValue
High value of the color range that is to be used as the color key.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.


DDDEVICEIDENTIFIER2

The DDDEVICEIDENTIFIER2 structure is passed to the IDirectDraw7::GetDeviceIdentifier method to obtain information about a device.

typedef struct tagDDDEVICEIDENTIFIER2 {
    char    szDriver[MAX_DDDEVICEID_STRING];
    char    szDescription[MAX_DDDEVICEID_STRING];
    LARGE_INTEGER  liDriverVersion;
    DWORD   dwVendorId;
    DWORD   dwDeviceId;
    DWORD   dwSubSysId;
    DWORD   dwRevision;
    GUID    guidDeviceIdentifier;
    DWORD   dwWHQLLevel;
} DDDEVICEIDENTIFIER2, * LPDDDEVICEIDENTIFIER2;

Members

szDriver
Name of the driver.
szDescription
Description of the driver.
liDriverVersion
Version of the driver. It is legal to do less than and greater than comparisons on all 64 bits. Caution should be exercised if you use this element to identify problematic drivers. Use guidDeviceIdentifier for this purpose.

The data takes the following form:

wProduct = HIWORD(liDriverVersion.HighPart)
wVersion = LOWORD(liDriverVersion.HighPart)
wSubVersion = HIWORD(liDriverVersion.LowPart)
wBuild = LOWORD(liDriverVersion.LowPart)
dwVendorId
Identifier of the manufacturer. Can be 0 if unknown.
dwDeviceId
Identifier of the type of chipset. Can be 0 if unknown.
dwSubSysId
Identifier of the subsystem. Typically, this means the particular board. Can be 0 if unknown.
dwRevision
Identifier of the revision level of the chipset. Can be 0 if unknown.
guidDeviceIdentifier
Unique identifier for the driver/chipset pair. Use this value if you want to track changes to the driver or chipset to reprofile the graphics subsystem. It can also be used to identify particular problematic drivers.
dwWHQLLevel
The Windows Hardware Quality Lab (WHQL) certification level for the device/driver pair.

Remarks

The values in szDriver and szDescription are for presentation to the user only. They should not be used to identify particular drivers because different strings might be associated with the same device, or the same driver from different vendors might be described differently.

The dwVendorId, dwDeviceId, dwSubSysId, and dwRevision members can be used to identify particular chipsets, but use extreme caution.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.


DDGAMMARAMP

The DDGAMMARAMP structure contains red, green, and blue ramp data for the IDirectDrawGammaControl::GetGammaRamp and IDirectDrawGammaControl::SetGammaRamp methods.

typedef struct _DDGAMMARAMP {
    WORD red[256];
    WORD green[256];
    WORD blue[256];
} DDGAMMARAMP, FAR * LPDDGAMMARAMP;

Members

red, green, and blue
Array of 256 WORD elements that describe the red, green, and blue gamma ramps.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.

See Also

Gamma and Color Controls


DDOVERLAYFX

The DDOVERLAYFX structure passes override information to the IDirectDrawSurface7::UpdateOverlay method.

typedef struct _DDOVERLAYFX{
    DWORD dwSize;
    DWORD dwAlphaEdgeBlendBitDepth;
    DWORD dwAlphaEdgeBlend;
    DWORD dwReserved;
    DWORD dwAlphaDestConstBitDepth;
    union
    {
        DWORD               dwAlphaDestConst;
        LPDIRECTDRAWSURFACE lpDDSAlphaDest;
    } DUMMYUNIONNAMEN(1);
    DWORD dwAlphaSrcConstBitDepth;
    union
    {
        DWORD               dwAlphaSrcConst;
        LPDIRECTDRAWSURFACE lpDDSAlphaSrc;
    } DUMMYUNIONNAMEN(2);
    DDCOLORKEY dckDestColorkey;
    DDCOLORKEY dckSrcColorkey;

    DWORD dwDDFX;
    DWORD dwFlags;
} DDOVERLAYFX,FAR *LPDDOVERLAYFX;

Members

dwSize
Size of the structure, in bytes. This members must be initialized before the structure is used.
dwAlphaEdgeBlendBitDepth
Bit depth used to specify the constant for an alpha edge blend.
dwAlphaEdgeBlend
Constant to use as the alpha for an edge blend.
dwReserved
Reserved for future use.
dwAlphaDestConstBitDepth
Bit depth used to specify the alpha constant for a destination.
dwAlphaDestConst
Constant to use as the alpha channel for a destination.
lpDDSAlphaDest
Address of a surface to use as the alpha channel for a destination.
dwAlphaSrcConstBitDepth
Bit depth used to specify the alpha constant for a source.
dwAlphaSrcConst
Constant to use as the alpha channel for a source.
lpDDSAlphaSrc
Address of a surface to use as the alpha channel for a source.
dckDestColorkey
Destination color key override.
dckSrcColorkey
Source color key override.
dwDDFX
The following overlay FX flags:
DDOVERFX_ARITHSTRETCHY
If stretching, use arithmetic stretching along the y-axis for this overlay.
DDOVERFX_MIRRORLEFTRIGHT
Mirror the overlay around the vertical axis.
DDOVERFX_MIRRORUPDOWN
Mirror the overlay around the horizontal axis.
dwFlags
Currently not used and must be set to 0.

Remarks

The unions in this structure have been updated to work with compilers that do not support nameless unions. If your compiler does not support nameless unions, define the NONAMELESSUNION token before including the Ddraw.h header file.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.


DDPIXELFORMAT

The DDPIXELFORMAT structure describes the pixel format of a DirectDrawSurface object for the IDirectDrawSurface7::GetPixelFormat method.

typedef struct _DDPIXELFORMAT{
    DWORD dwSize;
    DWORD dwFlags;
    DWORD dwFourCC;
    union
    {
        DWORD dwRGBBitCount;
        DWORD dwYUVBitCount;
        DWORD dwZBufferBitDepth;
        DWORD dwAlphaBitDepth;
        DWORD dwLuminanceBitCount;
        DWORD dwBumpBitCount;
    } DUMMYUNIONNAMEN(1);
    union
    {
        DWORD dwRBitMask;
        DWORD dwYBitMask;
        DWORD dwStencilBitDepth;
        DWORD dwLuminanceBitMask;
        DWORD dwBumpDuBitMask;
    } DUMMYUNIONNAMEN(2);
    union
    {
        DWORD dwGBitMask;
        DWORD dwUBitMask;
        DWORD dwZBitMask;
        DWORD dwBumpDvBitMask;
    } DUMMYUNIONNAMEN(3);
    union
    {
        DWORD dwBBitMask;
        DWORD dwVBitMask;
        DWORD dwStencilBitMask;
        DWORD dwBumpLuminanceBitMask;
    } DUMMYUNIONNAMEN(4);
    union
    {
        DWORD dwRGBAlphaBitMask;
        DWORD dwYUVAlphaBitMask;
        DWORD dwLuminanceAlphaBitMask;
        DWORD dwRGBZBitMask;
        DWORD dwYUVZBitMask;
    } DUMMYUNIONNAMEN(5);
} DDPIXELFORMAT, FAR* LPDDPIXELFORMAT;

Members

dwSize
Size of the structure, in bytes. This member must be initialized before the structure is used.
dwFlags
The following optional control flags:
DDPF_ALPHA
The pixel format describes an alpha-only surface.
DDPF_ALPHAPIXELS
The surface has alpha channel information in the pixel format.
DDPF_ALPHAPREMULT
The surface uses the premultiplied alpha format. That is, the color components in each pixel are premultiplied by the alpha component.
DDPF_BUMPLUMINANCE
The luminance data in the pixel format is valid, and the dwLuminanceBitMask member describes valid luminance bits for a luminance-only or luminance-alpha surface.
DDPF_BUMPDUDV
Bump-map data in the pixel format is valid. Bump-map information is in the dwBumpBitCount, dwBumpDuBitMask, dwBumpDvBitMask, and dwBumpLuminanceBitMask members.
DDPF_COMPRESSED
The surface accepts pixel data in the specified format and compress it during the write operation.
DDPF_FOURCC
The dwFourCC member is valid and contains a FOURCC code describing a non-RGB pixel format.
DDPF_LUMINANCE
The pixel format describes a luminance-only or luminance-alpha surface.
DDPF_PALETTEINDEXED1
DDPF_PALETTEINDEXED2
DDPF_PALETTEINDEXED4
DDPF_PALETTEINDEXED8
The surface is 1-, 2-, 4-, or 8-bit color-indexed.
DDPF_PALETTEINDEXEDTO8
The surface is 1-, 2-, or 4-bit color-indexed to an 8-bit palette.
DDPF_RGB
The RGB data in the pixel format structure is valid.
DDPF_RGBTOYUV
The surface accepts RGB data and translates it during the write operation to YUV data. The format of the data to be written is contained in the pixel format structure. The DDPF_RGB flag is set.
DDPF_STENCILBUFFER
The surface encodes stencil and depth information in each pixel of the z-buffer. This flag can be used only if the DDPF_ZBUFFER flag is also specified.
DDPF_YUV
The YUV data in the pixel format structure is valid.
DDPF_ZBUFFER
The pixel format describes a z-buffer surface.
DDPF_ZPIXELS
The surface contains z information in the pixels.
dwFourCC
FourCC code. For more information see, Four-Character Codes (FOURCC).
dwRGBBitCount
RGB bits per pixel (4, 8, 16, 24, or 32).
dwYUVBitCount
YUV bits per pixel (4, 8, 16, 24, or 32).
dwZBufferBitDepth
Z-buffer bit depth (8, 16, 24, or 32).
dwAlphaBitDepth
Alpha channel bit depth (1, 2, 4, or 8) for an alpha-only surface (DDPF_ALPHA). For pixel formats that contain alpha information interleaved with color data (DDPF_ALPHAPIXELS), count the bits in the dwRGBAlphaBitMask member to obtain the bit depth of the alpha component. For more information, see Remarks.
dwLuminanceBitCount
Total luminance bits per pixel. This member applies only to luminance-only and luminance-alpha surfaces.
dwBumpBitCount
Total bump-map bits per pixel in a bump-map surface.
dwRBitMask
Mask for red bits.
dwYBitMask
Mask for Y bits.
dwStencilBitDepth
Bit depth of the stencil buffer. This member specifies how many bits are reserved within each pixel of the z-buffer for stencil information (the total number of z-bits is equal to dwZBufferBitDepth minus dwStencilBitDepth).
dwLuminanceBitMask
Mask for luminance bits.
dwBumpDuBitMask
Mask for bump-map U-delta bits.
dwGBitMask
Mask for green bits.
dwUBitMask
Mask for U bits.
dwZBitMask
Mask for z bits.
dwBumpDvBitMask
Mask for bump-map V-delta bits.
dwBBitMask
Mask for blue bits.
dwVBitMask
Mask for V bits.
dwStencilBitMask
Mask for stencil bits within each z-buffer pixel.
dwBumpLuminanceBitMask
Mask for luminance in a bump-map pixel.
dwRGBAlphaBitMask and dwYUVAlphaBitMask and dwLuminanceAlphaBitMask
Masks for the alpha channel.
dwRGBZBitMask and dwYUVZBitMask
Masks for the z channel.

Remarks

The dwAlphaBitDepth member reflects the bit depth of an alpha-only pixel format (DDPF_ALPHA). For pixel formats that include the alpha component with color components (DDPF_ALPHAPIXELS), the alpha bit depth is obtained by counting the bits in the various mask members. The following code example returns the number of bits set in a given bitmask:

WORD GetNumberOfBits( DWORD dwMask )
{
    WORD wBits = 0;
    while( dwMask )
    {
        dwMask = dwMask & ( dwMask - 1 );
        wBits++;
    }
    return wBits;
}

The unions in this structure have been updated to work with compilers that do not support nameless unions. If your compiler does not support nameless unions, define the NONAMELESSUNION token before including the Ddraw.h header file.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.

See Also

Off-Screen Surface Formats


DDSCAPS

The DDSCAPS structure defines the capabilities of a DirectDrawSurface object. This structure is part of the DDCAPS and DDSURFACEDESC structures.

typedef struct _DDSCAPS{
    DWORD dwCaps;
} DDSCAPS, FAR* LPDDSCAPS;

Members

dwCaps
Capabilities of the surface. One or more of the following flags:
DDSCAPS_3D
Unsupported. Use DDSCAPS_3DDEVICE, instead.
DDSCAPS_3DDEVICE
This surface can be used for 3-D rendering. Applications can use this flag to ensure that a device that can render only to a certain heap has off-screen surfaces allocated from the correct heap. If this flag is set for a heap, the surface is not allocated from that heap.
DDSCAPS_ALLOCONLOAD
Not used.
DDSCAPS_ALPHA
This surface contains alpha-only information.
DDSCAPS_BACKBUFFER
This surface is the back buffer of a surface flipping structure. Typically, this capability is set by the CreateSurface method when the DDSCAPS_FLIP flag is used. Only the surface that immediately precedes the DDSCAPS_FRONTBUFFER surface has this capability set. The other surfaces are identified as back buffers by the presence of the DDSCAPS_FLIP flag, their attachment order, and the absence of the DDSCAPS_FRONTBUFFER and DDSCAPS_BACKBUFFER capabilities. If this capability is sent to the CreateSurface method, a stand-alone back buffer is being created. After this method is called, this surface could be attached to a front buffer, another back buffer, or both to form a flipping surface structure. For more information, see IDirectDrawSurface7::AddAttachedSurface. DirectDraw supports any number of surfaces in a flipping structure.
DDSCAPS_COMPLEX
A complex surface is being described. A complex surface results in the creation of more than one surface. The additional surfaces are attached to the root surface. The complex surface can be destroyed only by destroying the root.
DDSCAPS_FLIP
This surface is a part of a surface flipping structure. When this capability is passed to the CreateSurface method, a front buffer and one or more back buffers are created. DirectDraw sets the DDSCAPS_FRONTBUFFER bit on the front-buffer surface and the DDSCAPS_BACKBUFFER bit on the surface adjacent to the front-buffer surface. The dwBackBufferCount member of the DDSURFACEDESC structure must be set to at least 1 for the method call to succeed. The DDSCAPS_COMPLEX capability must always be set when creating multiple surfaces by using the CreateSurface method.
DDSCAPS_FRONTBUFFER
This surface is the front buffer of a surface flipping structure. This flag is typically set by the CreateSurface method when the DDSCAPS_FLIP capability is set. If this capability is sent to the CreateSurface method, a stand-alone front buffer is created. This surface does not have the DDSCAPS_FLIP capability. It can be attached to back buffers to form a flipping structure by using IDirectDrawSurface7::AddAttachedSurface.
DDSCAPS_HWCODEC
This surface can have a stream decompressed to it by the hardware.
DDSCAPS_LIVEVIDEO
This surface can receive live video.
DDSCAPS_LOCALVIDMEM
This surface exists in true, local video memory, rather than nonlocal video memory. If this flag is specified, DDSCAPS_VIDEOMEMORY must be specified, as well. This flag cannot be used with the DDSCAPS_NONLOCALVIDMEM flag.
DDSCAPS_MIPMAP
This surface is one level of a mipmap. This surface is attached to other DDSCAPS_MIPMAP surfaces to form the mipmap. This can be done explicitly by creating a number of surfaces and attaching them by using the IDirectDrawSurface7::AddAttachedSurface method, or implicitly by the CreateSurface method. If this capability is set, DDSCAPS_TEXTURE must also be set.
DDSCAPS_MODEX
This surface is a 320×200 or 320×240 Mode X surface.
DDSCAPS_NONLOCALVIDMEM
This surface exists in nonlocal video memory, rather than true, local video memory. If this flag is specified, the DDSCAPS_VIDEOMEMORY flag must be specified, as well. This cannot be used with the DDSCAPS_LOCALVIDMEM flag.
DDSCAPS_OFFSCREENPLAIN
This surface is any off-screen surface that is not an overlay, texture, z-buffer, front-buffer, back-buffer, or alpha surface. It is used to identify plain surfaces.
DDSCAPS_OPTIMIZED
Not currently implemented.
DDSCAPS_OVERLAY
This surface is an overlay. It might or might not be directly visible, depending on whether it is currently being overlaid onto the primary surface. DDSCAPS_VISIBLE can be used to determine if it is currently being overlaid.
DDSCAPS_OWNDC
This surface has a device context (DC) association for a long period of time.
DDSCAPS_PALETTE
This device driver allows unique DirectDrawPalette objects to be created and attached to this surface.
DDSCAPS_PRIMARYSURFACE
The surface is the primary surface. It represents what is currently visible.
DDSCAPS_STANDARDVGAMODE
This surface is a standard VGA mode surface, and not a Mode X surface. This flag cannot be used in combination with the DDSCAPS_MODEX flag.
DDSCAPS_SYSTEMMEMORY
This surface memory was allocated in system memory.
DDSCAPS_TEXTURE
This surface can be used as a 3-D texture. It does not indicate whether the surface is currently being used for that purpose.
DDSCAPS_VIDEOMEMORY
This surface exists in display memory.
DDSCAPS_VIDEOPORT
This surface can receive data from a video port.
DDSCAPS_VISIBLE
Changes made to this surface are immediately visible. It is always set for the primary surface, as well as for overlays while they are being overlaid and texture maps while they are being textured.
DDSCAPS_WRITEONLY
Only write access is permitted to the surface. Read access from the surface can cause a general protection (GP) fault, but the read results from this surface would be meaningful.
DDSCAPS_ZBUFFER
This surface is the z-buffer. The z-buffer contains information that cannot be displayed. Instead, it contains bit-depth information that is used to determine which pixels are visible and which are obscured.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.


DDSCAPS2

The DDSCAPS2 structure defines the capabilities of a DirectDrawSurface object. This structure is part of the DDSURFACEDESC2 structure.

typedef struct _DDSCAPS2 {
    DWORD    dwCaps;
    DWORD    dwCaps2;
    DWORD    dwCaps3;
    DWORD    dwCaps4;
} DDSCAPS2, FAR* LPDDSCAPS2;

Members

dwCaps
One or more of the following flag values representing the capabilities of the surface. (The flags in this member are identical to those in the corresponding member of the DDSCAPS structure.)
DDSCAPS_3D
Unsupported. Use the DDSCAPS_3DDEVICE instead.
DDSCAPS_3DDEVICE
This surface can be used for 3-D rendering. Applications can use this flag to ensure that a device that can render only to a certain heap has off-screen surfaces allocated from the correct heap. If this flag is set for a heap, the surface is not allocated from that heap.
DDSCAPS_ALLOCONLOAD
Not used.
DDSCAPS_ALPHA
This surface contains alpha-only information.
DDSCAPS_BACKBUFFER
This surface is the back buffer of a surface flipping structure. Typically, this capability is set by the CreateSurface method when the DDSCAPS_FLIP flag is used. Only the surface that immediately precedes the DDSCAPS_FRONTBUFFER surface has this capability set. The other surfaces are identified as back buffers by the presence of the DDSCAPS_FLIP flag, their attachment order, and the absence of DDSCAPS_FRONTBUFFER and DDSCAPS_BACKBUFFER capabilities. If this capability is sent to the CreateSurface method, a stand-alone back buffer is being created. After this method is called, this surface could be attached to a front buffer, another back buffer, or both to form a flipping surface structure. For more information, see IDirectDrawSurface7::AddAttachedSurface. DirectDraw supports any number of surfaces in a flipping structure.
DDSCAPS_COMPLEX
A complex surface is being described. A complex surface results in the creation of more than one surface. The additional surfaces are attached to the root surface. The complex surface can be destroyed only by destroying the root.
DDSCAPS_FLIP
This surface is a part of a surface-flipping structure. When this capability is passed to the CreateSurface method, a front buffer and one or more back buffers are created. DirectDraw sets the DDSCAPS_FRONTBUFFER bit on the front-buffer surface and the DDSCAPS_BACKBUFFER bit on the surface adjacent to the front-buffer surface. The dwBackBufferCount member of the DDSURFACEDESC structure must be set to at least 1 for the method call to succeed. The DDSCAPS_COMPLEX capability must always be set when creating multiple surfaces by using the CreateSurface method.
DDSCAPS_FRONTBUFFER
This surface is the front buffer of a surface-flipping structure. This flag is typically set by the CreateSurface method when the DDSCAPS_FLIP capability is set. If this capability is sent to the CreateSurface method, a stand-alone front buffer is created. This surface does not have the DDSCAPS_FLIP capability. It can be attached to back buffers to form a flipping structure by using IDirectDrawSurface7::AddAttachedSurface.
DDSCAPS_HWCODEC
This surface can have a stream decompressed to it by the hardware.
DDSCAPS_LIVEVIDEO
This surface can receive live video.
DDSCAPS_LOCALVIDMEM
This surface exists in true, local video memory, rather than nonlocal video memory. If this flag is specified, DDSCAPS_VIDEOMEMORY must be specified, as well. This flag cannot be used with the DDSCAPS_NONLOCALVIDMEM flag.
DDSCAPS_MIPMAP
This surface is one level of a mipmap. This surface is attached to other DDSCAPS_MIPMAP surfaces to form the mipmap. This can be done explicitly by creating a number of surfaces and attaching them by using the IDirectDrawSurface7::AddAttachedSurface method, or implicitly by the CreateSurface method. If this capability is set, DDSCAPS_TEXTURE must also be set.
DDSCAPS_MODEX
This surface is a 320×200 or 320×240 Mode X surface.
DDSCAPS_NONLOCALVIDMEM
This surface exists in nonlocal video memory, rather than true, local video memory. If this flag is specified, DDSCAPS_VIDEOMEMORY flag must be specified, as well. This cannot be used with the DDSCAPS_LOCALVIDMEM flag.
DDSCAPS_OFFSCREENPLAIN
This surface is any off-screen surface that is not an overlay, texture, z-buffer, front-buffer, back-buffer, or alpha surface. It is used to identify plain surfaces.
DDSCAPS_OPTIMIZED
Not currently implemented.
DDSCAPS_OVERLAY
This surface is an overlay. It might or might not be directly visible, depending on whether it is currently being overlaid onto the primary surface. DDSCAPS_VISIBLE can be used to determine if it is currently being overlaid.
DDSCAPS_OWNDC
This surface has a device context (DC) association for a long period of time.
DDSCAPS_PALETTE
This device driver allows unique DirectDrawPalette objects to be created and attached to this surface.
DDSCAPS_PRIMARYSURFACE
The surface is the primary surface. It represents what is currently visible.
DDSCAPS_STANDARDVGAMODE
This surface is a standard VGA mode surface, and not a Mode X surface. This flag cannot be used in combination with the DDSCAPS_MODEX flag.
DDSCAPS_SYSTEMMEMORY
This surface memory was allocated in system memory.
DDSCAPS_TEXTURE
This surface can be used as a 3-D texture. It does not indicate whether the surface is currently being used for that purpose.
DDSCAPS_VIDEOMEMORY
This surface exists in display memory.
DDSCAPS_VIDEOPORT
This surface can receive data from a video port.
DDSCAPS_VISIBLE
Changes made to this surface are immediately visible. It is always set for the primary surface, as well as for overlays while they are being overlaid and texture maps while they are being textured.
DDSCAPS_WRITEONLY
Only write access is permitted to the surface. Read access from the surface can cause a general protection (GP) fault, and the read results from this surface would not be meaningful.
DDSCAPS_ZBUFFER
This surface is the z-buffer. The z-buffer contains information that cannot be displayed. Instead, it contains bit-depth information that is used to determine which pixels are visible and which are obscured.
dwCaps2
Additional surface capabilities. This member can contain one or more of the following capability flags, or when using this structure with the IDirectDrawSurface7::SetSurfaceDesc method, this member can contain an additional flag to indicate how the surface memory was allocated:
Capability flags
DDSCAPS2_CUBEMAP
New for DirectX 7.0. This surface is a cubic environment map. When using this flag, also specify which face or faces of the cubic environment map to create.
DDSCAPS2_CUBEMAP_POSITIVEX
New for DirectX 7.0. This flag is used with the DDSCAPS2_CUBEMAP flag to create the positive X face of a cubic environment map.
DDSCAPS2_CUBEMAP_NEGATIVEX
New for DirectX 7.0. This flag is used with the DDSCAPS2_CUBEMAP flag to create the negative X face of a cubic environment map.
DDSCAPS2_CUBEMAP_POSITIVEY
New for DirectX 7.0. This flag is used with the DDSCAPS2_CUBEMAP flag to create the positive Y face of a cubic environment map.
DDSCAPS2_CUBEMAP_NEGATIVEY
New for DirectX 7.0. This flag is used with the DDSCAPS2_CUBEMAP flag to create the negative Y face of a cubic environment map.
DDSCAPS2_CUBEMAP_POSITIVEZ
New for DirectX 7.0. This flag is used with the DDSCAPS2_CUBEMAP flag to create the positive Z face of a cubic environment map.
DDSCAPS2_CUBEMAP_NEGATIVEZ
New for DirectX 7.0. This flag is used with the DDSCAPS2_CUBEMAP flag to create the negative Z face of a cubic environment map.
DDSCAPS2_CUBEMAP_ALLFACES
New for DirectX 7.0. This flag is used with the DDSCAPS2_CUBEMAP flag to create all six faces of a cubic environment map.
DDSCAPS2_D3DTEXTUREMANAGE
New for DirectX 7.0. The texture is always managed by Direct3D.
DDSCAPS2_DONOTPERSIST
New for DirectX 7.0. The managed surface can be safely lost.
DDSCAPS2_HARDWAREDEINTERLACE
This surface receives data from a video port, using the de-interlacing hardware. This allows the driver to allocate memory for any extra buffers that might be required. The DDSCAPS_VIDEOPORT and DDSCAPS_OVERLAY flags must also be set.
DDSCAPS2_HINTANTIALIASING
The application intends to use antialiasing. Only valid if DDSCAPS_3DDEVICE is also set. For more information, see Antialiasing.
DDSCAPS2_HINTDYNAMIC
Indicates to the driver that this surface is locked very frequently (for procedural textures, dynamic light maps, and so on). This flag can only be used for texture surfaces (DDSCAPS_TEXTURE flag set in the dwCaps member). This flag cannot be used with the DDSCAPS2_HINTSTATIC or DDSCAPS2_OPAQUE flags.
DDSCAPS2_HINTSTATIC
Indicates to the driver that this surface can be reordered or retiled on load. This operation does not change the size of the texture. It is relatively fast and symmetrical, since the application can lock these bits (although it degrades performance when doing so). This flag can only be used for texture surfaces (DDSCAPS_TEXTURE flag set in the dwCaps member). This flag cannot be used with the DDSCAPS2_HINTDYNAMIC or DDSCAPS2_OPAQUE flags.
DDSCAPS2_MIPMAPSUBLEVEL
New for DirectX 7.0. It enables easier use of GetAttachedSurface, rather than EnumAttachedSurfaces, for surface constructs such as cube maps, in which there is more than one mipmap surface attached to the root surface. This should be set on all non-top-level surfaces in a mipmapped cube map so that a call to GetAttachedSurface can distinguish between top-level faces and attached mipmap levels. This capability bit is ignored by CreateSurface.
DDSCAPS2_OPAQUE
Indicates to the driver that this surface will never be locked again. The driver is free to optimize this surface by retiling and compression. Such a surface cannot be locked or used in blit operations; attempts to lock or blit a surface with this capability fail. This flag can only be used for texture surfaces (DDSCAPS_TEXTURE flag set in the dwCaps member). This flag cannot be used with the DDSCAPS2_HINTDYNAMIC or DDSCAPS2_HINTSTATIC flags.
DDSCAPS2_STEREOSURFACELEFT
New for DirectX 7.0. This surface is part of a stereo flipping chain. When this flag is set during a IDirectDraw7::CreateSurface call, a pair of stereo surfaces are created for each buffer in the primary flipping chain. You must create a complex flipping chain (with back buffers). You cannot create a single set of stereo surfaces. The IDirectDrawSurface7::Flip method requires back buffers, so at least 4 surfaces must be created.

In addition, when this flag is set in a DDSURFACEDESC structure as the result of an IDirectDraw7::EnumDisplayModes or IDirectDraw7::GetDisplayMode call, it indicates support for stereo in that mode.

DDSCAPS2_TEXTUREMANAGE
The client would like this texture surface to be managed by the driver if the driver is capable; otherwise, it is managed by Direct3D Immediate Mode (new in DirectX 7.0). This flag can be used only for texture surfaces (DDSCAPS_TEXTURE flag set in the dwCaps member). For more information, see Automatic Texture Management in the Direct3D Immediate Mode documentation. Do not use this flag if your application uses Direct3D Retained Mode. Instead, create textures in system memory, and allow Retained Mode to manage them.
dwCaps3 and dwCaps4
Not currently used.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.


DDSURFACEDESC

The DDSURFACEDESC structure contains a description of a surface. This structure is passed to the IDirectDraw2::CreateSurface method. The relevant members differ for each potential type of surface.

When using the IDirectDraw7 interface, this structure is superseded by the DDSURFACEDESC2 structure.

typedef struct _DDSURFACEDESC {
    DWORD          dwSize;
    DWORD          dwFlags;
    DWORD          dwHeight;
    DWORD          dwWidth;
    union
    {
        LONG       lPitch;
        DWORD      dwLinearSize;
    };
    DWORD          dwBackBufferCount;
    union
    {
        DWORD      dwMipMapCount;
        DWORD      dwZBufferBitDepth;
        DWORD      dwRefreshRate;
    };
    DWORD          dwAlphaBitDepth;
    DWORD          dwReserved;
    LPVOID         lpSurface;
    DDCOLORKEY     ddckCKDestOverlay;
    DDCOLORKEY     ddckCKDestBlt;
    DDCOLORKEY     ddckCKSrcOverlay;
    DDCOLORKEY     ddckCKSrcBlt;
    DDPIXELFORMAT  ddpfPixelFormat;
    DDSCAPS        ddsCaps;
} DDSURFACEDESC, FAR* LPDDSURFACEDESC;

Members

dwSize
Size of the structure, in bytes. This member must be initialized before the structure is used.
dwFlags
Optional control flags. One or more of the following flags:
DDSD_ALL
All input members are valid.
DDSD_ALPHABITDEPTH
The dwAlphaBitDepth member is valid.
DDSD_BACKBUFFERCOUNT
The dwBackBufferCount member is valid.
DDSD_CAPS
The ddsCaps member is valid.
DDSD_CKDESTBLT
The ddckCKDestBlt member is valid.
DDSD_CKDESTOVERLAY
The ddckCKDestOverlay member is valid.
DDSD_CKSRCBLT
The ddckCKSrcBlt member is valid.
DDSD_CKSRCOVERLAY
The ddckCKSrcOverlay member is valid.
DDSD_HEIGHT
The dwHeight member is valid.
DDSD_LINEARSIZE
The dwLinearSize member is valid.
DDSD_LPSURFACE
The lpSurface member is valid.
DDSD_MIPMAPCOUNT
The dwMipMapCount member is valid.
DDSD_PITCH
The lPitch member is valid.
DDSD_PIXELFORMAT
The ddpfPixelFormat member is valid.
DDSD_REFRESHRATE
The dwRefreshRate member is valid.
DDSD_WIDTH
The dwWidth member is valid.
DDSD_ZBUFFERBITDEPTH
The dwZBufferBitDepth member is valid.
dwHeight and dwWidth
Dimensions of the surface to be created, in pixels.
lPitch
Distance, in bytes, to the start of next line. When used with the IDirectDrawSurface7::GetSurfaceDesc method, this is a return value. When creating a surface from existing memory or when calling the IDirectDrawSurface7::SetSurfaceDesc method, this is an input value that must be a DWORD multiple.
dwLinearSize
Size of the buffer. Currently returned only for compressed texture surfaces.
dwBackBufferCount
Number of back buffers.
dwMipMapCount
Number of mipmap levels.
dwZBufferBitDepth
Depth of the z-buffer. This member is obsolete for DirectX 6.0 and later. Use the IDirect3D7::EnumZBufferFormats to retrieve information about supported depth-buffer formats.
dwRefreshRate
Refresh rate (used when the display mode is described). The value of 0 indicates an adapter default.
dwAlphaBitDepth
Depth of the alpha buffer.
dwReserved
Reserved.
lpSurface
Address of the associated surface memory. When calling IDirectDrawSurface7::Lock, this member contains a valid pointer to surface memory after the call returns. When creating a surface from existing memory or using the IDirectDrawSurface7::SetSurfaceDesc method, this member is an input value that is the address of system memory allocated by the calling application. Do not set this member if your application needs DirectDraw to allocate and manage surface memory.
ddckCKDestOverlay
DDCOLORKEY structure that describes the destination color key for an overlay surface.
ddckCKDestBlt
DDCOLORKEY structure that describes the destination color key for blit operations.
ddckCKSrcOverlay
DDCOLORKEY structure that describes the source color key for an overlay surface.
ddckCKSrcBlt
DDCOLORKEY structure that describes the source color key for blit operations.
ddpfPixelFormat
DDPIXELFORMAT structure that describes the surface's pixel format.
ddsCaps
DDSCAPS structure that contains the surface's capabilities.

Remarks

This structure is similar to the DDSURFACEDESC2 structure, but contains a DDSCAPS structure as the ddsCaps member, rather than a DDSCAPS2 structure. Unlike DDSURFACEDESC2, this structure contains the dwZBufferBitDepth member.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.


DDSURFACEDESC2

The DDSURFACEDESC2 structure contains a description of a surface. This structure is used to pass surface parameters to the IDirectDraw7::CreateSurface and IDirectDrawSurface7::SetSurfaceDesc methods. It is also used to retrieve information about a surface in calls to IDirectDrawSurface7::Lock and IDirectDrawSurface7::GetSurfaceDesc. The relevant members differ for each potential type of surface.

typedef struct _DDSURFACEDESC2 {
    DWORD         dwSize;
    DWORD         dwFlags;
    DWORD         dwHeight;
    DWORD         dwWidth;
    union
    {
        LONG      lPitch;
        DWORD     dwLinearSize;
    } DUMMYUNIONNAMEN(1);
    DWORD         dwBackBufferCount;
    union
    {
        DWORD     dwMipMapCount;
        DWORD     dwRefreshRate;
    } DUMMYUNIONNAMEN(2);
    DWORD         dwAlphaBitDepth;
    DWORD         dwReserved;
    LPVOID        lpSurface;
    union
    {
        DDCOLORKEY    ddckCKDestOverlay;
        DWORD         dwEmptyFaceColor;
    } DUMMYUNIONNAMEN(3);
    DDCOLORKEY    ddckCKDestBlt;
    DDCOLORKEY    ddckCKSrcOverlay;
    DDCOLORKEY    ddckCKSrcBlt;
    DDPIXELFORMAT ddpfPixelFormat;
    DDSCAPS2      ddsCaps;
    DWORD         dwTextureStage;
} DDSURFACEDESC2, FAR* LPDDSURFACEDESC2;

Members

dwSize
Size of the structure, in bytes. This member must be initialized before the structure is used.
dwFlags
Optional control flags. One or more of the following flags:
DDSD_ALL
All input members are valid.
DDSD_ALPHABITDEPTH
The dwAlphaBitDepth member is valid.
DDSD_BACKBUFFERCOUNT
The dwBackBufferCount member is valid.
DDSD_CAPS
The ddsCaps member is valid.
DDSD_CKDESTBLT
The ddckCKDestBlt member is valid.
DDSD_CKDESTOVERLAY
The ddckCKDestOverlay member is valid.
DDSD_CKSRCBLT
The ddckCKSrcBlt member is valid.
DDSD_CKSRCOVERLAY
The ddckCKSrcOverlay member is valid.
DDSD_HEIGHT
The dwHeight member is valid.
DDSD_LINEARSIZE
The dwLinearSize member is valid.
DDSD_LPSURFACE
The lpSurface member is valid.
DDSD_MIPMAPCOUNT
The dwMipMapCount member is valid.
DDSD_PITCH
The lPitch member is valid.
DDSD_PIXELFORMAT
The ddpfPixelFormat member is valid.
DDSD_REFRESHRATE
The dwRefreshRate member is valid.
DDSD_TEXTURESTAGE
The dwTextureStage member is valid.
DDSD_WIDTH
The dwWidth member is valid.
DDSD_ZBUFFERBITDEPTH
Obsolete; see Remarks.
dwHeight and dwWidth
Dimensions of the surface to be created, in pixels.
lPitch
Distance, in bytes, to the start of next line. When used with the IDirectDrawSurface7::GetSurfaceDesc method, this is a return value. When used with the IDirectDrawSurface7::SetSurfaceDesc method, this is an input value that must be a DWORD multiple. For more information, see Remarks.
dwLinearSize
Size of the buffer. Currently returned only for compressed texture surfaces.
dwBackBufferCount
Number of back buffers.
dwMipMapCount
Number of mipmap levels.
dwRefreshRate
Refresh rate (used when the display mode is described). The value of 0 indicates an adapter default.
dwAlphaBitDepth
Depth of the alpha buffer.
dwReserved
Reserved.
lpSurface
Address of the associated surface memory. When calling IDirectDrawSurface7::Lock, this member is a valid pointer to surface memory. When calling IDirectDrawSurface7::SetSurfaceDesc, this member is a pointer to system memory that the caller explicitly allocates for the DirectDrawSurface object. For more information, see Remarks.
ddckCKDestOverlay
DDCOLORKEY structure that describes the destination color key for an overlay surface.
dwEmptyFaceColor
Physical color for empty cubemap faces.
ddckCKDestBlt
DDCOLORKEY structure that describes the destination color key for blit operations.
ddckCKSrcOverlay
DDCOLORKEY structure that describes the source color key for an overlay surface.
ddckCKSrcBlt
DDCOLORKEY structure that describes the source color key for blit operations.
ddpfPixelFormat
DDPIXELFORMAT structure that describes the pixel format of the surface.
ddsCaps
DDSCAPS2 structure that contains the capabilities of the surface.
dwTextureStage
Stage identifier used to bind a texture to a specific stage in a multitexture cascade 3-D device. Although not required for all hardware, setting this member is recommended for best performance on the largest variety of 3-D accelerators. Hardware that requires explicitly assigned textures exposes the D3DDEVCAPS_SEPARATETEXTUREMEMORIES 3-D device capability in the D3DDEVICEDESC structure that is filled by the IDirect3DDevice7::GetCaps method.

Remarks

The lPitch and lpSurface members are output values when calling the IDirectDrawSurface7::GetSurfaceDesc method. When creating surfaces from existing memory or updating surface characteristics, these members are input values that describe the pitch and location of memory allocated by the calling application for use by DirectDraw. DirectDraw does not attempt to manage or free memory allocated by the application. For more information, see Creating Client Memory Surfaces and Updating Surface Characteristics.

This structure is nearly identical to the DDSURFACEDESC structure, but contains a DDSCAPS2 structure as the ddsCaps member. Unlike DDSURFACEDESC, this structure does not contain the dwZBufferBitDepth member. Z-buffer depth is provided in the ddpfPixelFormat member.

The unions in this structure work with compilers that do not support nameless unions. If your compiler does not support nameless unions, define the NONAMELESSUNION token before including the Ddraw.h header file.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in ddraw.h.


DDVIDEOPORTBANDWIDTH

The DDVIDEOPORTBANDWIDTH structure describes the bandwidth characteristics of an overlay surface when used with a particular video-port and pixel-format configuration. This structure is used with the IDirectDrawVideoPort::GetBandwidthInfo method.

typedef struct _DDVIDEOPORTBANDWIDTH {
    DWORD dwSize;
    DWORD dwCaps;
    DWORD dwOverlay;
    DWORD dwColorkey;
    DWORD dwYInterpolate;
    DWORD dwYInterpAndColorkey;
    DWORD dwReserved1;
    DWORD dwReserved2;
} DDVIDEOPORTBANDWIDTH,*LPDDVIDEOPORTBANDWIDTH;

Members

dwSize
Size of this structure, in bytes. This member must be initialized before the structure is used.
dwCaps
Flag values specifying device dependency. This member can be one of the following values:
DDVPBCAPS_DESTINATION
This device's capabilities are described in terms of the minimum stretch factor of the overlay. Bandwidth information provided for this device refers to the destination overlay size.
DDVPBCAPS_SOURCE
This device's capabilities are described in terms of the required source overlay size. Bandwidth information provided for this device refers to the source overlay size.
dwOverlay
Stretch factor or overlay source size at which an overlay is supported, multiplied by 1000. For example 1.3 = 1300, or .75 = 750.
dwColorkey
Stretch factor or overlay source size at which an overlay with color keying is supported, multiplied by 1000. For example 1.3 = 1300, or .75 = 750.
dwYInterpolate
Stretch factor or overlay source size at which an overlay with y-axis interpolation is supported, multiplied by 1000. For example 1.3 = 1300, or .75 = 750.
dwYInterpAndColorkey
Stretch factor or overlay source size at which an overlay with y-axis interpolation and color keying is supported, multiplied by 1000. For example 1.3 = 1300, or .75 = 750.
dwReserved1 and dwReserved2
Reserved; set to 0.

Remarks

When DDVPBCAPS_DESTINATION is specified, the stretch factors described in the other members describe the minimum stretch factor required to display an overlay with the dimensions given when calling the GetBandwidthInfo method. Stretch factor values of less than 1000 mean that the video port is capable of shrinking an overlay when displayed, and values of more than 1000 mean that the overlay must be stretched larger than their source to be displayed.

When DDVPBCAPS_SOURCE is specified, the stretch factors described in the other members describe how much you must shrink the overlay source for it to be displayed. In this case, the best possible value is 1000, meaning that no shrinking is required. Smaller values mean that the source rectangle that you specified when calling GetBandwidthInfo was too large. For example, if the stretch factor is 750 and you specified 320 pixels for the dwWidth parameter, you cannot display the overlay at that size. To display the overlay, you must use a source rectangle 240 pixels wide.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dvp.h.


DDVIDEOPORTCAPS

The DDVIDEOPORTCAPS structure describes the capabilities and alignment restrictions of a video port. This structure is used with the IDDVideoPortContainer::EnumVideoPorts method.

typedef struct _DDVIDEOPORTCAPS {
    DWORD dwSize;
    DWORD dwFlags;
    DWORD dwMaxWidth;
    DWORD dwMaxVBIWidth;
    DWORD dwMaxHeight;
    DWORD dwVideoPortID;
    DWORD dwCaps;
    DWORD dwFX;
    DWORD dwNumAutoFlipSurfaces;
    DWORD dwAlignVideoPortBoundary;
    DWORD dwAlignVideoPortPrescaleWidth;
    DWORD dwAlignVideoPortCropBoundary;
    DWORD dwAlignVideoPortCropWidth;
    DWORD dwPreshrinkXStep;
    DWORD dwPreshrinkYStep;
    DWORD dwNumVBIAutoFlipSurfaces;
    DWORD dwNumPreferredAutoflip;
    WORD  wNumFilterTapsX;
    WORD  wNumFilterTapsY;
} DDVIDEOPORTCAPS, *LPDDVIDEOPORTCAPS;

Members

dwSize
Size of the structure, in bytes. This must be initialized before the structure is used.
dwFlags
Flag values indicating the fields that contain valid data. The following flags are defined:
DDVPD_AUTOFLIP
The dwNumAutoFlipSurfaces member is valid.
DDVPD_ALIGN
The dwAlignVideoPortBoundary, dwAlignVideoPortPrescaleWidth, dwAlignVideoPortCropBoundary, and dwAlignVideoPortCropWidth are valid.
DDVPD_CAPS
The dwCaps member is valid.
DDVPD_FILTERQUALITY
The wNumFilterTapsX and wNumFilterTapsY members are valid.
DDVPD_FX
The dwFX member is valid.
DDVPD_HEIGHT
The dwMaxHeight member is valid.
DDVPD_ID
The dwVideoPortID member is valid.
DDVPD_PREFERREDAUTOFLIP
The dwNumPreferredAutoflip member is valid.
DDVPD_WIDTH
The dwMaxWidth member is valid.
dwMaxWidth
Maximum width of the video port field.
dwMaxVBIWidth
Maximum width of the VBI data.
dwMaxHeight
Maximum height of the video port field.
dwVideoPortID
Zero-based index identifying the video port.
dwCaps
The following video-port capabilities:
DDVPCAPS_AUTOFLIP
Flip can be performed automatically to avoid tearing when a VREF occurs. If the data is being interleaved in memory, it flips on every other VREF.
DDVPCAPS_COLORCONTROL
Can perform color control operations on incoming data before writing to the frame buffer.
DDVPCAPS_INTERLACED
Supports interlaced video.
DDVPCAPS_NONINTERLACED
Supports noninterlaced video.
DDVPCAPS_OVERSAMPLEDVBI
Accepts VBI data in a different format or width than regular video data.
DDVPCAPS_READBACKFIELD
Supports the IDirectDrawVideoPort::GetFieldPolarity method.
DDVPCAPS_READBACKLINE
Supports the IDirectDrawVideoPort::GetVideoLine method.
DDVPCAPS_SHAREABLE
Supports two genlocked video streams that share the video port; one stream uses the even fields, and the other uses the odd fields. Separate parameters (including address, scaling, cropping, and so on) are maintained for each field.
DDVPCAPS_SKIPEVENFIELDS
Even fields of video can be automatically discarded.
DDVPCAPS_SKIPODDFIELDS
Odd fields of video can be automatically discarded.
DDVPCAPS_SYNCMASTER
Can drive the graphics refresh rate, based on the video port sync.
DDVPCAPS_SYSTEMMEMORY
Can write to surfaces created in system memory.
DDVPCAPS_VBIANDVIDEOINDEPENDENT
The VBI and video portions of the video stream can be controlled by independent processes.
DDVPCAPS_VBISURFACE
Data within the VBI can be written to a different surface.
dwFX
The following additional video-port capabilities:
DDVPFX_CROPTOPDATA
Limited cropping is available to crop VBI data.
DDVPFX_CROPX
Incoming data can be cropped in the x-direction before it is written to the surface.
DDVPFX_CROPY
Incoming data can be cropped in the y-direction before it is written to the surface.
DDVPFX_IGNOREVBIXCROP
The video port can ignore the left and right cropping coordinates when cropping oversampled VBI data.
DDVPFX_INTERLEAVE
Supports interleaving interlaced fields in memory.
DDVPFX_MIRRORLEFTRIGHT
Supports mirroring left to right as the video data is written into the frame buffer.
DDVPFX_MIRRORUPDOWN
Supports mirroring top to bottom as the video data is written into the frame buffer.
DDVPFX_PRESHRINKX
Data can be arbitrarily shrunk in the x-direction before it is written to the surface.
DDVPFX_PRESHRINKY
Data can be arbitrarily shrunk in the y-direction before it is written to the surface.
DDVPFX_PRESHRINKXB
Data can be binary shrunk (1/2, 1/4, 1/8, and so on) in the x-direction before it is written to the surface.
DDVPFX_PRESHRINKYB
Data can be binary shrunk (1/2, 1/4, 1/8, and so on) in the y-direction before it is written to the surface.
DDVPCAPS_PRESHRINKXS
Data can be shrunk in the x-direction by increments of 1/x, where x is specified in the dwShrinkXStep member.
DDVPCAPS_PRESHRINKYS
Data can be shrunk in the y-direction by increments of 1/y, where y is specified in the dwShrinkYStep
DDVPFX_PRESTRETCHX
Data can be arbitrarily stretched in the x-direction before it is written to the surface.
DDVPFX_PRESTRETCHY
Data can be arbitrarily stretched in the y-direction before it is written to the surface.
DDVPFX_PRESTRETCHXN
Data can be integer stretched in the x-direction before it is written to the surface. (1x, 2x, 3x, and so forth)
DDVPFX_PRESTRETCHYN
Data can be integer stretched in the y-direction before it is written to the surface. (1x, 2x, 3x, and so forth)
DDVPFX_VBICONVERT
Data within the VBI can be converted, independent of the remaining video data.
DDVPFX_VBINOINTERLEAVE
Interleaving can be disabled for data within the VBI.
DDVPFX_VBINOSCALE
Scaling can be disabled for data within the VBI.
dwNumAutoFlipSurfaces
Maximum number of autoflippable surfaces supported by the video port.
dwAlignVideoPortBoundary
Byte restriction of placement within the surface.
dwAlignVideoPortPrescaleWidth
Byte restriction of width after prescaling.
dwAlignVideoPortCropBoundary
Byte restriction of left cropping.
dwAlignVideoPortCropWidth
Byte restriction of cropping width.
dwPreshrinkXStep
Width can be shrunk in the x-direction in steps of 1/dwPreshrinkXStep.
dwPreshrinkYStep
Height can be shrunk in the y-direction in steps of 1/dwPreshrinkYStep.
dwNumVBIAutoFlipSurfaces
Maximum number of autoflipping surfaces capable of receiving data transmitted during the vertical blanking interval (VBI), independent of the remainder of the video stream. When constructing the autoflipping chain, the number of VBI surfaces must equal the number of surfaces receiving the remainder of the video data.
dwNumPreferredAutoflip
Optimal number of autoflippable surfaces supported by the hardware.
wNumFilterTapsX and wNumFilterTapsY
Number of taps that the prescaler filter uses in the x- and y-directions. The value of 0 indicates that no prescaling is performed in that direction, 1 indicates that the prescaler performs replication, 2 indicates that the prescaler uses two taps, and so on.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dvp.h.


DDVIDEOPORTCONNECT

The DDVIDEOPORTCONNECT structure describes a video port connection. This structure is used with the IDDVideoPortContainer::GetVideoPortConnectInfo method.

typedef struct _DDVIDEOPORTCONNECT{
    DWORD dwSize;
    DWORD dwPortWidth;
    GUID  guidTypeID;
    DWORD dwFlags;
    ULONG_PTR dwReserved1;
} DDVIDEOPORTCONNECT,*LPDDVIDEOPORTCONNECT;

Members

dwSize
Size of the structure, in bytes. This member must be initialized before the structure is used.
dwPortWidth
Width of the video port. This value represents the number of physical pins on the video port, not the width of a surface in memory. This member must always be set, even when the value in the guidTypeID member assumes a certain size.
guidTypeID
A GUID that describes the sync characteristics of the video port. The following port types are predefined:
DDVPTYPE_E_HREFH_VREFH
External syncs, where HREF is active high and VREF is active high.
DDVPTYPE_E_HREFH_VREFL
External syncs, where HREF is active high and VREF is active low.
DDVPTYPE_E_HREFL_VREFH
External syncs, where HREF is active low and VREF is active high.
DDVPTYPE_E_HREFL_VREFL
External syncs, where HREF is active low and VREF is active low.
DDVPTYPE_CCIR656
Sync information is embedded in the data stream, according to the CCIR656 specification.
DDVPTYPE_BROOKTREE
Sync information is embedded in the data stream, using the Brooktree definition.
DDVPTYPE_PHILIPS
Sync information is embedded in the data stream, using the Philips definition.
dwFlags
Flags describing the capabilities of the video-port connection. This member can be set by DirectDraw when connection information is being retrieved, or by the client when connection information is being set. This member can be a combination of the following flags:
DDVPCONNECT_DOUBLECLOCK
The video port either supports double-clocking data or should double-clock data. This flag is only valid with an external sync.
DDVPCONNECT_VACT
The video port either supports using an external VACT signal or should use the external VACT signal. This flag is only valid with an external sync.
DDVPCONNECT_INVERTPOLARITY
The video port is capable of inverting the field polarities or is to invert field polarities.

When a video port inverts field polarities, it treats even fields as odd fields, and vice versa.

DDVPCONNECT_DISCARDSVREFDATA
The video port discards any data written during the VREF period; it is not written to the frame buffer. This flag is read-only.
DDVPCONNECT_HALFLINE
The video port writes half lines into the frame buffer, sometimes causing the data to be displayed incorrectly. This flag is read-only.
DDVPCONNECT_INTERLACED
The signal is interlaced. This flag is used by the client only when creating a video port object.
DDVPCONNECT_SHAREEVEN
The physical video port is sharable, and this video-port object uses the even fields. This flag is used by the client only when creating the video-port object.
DDVPCONNECT_SHAREODD
The physical video port is sharable, and this video-port object uses the odd fields. This flag is used by the client only when creating the video-port object.
dwReserved1
Reserved; set to 0.

Remarks

This structure is used independently and as a member of the DDVIDEOPORTDESC structure.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dvp.h.


DDVIDEOPORTDESC

The DDVIDEOPORTDESC structure describes a video-port object to be created. This structure is used with the IDDVideoPortContainer::CreateVideoPort method.

typedef struct _DDVIDEOPORTDESC {
    DWORD dwSize;
    DWORD dwFieldWidth;
    DWORD dwVBIWidth;
    DWORD dwFieldHeight;
    DWORD dwMicrosecondsPerField;
    DWORD dwMaxPixelsPerSecond;
    DWORD dwVideoPortID;
    DWORD dwReserved1;
    DDVIDEOPORTCONNECT VideoPortType;
    ULONG_PTR dwReserved2;
    ULONG_PTR dwReserved3;
 } DDVIDEOPORTDESC, *LPDDVIDEOPORTDESC;

Members

dwSize
Size of this structure, in bytes. This member must be initialized before the structure is used.
dwFieldWidth
Width of incoming video stream, in pixels.
dwVBIWidth
Width of the VBI data in the incoming video stream, in pixels.
dwFieldHeight
Field height, in scan lines, for fields in the incoming video stream.
dwMicrosecondsPerField
Time interval, in microseconds, between live video VREF periods. This number should be rounded up to the nearest microsecond.
dwMaxPixelsPerSecond
Maximum pixel rate per second.
dwVideoPortID
The zero-based ID of the physical video port to be used.
dwReserved1
Reserved; set to 0.
VideoPortType
DDVIDEOPORTCONNECT structure describing the connection characteristics of the video port.
dwReserved2 and dwReserved3
Reserved; set to 0.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dvp.h.


DDVIDEOPORTINFO

The DDVIDEOPORTINFO structure describes the transfer of video data to a surface. This structure is used with the IDirectDrawVideoPort::StartVideo method.

typedef struct _DDVIDEOPORTINFO{
    DWORD dwSize;
    DWORD dwOriginX;
    DWORD dwOriginY;
    DWORD dwVPFlags;
    RECT rCrop;
    DWORD dwPrescaleWidth;
    DWORD dwPrescaleHeight;
    LPDDPIXELFORMAT lpddpfInputFormat;
    LPDDPIXELFORMAT lpddpfVBIInputFormat;
    LPDDPIXELFORMAT lpddpfVBIOutputFormat;
    DWORD dwVBIHeight;
    ULONG_PTR dwReserved1;
    ULONG_PTR dwReserved2;
} DDVIDEOPORTINFO,*LPDDVIDEOPORTINFO;

Members

dwSize
Size of this structure, in bytes. This member must be initialized before the structure is used.
dwOriginX and dwOriginY
X- and y-coordinates for the origin of the video data in the surface.
dwVPFlags
The following video-port options:
DDVP_AUTOFLIP
Perform automatic flipping. For more information, see Autoflipping.
DDVP_CONVERT
Perform conversion, using the information in the lpddpfVBIOutputFormat member.
DDVP_CROP
Perform cropping, using the rectangle specified by the rCrop member.
DDVP_IGNOREVBIXCROP
The video port should ignore left and right cropping coordinates when cropping oversampled VBI data.
DDVP_INTERLEAVE
Interlaced fields should be interleaved in memory.
DDVP_MIRRORLEFTRIGHT
Mirror image data from left to right as it is written into the frame buffer.
DDVP_MIRRORUPDOWN
Mirror image data from top to bottom as it is written into the frame buffer.
DDVP_OVERRIDEBOBWEAVE
Override automatic display method chosen by the driver, using only the display method set by the caller when creating the overlay surface.
DDVP_PRESCALE
Perform prescaling or prezooming, based on the values in the dwPrescaleHeight and dwPrescaleWidth members.
DDVP_SKIPEVENFIELDS
Ignore input of even fields.
DDVP_SKIPODDFIELDS
Ignore input of odd fields.
DDVP_SYNCMASTER
The video port VREF should drive the graphics VREF, locking the refresh rate to the video port.
DDVP_VBICONVERT
The lpddpfVBIOutputFormat member contains data to be used to convert VBI data.
DDVP_VBINOSCALE
VBI data should not be scaled.
DDVP_VBINOINTERLEAVE
Interleaving can be disabled for data within the VBI.
rCrop
Cropping rectangle. This member is optional.
dwPrescaleWidth
Prescaling or zooming in the x-direction. This member is optional.
dwPrescaleHeight
Prescaling or zooming in the y-direction. This member is optional.
lpddpfInputFormat
DDPIXELFORMAT structure describing the pixel format to be written to the video port. This is often identical to the surface's pixel format, but can differ if the video port is to perform conversion.
lpddpfVBIInputFormat and lpddpfVBIOutputFormat
DDPIXELFORMAT structures describing the input and output pixel formats of the data within the vertical blanking interval.
dwVBIHeight
Amount of data within the vertical blanking interval, in scan lines.
dwReserved1 and dwReserved2
Reserved; set to 0.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dvp.h.


DDVIDEOPORTSTATUS

The DDVIDEOPORTSTATUS structure describes the status of a video-port object. This structure is used with the IDDVideoPortContainer::QueryVideoPortStatus method.

typedef struct _DDVIDEOPORTSTATUS {
    DWORD dwSize;
    BOOL  bInUse;
    DWORD dwFlags;
    DWORD dwReserved1;
    DDVIDEOPORTCONNECT VideoPortType;
    ULONG_PTR dwReserved2;
    ULONG_PTR dwReserved3;
} DDVIDEOPORTSTATUS, *LPDDVIDEOPORTSTATUS;

Members

dwSize
Size of this structure, in bytes. This member must be initialized before the structure is used.
bInUse
Value indicating the current status of the video port. This member is TRUE if the video port is currently being used, and FALSE otherwise.
dwFlags
One ore more of the following flags:
DDVPSTATUS_VBIONLY
The video-port interface is controlling only the VBI portion of the video stream.
DDVPSTATUS_VIDEOONLY
The video-port interface is controlling only the video portion of the video stream.
dwReserved1
Reserved; set to 0.
VideoPortType
DDVIDEOPORTCONNECT structure that receives information about the video-port connection.
dwReserved2 and dwReserved3
Reserved; set to 0.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dvp.h.


Return Values

Errors are represented by negative values and cannot be combined. This table lists the values that can be returned by all methods of the IDirectDraw7, IDirectDrawSurface7, IDirectDrawPalette, IDirectDrawClipper, IDDVideoPortContainer, and IDirectDrawVideoPort interfaces. For a list of the error codes that each method can return, see the method description.

DD_OK
The request completed successfully.
DDERR_ALREADYINITIALIZED
The object has already been initialized.
DDERR_BLTFASTCANTCLIP
A DirectDrawClipper object is attached to a source surface that has passed into a call to the IDirectDrawSurface7::BltFast method.
DDERR_CANNOTATTACHSURFACE
A surface cannot be attached to another requested surface.
DDERR_CANNOTDETACHSURFACE
A surface cannot be detached from another requested surface.
DDERR_CANTCREATEDC
Windows cannot create any more device contexts (DCs), or a DC has requested a palette-indexed surface when the surface had no palette and the display mode was not palette-indexed (in this case DirectDraw cannot select a proper palette into the DC).
DDERR_CANTDUPLICATE
Primary and 3-D surfaces, or surfaces that are implicitly created, cannot be duplicated.
DDERR_CANTLOCKSURFACE
Access to this surface is refused because an attempt was made to lock the primary surface without DCI support.
DDERR_CANTPAGELOCK
An attempt to page-lock a surface failed. Page lock does not work on a display-memory surface or an emulated primary surface.
DDERR_CANTPAGEUNLOCK
An attempt to page-unlock a surface failed. Page unlock does not work on a display-memory surface or an emulated primary surface.
DDERR_CLIPPERISUSINGHWND
An attempt was made to set a clip list for a DirectDrawClipper object that is already monitoring a window handle.
DDERR_COLORKEYNOTSET
No source color key is specified for this operation.
DDERR_CURRENTLYNOTAVAIL
No support is currently available.
DDERR_DDSCAPSCOMPLEXREQUIRED
New for DirectX 7.0. The surface requires the DDSCAPS_COMPLEX flag.
DDERR_DCALREADYCREATED
A device context (DC) has already been returned for this surface. Only one DC can be retrieved for each surface.
DDERR_DEVICEDOESNTOWNSURFACE
Surfaces created by one DirectDraw device cannot be used directly by another DirectDraw device.
DDERR_DIRECTDRAWALREADYCREATED
A DirectDraw object representing this driver has already been created for this process.
DDERR_EXCEPTION
An exception was encountered while performing the requested operation.
DDERR_EXCLUSIVEMODEALREADYSET
An attempt was made to set the cooperative level when it was already set to exclusive.
DDERR_EXPIRED
The data has expired and is therefore no longer valid.
DDERR_GENERIC
There is an undefined error condition.
DDERR_HEIGHTALIGN
The height of the provided rectangle is not a multiple of the required alignment.
DDERR_HWNDALREADYSET
The DirectDraw cooperative-level window handle has already been set. It cannot be reset while the process has surfaces or palettes created.
DDERR_HWNDSUBCLASSED
DirectDraw is prevented from restoring state because the DirectDraw cooperative-level window handle has been subclassed.
DDERR_IMPLICITLYCREATED
The surface cannot be restored because it is an implicitly created surface.
DDERR_INCOMPATIBLEPRIMARY
The primary surface creation request does not match the existing primary surface.
DDERR_INVALIDCAPS
One or more of the capability bits passed to the callback function are incorrect.
DDERR_INVALIDCLIPLIST
DirectDraw does not support the provided clip list.
DDERR_INVALIDDIRECTDRAWGUID
The globally unique identifier (GUID) passed to the DirectDrawCreate function is not a valid DirectDraw driver identifier.
DDERR_INVALIDMODE
DirectDraw does not support the requested mode.
DDERR_INVALIDOBJECT
DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS
One or more of the parameters passed to the method are incorrect.
DDERR_INVALIDPIXELFORMAT
The pixel format was invalid as specified.
DDERR_INVALIDPOSITION
The position of the overlay on the destination is no longer legal.
DDERR_INVALIDRECT
The provided rectangle was invalid.
DDERR_INVALIDSTREAM
The specified stream contains invalid data.
DDERR_INVALIDSURFACETYPE
The surface was of the wrong type.
DDERR_LOCKEDSURFACES
One or more surfaces are locked, causing the failure of the requested operation.
DDERR_MOREDATA
There is more data available than the specified buffer size can hold.
DDERR_NEWMODE
New for DirectX 7.0. When IDirectDraw7::StartModeTest is called with the DDSMT_ISTESTREQUIRED flag, it may return this value to denote that some or all of the resolutions can and should be tested. IDirectDraw7::EvaluateMode returns this value to indicate that the test has switched to a new display mode.
DDERR_NO3D
No 3-D hardware or emulation is present.
DDERR_NOALPHAHW
No alpha-acceleration hardware is present or available, causing the failure of the requested operation.
DDERR_NOBLTHW
No blitter hardware is present.
DDERR_NOCLIPLIST
No clip list is available.
DDERR_NOCLIPPERATTACHED
No DirectDrawClipper object is attached to the surface object.
DDERR_NOCOLORCONVHW
No color-conversion hardware is present or available.
DDERR_NOCOLORKEY
The surface does not currently have a color key.
DDERR_NOCOLORKEYHW
There is no hardware support for the destination color key.
DDERR_NOCOOPERATIVELEVELSET
A create function was called without the IDirectDraw7::SetCooperativeLevel method.
DDERR_NODC
No device context (DC) has ever been created for this surface.
DDERR_NODDROPSHW
No DirectDraw raster-operation (ROP) hardware is available.
DDERR_NODIRECTDRAWHW
Hardware-only DirectDraw object creation is not possible; the driver does not support any hardware.
DDERR_NODIRECTDRAWSUPPORT
DirectDraw support is not possible with the current display driver.
DDERR_NODRIVERSUPPORT
New for DirectX 7.0. Testing cannot proceed because the display adapter driver does not enumerate refresh rates.
DDERR_NOEMULATION
Software emulation is not available.
DDERR_NOEXCLUSIVEMODE
The operation requires the application to have exclusive mode, but the application does not have exclusive mode.
DDERR_NOFLIPHW
Flipping visible surfaces is not supported.
DDERR_NOFOCUSWINDOW
An attempt was made to create or set a device window without first setting the focus window.
DDERR_NOGDI
No GDI is present.
DDERR_NOHWND
Clipper notification requires a window handle, or no window handle has been previously set as the cooperative level window handle.
DDERR_NOMIPMAPHW
No mipmap-capable texture mapping hardware is present or available.
DDERR_NOMIRRORHW
No mirroring hardware is present or available.
DDERR_NOMONITORINFORMATION
New for DirectX 7.0. Testing cannot proceed because the monitor has no associated EDID data.
DDERR_NONONLOCALVIDMEM
An attempt was made to allocate nonlocal video memory from a device that does not support nonlocal video memory.
DDERR_NOOPTIMIZEHW
The device does not support optimized surfaces.
DDERR_NOOVERLAYDEST
The IDirectDrawSurface7::GetOverlayPosition method is called on an overlay that the IDirectDrawSurface7::UpdateOverlay method has not been called on to establish as a destination.
DDERR_NOOVERLAYHW
No overlay hardware is present or available.
DDERR_NOPALETTEATTACHED
No palette object is attached to this surface.
DDERR_NOPALETTEHW
There is no hardware support for 16- or 256-color palettes.
DDERR_NORASTEROPHW
No appropriate raster-operation hardware is present or available.
DDERR_NOROTATIONHW
No rotation hardware is present or available.
DDERR_NOSTEREOHARDWARE
There is no stereo hardware present or available.
DDERR_NOSTRETCHHW
There is no hardware support for stretching.
DDERR_NOSURFACELEFT
There is no hardware present that supports stereo surfaces.
DDERR_NOT4BITCOLOR
The DirectDrawSurface object is not using a 4-bit color palette, and the requested operation requires a 4-bit color palette.
DDERR_NOT4BITCOLORINDEX
The DirectDrawSurface object is not using a 4-bit color index palette, and the requested operation requires a 4-bit color index palette.
DDERR_NOT8BITCOLOR
The DirectDrawSurface object is not using an 8-bit color palette, and the requested operation requires an 8-bit color palette.
DDERR_NOTAOVERLAYSURFACE
An overlay component is called for a nonoverlay surface.
DDERR_NOTEXTUREHW
The operation cannot be carried out because no texture-mapping hardware is present or available.
DDERR_NOTFLIPPABLE
An attempt was made to flip a surface that cannot be flipped.
DDERR_NOTFOUND
The requested item was not found.
DDERR_NOTINITIALIZED
An attempt was made to call an interface method of a DirectDraw object created by CoCreateInstance before the object was initialized.
DDERR_NOTLOADED
The surface is an optimized surface, but it has not yet been allocated any memory.
DDERR_NOTLOCKED
An attempt was made to unlock a surface that was not locked.
DDERR_NOTPAGELOCKED
An attempt was made to page-unlock a surface with no outstanding page locks.
DDERR_NOTPALETTIZED
The surface being used is not a palette-based surface.
DDERR_NOVSYNCHW
There is no hardware support for vertical blank–synchronized operations.
DDERR_NOZBUFFERHW
The operation to create a z-buffer in display memory or to perform a blit, using a z-buffer cannot be carried out because there is no hardware support for z-buffers.
DDERR_NOZOVERLAYHW
The overlay surfaces cannot be z-layered, based on the z-order because the hardware does not support z-ordering of overlays.
DDERR_OUTOFCAPS
The hardware needed for the requested operation has already been allocated.
DDERR_OUTOFMEMORY
DirectDraw does not have enough memory to perform the operation.
DDERR_OUTOFVIDEOMEMORY
DirectDraw does not have enough display memory to perform the operation.
DDERR_OVERLAPPINGRECTS
The source and destination rectangles are on the same surface and overlap each other.
DDERR_OVERLAYCANTCLIP
The hardware does not support clipped overlays.
DDERR_OVERLAYCOLORKEYONLYONEACTIVE
An attempt was made to have more than one color key active on an overlay.
DDERR_OVERLAYNOTVISIBLE
The IDirectDrawSurface7::GetOverlayPosition method was called on a hidden overlay.
DDERR_PALETTEBUSY
Access to this palette is refused because the palette is locked by another thread.
DDERR_PRIMARYSURFACEALREADYEXISTS
This process has already created a primary surface.
DDERR_REGIONTOOSMALL
The region passed to the IDirectDrawClipper::GetClipList method is too small.
DDERR_SURFACEALREADYATTACHED
An attempt was made to attach a surface to another surface to which it is already attached.
DDERR_SURFACEALREADYDEPENDENT
An attempt was made to make a surface a dependency of another surface on which it is already dependent.
DDERR_SURFACEBUSY
Access to the surface is refused because the surface is locked by another thread.
DDERR_SURFACEISOBSCURED
Access to the surface is refused because the surface is obscured.
DDERR_SURFACELOST
Access to the surface is refused because the surface memory is gone. Call the IDirectDrawSurface7::Restore method on this surface to restore the memory associated with it.
DDERR_SURFACENOTATTACHED
The requested surface is not attached.
DDERR_TESTFINISHED
New for DirectX 7.0. When returned by the IDirectDraw7::StartModeTest method, this value means that no test could be initiated because all the resolutions chosen for testing already have refresh rate information in the registry. When returned by IDirectDraw7::EvaluateMode, the value means that DirectDraw has completed a refresh rate test.
DDERR_TOOBIGHEIGHT
The height requested by DirectDraw is too large.
DDERR_TOOBIGSIZE
The size requested by DirectDraw is too large. However, the individual height and width are valid sizes.
DDERR_TOOBIGWIDTH
The width requested by DirectDraw is too large.
DDERR_UNSUPPORTED
The operation is not supported.
DDERR_UNSUPPORTEDFORMAT
The pixel format requested is not supported by DirectDraw.
DDERR_UNSUPPORTEDMASK
The bitmask in the pixel format requested is not supported by DirectDraw.
DDERR_UNSUPPORTEDMODE
The display is currently in an unsupported mode.
DDERR_VERTICALBLANKINPROGRESS
A vertical blank is in progress.
DDERR_VIDEONOTACTIVE
The video port is not active.
DDERR_WASSTILLDRAWING
The previous blit operation that is transferring information to or from this surface is incomplete.
DDERR_WRONGMODE
This surface cannot be restored because it was created in a different mode.
DDERR_XALIGN
The provided rectangle was not horizontally aligned on a required boundary.


Pixel Format Masks

This section contains information about the pixel formats supported by the hardware emulation layer (HEL). The following topics are discussed:

  • Texture-Map Formats
  • Off-Screen Surface Formats


Texture-Map Formats

A wide range of texture pixel formats are supported by the hardware emulation layer (HEL). The following table shows these formats. The Masks column contains the red, green, blue, and alpha masks for each set of pixel format flags and bit depths.

Pixel format flags | Bit depth | Masks
DDPF_RGB | DDPF_PALETTEINDEXED1 | 1 | R: 0x00000000 G: 0x00000000 B: 0x00000000 A: 0x00000000
DDPF_RGB | DDPF_PALETTEINDEXED1 | DDPF_PALETTEINDEXEDTO8 | 1 | R: 0x00000000 G: 0x00000000 B: 0x00000000 A: 0x00000000
DDPF_RGB | DDPF_PALETTEINDEXED2 | 2 | R: 0x00000000 G: 0x00000000 B: 0x00000000 A: 0x00000000
DDPF_RGB | DDPF_PALETTEINDEXED2 | DDPF_PALETTEINDEXEDTO8 | 2 | R: 0x00000000 G: 0x00000000 B: 0x00000000 A: 0x00000000
DDPF_RGB | DDPF_PALETTEINDEXED4 | 4 | R: 0x00000000 G: 0x00000000 B: 0x00000000 A: 0x00000000
DDPF_RGB | DDPF_PALETTEINDEXED4 | DDPF_PALETTEINDEXEDTO8 | 4 | R: 0x00000000 G: 0x00000000 B: 0x00000000 A: 0x00000000
DDPF_RGB | DDPF_PALETTEINDEXED8 | 8 | R: 0x00000000 G: 0x00000000 B: 0x00000000 A: 0x00000000
DDPF_RGB | 8 | R: 0x000000E0 G: 0x0000001C B: 0x00000003 A: 0x00000000
DDPF_RGB | DDPF_ALPHAPIXELS | 16 | R: 0x00000F00 G: 0x000000F0 B: 0x0000000F A: 0x0000F000
DDPF_RGB | 16 | R: 0x0000F800 G: 0x000007E0 B: 0x0000001F A: 0x00000000
DDPF_RGB | 16 | R: 0x0000001F G: 0x000007E0 B: 0x0000F800 A: 0x00000000
DDPF_RGB | 16 | R: 0x00007C00 G: 0x000003E0 B: 0x0000001F A: 0x00000000
DDPF_RGB | DDPF_ALPHAPIXELS | 16 | R: 0x00007C00 G: 0x000003E0 B: 0x0000001F A: 0x00008000
DDPF_RGB | 24 | R: 0x00FF0000 G: 0x0000FF00 B: 0x000000FF A: 0x00000000
DDPF_RGB | 24 | R: 0x000000FF G: 0x0000FF00 B: 0x00FF0000 A: 0x00000000
DDPF_RGB | 32 | R: 0x00FF0000 G: 0x0000FF00 B: 0x000000FF A: 0x00000000
DDPF_RGB | 32 | R: 0x000000FF G: 0x0000FF00 B: 0x00FF0000 A: 0x00000000
DDPF_RGB | DDPF_ALPHAPIXELS | 32 | R: 0x00FF0000 G: 0x0000FF00 B: 0x000000FF A: 0xFF000000
DDPF_RGB | DDPF_ALPHAPIXELS | 32 | R: 0x000000FF G: 0x0000FF00 B: 0x00FF0000 A: 0xFF000000

The HEL can create these formats in system memory. The DirectDraw device driver for a 3-D-accelerated display card can create textures of other formats in display memory. Such a driver exports the DDSCAPS_TEXTURE flag to indicate that it can create textures.


Off-Screen Surface Formats

The following table shows the pixel formats for off-screen plain surfaces supported by the DirectX hardware emulation layer (HEL). The Masks column contains the red, green, blue, and alpha masks for each set of pixel format flags and bit depths.

Pixel format flags | Bit depth | Masks
DDPF_RGB | DDPF_PALETTEINDEXED1 | 1 | R: 0x00000000 G: 0x00000000 B: 0x00000000 A: 0x00000000
DDPF_RGB | DDPF_PALETTEINDEXED2 | 2 | R: 0x00000000 G: 0x00000000 B: 0x00000000 A: 0x00000000
DDPF_RGB | DDPF_PALETTEINDEXED4 | 4 | R: 0x00000000 G: 0x00000000 B: 0x00000000 A: 0x00000000
DDPF_RGB | DDPF_PALETTEINDEXED8 | 8 | R: 0x00000000 G: 0x00000000 B: 0x00000000 A: 0x00000000
DDPF_RGB | 16 | R: 0x0000F800 G: 0x000007E0 B: 0x0000001F A: 0x00000000
DDPF_RGB | 16 | R: 0x00007C00 G: 0x000003E0 B: 0x0000001F A: 0x00000000
DDPF_RGB | 24 | R: 0x00FF0000 G: 0x0000FF00 B: 0x000000FF A: 0x00000000
DDPF_RGB | 24 | R: 0x000000FF G: 0x0000FF00 B: 0x00FF0000 A: 0x00000000
DDPF_RGB | 32 | R: 0x00FF0000 G: 0x0000FF00 B: 0x000000FF A: 0x00000000
DDPF_RGB | 32 | R: 0x000000FF G: 0x0000FF00 B: 0x00FF0000 A: 0x00000000
DDPF_RGB | DDPF_ZPIXELS | 32 | R: 0x0000F800 G: 0x000007E0 B: 0x0000001F Z: 0xFFFF0000
DDPF_RGB | DDPF_ZPIXELS | 32 | R: 0x00007C00 G: 0x000003E0 B: 0x0000001F Z: 0xFFFF0000

In addition to supporting a wide range of off-screen surface formats, the HEL also supports surfaces intended for use by Direct3D, or other 3-D renderers.


Four-Character Codes (FOURCC)

DirectDraw utilizes a special set of codes that are four characters in length. These codes, called four-character codes or FOURCCs, are stored in file headers of files that contain multimedia data, such as bitmap images, sound, or video. FOURCCs describe the software technology that was used to produce multimedia data. By implication, they also describe the format of the data itself.

DirectDraw applications use FOURCCs for image color and format conversion. If an application calls the IDirectDrawSurface7::GetPixelFormat method to request the pixel format of a surface whose format is not RGB, the dwFourCC member of the DDPIXELFORMAT structure identifies the FOURCC when the method returns.

In addition, the biCompression member of the BITMAPINFOHEADER structure can be set to a FOURCC to indicate the codec used to compress or decompress an image.

FOURCCs are registered with Microsoft by the vendors of the respective multimedia software technologies. Some common FOURCCs appear in the following list.

FOURCC | Company | Technology name
AUR2 | AuraVision Corporation | AuraVision Aura 2: YUV 422
AURA | AuraVision Corporation | AuraVision Aura 1: YUV 411
CHAM | Winnov, Inc. | MM_WINNOV_CAVIARA_CHAMPAGNE
CVID | Supermac | Cinepak by Supermac
CYUV | Creative Labs, Inc. | Creative Labs YUV
DXT1 | Microsoft Corporation | DirectX Texture Compression Format 1
DXT2 | Microsoft Corporation | DirectX Texture Compression Format 2
DXT3 | Microsoft Corporation | DirectX Texture Compression Format 3
DXT4 | Microsoft Corporation | DirectX Texture Compression Format 4
DXT5 | Microsoft Corporation | DirectX Texture Compression Format 5
FVF1 | Iterated Systems, Inc. | Fractal Video Frame
IF09 | Intel® Corporation | Intel Intermediate YUV9
IV31 | Intel Corporation | Indeo 3.1
JPEG | Microsoft Corporation | Still Image JPEG DIB
MJPG | Microsoft Corporation | Motion JPEG DIB Format
MRLE | Microsoft Corporation | Run Length Encoding
MSVC | Microsoft Corporation | Video 1
PHMO | IBM Corporation | Photomotion
RT21 | Intel Corporation | Indeo 2.1
ULTI | IBM Corporation | Ultimotion
V422 | Vitec Multimedia | 24-bit YUV 4:2:2
V655 | Vitec Multimedia | 16-bit YUV 4:2:2
VDCT | Vitec Multimedia | Video Maker Pro DIB
VIDS | Vitec Multimedia | YUV 4:2:2 CCIR 601 for V422
YU92 | Intel Corporation | YUV
YUV8 | Winnov, Inc. | MM_WINNOV_CAVIAR_YUV8
YUV9 | Intel Corporation | YUV9
YUYV | Canopus, Co., Ltd. | BI_YUYV, Canopus
ZPEG | Metheus | Video Zipper


DirectDraw Visual Basic Reference

This section contains reference information for the API elements that Microsoft® DirectDraw® provides. Reference material is divided into the following categories:

  • Classes
  • Types
  • Enumerations
  • Error Codes
  • Pixel Format Masks
  • Four-Character Codes (FOURCC)


Classes

This section contains reference information about the classes used with the DirectDraw component. The following classes are covered:

  • DirectDraw7
  • DirectDrawClipper
  • DirectDrawColorControl
  • DirectDrawEnum
  • DirectDrawEnumModes
  • DirectDrawEnumSurfaces
  • DirectDrawGammaControl
  • DirectDrawIdentifier
  • DirectDrawPalette
  • DirectDrawSurface7
  • DirectX7
  • IFont


DirectDraw7

Applications use the methods of the DirectDraw7 class to create DirectDraw objects and work with system-level variables. This section is a reference to the methods of this class. For a conceptual overview, see The DirectDraw Object.

The methods of the DirectDraw7 class can be organized into the following groups:

Cooperative levels | SetCooperativeLevel
 | TestCooperativeLevel
Creating objects | CreateClipper
 | CreatePalette
 | CreateSurface
 | CreateSurfaceFromFile
 | CreateSurfaceFromResource
 | GetDirect3D
 | LoadPaletteFromBitmap
Device capabilities | GetCaps
Display modes | GetDisplayMode
 | GetDisplayModesEnum
 | GetMonitorFrequency
 | RestoreDisplayMode
 | SetDisplayMode
 | WaitForVerticalBlank
Display status | GetScanLine
 | GetVerticalBlankStatus
Miscellaneous | GetAvailableTotalMem
 | GetDeviceIdentifier
 | GetFourCCCodes
 | GetFreeMem
 | GetNumFourCCCodes
Surface management | DuplicateSurface
 | FlipToGDISurface
 | GetGDISurface
 | GetSurfaceFromDC
 | GetSurfacesEnum
 | RestoreAllSurfaces

The DirectDraw7 class extends the features of previous versions of the class by offering methods enabling more flexible surface management than previous versions.


DirectDraw7.CreateClipper

The DirectDraw7.CreateClipper method creates a DirectDrawClipper object.

object.CreateClipper(flags As Long) As DirectDrawClipper

Parameters

object
Object expression that resolves to a DirectDraw7 object.
flags
Currently not used and must be set to 0.

Return Values

If the method succeeds, it returns a DirectDrawClipper object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOCOOPERATIVELEVELSET
DDERR_OUTOFMEMORY

Remarks

The DirectDrawClipper object can be attached to a DirectDrawSurface and used during DirectDrawSurface7.Blt operations.

See Also

DirectDrawSurface7.GetClipper, DirectDrawSurface7.SetClipper


DirectDraw7.CreatePalette

The DirectDraw7.CreatePalette method creates a DirectDrawPalette object for this DirectDraw object.

object.CreatePalette( _
    flags As CONST_DDPCAPSFLAGS, _
    pe() As PALETTEENTRY) As DirectDrawPalette

Parameters

object
Object expression that resolves to a DirectDraw7 object.
flags
One or more of the constants of the CONST_DDPCAPSFLAGS enumeration.
pe()
Array of 2, 4, 16, or 256 PALETTEENTRY types to initialize this DirectDrawPalette object.

Return Values

If the method succeeds, it returns a DirectDrawPalette object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOCOOPERATIVELEVELSET
DDERR_OUTOFMEMORY
DDERR_UNSUPPORTED


DirectDraw7.CreateSurface

The DirectDraw7.CreateSurface method creates a DirectDrawSurface7 object for this DirectDraw object.

object.CreateSurface( _
    dd As DDSURFACEDESC2) As DirectDrawSurface7

Parameters

object
Object expression that resolves to a DirectDraw7 object.
dd
DDSURFACEDESC2 type that describes the requested surface. A DDSCAPS2 type is a member of DDSURFACEDESC2.

Return Values

If the method succeeds, it returns a DirectDrawSurface7 object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INCOMPATIBLEPRIMARY
DDERR_INVALIDCAPS
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDPIXELFORMAT
DDERR_NOALPHAHW
DDERR_NOCOOPERATIVELEVELSET
DDERR_NODIRECTDRAWHW
DDERR_NOEMULATION
DDERR_NOEXCLUSIVEMODE
DDERR_NOFLIPHW
DDERR_NOMIPMAPHW
DDERR_NOOVERLAYHW
DDERR_NOZBUFFERHW
DDERR_OUTOFMEMORY
DDERR_OUTOFVIDEOMEMORY
DDERR_PRIMARYSURFACEALREADYEXISTS
DDERR_UNSUPPORTEDMODE


DirectDraw7.CreateSurfaceFromFile

The DirectDraw7.CreateSurfaceFromFile method creates a DirectDrawSurface7 object for this DirectDraw object and attaches the specified bitmap image to the DirectDrawSurface object.

object.CreateSurfaceFromFile( _
    file As String, _
    dd As DDSURFACEDESC2) As DirectDrawSurface7

Parameters

object
Object expression that resolves to a DirectDraw7 object.
file
Name of the bitmap image to load onto the surface that is created.
dd
DDSURFACEDESC2 type that describes the requested surface. A DDSCAPS2 type is a member of DDSURFACEDESC2.

Return Values

If the method succeeds, it returns a DirectDrawSurface7 object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INCOMPATIBLEPRIMARY
DDERR_INVALIDCAPS
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDPIXELFORMAT
DDERR_NOALPHAHW
DDERR_NOCOOPERATIVELEVELSET
DDERR_NODIRECTDRAWHW
DDERR_NOEMULATION
DDERR_NOEXCLUSIVEMODE
DDERR_NOFLIPHW
DDERR_NOMIPMAPHW
DDERR_NOOVERLAYHW
DDERR_NOZBUFFERHW
DDERR_OUTOFMEMORY
DDERR_OUTOFVIDEOMEMORY
DDERR_PRIMARYSURFACEALREADYEXISTS
DDERR_UNSUPPORTEDMODE

Remarks

If you are using 256 colors, set the display mode and the palette before you call this method to display correct palette information.


DirectDraw7.CreateSurfaceFromResource

The DirectDraw7.CreateSurfaceFromResource method creates a DirectDrawSurface7 object for this DirectDraw object and attaches the specified resource to the DirectDrawSurface object.

object.CreateSurfaceFromResource( _
    file As String, _
    resName As String, _
    ddsd As DDSURFACEDESC2) As DirectDrawSurface7

Parameters

object
Object expression that resolves to a DirectDraw7 object.
file
Filename of the resource that is loaded onto the surface that is created. If the resource is part of the executable, specifying an empty string for this parameter locates the resource. This parameter can also be the name of an OCX in which the resource is located.
resName
Name of the resource that is loaded onto the surface that is created.
ddsd
DDSURFACEDESC2 type that describes the requested surface. A DDSCAPS2 type is a member of DDSURFACEDESC2.

Return Values

If the method succeeds, it returns a DirectDrawSurface7 object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INCOMPATIBLEPRIMARY
DDERR_INVALIDCAPS
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDPIXELFORMAT
DDERR_NOALPHAHW
DDERR_NOCOOPERATIVELEVELSET
DDERR_NODIRECTDRAWHW
DDERR_NOEMULATION
DDERR_NOEXCLUSIVEMODE
DDERR_NOFLIPHW
DDERR_NOMIPMAPHW
DDERR_NOOVERLAYHW
DDERR_NOZBUFFERHW
DDERR_OUTOFMEMORY
DDERR_OUTOFVIDEOMEMORY
DDERR_PRIMARYSURFACEALREADYEXISTS
DDERR_UNSUPPORTEDMODE

Remarks

If you supply an empty string as the module name and run the application in the Microsoft® Visual Basic® environment, the resource cannot be found. Passing an empty string succeeds only if you are using a stand-alone executable.

The resource name needs to be a string, rather than a number. Place quotes around the resource name to make it a string, or the method fails.


DirectDraw7.DuplicateSurface

The DirectDraw7.DuplicateSurface method duplicates a DirectDrawSurface7 object.

object.DuplicateSurface( _
    ddIn As DirectDrawSurface7) As DirectDrawSurface7

Parameters

object
Object expression that resolves to a DirectDraw7 object.
ddIn
DirectDrawSurface7 object that is the surface to be duplicated.

Return Values

If the method succeeds, it returns a newly duplicated DirectDrawSurface7 object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_CANTDUPLICATE
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY
DDERR_SURFACELOST

Remarks

This method creates a new DirectDrawSurface7 object that points to the same surface memory as an existing DirectDrawSurface object. This duplicate can be used just like the original object. The surface memory is released after the last object that refers to it is released. A primary surface, 3-D surface or implicitly created surface cannot be duplicated.


DirectDraw7.FlipToGDISurface

The DirectDraw7.FlipToGDISurface method makes the surface that the GDI writes to the primary surface.

object.FlipToGDISurface()

Parameters

object
Object expression that resolves to a DirectDraw7 object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOTFOUND

Remarks

This method can be called at the end of a page-flipping application to ensure that the display memory that the GDI is writing to is visible.

This method disables stereo autoflipping.

See Also

DirectDraw7.GetGDISurface


DirectDraw7.GetAvailableTotalMem

The DirectDraw7.GetAvailableTotalMem method retrieves the total amount of display memory available for a given type of surface.

object.GetAvailableTotalMem( _
    ddsCaps As DDSCAPS2) As Long

Parameters

object
Object expression that resolves to a DirectDraw7 object.
ddsCaps
DDSCAPS2 type that indicates the hardware capabilities of the proposed surface.

Return Values

If the method succeeds, it returns the amount of total memory.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDCAPS
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NODIRECTDRAWHW

Remarks

This method provides only a snapshot of the current display-memory state. The amount of free display memory is subject to change as surfaces are created and released. Therefore, you should use the free memory value only as an approximation. In addition, a particular display adapter card might make no distinction between two different memory types. For example, the adapter might use the same portion of display memory to store z-buffers and textures, so allocating one type of surface (for example, a z-buffer) can affect the amount of display memory available for another type of surface (textures). Therefore, it is best to first allocate an application's fixed resources (such as front and back buffers , and z-buffers) before determining how much memory is available for dynamic use (such as texture mapping).


DirectDraw7.GetCaps

The DirectDraw7.GetCaps method fills in the capabilities of the device driver for the hardware and the hardware emulation layer (HEL).

object.GetCaps(hwCaps As DDCAPS, helCaps As DDCAPS)

Parameters

object
Object expression that resolves to a DirectDraw7 object.
hwCaps
DDCAPS type to be filled with the capabilities of the hardware, as reported by the device driver.
helCaps
DDCAPS type to be filled with the capabilities of the HEL.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS


DirectDraw7.GetDeviceIdentifier

The DirectDraw7.GetDeviceIdentifier method returns a DirectDrawIdentifier object filled with information about the DirectDraw device driver.

object.GetDeviceIdentifier( _
    flags As CONST_DDDEVICEIDFLAGS _ )
    As DirectDrawIdentifier

Parameters

object
Object expression that resolves to a DirectDraw7 object.
flags
One of the constants of the CONST_DDDEVICEIDFLAGS enumeration specifying information options.

Return Values

If the method succeeds, it returns a DirectDrawIdentifier object.

Error Codes

If the method fails, it raises an error, and Err.Number is set.


DirectDraw7.GetDirect3D

The DirectDraw7.GetDirect3D method creates a Direct3D7 object.

object.GetDirect3D() As Direct3D7

Parameters

object
Object expression that resolves to a DirectDraw7 object.

Return Values

If the method succeeds, it returns a Direct3D7 object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

E_INVALIDINTERFACE
E_OUTOFMEMORY

For information on trapping errors, see Visual Basic Error Trapping.

Remarks

The object returned by a successful function call must be assigned to a Direct3D7 object variable. For example:

Dim Direct3D as Direct3D7
Set Direct3D = object.GetDirect3D()


DirectDraw7.GetDisplayMode

The DirectDraw7.GetDisplayMode method retrieves the current display mode.

object.GetDisplayMode(surface As DDSURFACEDESC2)

Parameters

object
Object expression that resolves to a DirectDraw7 object.
surface
DDSURFACEDESC2 type to be filled with a description of the surface display mode.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_UNSUPPORTEDMODE

Remarks

An application should not save the information returned by this method to restore the display mode on clean-up. The application should use the DirectDraw7.RestoreDisplayMode method to restore the mode on clean-up, thus avoiding mode-setting conflicts that could arise in a multiprocess environment.

See Also

DirectDraw7.SetDisplayMode, DirectDraw7.RestoreDisplayMode, DirectDraw7.GetDisplayModesEnum


DirectDraw7.GetDisplayModesEnum

The DirectDraw7.GetDisplayModesEnum method returns a DirectDrawEnumModes object filled with display-mode information.

object.GetDisplayModesEnum( _
    flags As CONST_DDEDMFLAGS, _
    ddsd As DDSURFACEDESC2) As DirectDrawEnumModes

Parameters

object
Object expression that resolves to a DirectDraw7 object.
flags
One of the constants of the CONST_DDEDMFLAGS enumeration.
ddsd
DDSURFACEDESC2 type to be filled with a description of the surface display mode.

Return Values

If the method succeeds, it returns a DirectDrawEnumModes object that you can then query for a description of the display modes.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
E_OUTOFMEMORY

Remarks

An application should not save the information returned by this method to restore the display mode on clean-up. The application should use the DirectDraw7.RestoreDisplayMode method to restore the mode on clean-up, thus avoiding mode-setting conflicts that could arise in a multiprocess environment.

See Also

DirectDraw7.SetDisplayMode, DirectDraw7.RestoreDisplayMode, DirectDraw7.GetDisplayModesEnum


DirectDraw7.GetFourCCCodes

The DirectDraw7.GetFourCCCodes method retrieves the FOURCC codes supported by the DirectDraw object.

object.GetFourCCCodes(ccCodes() As Long)

Parameters

object
Object expression that resolves to a DirectDraw7 object.
ccCodes
Array of variables to be filled with the Four-Character Codes(FOURCC) supported by this DirectDraw object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

To retrieve the number of codes supported by a DirectDraw7 object, use DirectDraw7.GetNumFourCCCodes.


DirectDraw7.GetFreeMem

The DirectDraw7.GetFreeMem method retrieves the total amount of display memory currenty free.

object.GetFreeMem(ddsCaps As DDSCAPS2) As Long

Parameters

object
Object expression that resolves to a DirectDraw7 object.
ddsCaps
DDSCAPS2 type that indicates the hardware capabilities of the proposed surface.

Return Values

If the method succeds, it returns the total amount of memory.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDCAPS
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NODIRECTDRAWHW

Remarks

This method provides only a snapshot of the current display-memory state. The amount of free display memory is subject to change as surfaces are created and released. Therefore, you should use the free-memory value only as an approximation. In addition, a particular display adapter card might make no distinction between two different memory types. For example, the adapter might use the same portion of display memory to store z-buffers and textures. So, allocating one type of surface (for example, a z-buffer) can affect the amount of display memory available for another type of surface (textures). Therefore, it is best to first allocate an application's fixed resources (such as front and back buffers , and z-buffers) before determining how much memory is available for dynamic use (such as texture mapping).


DirectDraw7.GetGDISurface

The DirectDraw7.GetGDISurface method retrieves the DirectDrawSurface object that currently represents the surface memory that the GDI is treating as the primary surface.

object.GetGDISurface() As DirectDrawSurface7

Parameters

object
Object expression that resolves to a DirectDraw7 object.

Return Values

If the method succeeds, it returns a DirectDrawSurface7.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOTFOUND

See Also

DirectDraw7.FlipToGDISurface


DirectDraw7.GetMonitorFrequency

The DirectDraw7.GetMonitorFrequency method retrieves the frequency of the monitor being driven by the DirectDraw object.

object.GetMonitorFrequency() As Long

Parameters

object
Object expression that resolves to a DirectDraw7 object.

Return Values

If the method succeeds, it returns the monitor frequency, in Hz.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_UNSUPPORTED


DirectDraw7.GetNumFourCCCodes

The DirectDraw7.GetNumFourCCCodes method retrieves the number of FOURCC codes supported by the DirectDraw object.

object.GetFourCCCodes() As Long

Parameters

object
Object expression that resolves to a DirectDraw7 object.

Return Values

If the method succeeds, it returns the number of supported Four-Character Codes(FOURCC).

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

This method is typically called before calling DirectDraw7.GetFourCCCodes.


DirectDraw7.GetScanLine

The DirectDraw7.GetScanLine method retrieves the scan line that is currently being drawn on the monitor.

object.GetScanLine(lines As Long) As Long

Parameters

object
Object expression that resolves to a DirectDraw7 object.
lines
Current scan line.

Return Values

If the method succeeds, it returns DD_OK, indicating that the calling application can continue.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_UNSUPPORTED
DDERR_VERTICALBLANKINPROGRESS

Remarks

Scan lines are reported as zero-based integers. The returned scan line value is in the range from 0 through n, where 0 is the first visible scan line on the screen and n is the last visible scan line, plus any scan lines that occur during the vertical blank period. Therefore, in a case in which an application is running at 640×480, and there are 12 scan lines during vblank, the values returned by this method range from 0 through 491.

See Also

DirectDraw7.GetVerticalBlankStatus, DirectDraw7.WaitForVerticalBlank


DirectDraw7.GetSurfaceFromDC

The DirectDraw7.GetSurfaceFromDC method retrieves the DirectDrawSurface7 object for a surface, based on its GDI device context handle.

object.GetSurfaceFromDC(hdc As Long) As DirectDrawSurface7

Parameters

object
Object expression that resolves to a DirectDraw7 object.
hdc
Handle of a display device context.

Return Values

If the method succeeds, it returns a DirectDrawSurface7.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_GENERIC
DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY
DDERR_NOTFOUND

Remarks

This method succeeds only for device context handles that identify surfaces already associated with the DirectDraw object.

See Also

Surfaces and Device Contexts


DirectDraw7.GetSurfacesEnum

The DirectDraw7.GetSurfacesEnum method returns a DirectDrawEnumSurfaces object that is used to enumerate the attached surfaces of the DirectDraw7 object.

object.GetSurfacesEnum( _
    flags As CONST_DDENUMSURFACESFLAGS, _
    desc As DDSURFACEDESC2) As DirectDrawEnumSurfaces

Parameters

object
Object expression that resolves to a DirectDraw7 object.
flags
CONST_DDENUMSURFACESFLAGS enumeration containing a combination of one search-type flag and one matching flag. The search-type flag determines how the method searches for matching surfaces; you can search for surfaces that can be created, using the description in the desc parameter, or you can search for existing surfaces that already match that description. The matching flag determines whether the method enumerates all surfaces, only those that match, or only those that do not match the description in the desc parameter.
desc
DDSURFACEDESC2 type that defines the surface of interest.

Return Values

If the method succeeds, it returns a DirectDrawEnumSurfaces object that you can then query for a description of the attached surfaces.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
E_OUTOFMEMORY

Remarks

If the DDENUMSURFACES_CANBECREATED flag is set, this method attempts to temporarily create a surface that meets the search criteria.


DirectDraw7.GetVerticalBlankStatus

The DirectDraw7.GetVerticalBlankStatus method retrieves the status of the vertical blank.

object.GetVerticalBlankStatus() As Long

Parameters

object
Object expression that resolves to a DirectDraw7 object.

Return Values

If the method succeeds, it returns the status of the vertical blank. This parameter is 0 if a vertical blank is occurring, and nonzero otherwise.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

To synchronize with the vertical blank, use the DirectDraw7.WaitForVerticalBlank method.

See Also

DirectDraw7.GetScanLine, DirectDraw7.WaitForVerticalBlank


DirectDraw7.LoadPaletteFromBitmap

The DirectDraw7.LoadPaletteFromBitmap method creates a DirectDrawPalette object, based on the palette of the specified bitmap for this DirectDraw object.

object.LoadPaletteFromBitmap( _
    bName As String) As DirectDrawPalette

Parameters

object
Object expression that resolves to a DirectDraw7 object.
bName
Name of the bitmap from which to load the palette.

Return Values

If the method succeeds, it returns a DirectDrawPalette object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOCOOPERATIVELEVELSET
DDERR_OUTOFMEMORY
DDERR_UNSUPPORTED


DirectDraw7.RestoreAllSurfaces

The DirectDraw7.RestoreAllSurfaces method restores all the surfaces created for the DirectDraw object, in the order that they were created.

object.RestoreAllSurfaces()

Parameters

object
Object expression that resolves to a DirectDraw7 object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

This method is provided for convenience. Effectively, this method calls the DirectDrawSurface7.Restore method for each surface created by this DirectDraw object.

See Also

DirectDrawSurface7.Restore, Losing and Restoring Surfaces


DirectDraw7.RestoreDisplayMode

The DirectDraw7.RestoreDisplayMode method resets the mode of the display device hardware for the primary surface to what it was before the DirectDraw7.SetDisplayMode method was called. Exclusive-level access is required to use this method.

object.RestoreDisplayMode()

Parameters

object
Object expression that resolves to a DirectDraw7 object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_GENERIC
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_LOCKEDSURFACES
DDERR_NOEXCLUSIVEMODE

See Also

DirectDraw7.SetDisplayMode, DirectDrawEnumModes, DirectDraw7.SetCooperativeLevel


DirectDraw7.SetCooperativeLevel

The DirectDraw7.SetCooperativeLevel method determines the top-level behavior of the application.

object.SetCooperativeLevel( _
    hdl As Long, _
    flags As CONST_DDSCLFLAGS)

Parameters

object
Object expression that resolves to a DirectDraw7 object.
hdl
Window handle used for the application. Set to the calling application's top-level window handle (not a handle for any child windows created by the top-level window). This parameter can be 0 when the DDSCL_NORMAL flag is specified in the flags parameter.
flags
One or more of the constants from the CONST_DDSCLFLAGS enumeration.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_EXCLUSIVEMODEALREADYSET
DDERR_HWNDALREADYSET
DDERR_HWNDSUBCLASSED
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY

Remarks

This method must be called by the same thread that created the application window.

An application must set either the DDSCL_EXCLUSIVE or the DDSCL_NORMAL flag.

The DDSCL_EXCLUSIVE flag must be set to call functions that can have drastic performance consequences for other applications. For more information, see Cooperative Levels.

See Also

DirectDraw7.SetDisplayMode, DirectDraw7.GetDisplayModesEnum, Mode X and Mode 13 Display Modes, Focus and Device Windows.


DirectDraw7.SetDisplayMode

The DirectDraw7.SetDisplayMode method sets the mode of the display-device hardware.

object.SetDisplayMode( _
    w As Long, _
    h As Long, _
    bpp As Long, _
    ref As Long, _
    mode As CONST_DDSDMFLAGS)

Parameters

object
Object expression that resolves to a DirectDraw7 object.
w and h
Width and height of the new mode.
bpp
Resolution, in bits per pixel (bpp), of the new mode.
ref
Refresh rate of the new mode. Set this value to 0 to request the default refresh rate for the driver.
mode
One of the constants from the CONST_DDSDMFLAGS enumeration describing additional options. Currently, the only valid flag is DDSDM_STANDARDVGAMODE, which causes the method to set Mode 13, instead of Mode X 320x200x8 mode. If you set another resolution, bit depth, or a Mode X mode, do not use this flag; set the parameter to 0.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_GENERIC
DDERR_INVALIDMODE
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_LOCKEDSURFACES
DDERR_NOEXCLUSIVEMODE
DDERR_SURFACEBUSY
DDERR_UNSUPPORTED
DDERR_UNSUPPORTEDMODE
DDERR_WASSTILLDRAWING

Remarks

This method must be called by the same thread that created the application window.

If another application changes the display mode, the primary surface is lost, and the method returns DDERR_SURFACELOST until the primary surface is recreated to match the new display mode.

See Also

DirectDraw7.RestoreDisplayMode, DirectDraw7.GetDisplayModesEnum, DirectDraw7.SetCooperativeLevel, Setting Display Modes, Restoring Display Modes


DirectDraw7.TestCooperativeLevel

The DirectDraw7.TestCooperativeLevel method reports the current cooperative-level status of the DirectDraw device for a windowed or full-screen application.

object.TestCooperativeLevel() As Long

Parameters

object
Object expression that resolves to a DirectDraw7 object.

Return Values

If the method succeeds, it returns DD_OK, indicating that the calling application can continue executing.

Error Codes

If the method fails or DD_OK is not returned, an error is raised, and Err.Number can be set to one of the following values (see Remarks):

DDERR_INVALIDOBJECT
DDERR_EXCLUSIVEMODEALREADYSET
DDERR_NOEXCLUSIVEMODE
DD_OK
DDERR_WRONGMODE

Remarks

This method is particularly useful to applications that use the WM_ACTIVATEAPP and WM_DISPLAYCHANGE system messages as a notification to restore surfaces or recreate DirectDraw objects. A 0 return value always indicates that the application can continue without restoring or recreating surfaces, but the error codes are interpreted differently, depending on the cooperative level that the application uses. For more information, see Testing Cooperative Levels.


DirectDraw7.WaitForVerticalBlank

The DirectDraw7.WaitForVerticalBlank method helps the application synchronize itself with the vertical blank interval.

object.WaitForVerticalBlank( _
    flags As CONST_DDWAITVBFLAGS, _
    handle As Long) As Long

Parameters

object
Object expression that resolves to a DirectDraw7 object.
flags
One of the constants of the CONST_DDWAITVBFLAGS enumeration specifying how long to wait for the vertical blank.
handle
Handle of the event to be triggered when the vertical blank begins. This parameter is not currently used.

Return Values

If the method succeeds, it returns DD_OK, indicating that the calling application can continue.

Error Codes

If the method fails or the return value is not DD_OK, an error is raised, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_UNSUPPORTED
DD_OK
DDERR_WASSTILLDRAWING

See Also

DirectDraw7.GetVerticalBlankStatus, DirectDraw7.GetScanLine


DirectDrawClipper

Applications use the methods of the DirectDrawClipper class to manage clip lists. This section is a reference to the methods of this class. For a conceptual overview, see Clippers.

The methods of the DirectDrawClipper class can be organized into the following groups:

Clip lists | GetClipList
 | GetClipListSize
 | IsClipListChanged
 | SetClipList
Handles | GetHWnd
 | SetHWnd


DirectDrawClipper.GetClipList

The DirectDrawClipper.GetClipList method retrieves a copy of the clip list associated with a DirectDrawClipper object.

object.GetClipList(rects() As RECT)

Parameters

object
Object expression that resolves to a DirectDrawClipper object.
rects()
Array of RECT types filled with the clip list.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_GENERIC
DDERR_INVALIDCLIPLIST
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOCLIPLIST
DDERR_REGIONTOOSMALL

See Also

DirectDrawClipper.SetClipList


DirectDrawClipper.GetClipListSize

The DirectDrawClipper.GetClipListSize method retrieves the size of the clip list associated with a DirectDrawClipper object.

object.GetClipListSize() As Long

Parameters

object
Object expression that resolves to a DirectDrawClipper object.

Return Values

If the method succeeds, the size of the clip list, in bytes, is returned.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_GENERIC
DDERR_INVALIDPARAMS
DDERR_NOCLIPLIST


DirectDrawClipper.GetHWnd

The DirectDrawClipper.GetHWnd method retrieves the window handle previously associated with this DirectDrawClipper object by the DirectDrawClipper.SetHWnd method.

object.GetHWnd() As Long

Parameters

object
Object expression that resolves to a DirectDrawClipper object.

Return Values

If the method succeeds, it returns the window handle.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

See Also

DirectDrawClipper.SetHWnd


DirectDrawClipper.IsClipListChanged

The DirectDrawClipper.IsClipListChanged method monitors the status of the clip list if a window handle is associated with a DirectDrawClipper object.

object.IsClipListChanged() As Long

Parameters

object
Object expression that resolves to a DirectDrawClipper object.

Return Values

If the method succeeds, it returns the status of the clip list. The result is nonzero if the clip list has changed and 0 if it has not.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS


DirectDrawClipper.SetClipList

The DirectDrawClipper.SetClipList method sets or deletes the clip list used by the DirectDrawSurface7.Blt method on surfaces to which the parent DirectDrawClipper object is attached.

object.SetClipList( _
    count As Long, _
    rects() as RECT)

Parameters

object
Object expression that resolves to a DirectDrawClipper object.
count
Number of RECT types in the rects( ) array.
rects()
Array of RECT types that describe the clip list.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_CLIPPERISUSINGHWND
DDERR_INVALIDCLIPLIST
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY

Remarks

The clip list cannot be set if a window handle is already associated with the DirectDrawClipper object. The DirectDrawSurface7.BltFast method cannot clip.

See Also

DirectDrawClipper.GetClipList, DirectDrawSurface7.Blt, DirectDrawSurface7.BltFast


DirectDrawClipper.SetHWnd

The DirectDrawClipper.SetHWnd method sets the window handle to obtain the clipping information.

object.SetHWnd(hdl As Long)

Parameters

object
Object expression that resolves to a DirectDrawClipper object.
hdl
Window handle to obtain the clipping information.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDCLIPLIST
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY

See Also

DirectDrawClipper.GetHWnd


DirectDrawColorControl

The DirectDrawColorControl class allows you to get and set color controls. This object is created with a call to DirectDrawSurface7.GetDirectDrawColorControl. There are two methods in this class:

Color controls | GetColorControls
 | SetColorControls


DirectDrawColorControl.GetColorControls

The DirectDrawColorControl.GetColorControls method returns the current color control settings associated with the specified overlay or primary surface. The IFlags member of the DDCOLORCONTROL type indicates which of the color control options are supported.

object.GetColorControls(colorControl As DDCOLORCONTROL)

Parameters

object
Object expression that resolves to a DirectDrawColorControl object.
colorControl
DDCOLORCONTROL type to receive the current control settings of the specified surface.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_UNSUPPORTED

Remarks

This method fails if the DirectDraw device does not support color controls.

See Also

DirectDrawColorControl.SetColorControls, Using Color Controls, Gamma and Color Controls


DirectDrawColorControl.SetColorControls

The DirectDrawColorControl.SetColorControls method sets the color-control settings associated with the specified overlay or primary surface.

object.SetColorControls(colorControl As DDCOLORCONTROL)

Parameters

object
Object expression that resolves to a DirectDrawColorControl object.
colorControl
DDCOLORCONTROL type that contains the new values to be applied to the specified surface.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_UNSUPPORTED

See Also

DirectDrawColorControl.GetColorControls, Using Color Controls, Gamma and Color Controls


DirectDrawEnum

Applications use the methods of the DirectDrawEnum class to obtain information on video driver display adapters that are installed on the computer. This object is created and filled with data by the DirectX7.GetDDEnum method.

DirectDraw enumeration | GetCount
 | GetDescription
 | GetGuid
 | GetMonitorHandle
 | GetName


DirectDrawEnum.GetCount

The DirectDrawEnum.GetCount method returns the number of DirectDraw drivers installed on the system.

object.GetCount() As Long

Parameters

object
Object expression that resolves to a DirectDrawEnum object.

Return Values

If the method succeeds, it returns the number of entries in the enumeration object.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

Each entry represents a DirectDraw driver description. To get individual driver descriptions, use DirectDrawEnum.GetDescription, DirectDrawEnum.GetGuid, and DirectDrawEnum.GetName.


DirectDrawEnum.GetDescription

The DirectDrawEnum.GetDescription method returns the driver description of the specified DirectDraw device.

object.GetDescription(index As Long) As String

Parameters

object
Object expression that resolves to a DirectDrawEnum object.
index
Particular DirectDraw device in the DirectDrawEnum object.

Return Values

If the method succeeds, it returns the driver description of the device.

Error Codes

If the method fails, it raises an error, and Err.Number is set.


DirectDrawEnum.GetGuid

The DirectDrawEnum.GetGuid returns the unique identifier of the specified DirectDraw device.

object.GetGuid(index As Long) As String

Parameters

object
Object expression that resolves to a DirectDrawEnum object.
index
Particular DirectDraw device in the DirectDrawEnum object.

Return Values

If the method succeeds, it returns the unique identifier of the device.

Error Codes

If the method fails, it raises an error, and Err.Number is set.


DirectDrawEnum.GetMonitorHandle

The DirectDrawEnum.GetMonitorHandle returns the monitor handle of the specified DirectDraw device.

object.GetName(index As Long) As Long

Parameters

object
Object expression that resolves to a DirectDrawEnum object.
index
Particular DirectDraw device in the DirectDrawEnum object.

Return Values

If the method succeeds, it returns the monitor handle of the device.

Error Codes

If the method fails, it raises an error, and Err.Number is set.


DirectDrawEnum.GetName

The DirectDrawEnum.GetName returns the driver name of the specified DirectDraw device.

object.GetName(index As Long) As String

Parameters

object
Object expression that resolves to a DirectDrawEnum object.
index
Particular DirectDraw device in the DirectDrawEnum object.

Return Values

If the method succeeds, it returns the driver name of the device.

Error Codes

If the method fails, it raises an error, and Err.Number is set.


DirectDrawEnumModes

Applications use the methods of the DirectDrawEnumModes class to enumerate the computer's available video modes. This object is created and filled with data by the DirectDraw7.GetDisplayModesEnum method.

DirectDraw mode enumeration | GetCount
 | GetItem


DirectDrawEnumModes.GetCount

The DirectDrawEnumModes.GetCount method returns the number of available video modes.

object.GetCount() As Long

Parameters

object
Object expression that resolves to a DirectDrawEnumModes object.

Return Values

If the method succeeds, it returns the number of available video modes.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

Each entry represents a video mode. To get a description of an individual video mode, use DirectDrawEnumModes.GetItem.


DirectDrawEnumModes.GetItem

The DirectDrawEnumModes.GetItem method returns a video mode description for the specified element in the enumeration object.

object.GetItem(index As Long, info As DDSURFACEDESC2)

Parameters

object
Object expression that resolves to a DirectDrawEnumModes object.
index
Number specifying which element of the array to be accessed. Each element is an available video mode.
info
DDSURFACEDESC2 type to be filled with video-mode information.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

The number of video modes in the DirectDrawEnumModes object can be obtained from the DirectDrawEnumModes.GetCount.


DirectDrawEnumSurfaces

Applications use the methods of the DirectDrawEnumSurfaces class to enumerate all the created surfaces. This object is created and filled with data by the DirectDrawSurface7.GetAttachedSurfaceEnum method.

DirectDraw surface enumeration | GetCount
 | GetItem


DirectDrawEnumSurfaces.GetCount

The DirectDrawEnumSurfaces.GetCount method returns the number of created surfaces.

object.GetCount() As Long

Parameters

object
Object expression that resolves to a DirectDrawEnumSurfaces object.

Return Values

If the method succeeds, it returns the number of created surfaces.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

Each entry represents created DirectDraw surfaces. To get a description of a surface, use DirectDrawEnumSurfaces.GetItem.


DirectDrawEnumSurfaces.GetItem

The DirectDrawEnumSurfaces.GetItem method returns a specific surface from the list of created surfaces of the DirectDrawEnumSurfaces object.

object.GetItem(index As Long) As DirectDrawSurface7

Parameters

object
Object expression that resolves to a DirectDrawEnumSurfaces object.
index
Number specifying which element of the array to be accessed. Each element represents a created surface.

Return Values

DirectDrawSurface7 object describing the surface is returned.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

To obtain the number of created surfaces, call the DirectDrawEnumSurfaces.GetCount method.


DirectDrawGammaControl

Applications use the methods of the DirectDrawGammaControl class to adjust the red, green, and blue gamma ramp levels of the primary surface. This section is a reference to the methods of this class. This object is created with a call to the DirectDrawSurface7.GetDirectDrawGammaControl method.

For a conceptual overview, see Gamma and Color Controls.

Gamma ramps | GetGammaRamp
 | SetGammaRamp


DirectDrawGammaControl.GetGammaRamp

The DirectDrawGammaControl.GetGammaRamp method retrieves the red, green, and blue gamma ramps for the primary surface.

object.GetGammaRamp( _
    flags As CONST_DDSGRFLAGS, _
    gammaRamp As DDGAMMARAMP)

Parameters

object
Object expression that resolves to a DirectDrawGammaControl object.
flags
One of the constants of the CONST_DDSGRFLAGS enumeration indicating if gamma calibration is desired. Set this parameter to DDSGR_CALIBRATE to request that the calibrator adjust the gamma ramp according to the physical properties of the display, making the result identical on all systems. If calibration is not needed, set this parameter to 0.
gammaRamp
DDGAMMARAMP type to be filled with the current red, green, and blue gamma ramps. This type maps color values in the frame buffer to the color values to be passed to the digital-to-analog converter (DAC).

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_EXCEPTION
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

See Also

DirectDrawGammaControl.SetGammaRamp, Gamma and Color Controls


DirectDrawGammaControl.SetGammaRamp

The DirectDrawGammaControl.SetGammaRamp method sets the red, green, and blue gamma ramps for the primary surface.

object.SetGammaRamp( _
    flags As CONST_DDSGRFLAGS, _
    gammaRamp As DDGAMMARAMP)

Parameters

object
Object expression that resolves to a DirectDrawGammaControl object.
flags
One of the constants of the CONST_DDSGRFLAGS enumeration indicating whether gamma calibration is desired. Set this parameter DDSGR_CALIBRATE to request that the calibrator adjust the gamma ramp according to the physical properties of the display, making the result identical on all systems. If calibration is not needed, set this parameter to 0.
gammaRamp
DDGAMMARAMP type that contains the new red, green, and blue gamma ramp entries. Each array maps color values in the frame buffer to the color values to be passed to the digital-to-analog converter (DAC).

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_EXCEPTION
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY

Remarks

Not all systems support gamma calibration. To determine whether gamma calibration is supported, call DirectDraw7.GetCaps, and examine the lCaps2 member of the associated DDCAPS type after the method returns. If the DDCAPS_CANCALIBRATEGAMMA capability flag is present, gamma calibration is supported.

Calibrating gamma ramps incurs some processing overhead and should not be used frequently.

Including the DDSGR_CALIBRATE flag in the flags parameter when running on systems that do not support gamma calibration does not cause this method to fail. The method succeeds, setting new gamma ramp values without calibration.

See Also

DirectDrawGammaControl.GetGammaRamp, Gamma and Color Controls


DirectDrawIdentifier

Applications use the methods of the DirectDrawIdentifier class to obtain information about the DirectDraw driver. This object can be used, with caution, to recognize specific hardware installations to implement workarounds for poor driver or chipset behavior. This object is created with a call to the IDirectDraw7.GetDeviceIdentifier method.

The methods of the DirectDrawIdentifier can be organized into the following group:

Driver information | GetDescription
 | GetDeviceId
 | GetDeviceIdentifier
 | GetDriver
 | GetDriverSubVersion
 | GetDriverVersion
 | GetRevision
 | GetSubSysId
 | GetVendorId
 | GetWHQLLevel


DirectDrawIdentifier.GetDescription

The DirectDrawIdentifier.GetDescription method returns the description of the driver.

object.GetDescription() As String

Parameters

object
Object expression that resolves to a DirectDrawIdentifier object.

Return Values

If the method succeeds, it returns the driver description.

Error Codes

If the method fails, it raises an error, and Err.Number is set.


DirectDrawIdentifier.GetDeviceId

The DirectDrawIdentifier.GetDeviceId method returns the identifier of the type of chipset.

object.GetDeviceId() As Long

Parameters

object
Object expression that resolves to a DirectDrawIdentifier object.

Return Values

If the method succeeds, it returns the identifier of the type of chipset. Can be 0 if unknown.

Error Codes

If the method fails, it raises an error, and Err.Number is set.


DirectDrawIdentifier.GetDeviceIdentifier

The DirectDrawIdentifier.GetDeviceIndentifier method returns the unique identifier for the driver/chipset pair.

object.GetDeviceIndentifier() As String

Parameters

object
Object expression that resolves to a DirectDrawIdentifier object.

Return Values

If the method succeeds, it returns the GUID for the driver/chipset pair. This can be 0 if unknown.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

Use the returned GUID if you wish to track changes to the driver or chipset to reprofile the graphics subsystem. It can also be used to identify particular problematic drivers.


DirectDrawIdentifier.GetDriver

The DirectDrawIdentifier.GetDriver method returns the name of the DirectDraw device driver.

object.GetDriver() As String

Parameters

object
Object expression that resolves to a DirectDrawIdentifier object.

Return Values

If the method succeeds, it returns the driver name.

Error Codes

If the method fails, it raises an error, and Err.Number is set.


DirectDrawIdentifier.GetDriverSubVersion

The DirectDrawIdentifier.GetDriverSubVersion method returns the low part of the driver version.

object.GetDriverSubVersion() As Long

Parameters

object
Object expression that resolves to a DirectDrawIdentifier object.

Return Values

If the method succeeds, it returns the low part of the driver version.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

Caution should be exercised if you use this element to identify problematic drivers. It is recommended that the device identifier be used for this purpose.


DirectDrawIdentifier.GetDriverVersion

The DirectDrawIdentifier.GetDriverVersion method returns the high part of the driver version.

object.GetDriverVersion() As Long

Parameters

object
Object expression that resolves to a DirectDrawIdentifier object.

Return Values

If the method succeeds, it returns the high part of the driver version.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

Caution should be exercised if you use this element to identify problematic drivers. It is recommended that the device identifier be used for this purpose.


DirectDrawIdentifier.GetRevision

The DirectDrawIdentifier.GetRevision method returns the revision level of the chipset.

object.GetRevision() As Long

Parameters

object
Object expression that resolves to a DirectDrawIdentifier object.

Return Values

If the method succeeds, it returns the identifier of the revision level of the chipset. This can be 0 if unknown.

Error Codes

If the method fails, it raises an error, and Err.Number is set.


DirectDrawIdentifier.GetSubSysId

The DirectDrawIdentifier.GetSubSysId method returns the identifier of the subsystem.

object.GetSubSysId() As Long

Parameters

object
Object expression that resolves to a DirectDrawIdentifier object.

Return Values

If the method succeeds, it returns the identifier of the subsystem. Typically, this means the particular board. This can be 0 if unknown.

Error Codes

If the method fails, it raises an error, and Err.Number is set.


DirectDrawIdentifier.GetVendorId

The DirectDrawIdentifier.GetVendorId method returns the identifier of the manufacturer.

object.GetVendorId() As Long

Parameters

object
Object expression that resolves to a DirectDrawIdentifier object.

Return Values

If the method succeeds, it returns the identifier of the manufacturer. This can be 0 if unknown.

Error Codes

If the method fails, it raises an error, and Err.Number is set.


DirectDrawIdentifier.GetWHQLLevel

The DirectDrawIdentifier.GetWHQLLevel method retrieves the Windows Hardware Quality Lab (WHQL) certification level for the device/driver pair.

object.GetWHQLLevel() As Long

Parameters

object
Object expression that resolves to a DirectDrawIdentifier object.

Return Values

If the method succeeds, it returns the Windows Hardware Quality Lab (WHQL) certification level for the device/driver pair.

Error Codes

If the method fails, it raises an error, and Err.Number is set.


DirectDrawPalette

Applications use the methods of the DirectDrawPalette class to create DirectDrawPalette objects and work with system-level variables. A DirectDrawPalette object is created with a call to the DirectDrawSurface7.GetPalette method.

This section is a reference to the methods of this class. For a conceptual overview, see Palettes.

The methods of the DirectDrawPalette class can be organized into the following groups:

Palette capabilities | GetCaps
Palette entries | GetEntries
 | SetEntries


DirectDrawPalette.GetCaps

The DirectDrawPalette.GetCaps method retrieves the capabilities of this palette object.

object.GetCaps() As CONST_DDPCAPSFLAGS

Parameters

object
Object expression that resolves to a DirectDrawPalette object.

Return Values

If the method succeeds, it returns one of the constants of the CONST_DDPCAPSFLAGS enumeration indicating the capabilities of the palette object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS


DirectDrawPalette.GetEntries

The DirectDrawPalette.GetEntries method queries palette values from a DirectDrawPalette object.

object.GetEntries( _
    start As Long, _
    count As Long, _
    val() As PALETTEENTRY)

Parameters

object
Object expression that resolves to a DirectDrawPalette object.
start
Start of the entries to be retrieved sequentially.
count
Number of palette entries that can fit in the address specified in val(). The colors of each palette entry are returned in sequence, from the value of the start parameter through the value of the count parameter minus 1. (These parameters are set by DirectDrawPalette.SetEntries.)
val()
Array of variables of type PALETTEENTRY. The palette entries are 1 byte each if the DDPCAPS_8BITENTRIES flag was set in the flags parameter of the DirectDraw7.CreatePalette, and 4 bytes otherwise. Each field is a color description.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOTPALETTIZED

See Also

DirectDrawPalette.SetEntries


DirectDrawPalette.SetEntries

The DirectDrawPalette.SetEntries method changes entries in a DirectDrawPalette object immediately.

object.SetEntries( _
    start As Long, _
    count As Long, _
    val() As PALETTEENTRY)

Parameters

object
Object expression that resolves to a DirectDrawPalette object.
start
First entry to be set.
count
Number of palette entries to be changed.
val()
Array of variables of type PALETTEENTRY. The palette entries are 1 byte each if the DDPCAPS_8BITENTRIES flag was set in the flags parameter of the DirectDraw7.CreatePalette, and 4 bytes otherwise. Each field is a color description.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOPALETTEATTACHED
DDERR_NOTPALETTIZED
DDERR_UNSUPPORTED

See Also

DirectDrawPalette.GetEntries, DirectDrawSurface7.SetPalette


DirectDrawSurface7

Applications use the methods of the DirectDrawSurface7 class to create DirectDrawSurface objects and work with system-level variables. This section is a reference to the methods of this class. For a conceptual overview, see Surfaces.

The methods of the DirectDrawSurface7 class can be organized into the following groups:

Allocating memory | IsLost
 | Restore
Attaching surfaces | AddAttachedSurface
 | DeleteAttachedSurface
 | GetAttachedSurface
 | GetAttachedSurfaceEnum
Blitting | Blt
 | BltColorFill
 | BltFast
 | BltFx
 | BltToDC
 | GetBltStatus
Color keying | GetColorKey
 | SetColorKey
Device contexts | GetDC
 | ReleaseDC
Drawing and text | DrawBox
 | DrawCircle
 | DrawEllipse
 | DrawLine
 | DrawRoundedBox
 | DrawText
 | GetDrawStyle
 | GetDrawWidth
 | GetFillColor
 | GetFillStyle
 | GetFontBackColor
 | GetFontTransparency
 | GetForeColor
 | SetDrawStyle
 | SetDrawWidth
 | SetFillColor
 | SetFillStyle
 | SetFont
 | SetFontBackColor
 | SetFontTransparency
 | SetForeColor
Flipping | Flip
 | GetFlipStatus
Locking | GetLockedArray
 | GetLockedPixel
 | Lock
 | SetLockedPixel
 | Unlock
Miscellaneous | GetDirectDraw
 | GetDirectDrawColorControl
 | GetDirectDrawGammaControl
Overlays | GetOverlayPosition
 | GetOverlayZOrdersEnum
 | SetOverlayPosition
 | UpdateOverlay
 | UpdateOverlayFx
 | UpdateOverlayZOrder
Surface capabilities | GetCaps
Surface clipper | GetClipper
 | SetClipper
Surface characteristics | ChangeUniquenessValue
 | GetPixelFormat
 | GetSurfaceDesc
 | GetUniquenessValue
Surface palettes | GetPalette
 | SetPalette
Textures | GetLOD
 | GetPriority
 | SetLOD
 | SetPriority


DirectDrawSurface7.AddAttachedSurface

The DirectDrawSurface7.AddAttachedSurface method attaches the specified surface to this surface.

object.AddAttachedSurface(ddS As DirectDrawSurface7)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
ddS
DirectDrawSurface7 object for the surface to be attached.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_CANNOTATTACHSURFACE
DDERR_GENERIC
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_SURFACEALREADYATTACHED
DDERR_SURFACELOST
DDERR_WASSTILLDRAWING

Remarks

You can explicitly unattach the surface by using the DirectDrawSurface7.DeleteAttachedSurface method. Unlike complex surfaces that you create with a single call to DirectDraw7.CreateSurface, surfaces attached with this method are not automatically released. It is the application's responsibility to release such surfaces.

Possible attachments include z-buffers, alpha channels, and back buffers. Some attachments automatically break other attachments. For example, the 3-D z-buffer can be attached to only one back buffer at a time. Attachment is not bidirectional, and a surface cannot be attached to itself. Emulated surfaces (in system memory) cannot be attached to nonemulated surfaces. Unless one surface is a texture map, the two attached surfaces must be the same size. A flipping surface cannot be attached to another flipping surface of the same type; however, attaching two surfaces of different types is allowed. For example, a flipping z-buffer can be attached to a regular flipping surface. If a nonflipping surface is attached to another nonflipping surface of the same type, the two surfaces become a flipping chain. If a nonflipping surface is attached to a flipping surface, it becomes part of the existing flipping chain. Additional surfaces can be added to this chain, and each call to the DirectDrawSurface7.Flip method advances one step through the surfaces.

See Also

DirectDrawSurface7.DeleteAttachedSurface, DirectDrawSurface7.GetAttachedSurfaceEnum


DirectDrawSurface7.Blt

The DirectDrawSurface7.Blt method performs a bit block transfer (blit). This method does not support z-buffering or alpha blending (see alpha channel) during blit operations.

object.Blt( _
    destRect As RECT, _
    ddS As DirectDrawSurface7, _
    srcRect As RECT, _
    flags As CONST_DDBLTFLAGS) As Long

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
destRect
RECT type that defines the upper-left and lower-right points of the rectangle to blit to on the destination surface. If this parameter is an empty RECT type, the entire destination surface is used.
ddS
DirectDrawSurface7 object for the DirectDrawSurface object that is the source of the blit.
srcRect
RECT type that defines the upper-left and lower-right points of the rectangle to blit from on the source surface. If this parameter is an empty RECT, the entire source surface is used.
flags
Combination of constants from the CONST_DDBLTFLAGS enumeration that determines the valid members of the associated DDBLTFX type, which specify color key information, or request special behavior from the method.

Error Codes

If the method fails, it can return one of the following:

DDERR_GENERIC
DDERR_INVALIDCLIPLIST
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDRECT
DDERR_NOALPHAHW
DDERR_NOBLTHW
DDERR_NOCLIPLIST
DDERR_NODDROPSHW
DDERR_NOMIRRORHW
DDERR_NORASTEROPHW
DDERR_NOROTATIONHW
DDERR_NOSTRETCHHW
DDERR_NOZBUFFERHW
DDERR_SURFACEBUSY
DDERR_SURFACELOST
DDERR_UNSUPPORTED
DDERR_WASSTILLDRAWING

Remarks

This method is capable of synchronous or asynchronous blits (the latter is the default behavior), either display memory to display memory, display memory to system memory, system memory to display memory, or system memory to system memory. The blits can be performed by using source color keys and destination color keys. Arbitrary stretching or shrinking is performed if the source and destination rectangles are not the same size.

Typically, DirectDrawSurface7.Blt returns immediately with an error if the blitter is busy and the blit could not be set up. Specify the DDBLT_WAIT flag to request a synchronous blit. When you include the DDBLT_WAIT flag, the method waits until the blit can be set up or another error occurs before it returns.

Note that dstRect and srcRect parameters are defined so that the right and bottom members are exclusive—therefore, right minus left equals the width of the rectangle, not one less than the width.

Because this method often generates an error, instead of setting an error in the error object, the method returns the error code.


DirectDrawSurface7.BltColorFill

The DirectDrawSurface7.BltColorFill method performs a bit block transfer (blit) of a single color to the specified destination rectangle.

object.BltColorFill( _
    destRect As RECT, _
    fillvalue As Long) As Long

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
destRect
RECT type that defines the upper-left and lower-right points of the rectangle to blit to on the destination surface. If this parameter is an empty RECT type, the entire destination surface is used.
fillvalue
Color to blit.

Error Codes

If the method fails, it can return one of the following:

DDERR_GENERIC
DDERR_INVALIDCLIPLIST
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDRECT
DDERR_NOALPHAHW
DDERR_NOBLTHW
DDERR_NOCLIPLIST
DDERR_NODDROPSHW
DDERR_NOMIRRORHW
DDERR_NORASTEROPHW
DDERR_NOROTATIONHW
DDERR_NOSTRETCHHW
DDERR_NOZBUFFERHW
DDERR_SURFACEBUSY
DDERR_SURFACELOST
DDERR_UNSUPPORTED

Remarks

Because this method often generates an error, instead of setting an error in the error object, the method returns the error code.


DirectDrawSurface7.BltFast

The DirectDrawSurface7.BltFast method performs a source copy blit or transparent blit by using a source color key or destination color key.

object.BltFast( _
    dx As Long, _
    dy As Long, _
    ddS As DirectDrawSurface7, _
    srcRect As RECT, _
    trans As CONST_DDBLTFASTFLAGS) As Long

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
dx and dy
X- and y-coordinates to blit to on the destination surface.
ddS
DirectDrawSurface7 object for the DirectDrawSurface object that is the source of the blit.
srcRect
RECT type that defines the upper-left and lower-right points of the rectangle to blit from on the source surface.
trans
One of the constants from the CONST_DDBLTFASTFLAGS enumeration that identifies the type of transfer.

Error Codes

If the method fails, it can return one of the following:

DDERR_EXCEPTION
DDERR_GENERIC
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDRECT
DDERR_NOBLTHW
DDERR_SURFACEBUSY
DDERR_SURFACELOST
DDERR_UNSUPPORTED
DDERR_WASSTILLDRAWING

Remarks

This method always attempts an asynchronous blit if it is supported by the hardware.

This method works only on display memory surfaces and cannot clip when blitting. If you use this method on a surface with an attached clipper, the call fails, and the method returns DDERR_UNSUPPORTED.

The software implementation of DirectDrawSurface7.BltFast is 10 percent faster than the DirectDrawSurface7.Blt method. However, there is no speed difference between the two if display hardware is being used.

Typically, DirectDrawSurface7.BltFast returns immediately with an error if the blitter is busy and the blit cannot be set up. You can use the DDBLTFAST_WAIT flag, however, if you want this method not to return until either the blit can be set up or another error occurs.

Because this method often generates an error, instead of setting an error in the error object, the method returns the error code.


DirectDrawSurface7.BltFx

The DirectDrawSurface7.BltFx method performs a bit block transfer with additional blit effect behavior specified in the BltFx parameter.

object.BltFx( _
    destRect As RECT, _
    ddS As DirectDrawSurface7, _
    srcRect As RECT, _
    flags As CONST_DDBLTFLAGS, _
    BltFx As DDBLTFX) As Long

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
destRect
RECT type that defines the upper-left and lower-right points of the rectangle to blit to on the destination surface. If this parameter is an empty RECT type, the entire destination surface is used.
ddS
DirectDrawSurface7 object that is the source for the blit.
srcRect
RECT type that defines the upper-left and lower-right points of the rectangle to blit from on the source surface. If this parameter is an empty RECT, the entire source surface is used.
flags
Combination of constants of the CONST_DDBLTFLAGS enumeration that determines the valid members of the associated DDBLTFX type, specifies color-key information, or requesta special behavior from the method.
BltFx
DDBLTFX type specifying additional blit effect operations to be performed.

Error Codes

If the method fails, it can return one of the following:

DDERR_GENERIC
DDERR_INVALIDCLIPLIST
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDRECT
DDERR_NOALPHAHW
DDERR_NOBLTHW
DDERR_NOCLIPLIST
DDERR_NODDROPSHW
DDERR_NOMIRRORHW
DDERR_NORASTEROPHW
DDERR_NOROTATIONHW
DDERR_NOSTRETCHHW
DDERR_NOZBUFFERHW
DDERR_SURFACEBUSY
DDERR_SURFACELOST
DDERR_UNSUPPORTED

Remarks

Because this method often generates an error, instead of setting an error in the error object, the method returns the error code.


DirectDrawSurface7.BltToDC

The DirectDrawSurface7.BltToDC method performs a bit block transfer (blit) to the specified device context.

object.BltToDC( _
    hdc As LONG, _
    srcRect As RECT, _
    destRect As RECT)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
hdc
Handle of a device context.
srcRect
RECT type that defines the upper-left and lower-right points of the rectangle to blit from on the source surface. If this parameter is an empty RECT type, the entire source surface is used.
destRect
RECT type that defines the upper-left and lower-right points of the rectangle to blit to on the destination surface. If this parameter is an empty RECT, the entire source surface is used.

Error Codes

If the method fails, it can return one of the following:

DDERR_GENERIC
DDERR_INVALIDCLIPLIST
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDRECT
DDERR_NOALPHAHW
DDERR_NOBLTHW
DDERR_NOCLIPLIST
DDERR_NODDROPSHW
DDERR_NOMIRRORHW
DDERR_NORASTEROPHW
DDERR_NOROTATIONHW
DDERR_NOSTRETCHHW
DDERR_NOZBUFFERHW
DDERR_SURFACEBUSY
DDERR_SURFACELOST
DDERR_UNSUPPORTED

Remarks

Because this method often generates an error, instead of setting an error in the error object, the method returns the error code.


DirectDrawSurface7.ChangeUniquenessValue

The DirectDrawSurface7.ChangeUniquenessValue method manually updates the uniqueness value for this surface.

object.ChangeUniquenessValue()

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_EXCEPTION
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

DirectDraw automatically updates uniqueness values whenever the contents of a surface change.

See Also

DirectDrawSurface7.GetUniquenessValue


DirectDrawSurface7.DeleteAttachedSurface

The DirectDrawSurface7.DeleteAttachedSurface method detaches two attached surfaces.

object.DeleteAttachedSurface(ddS As DirectDrawSurface7)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
ddS
DirectDrawSurface7 object for the DirectDrawSurface object to be detached. If this parameter is Nothing, all attached surfaces are detached.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_CANNOTDETACHSURFACE
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_SURFACELOST
DDERR_SURFACENOTATTACHED

Remarks

Implicit attachments, those formed by DirectDraw, rather than the DirectDrawSurface7.AddAttachedSurface method, cannot be detached. Detaching surfaces from a flipping chain can alter other surfaces in the chain. If a front buffer is detached from a flipping chain, the next surface in the chain becomes the front buffer, and the following surface becomes the back buffer. If a back buffer is detached from a chain, the following surface becomes a back buffer. If a plain surface is detached from a chain, the chain simply becomes shorter. If a flipping chain has only two surfaces and they are detached, the chain is destroyed, and both surfaces return to their previous designations.

See Also

DirectDrawSurface7.Flip


DirectDrawSurface7.DrawBox

The DirectDrawSurface7.DrawBox method draws a box on the surface.

object.DrawBox( _
    x1 As Long, _
    y1 As Long, _
    x2 As Long, _
    y2 As Long)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
x1, y1, x2, y2
Upper-left and bottom-right points of the box to be drawn.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

The default draw style is a solid line, and the default fill style is set to transparent. Both styles can be changed with a call to DirectDrawSurface7.SetDrawStyle and DirectDrawSurface7.SetFillStyle, respectively.


DirectDrawSurface7.DrawCircle

The DirectDrawSurface7.DrawCircle method draws a circle on the surface.

object.DrawCircle( _
    x1 As Long, _
    y1 As Long, _
    r As Long)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
x1, y1, r
Center point and radius of the circle to be drawn.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

The default draw style is a solid line, and the default fill style is set to transparent. Both styles can be changed with a call to DirectDrawSurface7.SetDrawStyle and DirectDrawSurface7.SetFillStyle, respectively.


DirectDrawSurface7.DrawEllipse

The DirectDrawSurface7.DrawEllipse method draws an ellipse on the surface.

object.DrawEllipse(x1 As Long, _
    y1 As Long, _
    x2 As Long, _
    y2 As Long)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
x1, y1, x2, y2
Upper-left and lower-right corners of the bounding rectangle of the ellipse to be drawn.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

The default draw style is a solid line, and the default fill style is set to transparent. Both styles can be changed with a call to DirectDrawSurface7.SetDrawStyle and DirectDrawSurface7.SetFillStyle, respectively.


DirectDrawSurface7.DrawLine

The DirectDrawSurface7.DrawLine method draws a line on the surface.

object.DrawLine( _
    x1 As Long, _
    y1 As Long, _
    x2 As Long, _
    y2 As Long)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
x1, y1, x2, y2
End points of the line to be drawn.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

The default draw style is a solid line; this can be changed with a call to DirectDrawSurface7.SetDrawStyle.


DirectDrawSurface7.DrawRoundedBox

The DirectDrawSurface7.DrawRoundedBox method draws a rounded box on the surface.

object.DrawRoundedBox( _
    x1 As Long, _
    y1 As Long, _
    x2 As Long, _
    y2 As Long, _
    rw As Long, _
    rh As Long)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
x1, y1, x2, y2
Upper-left and lower-right points of the rectangle.
rw
Width of the ellipse used to draw the rounded corners.
rh
Height of the ellipse used to draw the rounded corners.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

The default draw style is a solid line, and the default fill style is set to transparent. Both styles can be changed with a call to DirectDrawSurface7.SetDrawStyle and DirectDrawSurface7.SetFillStyle, respectively.


DirectDrawSurface7.DrawText

The DirectDrawSurface7.DrawText method draws text on the surface.

object.DrawText( _
    x As Long, _
    y As Long, _
    text As String, _
    b As Boolean)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
x, y
Location on the surface to draw text.
text
Text to display.
b
Boolean value indicating whether to draw to the current cursor position. See Remarks.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

To append text to the end of the last call to DirectDrawSurface7.DrawText, pass 0,0 as the x- and y-coordinates, and declare b as True. If you declare b as False, calling this method causes text to be displayed at the specified x- and y-coordinates.


DirectDrawSurface7.Flip

The DirectDrawSurface7.Flip method makes the surface memory associated with the DDSCAPS_BACKBUFFER surface become associated with the front-buffer surface.

object.Flip( _
    ddS As DirectDrawSurface7, _
    flags As CONST_DDFLIPFLAGS)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
ddS
DirectDrawSurface7 object for an arbitrary surface in the flipping chain. The default for this parameter is Nothing, in which case DirectDraw cycles through the buffers in the order that they are attached to each other. If this parameter is not Nothing, DirectDraw flips to the specified surface, instead of the next surface in the flipping chain. The method fails if the specified surface is not a member of the flipping chain.
flags
One or more constants of the CONST_DDFLIPFLAGS enumeration specifying flip options.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_GENERIC
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOFLIPHW
DDERR_NOTFLIPPABLE
DDERR_SURFACEBUSY
DDERR_SURFACELOST
DDERR_UNSUPPORTED
DDERR_WASSTILLDRAWING

Remarks

This method can be called only for a surface that has the DDSCAPS_FLIP and DDSCAPS_FRONTBUFFER capabilities. The display memory previously associated with the front buffer is associated with the back buffer.

The ddS parameter is used in rare cases when the back buffer is not the buffer that should become the front buffer. Typically, this parameter is Nothing.

The DirectDrawSurface7.Flip method is always synchronized with the vertical blank. If the surface has been assigned to a video port, this method updates the visible overlay surface and the video port's target surface.

For more information, see Flipping Surfaces.

See Also

DirectDrawSurface7.GetFlipStatus


DirectDrawSurface7.GetAttachedSurface

The DirectDrawSurface7.GetAttachedSurface method obtains the attached surface that has the specified capabilities.

object.GetAttachedSurface( _
    caps As DDSCAPS2) As DirectDrawSurface7

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
caps
DDSCAPS2 type that contains the hardware capabilities of the surface.

Return Values

If the method succeeds, a DirectDrawSurface7 object is returned. The retrieved surface is the one that matches the description, according to the caps parameter.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOTFOUND
DDERR_SURFACELOST

Remarks

Attachments are used to connect multiple DirectDrawSurface objects into complex types, like the ones needed to support 3-D page flipping with z-buffers. This method fails if more than one surface is attached that matches the capabilities requested. In this case, the application must use the DirectDrawSurface7.GetAttachedSurfaceEnum method to obtain the attached surfaces.

The object returned by a successful function call must be assigned to a DirectDrawSurface7 object variable. For example:

Dim DDrawSurface as DirectDrawSurface7
Set DDrawSurface = object.GetAttachedSurface()


DirectDrawSurface7.GetAttachedSurfaceEnum

The DirectDrawSurface7.GetAttachedSurfaceEnum method returns a DirectDrawEnumSurfaces object that is filled with attached surfaces information .

object.GetAttachedSurfaceEnum() As DirectDrawEnumSurfaces

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.

Return Values

If the method succeeds, it returns a DirectDrawEnumSurfaces enumeration interface.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_SURFACELOST

Remarks

The number of attached surfaces is obtained with a call to DirectDrawEnumSurfaces.GetCount, and a description of the attached surface is obtained with a call to DirectDrawEnumSurfaces.GetItem

The object returned by a successful function call must be assigned to a DirectDrawEnumSurfaces object variable. For example:

Dim SurfaceEnum as DirectDrawEnumSurfaces
Set SurfaceEnum = object.GetAttachedSurfacesEnum()


DirectDrawSurface7.GetBltStatus

The DirectDrawSurface7.GetBltStatus method obtains the blitter status.

object.GetBltStatus(flags As CONST_DDGBSFLAGS) As Long

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
flags
One of the constants of the CONST_DDGBSFLAGS enumeration.

Return Values

If the method succeeds, depending on which constant is specified in the flags parameter, 0 is returned for False and nonzero for True.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DDERR_WASSTILLDRAWING if the surface has not finished its flipping process, or one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDSURFACETYPE
DDERR_SURFACEBUSY
DDERR_SURFACELOST
DD_OK
DDERR_UNSUPPORTED


DirectDrawSurface7.GetCaps

The DirectDrawSurface7.GetCaps method retrieves the capabilities of the surface. These capabilities are not necessarily related to the capabilities of the display device.

object.GetCaps(caps As DDSCAPS2)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
caps
DDSCAPS2 type to be filled with the hardware capabilities of the surface.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS


DirectDrawSurface7.GetClipper

The DirectDrawSurface7.GetClipper method retrieves the DirectDrawClipper object associated with this surface.

object.GetClipper() As DirectDrawClipper

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.

Return Values

If the method succeeds, it returns a DirectDrawClipper object associated with the surface.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOCLIPPERATTACHED

See Also

DirectDrawSurface7.SetClipper

Remarks

The object returned by a successful function call must be assigned to a DirectDrawClipper object variable. For example:

Dim Clipper as DirectDrawClipper
Set Clipper = object.GetClipper()


DirectDrawSurface7.GetColorKey

The DirectDrawSurface7.GetColorKey method retrieves the color key value for the DirectDrawSurface object.

object.GetColorKey(flags As Long, val As DDCOLORKEY)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
flags
Color key requested. One of the following:
DDCKEY_DESTBLT
A color key or color space to be used as a destination color key for blit operations.
DDCKEY_DESTOVERLAY
A color key or color space to be used as a destination color key for overlay operations.
DDCKEY_SRCBLT
A color key or color space to be used as a source color key for blit operations.
DDCKEY_SRCOVERLAY
A color key or color space to be used as a source color key for overlay operations.
val
DDCOLORKEY type to be filled with the current values for the specified color key of the DirectDrawSurface object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOCOLORKEY
DDERR_NOCOLORKEYHW
DDERR_SURFACELOST
DDERR_UNSUPPORTED

See Also

DirectDrawSurface7.SetColorKey


DirectDrawSurface7.GetDC

The DirectDrawSurface7.GetDC method creates a GDI-compatible handle of a device context for the surface.

object.GetDC() As Long

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.

Return Values

If the method succeeds, it returns the handle to a device context.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_DCALREADYCREATED
DDERR_GENERIC
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDSURFACETYPE
DDERR_SURFACELOST
DDERR_UNSUPPORTED
DDERR_WASSTILLDRAWING

Remarks

This method uses an internal version of the DirectDrawSurface7.Lock method to lock the surface. The surface remains locked until the DirectDrawSurface7.ReleaseDC method is called.

See Also

DirectDrawSurface7.Lock


DirectDrawSurface7.GetDirectDraw

The DirectDrawSurface7.GetDirectDraw method retrieves the DirectDraw object that was used to create the surface.

object.GetDirectDraw() As DirectDraw7

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.

Return Values

If the method succeeds, it returns a DirectDraw7 object.

Error Codes

If the method fails, itr raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

The object returned by a successful function call must be assigned to a DirectDraw7 object variable. For example:

Dim DDrawObject as DirectDraw7
Set DDrawObject = object.GetDDInterface()


DirectDrawSurface7.GetDirectDrawColorControl

The DirectDrawSurface7.GetDirectDrawColorControl method returns the DirectDrawColorControl object used with the surface.

object.GetDirectDrawColorControl() As DirectDrawColorControl

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.

Return Values

If the method succeeds, it returns a DirectDrawColorControl object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS


DirectDrawSurface7.GetDirectDrawGammaControl

The DirectDrawSurface7.GetDirectDrawGammaControl method returns the DirectDrawGammaControl object used with the surface.

object.GetDirectDrawGammaControl() As DirectDrawGammaControl

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.

Return Values

If the method succeeds, it returns a DirectDrawGammaControl object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS


DirectDrawSurface7.GetDrawStyle

The DirectDrawSurface7.GetDrawStyle returns the style set by DirectDrawSurface7.SetDrawStyle.

object.GetDrawStyle() As Long

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.

Return Values

The style set by DirectDrawSurface7.SetDrawStyle.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

The default draw style is a solid line.


DirectDrawSurface7.GetDrawWidth

The DirectDrawSurface7.GetDrawWidth returns the width set by DirectDrawSurface7.SetDrawWidth.

object.GetDrawWidth() As Long

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.

Return Values

The width set by DirectDrawSurface7.SetDrawWidth.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

The default draw width is 1.


DirectDrawSurface7.GetFillColor

The DirectDrawSurface7.GetFillColor returns the fill color set by DirectDrawSurface7.SetFillColor.

object.GetFillColor() As Long

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.

Return Values

If the method succeeds, it returns the fill color value set by DirectDrawSurface7.SetFillColor.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

The default fill color is black.


DirectDrawSurface7.GetFillStyle

The DirectDrawSurface7.GetFillStyle returns the fill style set by DirectDrawSurface7.SetFillStyle.

object.GetFillStyle() As Long

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.

Return Values

If the method succeeds, it returns the fill style set by DirectDrawSurface7.SetFillStyle.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

The default fill style is transparent.


DirectDrawSurface7.GetFlipStatus

The DirectDrawSurface7.GetFlipStatus method indicates whether the surface has finished its flipping process.

object.GetFlipStatus(flags As CONST_DDGFSFLAGS) As Long

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
flags
One of the constants of the CONST_DDGFSFLAGS enumeration.

Return Values

If the method succeeds, depending on which constant is specified in the flags parameter, 0 is returned for False and nonzero for True.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DDERR_WASSTILLDRAWING if the surface has not finished its flipping process, or one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDSURFACETYPE
DDERR_SURFACEBUSY
DDERR_SURFACELOST
DD_OK
DDERR_UNSUPPORTED

See Also

DirectDrawSurface7.Flip


DirectDrawSurface7.GetFontBackColor

The DirectDrawSurface7.GetFontBackColor returns the background color for the font.

object.GetFontBackColor() As Long

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.

Return Values

If the method succeeds, it returns the background color for the font.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

DirectDrawSurface7.SetFontBackColor


DirectDrawSurface7.GetFontTransparency

The DirectDrawSurface7.GetFontTransparency method returns the font transparency set by DirectDrawSurface7.SetFontTransparency.

object.GetFontTransparency() As Boolean

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.

Return Values

If the font is set to be transparent, nonzero is returned and 0 if the font is not set to be transparent.

Error Codes

If the method fails, it raises an error, and Err.Number is set.


DirectDrawSurface7.GetForeColor

The DirectDrawSurface7.GetForeColor returns the foreground color set by DirectDrawSurface7.SetForeColor.

object.GetForeColor() As Long

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.

Return Values

If the method succeeds, it returns the foreground color set by DirectDrawSurface7.SetForeColor.

Error Codes

If the method fails, it raises an error, and Err.Number is set.


DirectDrawSurface7.GetLockedArray

The DirectDrawSurface7.GetLockedArray method returns a pointer to the array of locked pixels after a call to DirectDrawSurface7.Lock.

object.GetLockedArray( _
    array() As Byte)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
array()
Array of locked pixels, in bytes.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

This method is provided for advanced users. Use this method only between DirectDrawSurface7.Lock and DirectDrawSurface7.Unlock calls. On some display cards, the pitch is not equal to the width of the surface; be sure not to write in memory beyond the array.


DirectDrawSurface7.GetLockedPixel

The DirectDrawSurface7.GetLockedPixel method returns the specified pixel set by DirectDrawSurface7.SetLockedPixel.

object.GetLockedPixel( _
    x As Long, _
    y As Long) As Long

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
x and y
Coordinates of the locked pixel.

Return Values

If the method succeeds, it returns the color of the locked pixel. This value is in the same format as the pixel format.

Error Codes

If the method fails, it raises an error, and Err.Number is set.


DirectDrawSurface7.GetLOD

The DirectDrawSurface7.GetLOD method retrieves the maximum level of detail currently set for a managed mipmap surface. This method succeeds only on managed textures (see Remarks).

object.GetLOD() As Long

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.

Return Values

If the method succeeds, it returns the maximum level of detail for the mipmap chain.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDPARAMS
DDERR_INVALIDOBJECT

Remarks

Applications can call this method only for managed textures (those that were created with the DDSCAPS2_TEXTUREMANAGE flag). Calling this method on a nonmanaged texture causes the method to fail and raise the DDERR_INVALIDOBJECT error.

This method communicates to the Direct3D texture manager the most detailed mipmap in this chain that it should load into local video memory. For example, in a five-level mipmap chain, a return value of 2 indicates that the texture manager only loads mipmap levels 2 through 4 into local video memory at any given time. Likewise, if the most detailed mipmap in the chain has the dimensions 256×256, a return value of 2 means that the largest mipmap ever present in video memory has dimensions 64×64.

See Also

DirectDrawSurface7.SetLOD, Texture Filtering With Mipmaps, Automatic Texture Management, Textures


DirectDrawSurface7.GetOverlayPosition

Given a visible, active overlay surface (DDSCAPS_OVERLAY flag set), the DirectDrawSurface7.GetOverlayPosition method returns the display coordinates of the surface.

object.GetOverlayPosition(x As Long, y As Long)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
x and y
Addresses of the x and y display coordinates.

Return Values

If the method succeeds, it returns the display coordinates of the active overlay surface.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_GENERIC
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDPOSITION
DDERR_NOOVERLAYDEST
DDERR_NOTAOVERLAYSURFACE
DDERR_OVERLAYNOTVISIBLE
DDERR_SURFACELOST

See Also

DirectDrawSurface7.SetOverlayPosition, DirectDrawSurface7.UpdateOverlay


DirectDrawSurface7.GetOverlayZOrdersEnum

The DirectDrawSurface7::GetOverlayZOrdersEnum method returns a DirectDrawEnumSurfaces object that is used to enumerate the overlay surfaces on the specified destination. The overlays can be enumerated in front-to-back or back-to-front order.

object.(flags As CONST_DDENUMOVERLAYZFLAGS) _
    As DirectDrawEnumSurfaces

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
flags
One of the constants of the CONST_DDENUMOVERLAYZFLAGS enumeration specifying enumeration options.

Return Values

If the method succeeds, it returns a DirectDrawEnumSurfaces object that you can then query for overlay surface z-order information.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

See Also

DirectDrawSurface7.UpdateOverlayZOrder


DirectDrawSurface7.GetPalette

The DirectDrawSurface7.GetPalette method retrieves the DirectDrawPalette object associated with this surface.

object.GetPalette() As DirectDrawPalette

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.

Return Values

If the method succeeds, it returns a DirectDrawPalette object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_GENERIC
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOEXCLUSIVEMODE
DDERR_NOPALETTEATTACHED
DDERR_SURFACELOST
DDERR_UNSUPPORTED

Remarks

The object returned by a successful function call must be assigned to a DirectDrawPalette object variable. For example:

Dim DDPalette as DirectDrawPalette
Set DDPalette = object.GetPalette()

See Also

DirectDrawSurface7.SetPalette


DirectDrawSurface7.GetPixelFormat

The DirectDrawSurface7.GetPixelFormat method retrieves the color and pixel format of the surface.

object.GetPixelFormat(pf As DDPIXELFORMAT)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
pf
DDPIXELFORMAT type to be filled with a detailed description of the current pixel and color space format of the surface.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDSURFACETYPE


DirectDrawSurface7.GetPriority

The DirectDrawSurface7.GetPriority method retrieves the texture management priority for this texture. This method succeeds only on managed textures (see Remarks).

object.GetPriority() As Long

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.

Return Values

If the method succeeds, it returns the texture priority.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DDERR_INVALIDOBJECT if the parameter is invalid or if the texture is not managed by Direct3D.

Remarks

Priorities are used to determine when managed textures are to be removed from memory. A texture assigned a low priority is removed before a texture with a high priority. If two textures have the same priority, the texture that was used more recently is kept in memory; the other texture is removed.

Applications can only set and retrieve priorities for managed textures (those that were created with the DDSCAPS2_TEXTUREMANAGE flag). Calling this method on a nonmanaged texture causes the method to fail and return DDERR_INVALIDOBJECT

See Also

DirectDrawSurface7.SetPriority, Automatic Texture Management


DirectDrawSurface7.GetSurfaceDesc

The DirectDrawSurface7.GetSurfaceDesc method retrieves a description of the surface in its current condition.

object.GetSurfaceDesc(surface As DDSURFACEDESC2)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
surface
DDSURFACEDESC2 type to be filled with the current description of this surface.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS


DirectDrawSurface7.GetUniquenessValue

The DirectDrawSurface7.GetUniquenessValue method retrieves the current uniqueness value for this surface.

object.GetUniquenessValue() As Long

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.

Return Values

If the method succeeds, it returns the current uniqueness value of the surface.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

The only defined uniqueness value is 0, to indicate that the surface is likely to be changing beyond the control of DirectDraw. Other uniqueness values are only significant if they differ from a previously cached uniqueness value. If the current value is different than a cached value, the contents of the surface have changed.

See Also

DirectDrawSurface7.ChangeUniquenessValue


DirectDrawSurface7.IsLost

The DirectDrawSurface7.IsLost method determines whether the surface memory associated with a DirectDrawSurface object has been freed.

object.IsLost() As Long

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.

Return Values

If the method succeeds, it returns 0 (False), indicating that the surface has not been freed and nonzero if it has been freed.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_SURFACELOST

Remarks

You can use this method to find out whether you need to reallocate surface memory by calling the DirectDrawSurface7.Restore method. When a DirectDrawSurface object loses its surface memory, most methods return DDERR_SURFACELOST and perform no other action.

Surfaces can lose their memory when the mode of the display card is changed or an application receives exclusive access to the display card and frees all surface memory currently allocated on the display card.

See Also

DirectDrawSurface7.Restore, Losing and Restoring Surfaces


DirectDrawSurface7.Lock

The DirectDrawSurface7.Lock method obtains a pointer to the surface memory.

object.Lock( _
    r As RECT, _
    desc As DDSURFACEDESC2, _
    flags As CONST_DDLOCKFLAGS, _
    hnd As Long)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
r
RECT type that defines the upper-left and lower-right points of the rectangle that identifies the region of surface that is being locked. If this is an empty RECT, the entire surface is locked.
desc
DDSURFACEDESC2 type to be filled with the relevant details about the surface.
flags
One or more of the constants of the CONST_DDLOCKFLAGS enumeration that describes the type of lock to be performed.
hnd
Not used and must be set to 0.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY
DDERR_SURFACEBUSY
DDERR_SURFACELOST
DDERR_WASSTILLDRAWING

Remarks

For more information on using this method, see Accessing Surface Memory Directly.

After retrieving a surface memory pointer, you can access the surface memory until a corresponding DirectDrawSurface7.Unlock method is called. When the surface is unlocked, the pointer to the surface memory is invalid.

Do not call DirectDraw blit functions to blit from a locked region of a surface. If you do, the blit returns either DDERR_SURFACEBUSY or DDERR_LOCKEDSURFACES. GDI blit functions also silently fail when used on a locked video-memory surface.

This method often causes DirectDraw to hold the Win16Mutex (also known as Win16Lock) until you call the DirectDrawSurface7.Unlock method. GUI debuggers cannot operate while the Win16Mutex is held.

See Also

DirectDrawSurface7.Unlock, DirectDrawSurface7.GetDC, DirectDrawSurface7.ReleaseDC


DirectDrawSurface7.ReleaseDC

The DirectDrawSurface7.ReleaseDC method releases the handle of a device context previously obtained by using the DirectDrawSurface7.GetDC method.

object.ReleaseDC(hdc As Long)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
hdc
Handle of a device context previously obtained by DirectDrawSurface7.GetDC.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_GENERIC
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_SURFACELOST
DDERR_UNSUPPORTED

Remarks

This method also unlocks the surface previously locked when the DirectDrawSurface7.GetDC method was called.

See Also

DirectDrawSurface7.GetDC


DirectDrawSurface7.Restore

The DirectDrawSurface7.Restore method restores a surface that has been lost. This occurs when the surface memory associated with the DirectDrawSurface object has been freed.

object.Restore()

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_GENERIC
DDERR_IMPLICITLYCREATED
DDERR_INCOMPATIBLEPRIMARY
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOEXCLUSIVEMODE
DDERR_OUTOFMEMORY
DDERR_UNSUPPORTED
DDERR_WRONGMODE

Remarks

This method restores the memory allocated for a surface, but does not reload any bitmaps that might have existed in the surface before it was lost. Only surfaces that were created with the DDSCAPS2_PERSISTENTCONTENT flag have their contents automatically restored. When surfaces without this capability are lost, you must completely reconstitute the graphics that they once held after you restore their memory.

Surfaces can be lost because the mode of the display card was changed or an application received exclusive access to the display card and freed all surface memory currently allocated on the card. When a DirectDrawSurface object loses its surface memory, many methods return DDERR_SURFACELOST and perform no other function. The DirectDrawSurface7.Restore method reallocates surface memory and reattaches it to the DirectDrawSurface object.

A single call to this method restores a DirectDrawSurface object's associated implicit surfaces (back buffers, and so on). An attempt to restore an implicitly created surface results in an error. DirectDrawSurface7.Restore does not work across explicit attachments created by using the DirectDrawSurface7.AddAttachedSurface method—each of these surfaces must be restored individually.

See Also

DirectDrawSurface7.IsLost


DirectDrawSurface7.SetClipper

The DirectDrawSurface7.SetClipper method attaches a clipper object to, or deletes one from, a surface.

object.SetClipper(val As DirectDrawClipper)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
val
DirectDrawClipper object for the DirectDrawClipper object to be attached to the DirectDrawSurface object. If this parameter is Nothing, the current DirectDrawClipper object is detached.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDSURFACETYPE
DDERR_NOCLIPPERATTACHED

Remarks

If you pass Nothing as the val parameter, the clipper is removed from the surface. This method is primarily used by surfaces that are being overlaid on or blitted to the primary surface. However, it can be used on any surface. After a DirectDrawClipper object has been attached and a clip list is associated with it, the DirectDrawClipper object is used for the DirectDrawSurface7.Blt operations involving the parent DirectDrawSurface object. This method can also detach a DirectDrawSurface object's current DirectDrawClipper object.

See Also

DirectDrawSurface7.GetClipper


DirectDrawSurface7.SetColorKey

The DirectDrawSurface7.SetColorKey method sets the color key value for the DirectDrawSurface object if the hardware supports color keys on a per-surface basis.

object.SetColorKey( _
    flags As CONST_DDCKEYFLAGS, _
    val As DDCOLORKEY)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
flags
One of the constants of the CONST_DDCKEYFLAGS enumeration specifying the type of color key requested.
val
DDCOLORKEY type that contains the new color key values for the DirectDrawSurface object. This value can be Nothing to remove a previously set color key.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_GENERIC
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDSURFACETYPE
DDERR_NOOVERLAYHW
DDERR_NOTAOVERLAYSURFACE
DDERR_SURFACELOST
DDERR_UNSUPPORTED
DDERR_WASSTILLDRAWING

Remarks

For transparent blits and overlays, set destination color on the destination surface and source color on the source surface.

See Also

DirectDrawSurface7.GetColorKey


DirectDrawSurface7.SetDrawStyle

The DirectDrawSurface7.SetDrawStyle sets the draw style.

object.SetDrawStyle(drawStyle As Long)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
drawStyle
One of the following draw styles to be set.
Setting | Description
0 | (Default) Solid
1 | Dash
2 | Dot
3 | Dash-dot
4 | Dash-dot-dot
5 | Transparent
6 | Inside solid

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

DirectDrawSurface7.GetDrawStyle


DirectDrawSurface7.SetDrawWidth

The DirectDrawSurface7.SetDrawWidth sets the width of the line used in drawing methods.

object.setDrawWidth(drawWidth As Long)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
drawWidth
Width of the line used in drawing methods. The default value is 1. Any value in the range from 1 through 32,767 is valid.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

DirectDrawSurface7.GetDrawWidth


DirectDrawSurface7.SetFillColor

The DirectDrawSurface7.SetFillColor specifies the fill color used in drawing methods.

object.SetFillColor(color As Long)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
color
RGB value to be used as the fill color in drawing methods. The default value is black (&H00000000).

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

DirectDrawSurface7.GetFillColor


DirectDrawSurface7.SetFillStyle

The DirectDrawSurface7.SetFillStyle specifies the fill style used in the drawing methods.

object.SetFillStyle(fillStyle As Long)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
fillStyle
One of the following fill styles to be used in drawing methods.
Setting | Description
0 | (Default) Solid
1 | Transparent
2 | Horizontal line
3 | Vertical line
4 | Upward diagonal
5 | Downward diagonal
6 | Cross
7 | Diagonal cross

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

DirectDrawSurface7.GetFillStyle


DirectDrawSurface7.SetFont

The DirectDrawSurface7.SetFont specifies the font to be used in DirectDrawSurface7.DrawText.

object.SetFont(font As IFont)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
font
Font, as specified in the IFont class.

Error Codes

If the method fails, it raises an error, and Err.Number is set.


DirectDrawSurface7.SetFontBackColor

The DirectDrawSurface7.SetFontBackColor method sets the back color of the font.

object.SetFontBackColor(color As Long)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
color
Back color of the font.

Error Codes

If the method fails, it raises an error, and Err.Number is set.


DirectDrawSurface7.SetFontTransparency

The DirectDrawSurface7.SetFontTransparency specifies whether the font to be used when the DirectDrawSurface7.DrawText called is transparent.

object.SetFontTransparency(b As Boolean)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
b
Set to D_TRUE if the font is transparent, or D_FALSE if the font is not transparent.

Error Codes

If the method fails, it raises an error, and Err.Number is set.


DirectDrawSurface7.SetForeColor

The DirectDrawSurface7.SetForeColor method sets the foreground color used in drawing methods.

object.SetForeColor(color As Long)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
color
RGB value to set as the foreground color.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

DirectDrawSurface7.GetForeColor


DirectDrawSurface7.SetLockedPixel

The DirectDrawSurface7.SetLockedPixel method sets a single pixel to the specified color and updates the locked surface.

object.SetLockedPixel( _
    x As Long, _
    y As Long, _
    col As Long)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
x and y
Coordinates of the pixel to set.
col
RGB value for the set pixel.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

You must first lock the surface with a call to DirectDrawSurface7.Lock.

See Also

DirectDrawSurface7.GetLockedPixel


DirectDrawSurface7.SetLOD

The DirectDrawSurface7.SetLOD method sets the maximum level of detail for a managed mipmap surface. This method succeeds only on managed textures (see Remarks).

object.SetLOD(lod As Long)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
lod
Maximum level-of-detail value to be set for the mipmap chain if the call succeeds.

Return Values

If the method succeeds, it return DD_OK.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

Applications can call this method only for managed textures (those that were created with the DDSCAPS2_TEXTUREMANAGE flag). Calling this method on a nonmanaged texture causes the method to fail and return DDERR_INVALIDOBJECT

This method communicates to the Direct3D texture manager the most detailed mipmap in this chain that it should load into local video memory. For example, in a five-level mipmap chain, setting lod to 2 indicates that the texture manager should only load mipmap levels 2 through 4 into local video memory at any given time. Likewise, if the most detailed mipmap in the chain has the dimensions 256×256, setting the maximum level to 2 means that the largest mipmap ever present in video memory has dimensions 64×64.

See Also

DirectDrawSurface7.GetLOD, Texture Filtering With Mipmaps, Automatic Texture Management , Textures


DirectDrawSurface7.SetOverlayPosition

The DirectDrawSurface7.SetOverlayPosition method changes the display coordinates of an overlay surface.

object.SetOverlayPosition(x As Long, y As Long)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
x and y
New x- and y-display coordinates.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_GENERIC
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDPOSITION
DDERR_NOOVERLAYDEST
DDERR_NOTAOVERLAYSURFACE
DDERR_OVERLAYNOTVISIBLE
DDERR_SURFACELOST
DDERR_UNSUPPORTED

See Also

DirectDrawSurface7.GetOverlayPosition


DirectDrawSurface7.SetPalette

The DirectDrawSurface7.SetPalette method attaches a palette object to (or detaches one from) a surface. The surface uses this palette for all subsequent operations. The palette change takes place immediately, without regard to refresh timing.

object.SetPalette(ddp As DirectDrawPalette)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
ddp
DirectDrawPalette object for the palette object to be used with this surface. If this parameter is Nothing, the current palette is detached.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_GENERIC
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDPIXELFORMAT
DDERR_INVALIDSURFACETYPE
DDERR_NOEXCLUSIVEMODE
DDERR_NOPALETTEATTACHED
DDERR_NOPALETTEHW
DDERR_NOT8BITCOLOR
DDERR_SURFACELOST
DDERR_UNSUPPORTED

Remarks

If you pass Nothing as the ddp parameter, the palette is removed from the surface.

See Also

DirectDrawSurface7.GetPalette, DirectDraw7.CreatePalette


DirectDrawSurface7.SetPriority

The DirectDrawSurface7.SetPriority method assigns the texture management priority for this texture. This method succeeds only on managed textures (see Remarks).

object.SetPriority(Priority As Long)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
Priority
Value specifying the new texture-management priority for the texture.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DDERR_INVALIDOBJECT if the parameter is invalid or the texture is not managed by Direct3D.

Remarks

Priorities are used to determine when managed textures are to be removed from memory. A texture assigned a low priority is removed before a texture with a high priority. If two textures have the same priority, the texture that was used more recently is kept in memory; the other texture is removed.

Applications can set and retrieve priorities only for managed textures (those that were created with the DDSCAPS2_TEXTUREMANAGE flag). Calling this method on a nonmanaged texture causes the method to fail and return DDERR_INVALIDOBJECT.

See Also

DirectDrawSurface7.GetPriority, Automatic Texture Management


DirectDrawSurface7.Unlock

The DirectDrawSurface7.Unlock method notifies DirectDraw that the direct surface manipulations are complete.

object.Unlock(r As RECT)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
r
RECT type that is used to lock the surface in the corresponding call to the DirectDrawSurface7.Lock method. This parameter can be Nothing only if the entire surface was locked by passing Nothing in the r parameter of the corresponding call to the DirectDrawSurface7.Lock method.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_GENERIC
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDRECT
DDERR_NOTLOCKED
DDERR_SURFACELOST

Remarks

Because it is possible to call DirectDrawSurface7.Lock multiple times for the same surface with different destination rectangles, the r parameter links the calls to the DirectDrawSurface7.Lock and DirectDrawSurface7.Unlock methods.

See Also

DirectDrawSurface7.Lock


DirectDrawSurface7.UpdateOverlay

The DirectDrawSurface7.UpdateOverlay method repositions or modifies the visual attributes of an overlay surface. These surfaces must have the DDSCAPS_OVERLAY flag set.

object.UpdateOverlay(RECT As RECT, _
    ddS As DirectDrawSurface7, _
    rectD As RECT, _
    flags As CONST_DDOVERFLAGS)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
RECT
RECT type that defines the x, y, width, and height of the region on the source surface being used as the overlay. This parameter can be an empty RECT when hiding an overlay or to indicate that the entire overlay surface is to be used and the overlay surface conforms to any boundary and size alignment restrictions imposed by the device driver.
ddS
DirectDrawSurface7 object for the surface that is being overlaid.
rectD
RECT type that defines the x, y, width, and height of the region on the destination surface that the overlay should be moved to. This parameter can be an empty RECT when hiding the overlay.
flags
One or more constants of the CONST_DDOVERFLAGS enumeration.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_DEVICEDOESNTOWNSURFACE
DDERR_GENERIC
DDERR_HEIGHTALIGN
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDRECT
DDERR_INVALIDSURFACETYPE
DDERR_NOSTRETCHHW
DDERR_NOTAOVERLAYSURFACE
DDERR_OUTOFCAPS
DDERR_SURFACELOST
DDERR_UNSUPPORTED
DDERR_XALIGN


DirectDrawSurface7.UpdateOverlayFx

The DirectDrawSurface7.UpdateOverlayFx method repositions or modifies the visual attributes of an overlay surface, using special overlay effects. These surfaces must have the DDSCAPS_OVERLAY flag set.

object.UpdateOverlayFx(RECT As RECT, _
    ddS As DirectDrawSurface7, _
    rectD As RECT, _
    flags As CONST_DDOVERFLAGS, _
    ddoverfx As DDOVERLAYFX)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
RECT
RECT type that defines the x, y, width, and height of the region on the source surface being used as the overlay. This parameter can be an empty RECT when hiding an overlay or to indicate that the entire overlay surface is to be used and the overlay surface conforms to any boundary and size alignment restrictions imposed by the device driver.
ddS
DirectDrawSurface7 object for the surface that is being overlaid.
rectD
RECT type that defines the x, y, width, and height of the region on the destination surface that the overlay should be moved to. This parameter can be an empty RECT when hiding the overlay.
flags
One or more constants of the CONST_DDOVERFLAGS enumeration. You must specify the DDOVER_DDFX flag to apply the effects set by the ddoverfx parameter.
ddoverfx
DDOVERLAYFX type describing additional effects to be applied to an overlay surface.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_DEVICEDOESNTOWNSURFACE
DDERR_GENERIC
DDERR_HEIGHTALIGN
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_INVALIDRECT
DDERR_INVALIDSURFACETYPE
DDERR_NOSTRETCHHW
DDERR_NOTAOVERLAYSURFACE
DDERR_OUTOFCAPS
DDERR_SURFACELOST
DDERR_UNSUPPORTED
DDERR_XALIGN


DirectDrawSurface7.UpdateOverlayZOrder

The DirectDrawSurface7.UpdateOverlayZOrder method sets the z-order of an overlay.

object.UpdateOverlayZOrder( _
    flags As CONST_DDOVERZFLAGS, _
    ddS As DirectDrawSurface7)

Parameters

object
Object expression that resolves to a DirectDrawSurface7 object.
flags
One of the constants of the CONST_DDOVERZFLAGS enumeration describing where to position the overlay.
ddS
DirectDrawSurface7 object for the DirectDraw surface to be used as a relative position in the overlay chain. This parameter is needed only for DDOVERZ_INSERTINBACKOF and DDOVERZ_INSERTINFRONTOF.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOTAOVERLAYSURFACE


IFont

The IFont class is used by the DirectDrawSurface7.SetFont method to specify the font used in the DirectDrawSurface7.DrawText method.

For information on this class and its associated methods, see the Font class documentation in Visual Basic.


DirectDraw Global Methods

The DirectX7 class is the main class of any DirectX for Visual Basic application. This class has methods that are used with all the DirectX components. The methods pertaining to DirectDraw are:

  • DirectX7.DirectDrawCreate
  • DirectX7.GetDDEnum


Types

This section contains information about the following types used with DirectDraw:

  • DDBLTFX
  • DDCAPS
  • DDCOLORCONTROL
  • DDCOLORKEY
  • DDGAMMARAMP
  • DDOVERLAYFX
  • DDPIXELFORMAT
  • DDSCAPS2
  • DDSURFACEDESC2
  • PALETTEENTRY
  • RECT


DDBLTFX

The DDBLTFX type passes raster operations, effects, and override information to the DirectDrawSurface7.Blt method.

Type DDBLTFX
    ddckDestColorKey_high As Long
    ddckDestColorKey_low As Long
    ddckSrcColorKey_high As Long
    ddckSrcColorKey_low As Long
    lAlphaDestConst As Long
    lAlphaDestConstBitDepth As Long
    lAlphaEdgeBlend As Long
    lAlphaEdgeBlendBitDepth As Long
    lAlphaSrcConst As Long
    lAlphaSrcConstBitDepth As Long
    lDDFX As CONST_DDBLTFXFLAGS
    lDDROP As Long
    lFill As Long
    lReserved As Long
    lROP As Long
    lRotationAngle As Long
    lZBufferBaseDest As Long
    lZBufferHigh As Long
    lZBufferLow As Long
    lZBufferOpCode As Long
    lZDestConst As Long
    lZDestConstBitDepth As Long
    lZSrcConst As Long
    lZSrcConstBitDepth As Long
End Type

Members

ddckDestColorKey_high
High value of the color range that is to be used as the destination color key.
ddckDestColorKey_low
Low value of the color range that is to be used as the destination color key.
ddckSrcColorKey_high
High value of the color range that is to be used as the source color key.
ddckSrcColorKey_low
Low value of the color range that is to be used as the source color key.
lAlphaDestConst
Constant used as the alpha channel destination.
lAlphaDestConstBitDepth
Bit depth of the destination alpha constant.
lAlphaEdgeBlend
Alpha constant used for edge blending.
lAlphaEdgeBlendBitDepth
Bit depth of the constant for an alpha edge blend.
lAlphaSrcConst
Constant used as the alpha channel source.
lAlphaSrcConstBitDepth
Bit depth of the source alpha constant.
lDDFX
Type of FX operations. One of the constants of the CONST_DDBLTFXFLAGS enumeration.
lDDROP
DirectDraw raster operations.
lFill
Color used to fill a surface when DDBLT_COLORFILL is specified. This value must be a pixel appropriate to the pixel format of the destination surface. For a palettized surface, it would be a palette index, and for a 16-bit RGB surface, it would be a 16-bit pixel value.
lReserved
Reserved for future use.
lROP
Win32 raster operations. You can retrieve a list of supported raster operations by calling the DirectDraw7.GetCaps method.
lRotationAngle
Rotation angle for the blit.
lZBufferBaseDest
Destination base value of a z-buffer.
lZBufferHigh
High limit of a z-buffer.
lZBufferLow
Low limit of a z-buffer.
lZBufferOpCode
Z-buffer compares.
lZDestConst
Constant used as the z-buffer destination.
lZDestConstBitDepth
Bit depth of the destination z-constant.
lZSrcConst
Constant used as the z-buffer source.
lZSrcConstBitDepth
Bit depth of the source z-constant.


DDCAPS

The DDCAPS type represents the capabilities of the hardware exposed through the DirectDraw object. This type contains a DDSCAPS2 type used in this context to describe what kinds of DirectDrawSurface objects can be created. It might not be possible to simultaneously create all the surfaces described by these capabilities. This type is used with the DirectDraw7.GetCaps method.

Type DDCAPS
    ddsCaps As DDSCAPS2
    lAlignBoundaryDest As Long
    lAlignBoundarySrc As Long
    lAlignSizeDest As Long
    lAlignSizeSrc As Long
    lAlignStrideAlign As Long
    lAlphaBltConstBitDepths As Long
    lAlphaBltPixelBitDepths As Long
    lAlphaBltSurfaceBitDepths As Long
    lAlphaOverlayConstBitDepths As Long
    lAlphaOverlayPixelBitDepths As Long
    lAlphaOverlaySurfaceBitDepths As Long
    lCaps As CONST_DDCAPS1FLAGS
    lCaps2 As CONST_DDCAPS2FLAGS
    lCKeyCaps As CONST_DDCKEYCAPSFLAGS
    lCurrVideoPorts As Long
    lCurrVisibleOverlays As Long
    lFXCaps As CONST_DDFXCAPSFLAGS
    lMaxHwCodecStretch As Long
    lMaxLiveVideoStretch As Long
    lMaxOverlayStretch As Long
    lMaxVideoPorts As Long
    lMaxVisibleOverlays As Long
    lMinHwCodecStretch As Long
    lMinLiveVideoStretch As Long
    lMinOverlayStretch As Long
    lNLVBCaps As CONST_DDCAPS1FLAGS
    lNLVBCaps2 As CONST_DDCAPS2FLAGS
    lNLVBCKeyCaps As CONST_DDCKEYCAPSFLAGS
    lNLVBFXCaps As CONST_DDFXCAPSFLAGS
    lNLVBRops (0 To 7) As Long
    lNumFourCCCodes As Long
    lPalCaps As CONST_DDPCAPSFLAGS
    lReserved1 As Long
    lReserved2 As Long
    lReserved3 As Long
    lReservedCaps As Long
    lRops (0 To 7) As Long
    lSSBCaps As CONST_DDCAPS1FLAGS
    lSSBCKeyCaps As CONST_DDCKEYCAPSFLAGS
    lSSBFXCaps As CONST_DDFXCAPSFLAGS
    lSSBRops (0 To 7) As Long
    lSVBCaps As CONST_DDCAPS1FLAGS
    lSVBCaps2 As CONST_DDCAPS2FLAGS
    lSVBCKeyCaps As CONST_DDCKEYCAPSFLAGS
    lSVBFXCaps As CONST_DDFXCAPSFLAGS
    lSVBRops (0 To 7) As Long
    lSVCaps As CONST_DDSTEREOCAPSFLAGS
    lVidMemFree As Long
    lVidMemTotal As Long
    lVSBCaps As CONST_DDCAPS1FLAGS
    lVSBCKeyCaps As CONST_DDCKEYCAPSFLAGS
    lVSBFXCaps As CONST_DDFXCAPSFLAGS
    lVSRops (0 To 7) As Long
    lZBufferBitDepths As Long
End Type

Members

ddsCaps
DDSCAPS2 type used for further capability descriptions.
lAlignBoundaryDest
Destination rectangle alignment for an overlay surface, in pixels.
lAlignBoundarySrc
Source rectangle alignment for an overlay surface, in pixels.
lAlignSizeDest
Destination rectangle size alignment for an overlay surface, in pixels. Overlay destination rectangles must have a pixel width that is a multiple of this value.
lAlignSizeSrc
Source rectangle size alignment for an overlay surface, in pixels. Overlay source rectangles must have a pixel width that is a multiple of this value.
lAlignStrideAlign
Stride alignment.
lAlphaBltConstBitDepths
DDBD_2, DDBD_4, or DDBD_8. (Indicates 2, 4, or 8 bits per pixel.)
lAlphaBltPixelBitDepths
DDBD_1, DDBD_2, DDBD_4, or DDBD_8. (Indicates 1, 2, 4, or 8 bits per pixel.)
lAlphaBltSurfaceBitDepths
DDBD_1, DDBD_2, DDBD_4, or DDBD_8. (Indicates 1, 2, 4, or 8 bits per pixel.)
lAlphaOverlayConstBitDepths
DDBD_2, DDBD_4, or DDBD_8. (Indicates 2, 4, or 8 bits per pixel.)
lAlphaOverlayPixelBitDepths
DDBD_1, DDBD_2, DDBD_4, or DDBD_8. (Indicates 1, 2, 4, or 8 bits per pixel.)
lAlphaOverlaySurfaceBitDepths
DDBD_1, DDBD_2, DDBD_4, or DDBD_8. (Indicates 1, 2, 4, or 8 bits per pixel.)
lCaps
Constants of the CONST_DDCAPS1FLAGS enumeration describing driver-specific capabilities.
lCaps2
Constants of the CONST_DDCAPS2FLAGS enumeration describing more driver-specific capabilities.
lCKeyCaps
Constants of the CONST_DDCKEYCAPSFLAGS enumeration describing color-key capabilities.
lCurrVideoPorts
Current number of live video ports.
lCurrVisibleOverlays
Current number of visible overlays or overlay sprites.
lFXCaps
Constants of the CONST_DDFXCAPSFLAGS enumeration describing driver-specific stretching and effects capabilities.
lMinHwCodecStretch and lMaxHwCodecStretch
Obsolete; do not use.
lMinLiveVideoStretch and lMaxLiveVideoStretch
Obsolete; do not use.
lMinOverlayStretch and lMaxOverlayStretch
Minimum and maximum overlay stretch factors, multiplied by 1000. For example, 1.3 = 1300.
lMaxVideoPorts
Maximum number of live video ports.
lMaxVisibleOverlays
Maximum number of visible overlays or overlay sprites.
lNLVBCaps
Constants of the CONST_DDCAPS1FLAGS enumeration describing driver-specific capabilities for blits from nonlocal to local video memory. Valid flags are identical to the blit-related flags used with the lCaps member.
lNLVBCaps2
Constants of the CONST_DDCAPS2FLAGS enumeration describing more driver-specific capabilities for blits from nonlocal to local video memory. Valid flags are identical to the blit-related flags used with the lCaps2 member.
lNLVBCKeyCaps
Constants of the CONST_DDCKEYCAPSFLAGS enumeration describing driver color-key capabilities for blits from nonlocal to local video memory. Valid flags are identical to the blit-related flags used with for the lCKeyCaps member.
lNLVBFXCaps
Constants of the CONST_DDFXCAPSFLAGS enumeration describing driver FX capabilities for blits from nonlocal to local video memory. Valid flags are identical to the blit-related flags used with the lFXCaps member.
lNLVBRops[0 to 7]
Raster operations supported for blits from nonlocal to local video memory.
lNumFourCCCodes
Number of FourCC codes.
lPalCaps
Constants of the CONST_DDPCAPSFLAGS enumeration describing palette capabilities.
lReserved1, lReserved2, lReserved3, and lReservedCaps
Reserved for future use.
lRops[0 To 7]
Raster operations supported.
lSSBCaps
Constants of the CONST_DDCAPS1FLAGS enumeration describing driver-specific capabilities for blits from system memory to system memory. Valid flags are identical to the blit-related flags used with the lCaps member.
lSSBCKeyCaps
Constants of the CONST_DDCKEYCAPSFLAGS enumeration describing driver color-key capabilities for blits from system memory to system memory. Valid flags are identical to the blit-related flags used with the lCKeyCaps member.
lSSBFXCaps
Constants of the CONST_DDFXCAPSFLAGS enumeration describing driver FX capabilities for blits from system memory to system memory. Valid flags are identical to the blit-related flags used with the lFXCaps member.
lSSBRops[0 To 7]
Raster operations supported for blits from system memory to system memory.
lSVBCaps
Constants of the CONST_DDCAPS1FLAGS enumeration describing driver-specific capabilities for blits from system memory to display memory. Valid flags are identical to the blit-related flags used with the lCaps member.
lSVBCaps2
Constants of the CONST_DDCAPS2FLAGS enumeration describing more driver-specific capabilities for blits from system memory to video memory. Valid flags are identical to the blit-related flags used with the lCaps2 member.
lSVBCKeyCaps
Constants of the CONST_DDCKEYCAPSFLAGS enumeration describing driver color-key capabilities for blits from system memory to display memory. Valid flags are identical to the blit-related flags used with for the lCKeyCaps member.
lSVBFXCaps
Constants of the CONST_DDFXCAPSFLAGS enumeration describing driver FX capabilities for blits from system memory to display memory. Valid flags are identical to the blit-related flags used with the lFXCaps member.
lSVBRops[0 To 7]
Raster operations supported for blits from system memory to display memory.
lSVCaps
Constants of the CONST_DDSTEREOCAPSFLAGS enumeration describing stereo vision capabilities.
lVidMemFree
Amount of free display memory.
lVidMemTotal
Total amount of display memory.
lVSBCaps
Constants of the CONST_DDCAPS1FLAGS enumeration describing driver-specific capabilities for blits from display memory to system memory. Valid flags are identical to the blit-related flags used with the lCaps member.
lVSBCKeyCaps
Constants of the CONST_DDCKEYCAPSFLAGS enumeration describing driver color-key capabilities blits from for display memory to system-memory. Valid flags are identical to the blit-related flags used with for the lCKeyCaps member.
lVSBFXCaps
Constants of the CONST_DDFXCAPSFLAGS enumeration describing driver FX capabilities for blits from display memory to system memory. Valid flags are identical to the blit-related flags used with the lFXCaps member.
lVSRops[0 To 7]
Raster operations supported for blits from display memory to system-memory.
lZBufferBitDepths
DDBD_8, DDBD_16, or DDBD_24. (Indicates 8, 16, and 24 bits per pixel.) 32-bit z-buffers are not supported.


DDCOLORCONTROL

The DDCOLORCONTROL type defines the color controls associated with a DirectDrawVideoPortObject or a primary surface.

Type DDCOLORCONTROL
    lBrightness As Long
    lColorEnable As Long
    lContrast As Long
    lFlags As CONST_DDCOLORFLAGS
    lGamma As Long
    lHue As Long
    lReserved1 As Long
    lSaturation As Long
    lSharpness As Long
End Type

Members

lBrightness
Luminance intensity, in IRE units times 100. The valid range is from 0 through 10,000. The default is 750, which translates to 7.5 IRE.
lColorEnable
Flag indicating whether color is used. If this member is 0, color is not used; if it is 1, color is used. The default value is 1.
lContrast
Relative difference between higher and lower intensity luminance values, in IRE units times 100. The valid range is from 0 through 20,000. The default value is 10,000 (100 IRE). Higher values of contrast cause darker luminance values to tend toward black and lighter luminance values to tend toward white. Lower values of contrast cause all luminance values to move toward the middle of the scale.
lFlags
Constants of the CONST_DDCOLORFLAGS enumeration specifying which type members contain valid data . When the type is returned by the DirectDrawColorControl.GetColorControls method, it also indicates which options are supported by the device.
lGamma
Controls the amount of gamma correction applied to the luminance values. The valid range is from 1 through 500 gamma units, with a default of 1.
lHue
Phase relationship of the chrominance components. Hue is specified in degrees, and the valid range is from –180 through 180. The default is 0.
lReserved1
Reserved.
lSaturation
Color intensity, in IRE units times 100. The valid range is from 0 through 20,000. The default value is 10,000, which translates to 100 IRE.
lSharpness
Sharpness, in arbitrary units. The valid range is from 0 trhough 10. The default value is 5.


DDCOLORKEY

The DDCOLORKEY type describes a source color key, destination color key, or color space. A color key is specified if the low and high range values are the same. This type is used with the DirectDrawSurface7.GetColorKey and DirectDrawSurface7.SetColorKey methods.

Type COLORKEY
    high As Long
    low As Long
End Type

Members

high
High value of the color range that is to be used as the color key.
low
Low value of the color range that is to be used as the color key.


DDGAMMARAMP

The DDGAMMARAMP type contains red, green, and blue ramp data for the DirectDrawGammaControl.GetGammaRamp and DirectDrawGammaControl.SetGammaRamp methods.

Type DDGAMMARAMP
    blue(0 To 255) As Integer
    green(0 To 255) As Integer
    red(0 To 255) As Integer
End Type

Members

red, green, and blue
Red, green, and blue gamma ramps.

See Also

Gamma and Color Controls


DDOVERLAYFX

The DDOVERLAYFX type passes override information to the DirectDrawSurface7.UpdateOverlay method.

type DDOVERLAYFX
    dckDestColorkey As DDCOLORKEY
    dckSrcColorkey As DDCOLORKEY
    lAlphaDestConst As Long
    lAlphaDestConstBitDepth As Long
    lAlphaEdgeBlend As Long
    lAlphaEdgeBlendBitDepth As Long
    lAlphaSrcConst As Long
    lAlphaSrcConstBitDepth As Long
    lDDFX As CONST_DDOVERFXFLAGS
    lFlags As Long
End Type

Members

dckDestColorkey
Destination color key override.
dckSrcColorkey
Source color key override.
lAlphaDestConst
Constant to use as the alpha channel for a destination.
lAlphaDestConstBitDepth
Bit depth used to specify the alpha constant for a destination.
lAlphaEdgeBlend
Constant to use as the alpha for an edge blend.
lAlphaEdgeBlendBitDepth
Bit depth used to specify the constant for an alpha edge blend.
lAlphaSrcConst
Constant to use as the alpha channel for a source.
lAlphaSrcConstBitDepth
Bit depth used to specify the alpha constant for a source.
lDDFX
One of the constants of the CONST_DDOVERFXFLAGS enumeration.
lFlags
Currently not used and must be set to 0.


DDPIXELFORMAT

The DDPIXELFORMAT type describes the pixel format of a DirectDrawSurface object for the DirectDrawSurface7.GetPixelFormat method.

Type DDPIXELFORMAT
    lAlphaBitDepth As Long
    lBBitMask As Long
    lBumpBitCount As Long
    lBumpDuBitMask As Long
    lBumpDvBitMask As Long
    lBumpLuminanceBitMask As Long
    lFlags As CONST_DDPIXELFORMATFLAGS
    lFourCC As Long
    lGBitMask As Long
    lLuminanceAlphaBitMask As Long
    lLuminanceBitCount As Long
    lLuminanceBitMask As Long
    lRBitMask As Long
    lRGBAlphaBitMask As Long
    lRGBBitCount As Long
    lRGBZBitMask As Long
    lStencilBitDepth As Long
    lStencilBitMask As Long
    lUBitMask As Long
    lVBitMask As Long
    lYBitMask As Long
    lYUVAlphaBitMask As Long
    lYUVBitCount As Long
    lYUVZBitMask As Long
    lZBitMask As Long
    lZBufferBitDepth As Long
End Type

Members

lAlphaBitDepth
Alpha channel bit depth (1, 2, 4, or 8) for an alpha-only surface (DDPF_ALPHA). For pixel formats that contain alpha information interleaved with color data (DDPF_ALPHAPIXELS), you must count the bits in the lRGBAlphaBitMask member to obtain the bit depth of the alpha component.
lBBitMask
Mask for blue bits.
lBumpBitCount
Total bump-map bits per pixel in a bump-map surface.
lBumpDuBitMask
Mask for bump-map U-delta bits
lBumpDvBitMask
Mask for bump-map V-delta bits.
lBumpLuminanceBitMask
Mask for luminance in a bump-map pixel.
lFlags
Constants of the CONST_DDPIXELFORMATFLAGS enumeration describing optional control flags.
lFourCC
FourCC code. For more information see, Four-Character Codes (FOURCC).
lGBitMask
Mask for green bits.
lRGBAlphaBitMask and lYUVAlphaBitMask and lLuminanceAlphaBitMask
Masks for the alpha channel.
lLuminanceBitCount
Total luminance bits per pixel. This member applies only to luminance-only and luminance-alpha surfaces.
lLuminanceBitMask
Mask for luminance bits.
lRBitMask
Mask for red bits.
lRGBAlphaBitMask and lYUVAlphaBitMask
Masks for the alpha channel.
lRGBBitCount
RGB bits per pixel (4, 8, 16, 24, or 32).
lRGBZBitMask and lYUVZBitMask
Masks for z channel.
lStencilBitDepth
Bit depth of the stencil buffer. This member specifies how many bits are reserved within each pixel of the z-buffer for stencil information (the total number of z-bits is equal to lZBufferBitDepth minus lStencilBitDepth).
lStencilBitMask
Mask for stencil bits within each z-buffer pixel.
lUBitMask
Mask for U bits.
lVBitMask
Mask for V bits.
lYBitMask
Mask for Y bits.
lYUVBitCount
YUV bits per pixel (4, 8, 16, 24, or 32).
lZBitMask
Mask for z bits.
lZBufferBitDepth
Z-buffer bit depth (8, 16, or 24); 32-bit z-buffers are not supported.


DDSCAPS2

The DDSCAPS2 type defines the capabilities of a DirectDrawSurface object. This type is part of the DDSURFACEDESC2 type.

Type DDSCAPS2
   lCaps As CONST_DDSURFACECAPSFLAGS
   lCaps2 As CONST_DDSURFACECAPS2FLAGS
   lCaps3 As Long
   lCaps4 As Long
End Type

Members

lCaps
One or more constants of the CONST_DDSURFACECAPSFLAGS enumeration representing the capabilities of the surface.
lCaps2
Additional surface capabilities. This member can contain one or more of the capability constants of the CONST_DDSURFACECAPS2FLAGS enumeration and can contain an additional flag to indicate how the surface memory was allocated:
lCaps3 and lCaps4
Not currently used.


DDSURFACEDESC2

The DDSURFACEDESC2 type contains a description of a surface. This type is passed to the DirectDraw7.CreateSurface method. The relevant members differ for each potential type of surface.

Type DDSURFACEDESC2
    ddckCKDestBlt As DDCOLORKEY
    ddckCKDestOverlay As DDCOLORKEY
    ddckCKSrcBlt As DDCOLORKEY
    ddckCKSrcOverlay As DDCOLORKEY
    ddpfPixelFormat As DDPIXELFORMAT
    ddsCaps As DDSCAPS2
    lAlphaBitDepth As Long
    lBackBufferCount As Long
    lFlags As CONST_DDSURFACEDESCFLAGS
    lHeight As Long
    lLinearSize As Long
    lMipMapCount As Long
    lPitch As Long
    lRefreshRate As Long
    lTextureStage As Long
    lWidth As Long
    lZBufferBitDepth As Long
End Type

Members

ddckCKDestBlt
DDCOLORKEY type that describes the destination color key for blit operations.
ddckCKDestOverlay
DDCOLORKEY type that describes the destination color key to be used for an overlay surface.
ddckCKSrcBlt
DDCOLORKEY type that describes the source color key for blit operations.
ddckCKSrcOverlay
DDCOLORKEY type that describes the source color key to be used for an overlay surface.
ddpfPixelFormat
DDPIXELFORMAT type that describes the surface's pixel format.
ddsCaps
DDSCAPS2 type that contains the capabilities of the surface.
lAlphaBitDepth
Depth of alpha buffer.
lBackBufferCount
Number of back buffers.
lFlags
Optional control flags. One or more of the constants of the CONST_DDSURFACEDESCFLAGS enumeration.
lHeight and lWidth
Dimensions of the surface to be created, in pixels.
lLinearSize
Not currently used.
lMipMapCount
Number of mipmap levels.
lPitch
Distance, in bytes, to the start of next line. When used with the DirectDrawSurface7.GetSurfaceDesc method, this is a return value. When creating a surface from existing memory, this is an input value that must be a multiple.
lRefreshRate
Refresh rate (used when the display mode is described). The value of 0 indicates an adapter default.
lTextureStage
Stage identifier used to bind a texture to a specific stage in the multitexture cascade of a 3-D device. Although not required for all hardware, setting this member is recommended for best performance on the largest variety of 3-D accelerators. Hardware that requires explicitly assigned textures exposes the D3DDEVCAPS_SEPARATETEXTUREMEMORIES 3-D device capability in the D3DDEVICEDESC structure that is filled by the Direct3DDevice7.GetCaps method.
lZBufferBitDepth
Depth of z-buffer; 32-bit z-buffers are not supported.

Remarks

The lPitch member is an output values when calling the DirectDrawSurface7.GetSurfaceDesc method. When creating surfaces from existing memory, or updating surface characteristics, these members are input values that describe the pitch and location of memory allocated by the calling application for use by DirectDraw. DirectDraw does not attempt to manage or free memory allocated by the application. For more information, see Creating Client Memory Surfaces and Updating Surface Characteristics.


PALETTEENTRY

The PALETTEENTRY type specifies the color and usage of an entry in a logical color palette.

Type PALETTEENTRY
    blue As Byte
    flags As Byte
    green As Byte
    red As Byte
End Type

Members

blue
Specifies a blue intensity value for the palette entry.
flags
Specifies how the palette entry is to be used. The flags member can be set to Nothing or one of the following values:
Value | Meaning
PC_EXPLICIT | The low-order word of the logical palette entry designates a hardware palette index. This flag allows the application to show the contents of the display device palette.
PC_NOCOLLAPSE | The color should be placed in an unused entry in the system palette, instead of being matched to an existing color in the system palette. If there are no unused entries in the system palette, the color is matched normally. Once this color is in the system palette, colors in other logical palettes can be matched to this color.
PC_RESERVED | The logical palette entry be used for palette animation. This flag prevents other windows from matching colors to the palette entry since the color frequently changes. If an unused system-palette entry is available, the color is placed in that entry. Otherwise, the color is not available for animation.

green
Green intensity value for the palette entry.
red
Red intensity value for the palette entry.


RECT

The RECT type defines the coordinates of the upper-left and lower-right corners of a rectangle.

Type RECT
    Bottom As Long
    Left As Long
    Right As Long
    Top As Long
End Type

Members

Bottom
Y-coordinate of the lower-right corner of the rectangle.
Left
X-coordinate of the upper-left corner of the rectangle.
Right
X-coordinate of the lower-right corner of the rectangle.
Top
Y-coordinate of the upper-left corner of the rectangle.


Enumerations

DirectDraw uses enumerations to group constants and take advantage of the statement-completion feature of Visual Basic. The enumerations used in DirectDraw are the following:

  • CONST_DDBITDEPTHFLAGS
  • CONST_DDBLTFASTFLAGS
  • CONST_DDBLTFLAGS
  • CONST_DDBLTFXFLAGS
  • CONST_DDCAPS1FLAGS
  • CONST_DDCAPS2FLAGS
  • CONST_DDCKEYCAPSFLAGS
  • CONST_DDCKEYFLAGS
  • CONST_DDCOLORFLAGS
  • CONST_DDDEVICEIDFLAGS
  • CONST_DDEDMFLAGS
  • CONST_DDENUMOVERLAYZFLAGS
  • CONST_DDENUMSURFACESFLAGS
  • CONST_DDFLIPFLAGS
  • CONST_DDFXCAPSFLAGS
  • CONST_DDGBSFLAGS
  • CONST_DDGFSFLAGS
  • CONST_DDLOCKFLAGS
  • CONST_DDOVERFLAGS
  • CONST_DDOVERFXFLAGS
  • CONST_DDOVERZFLAGS
  • CONST_DDPALFLAGS
  • CONST_DDPCAPSFLAGS
  • CONST_DDPIXELFORMATFLAGS
  • CONST_DDRAW
  • CONST_DDRAWERR
  • CONST_DDSCLFLAGS
  • CONST_DDSDMFLAGS
  • CONST_DDSGRFLAGS
  • CONST_DDSTEREOCAPSFLAGS
  • CONST_DDSURFACECAPS2FLAGS
  • CONST_DDSURFACECAPSFLAGS
  • CONST_DDSURFACEDESCFLAGS
  • CONST_DDWAITVBFLAGS


CONST_DDBITDEPTHFLAGS

The CONST_DDBITDEPTHFLAGS enumeration is used to specify the bit depth.

Enum CONST_DDBITDEPTHFLAGS
    DDBD_1 = 16384
    DDBD_16 = 1024
    DDBD_2  = 8192
    DDBD_24 =  512
    DDBD_32 =  256
    DDBD_4  = 4096
    DDBD_8  = 2048
End Enum
DDBD_1 to 32
Bits per pixel.


CONST_DDBLTFASTFLAGS

The CONST_DDBLTFASTFLAGS enumeration is used in the trans parameter of the DirectDrawSurface7.BltFast method to determine the type of transfer.

Enum CONST_DDBLTFASTFLAGS
    DDBLTFAST_DESTCOLORKEY =  2
    DDBLTFAST_DONOTWAIT    = 32
    DDBLTFAST_NOCOLORKEY   =  0
    DDBLTFAST_SRCCOLORKEY  =  1
    DDBLTFAST_WAIT         = 16
End Enum
DDBLTFAST_DESTCOLORKEY
Transparent blit that uses the destination's color key.
DDBLTFAST_DONOTWAIT
Does not wait to blit if the blitter is busy and returns without blitting.
DDBLTFAST_NOCOLORKEY
Normal copy blit with no transparency.
DDBLTFAST_SRCCOLORKEY
Transparent blit that uses the source's color key.
DDBLTFAST_WAIT
Postpones the DDERR_WASSTILLDRAWING message if the blitter is busy, and returns as soon as the blit can be set up or another error occurs.


CONST_DDBLTFLAGS

The CONST_DDBLTFLAGS enumeration is used in the flags parameter of the DirectDrawSurface7.Blt and DirectDrawSurface7.BltFx methods to determine the valid members of the associated DDBLTFX type. The DDBLTFX type specifies color-key information or requests special behavior from the methods.

Enum CONST_DDBLTFLAGS
    DDBLT_ASYNC = 512
    DDBLT_COLORFILL = 1024
    DDBLT_DDFX = 2048
    DDBLT_DDROPS = 4096
    DDBLT_DEPTHFILL = 33554432
    DDBLT_DONOTWAIT = 134217728
    DDBLT_KEYDEST = 8192
    DDBLT_KEYDESTOVERRIDE = 16384
    DDBLT_KEYSRC = 32768
    DDBLT_KEYSRCOVERRIDE = 65536
    DDBLT_ROP = 131072
    DDBLT_ROTATIONANGLE = 262144
    DDBLT_WAIT = 16777216
End Enum
Validation flags
DDBLT_COLORFILL
Uses the lFill member of the DDBLTFX structure as the RGB color that fills the destination rectangle on the destination surface.
DDBLT_DDFX
Uses the lDDFX member of the DDBLTFX structure to specify the effects to use for this blit.
DDBLT_DDROPS
Uses the lROP member of the DDBLTFX structure to specify the raster operations (ROPS) that are not part of the Win32 API.
DDBLT_DEPTHFILL
Uses the lFill member of the DDBLTFX structure as the depth value with which to fill the destination rectangle on the destination z-buffer surface.
DDBLT_DONOTWAIT
If the blitter is busy, does not wait for the blitter to become available but returns without blitting.
DDBLT_KEYDESTOVERRIDE
Uses the ddckDestColorKey_high and ddckDestColorKey_low members of the DDBLTFX structure as the color key for the destination surface.
DDBLT_KEYSRCOVERRIDE
Uses the ddckSrcColorKey_high and ddckSrcColorKey_low members of the DDBLTFX structure as the color key for the source surface.
DDBLT_ROP
Uses the lROP member of the DDBLTFX structure for the ROP for this blit. These ROPs are the same as those defined in the Win32 API.
DDBLT_ROTATIONANGLE
Uses the lRotationAngle member of the DDBLTFX structure as the rotation angle (specified in 1/100s of a degree) for the surface.
Color key flags
DDBLT_KEYDEST
Uses the color key associated with the destination surface.
DDBLT_KEYSRC
Uses the color key associated with the source surface.
Behavior flags
DDBLT_ASYNC
Performs this blit asynchronously through the first in, first out (FIFO) hardware in the order received. If no room is available in the FIFO hardware, the call fails.
DDBLT_WAIT
Postpones the DDERR_WASSTILLDRAWING return value if the blitter is busy, and returns as soon as the blit can be set up or another error occurs.


CONST_DDBLTFXFLAGS

The CONST_DDBLTFXFLAGS enumeration is used in the lDDFX member of the DDBLTFX type to specify the type of FX operation.

Enum CONST_DDBLTFXFLAGS
    DDBLTFX_ARITHSTRETCHY   =   1
    DDBLTFX_MIRRORLEFTRIGHT =   2
    DDBLTFX_MIRRORUPDOWN    =   4
    DDBLTFX_NOTEARING       =   8
    DDBLTFX_ROTATE180       =  16
    DDBLTFX_ROTATE270       =  32
    DDBLTFX_ROTATE90        =  64
    DDBLTFX_ZBUFFERBASEDEST = 256
    DDBLTFX_ZBUFFERRANGE    = 128
End Enum
DDBLTFX_ARITHSTRETCHY
Uses arithmetic stretching along the y-axis for this blit.
DDBLTFX_MIRRORLEFTRIGHT
Turns the surface on its y-axis. This blit mirrors the surface from left to right.
DDBLTFX_MIRRORUPDOWN
Turns the surface on its x-axis. This blit mirrors the surface from top to bottom.
DDBLTFX_NOTEARING
Schedules this blit to avoid tearing.
DDBLTFX_ROTATE180
Rotates the surface 180 degrees clockwise during this blit.
DDBLTFX_ROTATE270
Rotates the surface 270 degrees clockwise during this blit.
DDBLTFX_ROTATE90
Rotates the surface 90 degrees clockwise during this blit.
DDBLTFX_ZBUFFERBASEDEST
Adds the lZBufferBaseDest member of the DDBLTFX type to each of the source z-values before comparing them with the destination z-values during this z-blit.
DDBLTFX_ZBUFFERRANGE
Uses the lZBufferLow and lZBufferHigh members of the DDBLTFX type as range values to specify limits to the bits copied from a source surface during this z-blit.


CONST_DDCAPS1FLAGS

The CONST_DDCAPS1FLAGS enumeration is used by the lCaps, lNLVBCaps, lSSBCaps, lSVBCaps, and the lVSBCaps members of the DDCAPS type to describe hardware capabilities.

Enum CONST_DDCAPS1FLAGS
    DDCAPS_3D               =           1
    DDCAPS_ALIGNBOUNDARYDEST =          2
    DDCAPS_ALIGNBOUNDARYSRC =           8
    DDCAPS_ALIGNSIZEDEST    =           4
    DDCAPS_ALIGNSIZESRC     =          16
    DDCAPS_ALIGNSTRIDE      =          32
    DDCAPS_ALPHA            =     8388608
    DDCAPS_BANKSWITCHED     =   134217728
    DDCAPS_BLT              =          64
    DDCAPS_BLTCOLORFILL     =    67108864
    DDCAPS_BLTDEPTHFILL     =   268435456
    DDCAPS_BLTFOURCC        =         256
    DDCAPS_BLTQUEUE         =         128
    DDCAPS_BLTSTRETCH       =         512
    DDCAPS_CANBLTSYSMEM     = -2147483648
    DDCAPS_CANCLIP          =   536870912
    DDCAPS_CANCLIPSTRETCHED =  1073741824
    DDCAPS_COLORKEY         =     4194304
    DDCAPS_COLORKEYHWASSIST =    16777216
    DDCAPS_GDI              =        1024
    DDCAPS_NOHARDWARE       =    33554432
    DDCAPS_OVERLAY          =        2048
    DDCAPS_OVERLAYCANTCLIP  =        4096
    DDCAPS_OVERLAYFOURCC    =        8192
    DDCAPS_OVERLAYSTRETCH   =       16384
    DDCAPS_PALETTE          =       32768
    DDCAPS_PALETTEVSYNC     =       65536
    DDCAPS_READSCANLINE     =      131072
    DDCAPS_VBI              =      524288
    DDCAPS_ZBLTS            =     1048576
    DDCAPS_ZOVERLAYS        =     2097152
End Enum
DDCAPS_3D
The display hardware has 3-D acceleration.
DDCAPS_ALIGNBOUNDARYDEST
DirectDraw supports only those overlay destination rectangles with the x-axis aligned to the lAlignBoundaryDest boundaries of the surface.
DDCAPS_ALIGNBOUNDARYSRC
DirectDraw supports only those overlay source rectangles with the x-axis aligned to the lAlignBoundarySrc boundaries of the surface.
DDCAPS_ALIGNSIZEDEST
DirectDraw supports only those overlay destination rectangles whose x-axis sizes, in pixels, are lAlignSizeDest multiples.
DDCAPS_ALIGNSIZESRC
DirectDraw supports only those overlay source rectangles whose x-axis sizes, in pixels, are lAlignSizeSrc multiples.
DDCAPS_ALIGNSTRIDE
DirectDraw creates display memory surfaces that have a stride alignment equal to the lAlignStrideAlign value.
DDCAPS_ALPHA
The display hardware supports alpha-only surfaces. (See alpha channel)
DDCAPS_BANKSWITCHED
The display hardware is bank-switched and is potentially very slow at random access to display memory.
DDCAPS_BLT
Display hardware is capable of blit operations.
DDCAPS_BLTCOLORFILL
Display hardware is capable of color filling with a blitter.
DDCAPS_BLTDEPTHFILL
Display hardware is capable of depth filling z-buffers with a blitter.
DDCAPS_BLTFOURCC
Display hardware is capable of color-space conversions during blit operations.
DDCAPS_BLTQUEUE
Display hardware is capable of asynchronous blit operations.
DDCAPS_BLTSTRETCH
Display hardware is capable of stretching during blit operations.
DDCAPS_CANBLTSYSMEM
Display hardware is capable of blitting to or from system memory.
DDCAPS_CANCLIP
Display hardware is capable of clipping with blitting.
DDCAPS_CANCLIPSTRETCHED
Display hardware is capable of clipping while stretch blitting.
DDCAPS_COLORKEY
Supports some form of color key in either overlay or blit operations. More specific color key capability information can be found in the lCKeyCaps member.
DDCAPS_COLORKEYHWASSIST
The color key is partially hardware assisted. This means that other resources (CPU or video memory) might be used. If this bit is not set, full hardware support is in place.
DDCAPS_GDI
Display hardware is shared with the GDI.
DDCAPS_NOHARDWARE
There is no hardware support.
DDCAPS_OVERLAY
Display hardware supports overlays.
DDCAPS_OVERLAYCANTCLIP
Display hardware supports overlays but cannot clip them.
DDCAPS_OVERLAYFOURCC
Overlay hardware is capable of color-space conversions during overlay operations.
DDCAPS_OVERLAYSTRETCH
Overlay hardware is capable of stretching. The lMinOverlayStretch and lMaxOverlayStretch members contain valid data.
DDCAPS_PALETTE
DirectDraw is capable of creating and supporting DirectDrawPalette objects for more surfaces than only the primary surface.
DDCAPS_PALETTEVSYNC
DirectDraw is capable of updating a palette synchronized with the vertical refresh.
DDCAPS_READSCANLINE
Display hardware is capable of returning the current scan line.
DDCAPS_VBI
Display hardware is capable of generating a vertical-blank interrupt.
DDCAPS_ZBLTS
Supports the use of z-buffers with blit operations.
DDCAPS_ZOVERLAYS
Supports the use of the DirectDrawSurface7.UpdateOverlayZOrder method as a z-value for overlays to control their layering.


CONST_DDCAPS2FLAGS

The CONST_DDCAPS2FLAGS enumeration is used in the lCaps2, lNLVBCaps2, lSVBCaps2 members of the DDCAPS type to describe additional driver-specific capabilities.

Enum CONST_DDCAPS2FLAGS
    DDCAPS2_AUTOFLIPOVERLAY    =     8
    DDCAPS2_CANBOBHARDWARE     = 16384
    DDCAPS2_CANBOBINTERLEAVED  =    16
    DDCAPS2_CANBOBNONINTERLEAVED =  32
    DDCAPS2_CANCALIBRATEGAMMA  = 1048576
    DDCAPS2_CANDROPZ16BIT      =   256
    DDCAPS2_CANFLIPODDEVEN     =  8192
    DDCAPS2_CANMANAGETEXTURE   = 8388608
    DDCAPS2_CANRENDERWINDOWED  = 524288
    DDCAPS2_CERTIFIED          =     1
    DDCAPS2_COLORCONTROLOVERLAY =   64
    DDCAPS2_COLORCONTROLPRIMARY =  128
    DDCAPS2_COPYFOURCC         = 32768
    DDCAPS2_FLIPINTERVAL       = 2097152
    DDCAPS2_FLIPNOVSYNC        = 4194304
    DDCAPS2_NO2DDURING3DSCENE  =     2
    DDCAPS2_NONLOCALVIDMEM     =   512
    DDCAPS2_NONLOCALVIDMEMCAPS =  1024
    DDCAPS2_NOPAGELOCKREQUIRED =  2048
    DDCAPS2_PRIMARYGAMMA       = 131072
    DDCAPS2_STEREO             = 33554432
    DDCAPS2_VIDEOPORT          =     4
    DDCAPS2_WIDESURFACES       =  4096
End Enum
DDCAPS2_AUTOFLIPOVERLAY
The overlay can be automatically flipped to the next surface in the flip chain each time a video port VSYNC occurs, allowing the video port and the overlay to double-buffer the video without CPU overhead. This option is valid only when the surface is receiving data from a video port. If the video port data is noninterlaced or noninterleaved, it flips on every VSYNC. If the data is being interleaved in memory, it flips on every other VSYNC.
DDCAPS2_CANBOBHARDWARE
The overlay hardware can display each field of an interlaced video stream individually.
DDCAPS2_CANBOBINTERLEAVED
The overlay hardware can display each field of an interlaced video stream individually while it is interleaved in memory without causing any artifacts that might normally occur without special hardware support. This option is only valid when the surface is receiving data from a video port and the video is zoomed at least two times in the vertical direction.
DDCAPS2_CANBOBNONINTERLEAVED
The overlay hardware can display each field of an interlaced video stream individually while it is not interleaved in memory without causing any artifacts that might normally occur without special hardware support. This option is valid only when the surface is receiving data from a video port and the video is zoomed at least two times in the vertical direction.
DDCAPS2_CANCALIBRATEGAMMA
The system has a calibrator installed that can automatically adjust the gamma ramp so that the result is identical on all systems that have a calibrator. To invoke the calibrator when setting new gamma levels, use the DDSGR_CALIBRATE flag when calling the DirectDrawGammaControl.SetGammaRamp method. Calibrating gamma ramps incurs some processing overhead and should not be used frequently.
DDCAPS2_CANDROPZ16BIT
Sixteen-bit RGBZ values can be converted into 16-bit RGB values. (The system does not support 8-bit conversions.)
DDCAPS2_CANFLIPODDEVEN
The driver is capable of performing odd and even flip operations, as specified by the DDFLIP_ODD and DDFLIP_EVEN flags used with the DirectDrawSurface7.Flip method.
DDCAPS2_CANMANAGETEXTURE
The Microsoft® Direct3D® texture manager uses this capability to decide whether to put managed surfaces in nonlocal video memory. If the capability is set, the texture manager puts managed surfaces in nonlocal video memory. Drivers that cannot texture from local video memory should not set this capability.
DDCAPS2_CANRENDERWINDOWED
The driver is capable of rendering in windowed mode.
DDCAPS2_CERTIFIED
Display hardware is certified.
DDCAPS2_COLORCONTROLOVERLAY
The overlay surface contains color controls (such as brightness and sharpness)
DDCAPS2_COLORCONTROLPRIMARY
The primary surface contains color controls (for instance, gamma)
DDCAPS2_COPYFOURCC
The driver supports blitting any FOURCC surface to another surface of the same FOURCC.
DDCAPS2_FLIPINTERVAL
The driver responds to the DDFLIP_INTERVAL* flags. (see DirectDrawSurface7.Flip).
DDCAPS2_FLIPNOVSYNC
The driver responds to the DDFLIP_NOVSYNC flag (see DirectDrawSurface7.Flip).
DDCAPS2_NO2DDURING3DSCENE
Two-dimensional operations such as DirectDrawSurface7.Blt and DirectDrawSurface7.Lock cannot be performed on any surfaces that Direct3D is using between calls to the Direct3DDevice7.BeginScene and Direct3DDevice7.EndScene methods.
DDCAPS2_NONLOCALVIDMEM
The display driver supports surfaces in nonlocal video memory.
DDCAPS2_NONLOCALVIDMEMCAPS
Blit capabilities for nonlocal video-memory surfaces differ from local video memory surfaces. If this flag is present, the DDCAPS2_NONLOCALVIDMEM flag is also present.
DDCAPS2_NOPAGELOCKREQUIRED
DMA blit operations are supported on system-memory surfaces that are not page-locked.
DDCAPS2_PRIMARYGAMMA
Dynamic gamma ramps are supported for the primary surface. For more information, see Gamma and Color Controls.
DDCAPS2_STEREO
New for DirectX 7.0. Turns on the ddcaps.dwSVCaps bit to support stereo mode. The driver can do stereo in at least one mode other than the current mode. The application can use DirectDraw7.GetDisplayMode or DirectDraw7.GetDisplayModesEnum to get per-mode stereo information.
DDCAPS2_VIDEOPORT
Display hardware supports live video.
DDCAPS2_WIDESURFACES
The display surface supports surfaces wider than the primary surface.


CONST_DDCKEYCAPSFLAGS

The CONST_DDCKEYCAPSFLAGS enumeration is used by the lCKeyCaps, lNLVBCKeyCaps, lSSBCKeyCaps, lSVBCKeyCaps, and lVSBCKeyCaps members of the DDCAPS type to describe the color-key capabilities of the hardware.

Enum CONST_DDCKEYCAPSFLAGS
    DDCKEYCAPS_DESTBLT               =      1
    DDCKEYCAPS_DESTBLTCLRSPACE       =      2
    DDCKEYCAPS_DESTBLTCLRSPACEYUV    =      4
    DDCKEYCAPS_DESTBLTYUV            =      8
    DDCKEYCAPS_DESTOVERLAY           =     16
    DDCKEYCAPS_DESTOVERLAYCLRSPACE   =     32
    DDCKEYCAPS_DESTOVERLAYCLRSPACEYUV =    64
    DDCKEYCAPS_DESTOVERLAYONEACTIVE  =    128
    DDCKEYCAPS_DESTOVERLAYYUV        =    256
    DDCKEYCAPS_NOCOSTOVERLAY         = 262144
    DDCKEYCAPS_SRCBLT                =    512
    DDCKEYCAPS_SRCBLTCLRSPACE        =   1024
    DDCKEYCAPS_SRCBLTCLRSPACEYUV     =   2048
    DDCKEYCAPS_SRCBLTYUV             =   4096
    DDCKEYCAPS_SRCOVERLAY            =   8192
    DDCKEYCAPS_SRCOVERLAYCLRSPACE    =  16384
    DDCKEYCAPS_SRCOVERLAYCLRSPACEYUV =  32768
    DDCKEYCAPS_SRCOVERLAYONEACTIVE   =  65536
    DDCKEYCAPS_SRCOVERLAYYUV         = 131072
End Enum
DDCKEYCAPS_DESTBLT
Supports transparent blitting with a color key that identifies the replaceable bits of the destination surface for RGB colors.
DDCKEYCAPS_DESTBLTCLRSPACE
Supports transparent blitting with a color space that identifies the replaceable bits of the destination surface for RGB colors.
DDCKEYCAPS_DESTBLTCLRSPACEYUV
Supports transparent blitting with a color space that identifies the replaceable bits of the destination surface for YUV colors.
DDCKEYCAPS_DESTBLTYUV
Supports transparent blitting with a color key that identifies the replaceable bits of the destination surface for YUV colors.
DDCKEYCAPS_DESTOVERLAY
Supports overlaying with color keying of the replaceable bits of the destination surface being overlaid for RGB colors.
DDCKEYCAPS_DESTOVERLAYCLRSPACE
Supports a color space as the color key for the destination of RGB colors.
DDCKEYCAPS_DESTOVERLAYCLRSPACEYUV
Supports a color space as the color key for the destination of YUV colors.
DDCKEYCAPS_DESTOVERLAYONEACTIVE
Supports only one active destination color key value for visible overlay surfaces .
DDCKEYCAPS_DESTOVERLAYYUV
Supports overlaying, using color keying of the replaceable bits of the destination surface being overlaid for YUV colors.
DDCKEYCAPS_NOCOSTOVERLAY
There are no BANDWIDTH trade-offs for using the color key with an overlay.
DDCKEYCAPS_SRCBLT
Supports transparent blitting, using the color key for the source with this surface for RGB colors.
DDCKEYCAPS_SRCBLTCLRSPACE
Supports transparent blitting, using a color space for the source with this surface for RGB colors.
DDCKEYCAPS_SRCBLTCLRSPACEYUV
Supports transparent blitting, using a color space for the source with this surface for YUV colors.
DDCKEYCAPS_SRCBLTYUV
Supports transparent blitting, using the color key for the source with this surface for YUV colors.
DDCKEYCAPS_SRCOVERLAY
Supports overlaying, using the color key for the source with this overlay surface for RGB colors.
DDCKEYCAPS_SRCOVERLAYCLRSPACE
Supports overlaying, using a color space as the source color key for the overlay surface for RGB colors.
DDCKEYCAPS_SRCOVERLAYCLRSPACEYUV
Supports overlaying, using a color space as the source color key for the overlay surface for YUV colors.
DDCKEYCAPS_SRCOVERLAYONEACTIVE
Supports only one active source color key value for visible overlay surfaces.
DDCKEYCAPS_SRCOVERLAYYUV
Supports overlaying, using the color key for the source with this overlay surface for YUV colors.


CONST_DDCKEYFLAGS

The CONST_DDCKEYFLAGS enumeration is used in the flags parameter of the DirectDrawSurface7.SetColorKey method to specify the type of color key requested.

Enum CONST_DDCKEYFLAGS
    DDCKEY_COLORSPACE =  1
    DDCKEY_DESTBLT    =  2
    DDCKEY_DESTOVERLAY = 4
    DDCKEY_SRCBLT     =  8
    DDCKEY_SRCOVERLAY = 16
End Enum
DDCKEY_COLORSPACE
Color space. Not set if the type contains a single color key.
DDCKEY_DESTBLT
Color key or color space to be used as a destination color key for blit operations.
DDCKEY_DESTOVERLAY
Color key or color space to be used as a destination color key for overlay operations.
DDCKEY_SRCBLT
Color key or color space to be used as a source color key for blit operations.
DDCKEY_SRCOVERLAY
Color key or color space to be used as a source color key for overlay operations.


CONST_DDCOLORFLAGS

The CONST_DDCOLORFLAGS enumeration is used in the lFlags member of the DDCOLORCONTROL type to specify which members of the DDCOLORCONTROL type contain valid data.

Enum CONST_DDCOLORFLAGS
    DDCOLOR_BRIGHTNESS  =  1
    DDCOLOR_COLORENABLE = 64
    DDCOLOR_CONTRAST    =  2
    DDCOLOR_GAMMA       = 32
    DDCOLOR_HUE         =  4
    DDCOLOR_SATURATION  =  8
    DDCOLOR_SHARPNESS   = 16
End Enum
DDCOLOR_BRIGHTNESS
The lBrightness member contains valid data.
DDCOLOR_COLORENABLE
The lColorEnable member contains valid data.
DDCOLOR_CONTRAST
The lContrast member contains valid data.
DDCOLOR_GAMMA
The lGamma member contains valid data.
DDCOLOR_HUE
The lHue member contains valid data.
DDCOLOR_SATURATION
The lSaturation member contains valid data.
DDCOLOR_SHARPNESS
The lSharpness member contains valid data.


CONST_DDDEVICEIDFLAGS

The CONST_DDDEVICEIDFLAGS enumeration is used in the flags parameter of the DirectDraw7.GetDeviceIdentifier method to return information about the host (typically 2-D) adapter in a system equipped with a stacked secondary 3-D adapter.

Enum CONST_DDDEVICEIDFLAGS
    DDGDI_DEFAULT           = 0
    DDGDI_GETHOSTIDENTIFIER = 1
End Enum
DDGDI_DEFAULT
Perform a normal enumeration on the host adapter.
DDGDI_GETHOSTIDENTIFIER
Causes the method to return information about the host (typically 2-D) adapter in a system equipped with a stacked secondary 3-D adapter. Such an adapter appears to the application as if it were part of the host adapter, but is typically located on a separate card. When the dwFlags parameter is 0, the stacked secondary's information is returned because this most accurately reflects the qualities of the DirectDraw object involved.


CONST_DDEDMFLAGS

The CONST_DDEDMFLAGS enumeration is used in the flags parameter of the DirectDraw7.GetDisplayModesEnum method to specify the type of enumeration.

Enum CONST_DDEDMFLAGS
    DDEDM_DEFAULT          = 0
    DDEDM_REFRESHRATES     = 1
    DDEDM_STANDARDVGAMODES = 2
End Enum
DDEDM_DEFAULT
Performs a normal enumeration of the display modes.
DDEDM_REFRESHRATES
Enumerates modes with different refresh rates. This guarantees that a particular mode is enumerated only once. This flag specifies whether the refresh rate is taken into account when determining if a mode is unique.
DDEDM_STANDARDVGAMODES
Enumerates Mode 13 in addition to the 320x200x8 Mode X mode.


CONST_DDENUMOVERLAYZFLAGS

The CONST_DDENUMOVERLAYZFLAGS enumeration is used by the flags parameter of the DirectDrawSurface7.GetOverlayZOrdersEnum method to control how the method enumerates the overlay z-order.

Enum CONST_DDENUMSURFACESFLAGS
    DDENUMOVERLAYZ_BACKTOFRONT = 0
    DDENUMOVERLAYZ_FRONTTOBACK = 1
End Enum
DDENUMOVERLAYZ_BACKTOFRONT
Enumerates overlays back to front.
DDENUMOVERLAYZ_FRONTTOBACK
Enumerates overlays front to back.


CONST_DDENUMSURFACESFLAGS

The CONST_DDENUMSURFACESFLAGS enumeration is used by the DirectDraw7.GetSurfacesEnum method to control how the method enumerates attached surfaces.

Enum CONST_DDENUMSURFACESFLAGS
    DDENUMSURFACES_ALL          =  1
    DDENUMSURFACES_CANBECREATED =  8
    DDENUMSURFACES_DOESEXIST    = 16
    DDENUMSURFACES_MATCH        =  2
    DDENUMSURFACES_NOMATCH      =  4
End Enum
Search type flags
DDENUMSURFACES_CANBECREATED
Enumerates the first surface that can be created and meets the search criterion. This flag can only be used with the DDENUMSURFACES_MATCH flag.
DDENUMSURFACES_DOESEXIST
Enumerates the already existing surfaces that meet the search criterion.
Matching flags
DDENUMSURFACES_ALL
Enumerates all the surfaces that meet the search criterion. This flag can only be used with the DDENUMSURFACES_DOESEXIST search type flag.
DDENUMSURFACES_MATCH
Searches for any surface that matches the surface description.
DDENUMSURFACES_NOMATCH
Searches for any surface that does not match the surface description.


CONST_DDFLIPFLAGS

The CONST_DDFLIPFLAGS enumeration is used in the flags parameter of the DirectDrawSurface7.Flip method to specify flip options.

Enum CONST_DDFLIPFLAGS
    DDFLIP_DONOTWAIT  =         32
    DDFLIP_EVEN       =          2
    DDFLIP_INTERFVAL2 =  536870912
    DDFLIP_INTERFVAL3 =  805306368
    DDFLIP_INTERFVAL4 = 1073741824
    DDFLIP_NOVSYNC    =          8
    DDFLIP_ODD        =          4
    DDFLIP_WAIT       =          1
    DDFLIP_STEREO     =         16
End Enum
DDFLIP_DONOTWAIT
The default is DDFLIP_WAIT. If you want to override the default and use time when the accelerator is busy (as denoted by the DDERR_WASSTILLDRAWING error value), use DDFLIP_DONOTWAIT.
DDFLIP_EVEN
For use only when displaying video in an overlay surface. The new surface contains data from the even field of a video signal. This flag cannot be used with the DDFLIP_ODD flag.
DDFLIP_INTERFVAL2, DDFLIP_INTERFVAL3,
DDFLIP_INTERFVAL4
These flags indicate how many vertical retraces to wait between each flip. The default is 1. DirectDraw returns DERR_WASSTILLDRAWING for each surface involved in the flip until the specified number of vertical retraces has occurred. If DDFLIP_INTERFVAL2 is set, DirectDraw flips on every second vertical sync; if DDFLIP_INTERFVAL3, on every third sync; and if DDFLIP_INTERFVAL4, on every fourth sync.

These flags are effective only if DDCAPS2_FLIPINTERVAL is set in the DDCAPS type returned for the device.

DDFLIP_NOVSYNC
Causes DirectDraw to perform the physical flip as close as possible to the next scan line. Subsequent operations involving the two flipped surfaces do not check to see if the physical flip has finished—that is, they do not return DDERR_WASSTILLDRAWING for that reason (but may for other reasons). This allows an application to perform flips at a higher frequency than the monitor refresh rate, but might introduce visible artifacts.

If DDCAPS2_FLIPNOVSYNC is not set in the DDCAPS type returned for the device, DDFLIP_NOVSYNC has no effect.

DDFLIP_ODD
For use only when displaying video in an overlay surface. The new surface contains data from the odd field of a video signal. This flag cannot be used with the DDFLIP_EVEN flag.
DDFLIP_STEREO
DirectDraw flips and displays a main stereo surface. When this flag is set, stereo autoflipping is enabled. The hardware automatically flips between the left and right buffers during each screen refresh.
DDFLIP_WAIT
Typically, if the flip cannot be set up because the state of the display hardware is not appropriate, the DDERR_WASSTILLDRAWING error returns immediately, and no flip occurs. Setting this flag causes the method to continue trying to flip if it receives the DDERR_WASSTILLDRAWING error from the hardware abstraction layer (HAL). The method does not return until the flipping operation has been successfully set up, or another error, such as DDERR_SURFACEBUSY, is returned.


CONST_DDFXCAPSFLAGS

The CONST_DDFXCAPSFLAGS enumeration is used in the lFXCaps, lNLVBFXCaps, lSSBFXCaps, lSVBFXCaps, and lVSBFXCaps members of the DDCAPS type to describe driver-specific stretching and effects capabilities, nonlocal-to-local video-memory blit capabilities, system-memory-to-system-memory blit capabilities, system-memory-to-display-memory blit capabilities, and display-memory-to-system-memory blit capabilities.

Enum CONST_DDFXCAPSFLAGS
    DDFXCAPS_BLTALPHA               =         1
    DDFXCAPS_BLTARITHSTRETCHY       =        32
    DDFXCAPS_BLTARITHSTRETCHYN      =        16
    DDFXCAPS_BLTFILTER              =        32
    DDFXCAPS_BLTMIRRORLEFTRIGHT     =        64
    DDFXCAPS_BLTMIRRORUPDOWN        =       128
    DDFXCAPS_BLTROTATION            =       256
    DDFXCAPS_BLTROTATION90          =       512
    DDFXCAPS_BLTSHRINKX             =      1024
    DDFXCAPS_BLTSHRINKXN            =      2048
    DDFXCAPS_BLTSHRINKY             =      4096
    DDFXCAPS_BLTSHRINKYN            =      8192
    DDFXCAPS_BLTSTRETCHX            =     16384
    DDFXCAPS_BLTSTRETCHXN           =     32768
    DDFXCAPS_BLTSTRETCHY            =     65536
    DDFXCAPS_BLTSTRETCHYN           =    131072
    DDFXCAPS_BLTTRANSFORM           =         2
    DDFXCAPS_OVERLAYALPHA           =         4
    DDFXCAPS_OVERLAYARITHSTRETCHY   =    262144
    DDFXCAPS_OVERLAYARITHSTRETCHYN  =         8
    DDFXCAPS_OVERLAYFILTER          =    262144
    DDFXCAPS_OVERLAYMIRRORLEFTRIGHT = 134217728
    DDFXCAPS_OVERLAYMIRRORUPDOWN    = 268435456
    DDFXCAPS_OVERLAYSHRINKX         =    524288
    DDFXCAPS_OVERLAYSHRINKXN        =   1048576
    DDFXCAPS_OVERLAYSHRINKY         =   2097152
    DDFXCAPS_OVERLAYSHRINKYN        =   4194304
    DDFXCAPS_OVERLAYSTRETCHX        =   8388608
    DDFXCAPS_OVERLAYSTRETCHXN       =  16777216
    DDFXCAPS_OVERLAYSTRETCHY        =  33554432
    DDFXCAPS_OVERLAYSTRETCHYN       =  67108864
    DDFXCAPS_OVERLAYTRANSFORM       = 536870912
End Enum
DDFXCAPS_BLTALPHA
Supports alpha-blended blit operations.
DDFXCAPS_BLTARITHSTRETCHY
Uses arithmetic operations, rather than pixel-doubling techniques, to stretch and shrink surfaces during a blit operation. Occurs along the y-axis (vertically).
DDFXCAPS_BLTARITHSTRETCHYN
Uses arithmetic operations, rather than pixel-doubling techniques, to stretch and shrink surfaces during a blit operation. Occurs along the y-axis (vertically), and works only for integer stretching (×1, ×2, and so on).
DDFXCAPS_BLTFILTER
Driver can do surface-reconstruction filtering for warped blits.
DDFXCAPS_BLTMIRRORLEFTRIGHT
Supports mirroring left to right in a blit operation.
DDFXCAPS_BLTMIRRORUPDOWN
Supports mirroring top to bottom in a blit operation.
DDFXCAPS_BLTROTATION
Supports arbitrary rotation in a blit operation.
DDFXCAPS_BLTROTATION90
Supports 90-degree rotations in a blit operation.
DDFXCAPS_BLTSHRINKX
Supports arbitrary shrinking of a surface along the x-axis (horizontally). This flag is valid only for blit operations.
DDFXCAPS_BLTSHRINKXN
Supports integer shrinking (×1, ×2, and so on) of a surface along the x-axis (horizontally). This flag is valid only for blit operations.
DDFXCAPS_BLTSHRINKY
Supports arbitrary shrinking of a surface along the y-axis (vertically). This flag is valid only for blit operations.
DDFXCAPS_BLTSHRINKYN
Supports integer shrinking (×1, ×2, and so on) of a surface along the y-axis (vertically). This flag is valid only for blit operations.
DDFXCAPS_BLTSTRETCHX
Supports arbitrary stretching of a surface along the x-axis (horizontally). This flag is valid only for blit operations.
DDFXCAPS_BLTSTRETCHXN
Supports integer stretching (×1, ×2, and so on) of a surface along the x-axis (horizontally). This flag is valid only for blit operations.
DDFXCAPS_BLTSTRETCHY
Supports arbitrary stretching of a surface along the y-axis (vertically). This flag is valid only for blit operations.
DDFXCAPS_BLTSTRETCHYN
Supports integer stretching (×1, ×2, and so on) of a surface along the y-axis (vertically). This flag is valid only for blit operations.
DDFXCAPS_BLTTRANSFORM
Supports geometric transformations (or warps) for blitted sprites. Transformations are not currently supported for explicit blit operations.
DDFXCAPS_OVERLAYALPHA
Supports alpha blending for overlay surfaces.
DDFXCAPS_OVERLAYARITHSTRETCHY
Supports arbitrary stretching of a surface along the y-axis (vertically) for overlays.
DDFXCAPS_OVERLAYARITHSTRETCHYN
Supports integer stretching (x1, x2, and so on) of an overlay surface along the y-axis (vertically)
DDFXCAPS_OVERLAYFILTER
Supports surface-reconstruction filtering for warped overlay sprites. Filtering is not currently supported for explicitly displayed overlay surfaces (those displayed with calls to DirectDrawSurface7.UpdateOverlay).
DDFXCAPS_OVERLAYMIRRORLEFTRIGHT
Supports mirroring of overlays across the vertical axis.
DDFXCAPS_OVERLAYMIRRORUPDOWN
Supports mirroring of overlays across the horizontal axis.
DDFXCAPS_OVERLAYSHRINKX
Supports arbitrary shrinking of a surface along the x-axis (horizontally). This flag is valid only for DDSCAPS_OVERLAY surfaces. This flag indicates only the capabilities of a surface; it does not indicate that shrinking is available.
DDFXCAPS_OVERLAYSHRINKXN
Supports integer shrinking (×1, ×2, and so on) of a surface along the x-axis (horizontally). This flag is valid only for DDSCAPS_OVERLAY surfaces. This flag indicates only the capabilities of a surface; it does not indicate that shrinking is available.
DDFXCAPS_OVERLAYSHRINKY
Supports arbitrary shrinking of a surface along the y-axis (vertically). This flag is valid only for DDSCAPS_OVERLAY surfaces. This flag indicates only the capabilities of a surface; it does not indicate that shrinking is available.
DDFXCAPS_OVERLAYSHRINKYN
Supports integer shrinking (×1, ×2, and so on) of a surface along the y-axis (vertically). This flag is valid only for DDSCAPS_OVERLAY surfaces. This flag indicates only the capabilities of a surface; it does not indicate that shrinking is available.
DDFXCAPS_OVERLAYSTRETCHX
Supports arbitrary stretching of a surface along the x-axis (horizontally). This flag is valid only for DDSCAPS_OVERLAY surfaces. This flag indicates only the capabilities of a surface; it does not indicate that stretching is available.
DDFXCAPS_OVERLAYSTRETCHXN
Supports integer stretching (×1, ×2, and so on) of a surface along the x-axis (horizontally). This flag is valid only for DDSCAPS_OVERLAY surfaces. This flag indicates only the capabilities of a surface; it does not indicate that stretching is available.
DDFXCAPS_OVERLAYSTRETCHY
Supports arbitrary stretching of a surface along the y-axis (vertically). This flag is valid only for DDSCAPS_OVERLAY surfaces. This flag indicates only the capabilities of a surface; it does not indicate that stretching is available.
DDFXCAPS_OVERLAYSTRETCHYN
Supports integer stretching (×1, ×2, and so on) of a surface along the y-axis (vertically). This flag is valid only for DDSCAPS_OVERLAY surfaces. This flag indicates only the capabilities of a surface; it does not indicate that stretching is available.
DDFXCAPS_OVERLAYTRANSFORM
Supports geometric transformations (or warps) for overlay sprites. Transformations are not currently supported for explicitly displayed overlay surfaces (those displayed with calls to DirectDrawSurface7.UpdateOverlay).


CONST_DDGBSFLAGS

The CONST_DDGBSFLAGS enumeration is used by the flags parameter of the DirectDrawSurface7.GetBltStatus method to specify what type of status to obtain.

Enum CONST_DDGBSFLAGS
    DDGBS_CANBLT    = 1
    DDGBS_ISBLTDONE = 2
End Enum
DDGBS_CANBLT
Inquires whether a blit involving this surface can occur immediately, and returns DD_OK if the blit can be completed.
DDGBS_ISBLTDONE
Inquires whether the blit is done, and returns DD_OK if the last blit on this surface has completed.


CONST_DDGFSFLAGS

The CONST_DDGFSFLAGS enumeration is used by the flags parameter of the DirectDrawSurface7.GetFlipStatus method to specify the type of flip status to obtain.

Enum CONST_DDGFSFLAGS
    DDGFS_CANFLIP    = 1
    DDGFS_ISFLIPDONE = 2
End Enum
DDGFS_CANFLIP
Inquires whether this surface can be flipped immediately, and returns DD_OK if the flip can be completed.
DDGFS_ISFLIPDONE
Inquires whether the flip has finished, and returns DD_OK if the last flip on this surface has completed.


CONST_DDLOCKFLAGS

The CONST_DDLOCKFLAGS enumeration is used by the flags parameter of the DirectDrawSurface7.Lock and Direct3DVertexBuffer7.Lock methods to indicate how the lock is to be performed.

Enum CONST_DDLOCKFLAGS
    DDLOCK_DONOTWAIT    = 16384
    DDLOCK_EVENT         =    2
    DDLOCK_NOSYSLOCK     = 2048
    DDLOCK_READONLY      =   16
    DDLOCK_SURFACEMEMORYPTR = 0
    DDLOCK_WAIT          =    1
    DDLOCK_WRITEONLY     =   32
End Enum
DDLOCK_DONOTWAIT
The default is DDLOCK_WAIT. If you wish to override the default and use time when the accelerator is busy (as denoted by the DDERR_WASSTILLDRAWING error value). use DDLOCK_DONOTWAIT.
DDLOCK_EVENT
Not currently implemented.
DDLOCK_NOSYSLOCK
If possible, do not take the Win16Mutex (also known as Win16Lock). This flag is ignored when locking the primary surface.
DDLOCK_READONLY
The surface being locked is read-only.
DDLOCK_SURFACEMEMORYPTR
A valid memory pointer to the top of the specified rectangle should be returned. If no rectangle is specified, a pointer to the top of the surface is returned. This is the default.
DDLOCK_WAIT
If a lock cannot be obtained because a blit operation is in progress, the method retries until a lock is obtained or another error occurs, such as DDERR_SURFACEBUSY.
DDLOCK_WRITEONLY
The surface being locked is write-enabled.


CONST_DDOVERFLAGS

The flags in the CONST_DDOVERFLAGS enumeration are used by the flags member of the DirectDrawSurface7.UpdateOverlay method to modify the visual attributes on an overlay.

Enum CONST_DDOVERFLAGS
    DDOVER_ADDDIRTYRECT             = 32768
    DDOVER_ALPHADEST                = 1
    DDOVER_ALPHADESTCONSTOVERRIDE   = 2
    DDOVER_ALPHADESTNEG             = 4
    DDOVER_ALPHADESTSURFACEOVERRIDE = 8
    DDOVER_ALPHAEDGEBLEND           = 16
    DDOVER_ALPHASRC                 = 32
    DDOVER_ALPHASRCCONSTOVERRIDE    = 64
    DDOVER_ALPHASRCNEG              = 128
    DDOVER_ALPHASRCSURFACEOVERRIDE  = 256
    DDOVER_ARGBSCALEFACTORS         = 33554432
    DDOVER_AUTOFLIP                 = 1048576
    DDOVER_BOB                      = 2097152
    DDOVER_DDFX                     = 524288
    DDOVER_DEGRADEARGBSCALING       = 67108864
    DDOVER_HIDE                     = 512
    DDOVER_INTERLEAVED              = 8388608
    DDOVER_KEYDEST                  = 1024
    DDOVER_KEYDESTOVERRIDE          = 2048
    DDOVER_KEYSRC                   = 4096
    DDOVER_KEYSRCOVERRIDE           = 8192
    DDOVER_OVERRIDEBOBWEAVE         = 4194304
    DDOVER_REFRESHALL               = 131072
    DDOVER_REFRESHDIRTYRECTS        = 65536
    DDOVER_SHOW                     = 16384
End Enum
DDOVER_ADDDIRTYRECT
Adds a dirty rectangle to an emulated overlay surface.
DDOVER_ALPHADEST
Obsolete.
DDOVER_ALPHADESTCONSTOVERRIDE
Uses the lAlphaDestConst member of the DDOVERLAYFX type as the destination alpha channel for this overlay.
DDOVER_ALPHADESTNEG
The destination surface becomes more transparent as the alpha value increases (0 is opaque).
DDOVER_ALPHADESTSURFACEOVERRIDE
Uses the lpDDSAlphaDest member of the DDOVERLAYFX type as the alpha channel destination for this overlay.
DDOVER_ALPHAEDGEBLEND
Uses the lAlphaEdgeBlend member of the DDOVERLAYFX type as the alpha channel for the edges of the image that border the color key colors.
DDOVER_ALPHASRC
Uses either the alpha information in pixel format or the alpha channel surface attached to the source surface as the source alpha channel for this overlay.
DDOVER_ALPHASRCCONSTOVERRIDE
Uses the lAlphaSrcConst member of the DDOVERLAYFX type as the source alpha channel for this overlay.
DDOVER_ALPHASRCNEG
The source surface becomes more transparent as the alpha value increases (0 is opaque).
DDOVER_ALPHASRCSURFACEOVERRIDE
Uses the lpDDSAlphaSrc member of the DDOVERLAYFX structure as the alpha channel source for this overlay.
DDOVER_ARGBSCALEFACTORS
New for DirectX 7.0. Overlay FX structure contains valid ARGB scaling factors.
DDOVER_AUTOFLIP
Automatically flips to the next surface in the flip chain each time a video port VSYNC occurs.
DDOVER_BOB
Displays each field of the interlaced video stream individually without causing any artifacts.
DDOVER_DDFX
When calling the DirectDrawSurface7.UpdateOverlayFx, setting this flag uses the flags set in the ddoverfx parameter to define special overlay effects. This flag must be set, or the ddoverfx parameter is ignored.
DDOVER_DEGRADEARGBSCALING
New for DirectX 7.0. ARGB scaling factors can be degraded to fit driver capabilities.
DDOVER_HIDE
Turns off this overlay.
DDOVER_INTERLEAVED
The surface memory is composed of interleaved fields.
DDOVER_KEYDEST
Uses the color key associated with the destination surface.
DDOVER_KEYDESTOVERRIDE
Uses the dckDestColorkey member of the DDOVERLAYFX type as the color key for the destination surface.
DDOVER_KEYSRC
Uses the color key associated with the source surface.
DDOVER_KEYSRCOVERRIDE
Uses the dckSrcColorkey member of the DDOVERLAYFX type as the color key for the source surface.
DDOVER_OVERRIDEBOBWEAVE
Bob and weave decisions should not be overridden by other interfaces.
DDOVER_REFRESHALL
Redraws the entire surface on an emulated overlayed surface.
DDOVER_REFRESHDIRTYRECTS
Redraws all dirty rectangles on an emulated overlayed surface.
DDOVER_SHOW
Turns on this overlay.


CONST_DDOVERFXFLAGS

The flags in the CONST_DDOVERFXFLAGS enumeration are used by the lDDFX member in the DDOVERLAYFX type to specify how the overlay is used.

Enum CONST_DDPALFLAGS
    DDOVERFX_ARITHSTRETCHY   = 1
    DDOVERFX_MIRRORLEFTRIGHT = 2
    DDOVERFX_MIRRORUPDOWN    = 4
End Enum
DDOVERFX_ARITHSTRETCHY
If stretching, use arithmetic stretching along the y-axis for this overlay.
DDOVERFX_MIRRORLEFTRIGHT
Mirror the overlay around the vertical axis.
DDOVERFX_MIRRORUPDOWN
Mirror the overlay around the horizontal axis.


CONST_DDOVERZFLAGS

The flags in the CONST_DDOVERZFLAGS enumeration are used by the flags member in the DirectDrawSurface7.UpdateOverlayZOrder type to set the z-order of an overlay.

Enum CONST_DDPALFLAGS
    DDOVERZ_INSERTINBACKOF  = 5
    DDOVERZ_INSERTINFRONTOF = 4
    DDOVERZ_MOVEBACKWARD    = 3
    DDOVERZ_MOVEFORWARD     = 2
    DDOVERZ_SENDTOBACK      = 1
    DDOVERZ_SENDTOFRONT     = 0
End Enum
DDOVERZ_INSERTINBACKOF
Inserts this overlay in the overlay chain behind the reference overlay.
DDOVERZ_INSERTINFRONTOF
Inserts this overlay in the overlay chain in front of the reference overlay.
DDOVERZ_MOVEBACKWARD
Moves this overlay one position backward in the overlay chain.
DDOVERZ_MOVEFORWARD
Moves this overlay one position forward in the overlay chain.
DDOVERZ_SENDTOBACK
Moves this overlay to the back of the overlay chain.
DDOVERZ_SENDTOFRONT
Moves this overlay to the front of the overlay chain.


CONST_DDPALFLAGS

The flags in the CONST_DDPALFLAGS enumeration are used by the flags member in the PALETTEENTRY type to specify how the palette entry is used.

Enum CONST_DDPALFLAGS
    PC_DEFAULT     = 0
    PC_EXPLICIT    = 2
    PC_NOCOLLAPSE  = 4
    PC_RESERVED    = 1
End Enum
PC_DEFAULT
The palette entry is to be used without modification from the flags below.
PC_EXPLICIT
The low-order word of the logical palette entry designates a hardware palette index. This flag allows the application to show the contents of the display device palette.
PC_NOCOLLAPSE
The color is placed in an unused entry in the system palette, instead of being matched to an existing color in the system palette. If there are no unused entries in the system palette, the color is matched normally. Once this color is in the system palette, colors in other logical palettes can be matched to this color.
PC_RESERVED
The logical palette entry is used for palette animation. This flag prevents other windows from matching colors to the palette entry since the color frequently changes. If an unused system-palette entry is available, the color is placed in that entry. Otherwise, the color is not available for animation.

Remarks

The type library defines the flags member of PALETTEENTRY to be a byte, rather than this enumeration; therefore, autocompletion is not enabled. The flags in this enumeration are valid for the flags member and can be specified to modify behavior.


CONST_DDPCAPSFLAGS

The CONST_DDPCAPSFLAGS enumeration is used by the flags parameter of DirectDraw7.CreatePalette as a return value for DirectDrawPalette.GetCaps and by the lPalCaps member of DDCAPS to describe the capabilities of the palette.

Enum CONST_DDPCAPSFLAGS
    DDPCAPS_1BIT             =  256
    DDPCAPS_2BIT             =  512
    DDPCAPS_4BIT             =    1
    DDPCAPS_8BIT             =    4
    DDPCAPS_8BITENTRIES      =    2
    DDPCAPS_ALLOW256         =   64
    DDPCAPS_ALPHA            = 1024
    DDPCAPS_INITIALIZE       =    8
    DDPCAPS_PRIMARYSURFACE   =   16
    DDPCAPS_PRIMARYSURFACELEFT = 32
    DDPCAPS_VSYNC            =  128
End Enum
DDPCAPS_1BIT
The index is 1 bit. There are two entries in the color table.
DDPCAPS_2BIT
The index is 2 bits. There are four entries in the color table.
DDPCAPS_4BIT
The index is 4 bits. There are 16 entries in the color table.
DDPCAPS_8BIT
The index is 8 bits. There are 256 entries in the color table_dx_color_table_glos.
DDPCAPS_8BITENTRIES
The index refers to an 8-bit color index. This flag is valid only when used with the DDPCAPS_1BIT, DDPCAPS_2BIT, or DDPCAPS_4BIT flag and when the target surface is 8 bpp. Each color entry is 1 byte long and is an index to a destination surface's 8-bpp palette.
DDPCAPS_ALLOW256
This palette can have all 256 entries defined.
DDPCAPS_ALPHA
The flags member of the associated PALETTEENTRY type is to be interpreted as a single 8-bit alpha value. A palette created with this flag can be attached only to a texture (a surface created with the DDSCAPS_TEXTURE capability flag).
DDPCAPS_INITIALIZE
Obsolete and ignored by DirectDraw.
DDPCAPS_PRIMARYSURFACE
This palette is attached to the primary surface. Changing this palette's color table immediately affects the display unless DDPSETPAL_VSYNC is specified and supported.
DDPCAPS_PRIMARYSURFACELEFT
This palette is the one attached to the left-eye primary surface. Changing this palette's color table immediately affects the left-eye display unless DDPSETPAL_VSYNC is specified and supported.
DDPCAPS_VSYNC
This palette can have modifications to it synchronized with the monitors refresh rate.


CONST_DDPIXELFORMATFLAGS

The CONST_DDPIXELFORMATFLAGS enumeration is used by the lFlags member of the DDPIXELFORMAT type to specify optional control flags.

Enum CONST_DDPIXELFORMATFLAGS
    DDPF_ALPHA          =      2
    DDPF_ALPHAPIXELS    =      1
    DDPF_ALPHAPREMULT   =  32768
    DDPF_BUMPDUDV       = 524288
    DDPF_BUMPLUMINANCE  = 262144
    DDPF_COMPRESSED     =    128
    DDPF_FOURCC         =      4
    DDPF_LUMINANCE      = 131072
    DDPF_PALETTEINDEXED1 =  2048
    DDPF_PALETTEINDEXED2 =  4096
    DDPF_PALETTEINDEXED4 =     8
    DDPF_PALETTEINDEXED8 =    32
    DDPF_PALETTEINDEXEDTO8 =  16
    DDPF_RGB             =    64
    DDPF_RGBTOYUV        =   256
    DDPF_STENCILBUFFER   = 16384
    DDPF_YUV             =   512
    DDPF_ZBUFFER         =  1024
    DDPF_ZPIXELS         =  8192
End Enum
DDPF_ALPHA
The pixel format describes an alpha-only surface.
DDPF_ALPHAPIXELS
The surface has alpha channel information in the pixel format.
DDPF_ALPHAPREMULT
The surface uses the premultiplied alpha format. That is, the color components in each pixel are premultiplied by the alpha component.
DDPF_BUMPDUDV
Bump-map data in the pixel format is valid. Bump-map information is in the lBumpBitCount, lBumpDuBitMask, lBumpDvBitMask, and lBumpLuminanceBitMask members.
DDPF_BUMPLUMINANCE
The luminance data in the pixel format is valid, and the lLuminanceBitMask member descibes valid luminance bits for a luminance-only or luminance-alpha surface.
DDPF_COMPRESSED
The surface accepts pixel data in the specified format and compresses it during the write operation.
DDPF_FOURCC
The lFourCC member is valid and contains a FOURCC code describing a non-RGB pixel format.
DDPF_LUMINANCE
The pixel format describes a luminance-only or luminance-alpha surface.
DDPF_PALETTEINDEXED1
DDPF_PALETTEINDEXED2
DDPF_PALETTEINDEXED4
DDPF_PALETTEINDEXED8
The surface is 1-, 2-, 4-, or 8-bit color indexed.
DDPF_PALETTEINDEXEDTO8
The surface is 1-, 2-, or 4-bit color indexed to an 8-bit palette.
DDPF_RGB
The RGB data in the pixel format type is valid.
DDPF_RGBTOYUV
The surface accepts RGB data and translates it during the write operation to YUV data. The format of the data to be written is contained in the pixel format type. The DDPF_RGB flag is set.
DDPF_STENCILBUFFER
The surface encodes stencil and depth information in each pixel of the z-buffer.
DDPF_YUV
The YUV data in the pixel format type is valid.
DDPF_ZBUFFER
The pixel format describes a z-buffer-only surface.
DDPF_ZPIXELS
The surface contains z information in the pixels.


CONST_DDRAW

The CONST_DDRAW enumeration contains constants used throughout DirectDraw.

Enum CONST_DDRAW
    DD_ROP_SPACE = 8
End Enum
DD_ROP_SPACE
The default Win32 raster operations.


CONST_DDRAWERR

For information on error values in DirectDraw see Error Codes.


CONST_DDSCLFLAGS

The CONST_DDSCLFLAGS enumeration is used in the flags parameter of the DirectDraw7.SetCooperativeLevel method to determine the top-level behavior of the application.

Enum CONST_DDSCLFLAGS
    DDSCL_ALLOWMODEX       =    64
    DDSCL_ALLOWREBOOT      =     2
    DDSCL_CREATEDEVICEWINDOW = 512
    DDSCL_EXCLUSIVE        =    16
    DDSCL_FULLSCREEN       =     1
    DDSCL_MULTITHREADED    =  1024
    DDSCL_NORMAL           =     8
    DDSCL_NOWINDOWCHANGES  =     4
    DDSCL_SETDEVICEWINDOW  =   256
    DDSCL_SETFOCUSWINDOW   =   128
End Enum
DDSCL_ALLOWMODEX
Allows the use of Mode X display modes. This flag can only be used if the DDSCL_EXCLUSIVE and DDSCL_FULLSCREEN flags are present.
DDSCL_ALLOWREBOOT
Allows CTRL+ALT+DEL to function while in exclusive (full-screen) mode.
DDSCL_CREATEDEVICEWINDOW
This flag is supported in Windows 98 and Windows 2000 only. Indicates that DirectDraw is to create and manage a default device window for this DirectDraw object. For more information, see Focus and Device Windows.
DDSCL_EXCLUSIVE
Requests the exclusive level. This flag must be used with the DDSCL_FULLSCREEN flag.
DDSCL_FULLSCREEN
Indicates that the exclusive-mode owner is responsible for the entire primary surface. The GDI can be ignored. This flag must be used with the DDSCL_EXCLUSIVE flag.
DDSCL_MULTITHREADED
Requests multithread-safe DirectDraw behavior. This causes Direct3D to take the global critical section more frequently.
DDSCL_NORMAL
The application functions as a regular Windows application. This flag cannot be used with the DDSCL_ALLOWMODEX, DDSCL_EXCLUSIVE, or DDSCL_FULLSCREEN flags.
DDSCL_NOWINDOWCHANGES
DirectDraw is not allowed to minimize or restore the application window on activation.
DDSCL_SETDEVICEWINDOW
This flag is supported in Windows 98 and Windows 2000 only. Indicates that the hdl parameter is the window handle of the device window for this DirectDraw object. This flag cannot be used with the DDSCL_SETFOCUSWINDOW flag.
DDSCL_SETFOCUSWINDOW
This flag is supported in Windows 98 and Windows 2000 only. Indicates that the hdl parameter is the window handle of the focus window for this DirectDraw object. This flag cannot be used with the DDSCL_SETDEVICEWINDOW flag.


CONST_DDSDMFLAGS

The CONST_DDSDMFLAGS enumeration is used in the flags parameter of the DirectDraw7.SetDisplayMode method to set the mode of the display-device hardware.

Enum CONST_DDSDMFLAGS
    DDSDM_DEFAULT = 0
    DDSDM_STANDARDVGAMODE = 1
End Enum
DDSDM_DEFAULT
Sets the mode without substituting Mode 13 for Mode X.
DDSDM_STANDARDVGAMODE
Causes the method to set Mode 13, instead of Mode X 320x200x8 mode. If you are setting another resolution, bit depth, or a Mode X mode, do not use this flag, and set the parameter to 0.


CONST_DDSGRFLAGS

The CONST_DDSGRFLAGS enumeration is used in the flags parameter of the DirectDrawGammaControl.SetGammaRamp method to indicate that gamma calibration is desired.

Enum CONST_DDSGRFLAGS
    DDSGR_CALIBRATE = 1
    DDSGR_DEFAULT = 0
End Enum
DDSGR_DEFAULT
Sets the gamma ramp without calibrating the gamma ramp to the physical properties of the display.
DDSGR_CALIBRATE
Requests that the calibrator adjust the gamma ramp according to the physical properties of the display, making the result identical on all systems. If calibration is not needed, set this parameter to 0.


CONST_DDSTEREOCAPSFLAGS

The CONST_DDSTEREOCAPSFLAGS enumeration is used by the lSVCaps member of the DDCAPS type to describe stereo-vision capabilities.

Enum CONST_DDSTEREOCAPSFLAGS
    DDSVCAPS_ENIGMA  = 1
    DDSVCAPS_FLICKER = 2
    DDSVCAPS_REDBLUE = 4
    DDSVCAPS_SPLIT   = 8
    DDSVCAPS_STEREOSEQUENTIAL = 16
End Enum
DDSVCAPS_ENIGMA
The stereo view is accomplished using Enigma encoding.
DDSVCAPS_FLICKER
The stereo view is accomplished using high-frequency flickering.
DDSVCAPS_REDBLUE
The stereo view is accomplished when the viewer looks at the image through red and blue filters placed over the left and right eyes. All images must adapt their color spaces for this process.
DDSVCAPS_SPLIT
The stereo view is accomplished with split-screen technology.
DDSVCAPS_STEREOSEQUENTIAL
The driver can do stereo in at least one mode other than the current mode. The application can use DirectDraw7.GetDisplayMode or DirectDraw7.GetDisplayModesEnum to get per-mode stereo information.


CONST_DDSURFACECAPS2FLAGS

The CONST_DDSURFACECAPS2FLAGS enumeration is used by the lCaps2 member of the DDSCAPS2 type to describe additional surface capabilities.

Enum CONST_DDSURFACECAPS2FLAGS
    DDSCAPS2_CUBEMAP             = 512
    DDSCAPS2_CUBEMAP_ALLFACES    = 65024
    DDSCAPS2_CUBEMAP_NEGATIVEX   = 2048
    DDSCAPS2_CUBEMAP_NEGATIVEY   = 8192
    DDSCAPS2_CUBEMAP_NEGATIVEZ   = 32768
    DDSCAPS2_CUBEMAP_POSITIVEX   = 1024
    DDSCAPS2_CUBEMAP_POSITIVEY   = 4096
    DDSCAPS2_CUBEMAP_POSITIVEZ   = 16384
    DDSCAPS2_D3DTEXTUREMANAGE    = 131072
    DDSCAPS2_HARDWAREDEINTERLACE = 2
    DDSCAPS2_HINTANTIALIASING    = 256
    DDSCAPS2_HINTDYNAMIC         = 4
    DDSCAPS2_HINTSTATIC          = 8
    DDSCAPS2_MIPMAPSUBLEVEL      = 65536
    DDSCAPS2_OPAQUE              = 128
    DDSCAPS2_STEREOSURFACELEFT   = 524288
    DDSCAPS2_TEXTUREMANAGE       = 16
End Enum
Capability flags
DDSCAPS2_CUBEMAP
New for DirectX 7.0. This surface is a cubic environment map.
DDSCAPS2_CUBEMAP_ALLFACES
New for DirectX 7.0. This flag is used with the DDSCAPS2_CUBEMAP flag to create all six faces of a cubic environment map.
DDSCAPS2_CUBEMAP_NEGATIVEX
New for DirectX 7.0. This flag is used with the DDSCAPS2_CUBEMAP flag to create the negative X face of a cubic environment map.
DDSCAPS2_CUBEMAP_NEGATIVEY
New for DirectX 7.0. This flag is used with the DDSCAPS2_CUBEMAP flag to create the negative Y face of a cubic environment map.
DDSCAPS2_CUBEMAP_NEGATIVEZ
New for DirectX 7.0. This flag is used with the DDSCAPS2_CUBEMAP flag to create the negative Z face of a cubic environment map.
DDSCAPS2_CUBEMAP_POSITIVEX
New for DirectX 7.0. This flag is used with the DDSCAPS2_CUBEMAP flag to create the positive X face of a cubic environment map.
DDSCAPS2_CUBEMAP_POSITIVEY
New for DirectX 7.0. This flag is used with the DDSCAPS2_CUBEMAP flag to create the positive Y face of a cubic environment map.
DDSCAPS2_CUBEMAP_POSITIVEZ
New for DirectX 7.0. This flag is used with the DDSCAPS2_CUBEMAP flag to create the positive Z face of a cubic environment map.
DDSCAPS2_D3DTEXTUREMANAGE
New for DirectX 7.0. The texture is always managed by Direct3D.
DDSCAPS2_HARDWAREDEINTERLACE
This surface receives data from a video port using the de-interlacing hardware. This allows the driver to allocate memory for any extra buffers that might be required. The DDSCAPS_VIDEOPORT and DDSCAPS_OVERLAY flags must also be set.
DDSCAPS2_HINTANTIALIASING
The application intends to use antialiasing. Only valid if DDSCAPS_3DDEVICE is also set.
DDSCAPS2_HINTDYNAMIC
Indicates to the driver that this surface is locked very frequently (for procedural textures, dynamic lightmaps, and so on). This flag can only be used for texture surfaces (the DDSCAPS_TEXTURE flag set in the lCaps2 member). This flag cannot be used with the DDSCAPS2_HINTSTATIC or DDSCAPS2_OPAQUE flags.
DDSCAPS2_HINTSTATIC
Indicates to the driver that this surface can be reordered or retiled on load. This operation does not change the size of the texture. It is relatively fast and symmetrical, since the application can lock these bits (although it degrades performance when doing so). This flag can be used only for texture surfaces (the DDSCAPS_TEXTURE flag set in the lCaps2 member). This flag cannot be used with the DDSCAPS2_HINTDYNAMIC or DDSCAPS2_OPAQUE flags.
DDSCAPS2_MIPMAPSUBLEVEL
New for DirectX 7.0. Enables easier use of GetAttachedSurface, rather than EnumAttachedSurfaces, for surface constructs such as cube maps in which there is more than one mipmap surface attached to the root surface. This should be set on all non-top-level surfaces in a mipmapped cubemap so that a call to GetAttachedSurface can distinguish between top-level faces and attached mipmap levels. This capabilities bit is ignored by CreateSurface.
DDSCAPS2_OPAQUE
Indicates to the driver that this surface will never be locked again. The driver is free to optimize this surface by retiling and compression. Such a surface cannot be locked or used in blit operations; attempts to lock or blit a surface with this capability fail. This flag can only be used for texture surfaces (DDSCAPS_TEXTURE flag set in the lCaps2 member). This flag cannot be used with the DDSCAPS2_HINTDYNAMIC or the DDSCAPS2_HINTSTATIC flag.
DDSCAPS2_STEREOSURFACELEFT
New for DirectX 7.0. This surface is part of a stereo flipping chain. When this flag is set during a DirectDraw7.CreateSurface call, a pair of stereo surfaces is created for each buffer in the primary flipping chain. You must create a complex flipping chain (with back-buffers). You cannot create a single set of stereo surfaces. The DirectDrawSurface7.Flip method requires that you have back-buffers (at least four surfaces are created).

In addition, when this flag is set in a DDSURFACEDESC2 type as the result of an DirectDraw7.GetDisplayModesEnum or DirectDraw7.GetDisplayMode call, it indicates support for stereo in that mode.

DDSCAPS2_TEXTUREMANAGE
The client would like this texture surface to be managed by the driver if the driver is capable; otherwise, it is managed by Direct3D Immediate Mode (new in DirectX 7.0). This flag can be used only for texture surfaces (DDSCAPS_TEXTURE flag set in the lCaps2 member). For more information, see Automatic Texture Management in the Direct3D Immediate Mode documentation. Do not use this flag if your application uses Direct3D Retained Mode. Instead, create textures in system memory, and allow Retained Mode to manage them.


CONST_DDSURFACECAPSFLAGS

The CONST_DDSURFACECAPSFLAGS enumeration is used in the lCaps member of the DDSCAPS2 type to describe the capabilities of the surface.

Enum CONST_DDSURFACECAPSFLAGS
    DDSCAPS_3DDEVICE        =        8192
    DDSCAPS_ALLOCONLOAD     =    67108864
    DDSCAPS_ALPHA           =           2
    DDSCAPS_BACKBUFFER      =           4
    DDSCAPS_COMPLEX         =           8
    DDSCAPS_FLIP            =          16
    DDSCAPS_FRONTBUFFER     =          32
    DDSCAPS_HWCODEC         =     1048576
    DDSCAPS_LIVEVIDEO       =      524288
    DDSCAPS_LOCALVIDMEM     =   268435456
    DDSCAPS_MIPMAP          =     4194304
    DDSCAPS_MODEX           =     2097152
    DDSCAPS_NONLOCALVIDMEM  =   536870912
    DDSCAPS_OFFSCREENPLAIN  =          64
    DDSCAPS_OPTIMIZED       = -2147483648
    DDSCAPS_OVERLAY         =         128
    DDSCAPS_OWNDC           =      262144
    DDSCAPS_PALETTE         =         256
    DDSCAPS_PRIMARYSURFACE  =         512
    DDSCAPS_RESERVED2       =     8388608
    DDSCAPS_STANDARDVGAMODE =  1073741824
    DDSCAPS_SYSTEMMEMORY    =        2048
    DDSCAPS_TEXTURE         =        4096
    DDSCAPS_VIDEOMEMORY     =       16384
    DDSCAPS_VIDEOPORT       =   134217728
    DDSCAPS_VISIBLE         =       32768
    DDSCAPS_WRITEONLY       =       65536
    DDSCAPS_ZBUFFER         =      131072
End Enum
DDSCAPS_3DDEVICE
This surface can be used for 3-D rendering. Applications can use this flag to ensure that a device that can render only to a certain heap has off-screen surfaces allocated from the correct heap. If this flag is set for a heap, the surface is not allocated from that heap.
DDSCAPS_ALLOCONLOAD
Not used; ignored by DirectDraw and Direct3D.
DDSCAPS_ALPHA
This surface contains alpha-only information.
DDSCAPS_BACKBUFFER
This surface is the back buffer of a surface flipping type. Typically, this capability is set by the CreateSurface method when the DDSCAPS_FLIP flag is used. Only the surface that immediately precedes the DDSCAPS_FRONTBUFFER surface has this capability set. The other surfaces are identified as back buffers by the presence of the DDSCAPS_FLIP flag, their attachment order, and the absence of the DDSCAPS_FRONTBUFFER and DDSCAPS_BACKBUFFER capabilities. If this capability is sent to the CreateSurface method, a stand-alone back buffer is being created. After this method is called, this surface could be attached to a front buffer, another back buffer, or both to form a flipping surface type. For more information, see DirectDrawSurface7.AddAttachedSurface. DirectDraw supports an arbitrary number of surfaces in a flipping type.
DDSCAPS_COMPLEX
A complex surface is being described. A complex surface results in the creation of more than one surface. The additional surfaces are attached to the root surface. The complex type can be destroyed only by destroying the root.
DDSCAPS_FLIP
This surface is a part of a surface flipping type. When this capability is passed to the CreateSurface method, a front buffer and one or more back buffers are created. DirectDraw sets the DDSCAPS_FRONTBUFFER bit on the front-buffer surface and the DDSCAPS_BACKBUFFER bit on the surface adjacent to the front-buffer surface. The lBackBufferCount member of the DDSURFACEDESC2 type must be set to at least 1 for the method call to succeed. The DDSCAPS_COMPLEX capability must always be set when creating multiple surfaces by using the CreateSurface method.
DDSCAPS_FRONTBUFFER
This surface is the front buffer of a surface flipping type. This flag is typically set by the CreateSurface method when the DDSCAPS_FLIP capability is set. If this capability is sent to the CreateSurface method, a stand-alone front buffer is created. This surface does not have the DDSCAPS_FLIP capability. It can be attached to other back buffers to form a flipping type by using DirectDrawSurface7.AddAttachedSurface.
DDSCAPS_HWCODEC
This surface can have a stream decompressed to it by the hardware.
DDSCAPS_LIVEVIDEO
This surface can receive live video.
DDSCAPS_LOCALVIDMEM
This surface exists in true, local video memory, rather than nonlocal video memory. If this flag is specified, DDSCAPS_VIDEOMEMORY must be specified, as well. This flag cannot be used with the DDSCAPS_NONLOCALVIDMEM flag.
DDSCAPS_MIPMAP
This surface is one level of a mipmap. This surface is attached to other DDSCAPS_MIPMAP surfaces to form the mipmap. This can be done explicitly by creating a number of surfaces and attaching them by using the DirectDrawSurface7.AddAttachedSurface method, or implicitly by the CreateSurface method. If this capability is set, DDSCAPS_TEXTURE must also be set.
DDSCAPS_MODEX
This surface is a 320×200 or 320×240 Mode X surface.
DDSCAPS_NONLOCALVIDMEM
This surface exists in nonlocal video memory, rather than true, local video memory. If this flag is specified, DDSCAPS_VIDEOMEMORY flag must be specified, as well. This cannot be used with the DDSCAPS_LOCALVIDMEM flag.
DDSCAPS_OFFSCREENPLAIN
This surface is any off-screen surface that is not an overlay, texture, z-buffer, front-buffer, back-buffer, or alpha surface. It is used to identify plain surfaces.
DDSCAPS_OPTIMIZED
Not currently implemented.
DDSCAPS_OVERLAY
This surface is an overlay. It might or might not be directly visible, depending on whether it is currently being overlaid onto the primary surface. DDSCAPS_VISIBLE can be used to determine if it is currently being overlaid.
DDSCAPS_OWNDC
This surface has a device context (DC) association for a long period of time.
DDSCAPS_PALETTE
This device driver allows unique DirectDrawPalette objects to be created and attached to this surface.
DDSCAPS_PRIMARYSURFACE
Surface is the primary surface. It represents what is currently visible.
DDSCAPS_RESERVED2
Reserved for future use.
DDSCAPS_STANDARDVGAMODE
This surface is a standard VGA mode surface, and not a Mode X surface. This flag cannot be used in combination with the DDSCAPS_MODEX flag.
DDSCAPS_SYSTEMMEMORY
This surface memory was allocated in system memory.
DDSCAPS_TEXTURE
This surface can be used as a 3-D texture. This member does not indicate whether the surface is being used for that purpose.
DDSCAPS_VIDEOMEMORY
This surface exists in display memory.
DDSCAPS_VIDEOPORT
This surface can receive data from a video port.
DDSCAPS_VISIBLE
Changes made to this surface are immediately visible. It is always set for the primary surface, as well as for overlays while they are being overlaid and texture maps while they are being textured.
DDSCAPS_WRITEONLY
Only write access is permitted to the surface. Read access from the surface can generate a general protection (GP) fault, but the read results from this surface are not meaningful.
DDSCAPS_ZBUFFER
This surface is the z-buffer. The z-buffer contains information that cannot be displayed. Instead, it contains bit-depth information that is used to determine which pixels are visible and which are obscured.


CONST_DDSURFACEDESCFLAGS

The CONST_DDSURFACEDESCFLAGS enumeration is used in the lFlags member of the DDSURFACEDESC2 type to specify which members of DDSURFACEDESC2 contain valid data.

Enum CONST_DDSURFACEDESCFLAGS
    DDSD_ALL          = 1047022
    DDSD_ALPHABITDEPTH =    128
    DDSD_BACKBUFFERCOUNT =   32
    DDSD_CAPS         =       1
    DDSD_CKDESTBLT    =   16384
    DDSD_CKDESTOVERLAY =   8192
    DDSD_CKSRCBLT     =   65536
    DDSD_CKSRCOVERLAY =   32768
    DDSD_HEIGHT       =       2
    DDSD_LINEARSIZE   =  524288
    DDSD_LPSURFACE    =    2048
    DDSD_MIPMAPCOUNT  =  131072
    DDSD_PITCH        =       8
    DDSD_PIXELFORMAT  =    4096
    DDSD_REFRESHRATE  =  262144
    DDSD_TEXTURESTAGE = 1048576
    DDSD_WIDTH        =       4
    DDSD_ZBUFFERBITDEPTH =   64
End Enum
DDSD_ALL
All input members are valid.
DDSD_ALPHABITDEPTH
The lAlphaBitDepth member is valid.
DDSD_BACKBUFFERCOUNT
The lBackBufferCount member is valid.
DDSD_CAPS
The ddsCaps member is valid.
DDSD_CKDESTBLT
The ddckCKDestBlt member is valid.
DDSD_CKDESTOVERLAY
The ddckCKDestOverlay member is valid.
DDSD_CKSRCBLT
The ddckCKSrcBlt member is valid.
DDSD_CKSRCOVERLAY
The ddckCKSrcOverlay member is valid.
DDSD_HEIGHT
The lHeight member is valid.
DDSD_LINEARSIZE
Not used.‹This will be implemented sometime after DX6 and beyond Indicates that lLinearSize member is valid.›
DDSD_LPSURFACE
The lpSurface member is valid.
DDSD_MIPMAPCOUNT
The lMipMapCount member is valid.
DDSD_PITCH
The lPitch member is valid.
DDSD_PIXELFORMAT
The ddpfPixelFormat member is valid.
DDSD_REFRESHRATE
The lRefreshRate member is valid.
DDSD_TEXTURESTAGE
The lTextureStage member is valid.
DDSD_WIDTH
The lWidth member is valid.
DDSD_ZBUFFERBITDEPTH
The lZBufferBitDepth member is valid.


CONST_DDWAITVBFLAGS

The CONST_DDWAITVBFLAGS enumeration is used by the flags parameter of the DirectDraw7.WaitForVerticalBlank method to specify how long to wait for the vertical blank.

Enum CONST_DDWAITVBFLAGS
    DDWAITVB_BLOCKBEGIN      = 1
    DDWAITVB_BLOCKBEGINEVENT = 2
    DDWAITVB_BLOCKEND        = 4
End Enum
DDWAITVB_BLOCKBEGIN
Returns when the vertical-blank interval begins.
DDWAITVB_BLOCKBEGINEVENT
Triggers an event when the vertical blank begins. This value is not currently supported.
DDWAITVB_BLOCKEND
Returns when the vertical-blank interval ends and the display begins.


Error Codes

Errors are represented by negative values and cannot be combined. This table lists the values that can be returned by all methods of the DirectDraw7, DirectDrawSurface7, DirectDrawPalette, and DirectDrawClipper objects. For a list of the error codes that each method can return, see the method description.

DD_OK
The request completed successfully.
DDERR_ALREADYINITIALIZED
The object has already been initialized.
DDERR_BLTFASTCANTCLIP
A DirectDrawClipper object is attached to a source surface that has passed into a call to the DirectDrawSurface7.BltFast method.
DDERR_CANNOTATTACHSURFACE
A surface cannot be attached to another requested surface.
DDERR_CANNOTDETACHSURFACE
A surface cannot be detached from another requested surface.
DDERR_CANTCREATEDC
Windows cannot create any more device contexts (DCs), or a DC was requested for a palette-indexed surface when the surface had no palette and the display mode was not palette-indexed (in this case DirectDraw cannot select a proper palette into the DC).
DDERR_CANTDUPLICATE
Primary and 3-D surfaces, or surfaces that are implicitly created, cannot be duplicated.
DDERR_CANTLOCKSURFACE
Access to this surface is refused because an attempt was made to lock the primary surface without DCI support.
DDERR_CANTPAGELOCK
An attempt to page-lock a surface failed. Page lock does not work on a display-memory surface or an emulated primary surface.
DDERR_CANTPAGEUNLOCK
An attempt to page-unlock a surface failed. Page unlock does not work on a display-memory surface or an emulated primary surface.
DDERR_CLIPPERISUSINGHWND
An attempt was made to set a clip list for a DirectDrawClipper object that is already monitoring a window handle.
DDERR_COLORKEYNOTSET
No source color key is specified for this operation.
DDERR_CURRENTLYNOTAVAIL
No support is currently available.
DDERR_DCALREADYCREATED
A device context (DC) has already been returned for this surface. Only one DC can be retrieved for each surface.
DDERR_DEVICEDOESNTOWNSURFACE
Surfaces created by one DirectDraw device cannot be used directly by another DirectDraw device.
DDERR_DIRECTDRAWALREADYCREATED
A DirectDraw object representing this driver has already been created for this process.
DDERR_EXCEPTION
An exception was encountered while performing the requested operation.
DDERR_EXCLUSIVEMODEALREADYSET
An attempt was made to set the cooperative level when it was already set to exclusive.
DDERR_EXPIRED
The data has expired and is therefore no longer valid.
DDERR_GENERIC
There is an undefined error condition.
DDERR_HEIGHTALIGN
The height of the provided rectangle is not a multiple of the required alignment.
DDERR_HWNDALREADYSET
The DirectDraw cooperative level window handle has already been set. It cannot be reset while the process has surfaces or palettes created.
DDERR_HWNDSUBCLASSED
DirectDraw is prevented from restoring state because the DirectDraw cooperative level window handle has been subclassed.
DDERR_IMPLICITLYCREATED
The surface cannot be restored because it is an implicitly created surface.
DDERR_INCOMPATIBLEPRIMARY
The primary surface creation request does not match with the existing primary surface.
DDERR_INVALIDCAPS
One or more of the capability bits passed to the callback function are incorrect.
DDERR_INVALIDCLIPLIST
DirectDraw does not support the provided clip list.
DDERR_INVALIDDIRECTDRAWGUID
The globally unique identifier (GUID) passed to the DirectX7.DirectDrawCreate function is not a valid DirectDraw driver identifier.
DDERR_INVALIDMODE
DirectDraw does not support the requested mode.
DDERR_INVALIDOBJECT
DirectDraw received a pointer that was an invalid DirectDraw object.
DDERR_INVALIDPARAMS
One or more of the parameters passed to the method are incorrect.
DDERR_INVALIDPIXELFORMAT
The pixel format was invalid as specified.
DDERR_INVALIDPOSITION
The position of the overlay on the destination is no longer legal.
DDERR_INVALIDRECT
The provided rectangle was invalid.
DDERR_INVALIDSTREAM
The specified stream contains invalid data.
DDERR_INVALIDSURFACETYPE
The requested operation could not be performed because the surface was of the wrong type.
DDERR_LOCKEDSURFACES
One or more surfaces are locked.
DDERR_MOREDATA
There is more data available than the specified buffer size can hold.
DDERR_NO3D
No 3-D hardware or emulation is present.
DDERR_NOALPHAHW
No alpha acceleration hardware is present or available.
DDERR_NOBLTHW
No blitter hardware is present.
DDERR_NOCLIPLIST
No clip list is available.
DDERR_NOCLIPPERATTACHED
No DirectDrawClipper object is attached to the surface object.
DDERR_NOCOLORCONVHW
No color-conversion hardware is present or available.
DDERR_NOCOLORKEY
The surface does not currently have a color key.
DDERR_NOCOLORKEYHW
There is no hardware support for the destination color key.
DDERR_NOCOOPERATIVELEVELSET
A create function was called when the DirectDraw7.SetCooperativeLevel method had not been called.
DDERR_NODC
No DC has ever been created for this surface.
DDERR_NODDROPSHW
No DirectDraw raster operation (ROP) hardware is available.
DDERR_NODIRECTDRAWHW
Hardware-only DirectDraw object creation is not possible; the driver does not support any hardware.
DDERR_NODIRECTDRAWSUPPORT
DirectDraw support is not possible with the current display driver.
DDERR_NOEMULATION
Software emulation is not available.
DDERR_NOEXCLUSIVEMODE
The operation requires the application to have exclusive mode, but the application does not have exclusive mode.
DDERR_NOFLIPHW
Flipping visible surfaces is not supported.
DDERR_NOFOCUSWINDOW
An attempt was made to create or set a device window without first setting the focus window.
DDERR_NOGDI
No GDI is present.
DDERR_NOHWND
Clipper notification requires a window handle, or no window handle was previously set as the cooperative level window handle.
DDERR_NOMIPMAPHW
No mipmap-capable texture mapping hardware is present or available.
DDERR_NOMIRRORHW
No mirroring hardware is present or available.
DDERR_NONONLOCALVIDMEM
An attempt was made to allocate nonlocal video memory from a device that does not support nonlocal video memory.
DDERR_NOOPTIMIZEHW
The device does not support optimized surfaces.
DDERR_NOOVERLAYHW
No overlay hardware is present or available.
DDERR_NOPALETTEATTACHED
No palette object is attached to this surface.
DDERR_NOPALETTEHW
There is no hardware support for 16- or 256-color palettes.
DDERR_NORASTEROPHW
No appropriate raster operation hardware is present or available.
DDERR_NOROTATIONHW
No rotation hardware is present or available.
DDERR_NOSTEREOHARDWARE
No stereo hardware is present or available.
DDERR_NOSTRETCHHW
There is no hardware support for stretching.
DDERR_NOSURFACELEFT
No hardware is present that supports stereo surfaces.
DDERR_NOT4BITCOLOR
The DirectDrawSurface object is not using a 4-bit color palette, and the requested operation requires a 4-bit color palette.
DDERR_NOT4BITCOLORINDEX
The DirectDrawSurface object is not using a 4-bit color index palette, and the requested operation requires a 4-bit color index palette.
DDERR_NOT8BITCOLOR
The DirectDrawSurface object is not using an 8-bit color palette, and the requested operation requires an 8-bit color palette.
DDERR_NOTAOVERLAYSURFACE
An overlay component was called for a non-overlay surface.
DDERR_NOTEXTUREHW
No texture-mapping hardware is present or available.
DDERR_NOTFLIPPABLE
An attempt was made to flip a surface that cannot be flipped.
DDERR_NOTFOUND
The requested item was not found.
DDERR_NOTINITIALIZED
An attempt was made to call an interface method of a DirectDraw object created by CoCreateInstance before the object was initialized.
DDERR_NOTLOADED
The surface is an optimized surface, but it has not yet been allocated any memory.
DDERR_NOTLOCKED
An attempt was made to unlock a surface that was not locked.
DDERR_NOTPAGELOCKED
An attempt was made to page-unlock a surface with no outstanding page locks.
DDERR_NOTPALETTIZED
The surface being used is not a palette-based surface.
DDERR_NOVSYNCHW
There is no hardware support for vertical blank synchronized operations.
DDERR_NOZBUFFERHW
There is no hardware support for z-buffers.
DDERR_NOZOVERLAYHW
The hardware does not support z-ordering of overlays.
DDERR_OUTOFCAPS
The hardware needed for the requested operation has already been allocated.
DDERR_OUTOFMEMORY
DirectDraw does not have enough memory to perform the operation.
DDERR_OUTOFVIDEOMEMORY
DirectDraw does not have enough display memory to perform the operation.
DDERR_OVERLAPPINGRECTS
The source and destination rectangles are on the same surface and overlap each other.
DDERR_OVERLAYCANTCLIP
The hardware does not support clipped overlays.
DDERR_OVERLAYCOLORKEYONLYONEACTIVE
An attempt was made to have more than one color key active on an overlay.
DDERR_OVERLAYNOTVISIBLE
The method was called on a hidden overlay.
DDERR_PALETTEBUSY
Access to this palette is refused because the palette is locked by another thread.
DDERR_PRIMARYSURFACEALREADYEXISTS
This process has already created a primary surface.
DDERR_REGIONTOOSMALL
The region passed to the DirectDrawClipper.GetClipList method is too small.
DDERR_SURFACEALREADYATTACHED
An attempt was made to attach a surface to another surface to which it is already attached.
DDERR_SURFACEALREADYDEPENDENT
An attempt was made to make a surface a dependency of another surface on which it is already dependent.
DDERR_SURFACEBUSY
Access to the surface is refused because the surface is locked by another thread.
DDERR_SURFACEISOBSCURED
Access to the surface is refused because the surface is obscured.
DDERR_SURFACELOST
Access to the surface is refused because the surface memory is gone. Call the DirectDrawSurface7.Restore method on this surface to restore the memory associated with it.
DDERR_SURFACENOTATTACHED
The requested surface is not attached.
DDERR_TOOBIGHEIGHT
The height requested by DirectDraw is too large.
DDERR_TOOBIGSIZE
The size requested by DirectDraw is too large. However, the individual height and width are valid sizes.
DDERR_TOOBIGWIDTH
The width requested by DirectDraw is too large.
DDERR_UNSUPPORTED
The operation is not supported.
DDERR_UNSUPPORTEDFORMAT
The FourCC format requested is not supported by DirectDraw.
DDERR_UNSUPPORTEDMASK
The bitmask in the pixel format requested is not supported by DirectDraw.
DDERR_UNSUPPORTEDMODE
The display is currently in an unsupported mode.
DDERR_VERTICALBLANKINPROGRESS
A vertical blank is in progress.
DDERR_VIDEONOTACTIVE
The video port is not active.
DDERR_WASSTILLDRAWING
The previous blit operation that is transferring information to or from this surface is incomplete.
DDERR_WRONGMODE
This surface cannot be restored because it was created in a different mode.
DDERR_XALIGN
The provided rectangle was not horizontally aligned on a required boundary.
E_INVALIDINTERFACE
The specified interface is invalid or does not exist.
E_OUTOFMEMORY
Not enough free memory to complete the method.


Texture-Map Formats

A wide range of texture pixel formats are supported by the HEL. The following table shows these formats. The Masks column contains the red, green, blue, and alpha masks for each set of pixel format flags and bit depths.

Pixel format flags | Bit depth | Masks
DDPF_RGB | DDPF_PALETTEINDEXED1 | 1 | R: 0x00000000 G: 0x00000000 B: 0x00000000 A: 0x00000000
DDPF_RGB | DDPF_PALETTEINDEXED1 | DDPF_PALETTEINDEXEDTO8 | 1 | R: 0x00000000 G: 0x00000000 B: 0x00000000 A: 0x00000000
DDPF_RGB | DDPF_PALETTEINDEXED2 | 2 | R: 0x00000000 G: 0x00000000 B: 0x00000000 A: 0x00000000
DDPF_RGB | DDPF_PALETTEINDEXED2 | DDPF_PALETTEINDEXEDTO8 | 2 | R: 0x00000000 G: 0x00000000 B: 0x00000000 A: 0x00000000
DDPF_RGB | DDPF_PALETTEINDEXED4 | 4 | R: 0x00000000 G: 0x00000000 B: 0x00000000 A: 0x00000000
DDPF_RGB | DDPF_PALETTEINDEXED4 | DDPF_PALETTEINDEXEDTO8 | 4 | R: 0x00000000 G: 0x00000000 B: 0x00000000 A: 0x00000000
DDPF_RGB | DDPF_PALETTEINDEXED8 | 8 | R: 0x00000000 G: 0x00000000 B: 0x00000000 A: 0x00000000
DDPF_RGB | 8 | R: 0x000000E0 G: 0x0000001C B: 0x00000003 A: 0x00000000
DDPF_RGB | DDPF_ALPHAPIXELS | 16 | R: 0x00000F00 G: 0x000000F0 B: 0x0000000F A: 0x0000F000
DDPF_RGB | 16 | R: 0x0000F800 G: 0x000007E0 B: 0x0000001F A: 0x00000000
DDPF_RGB | 16 | R: 0x0000001F G: 0x000007E0 B: 0x0000F800 A: 0x00000000
DDPF_RGB | 16 | R: 0x00007C00 G: 0x000003E0 B: 0x0000001F A: 0x00000000
DDPF_RGB | DDPF_ALPHAPIXELS | 16 | R: 0x00007C00 G: 0x000003E0 B: 0x0000001F A: 0x00008000
DDPF_RGB | 24 | R: 0x00FF0000 G: 0x0000FF00 B: 0x000000FF A: 0x00000000
DDPF_RGB | 24 | R: 0x000000FF G: 0x0000FF00 B: 0x00FF0000 A: 0x00000000
DDPF_RGB | 32 | R: 0x00FF0000 G: 0x0000FF00 B: 0x000000FF A: 0x00000000
DDPF_RGB | 32 | R: 0x000000FF G: 0x0000FF00 B: 0x00FF0000 A: 0x00000000
DDPF_RGB | DDPF_ALPHAPIXELS | 32 | R: 0x00FF0000 G: 0x0000FF00 B: 0x000000FF A: 0xFF000000
DDPF_RGB | DDPF_ALPHAPIXELS | 32 | R: 0x000000FF G: 0x0000FF00 B: 0x00FF0000 A: 0xFF000000

The HEL can create these formats in system memory. The DirectDraw device driver for a 3-D-accelerated display card can create textures of other formats in display memory. Such a driver exports the DDSCAPS_TEXTURE flag to indicate that it can create textures.


Off-Screen Surface Formats

The following table shows the pixel formats for off-screen plain surfaces supported by the DirectX 5.0 HEL. The Masks column contains the red, green, blue, and alpha masks for each set of pixel format flags and bit depths.

Pixel format flags | Bit depth | Masks
DDPF_RGB | DDPF_PALETTEINDEXED1 | 1 | R: 0x00000000 G: 0x00000000 B: 0x00000000 A: 0x00000000
DDPF_RGB | DDPF_PALETTEINDEXED2 | 2 | R: 0x00000000 G: 0x00000000 B: 0x00000000 A: 0x00000000
DDPF_RGB | DDPF_PALETTEINDEXED4 | 4 | R: 0x00000000 G: 0x00000000 B: 0x00000000 A: 0x00000000
DDPF_RGB | DDPF_PALETTEINDEXED8 | 8 | R: 0x00000000 G: 0x00000000 B: 0x00000000 A: 0x00000000
DDPF_RGB | 16 | R: 0x0000F800 G: 0x000007E0 B: 0x0000001F A: 0x00000000
DDPF_RGB | 16 | R: 0x00007C00 G: 0x000003E0 B: 0x0000001F A: 0x00000000
DDPF_RGB | 24 | R: 0x00FF0000 G: 0x0000FF00 B: 0x000000FF A: 0x00000000
DDPF_RGB | 24 | R: 0x000000FF G: 0x0000FF00 B: 0x00FF0000 A: 0x00000000
DDPF_RGB | 32 | R: 0x00FF0000 G: 0x0000FF00 B: 0x000000FF A: 0x00000000
DDPF_RGB | 32 | R: 0x000000FF G: 0x0000FF00 B: 0x00FF0000 A: 0x00000000
DDPF_RGB | DDPF_ZPIXELS | 32 | R: 0x0000F800 G: 0x000007E0 B: 0x0000001F Z: 0xFFFF0000
DDPF_RGB | DDPF_ZPIXELS | 32 | R: 0x00007C00 G: 0x000003E0 B: 0x0000001F Z: 0xFFFF0000

In addition to supporting a wide range of off-screen surface formats, the HEL also supports surfaces intended for use by Direct3D, or other 3-D renderers.


Four-Character Codes (FOURCC)

DirectDraw utilizes a special set of codes that are four characters in length. These codes, called four-character codes (FOURCCs), are stored in file headers of files containing multimedia data such as bitmap images, sound, or video. FOURCCs describe the software technology that was used to produce multimedia data. By implication, they also describe the format of the data itself.

DirectDraw applications use FOURCCs for image color and format conversion. If an application calls the DirectDrawSurface7.GetPixelFormat method to request the pixel format of a surface whose format is not RGB, the lFourCC member of the DDPIXELFORMAT type identifies the FOURCC when the method returns.

In addition, the biCompression member of the BITMAPINFOHEADER type can be set to a FOURCC to indicate the codec used to compress or decompress an image.

FOURCCs are registered with Microsoft by the vendors of the respective multimedia software technologies. Some common FOURCCs appear in the following list.

FOURCC | Company | Technology name
AUR2 | AuraVision Corporation | AuraVision Aura 2: YUV 422
AURA | AuraVision Corporation | AuraVision Aura 1: YUV 411
CHAM | Winnov, Inc. | MM_WINNOV_CAVIARA_CHAMPAGNE
CVID | Supermac | Cinepak by Supermac
CYUV | Creative Labs, Inc. | Creative Labs YUV
FVF1 | Iterated Systems, Inc. | Fractal Video Frame
IF09 | Intel® Corporation | Intel Intermediate YUV9
IV31 | Intel Corporation | Indeo 3.1
JPEG | Microsoft Corporation | Still Image JPEG DIB
MJPG | Microsoft Corporation | Motion JPEG DIB Format
MRLE | Microsoft Corporation | Run Length Encoding
MSVC | Microsoft Corporation | Video 1
PHMO | IBM Corporation | Photomotion
RT21 | Intel Corporation | Indeo 2.1
ULTI | IBM Corporation | Ultimotion
V422 | Vitec Multimedia | 24-bit YUV 4:2:2
V655 | Vitec Multimedia | 16-bit YUV 4:2:2
VDCT | Vitec Multimedia | Video Maker Pro DIB
VIDS | Vitec Multimedia | YUV 4:2:2 CCIR 601 for V422
YU92 | Intel Corporation | YUV
YUV8 | Winnov, Inc. | MM_WINNOV_CAVIAR_YUV8
YUV9 | Intel Corporation | YUV9
YUYV | Canopus, Co., Ltd. | BI_YUYV, Canopus
ZPEG | Metheus | Video Zipper


DirectDraw Tools and Samples

This section describes sample applications included with the DirectX SDK that demonstrate the use of DirectDraw and aid in the development of DirectDraw applications. Descriptions are organized as follows:

  • DirectDraw Tools
  • DirectDraw C/C++ Samples
  • DirectDraw Visual Basic Samples


DirectDraw Tools

This section describes applications included with the DirectX SDK that can be used in the development of applications using DirectDraw. The following tools are described:

  • DirectDraw Caps
  • DirectDraw Test
  • DirectX Texture Tool
  • KillHelp


DirectDraw Caps

Description

This utility allows you to examine the DirectDraw capabilities of a device and to test different screen resolutions.

Path

Executable: (SDK root)\bin\DXUtils\DDCaps.exe

User's Guide

Choose from the Driver and HEL menus to see a list of capabilities. Turn off capabilities in the hardware or in the emulation layer by deselecting check boxes.

To check capabilities for a different resolution, double-click on the desired resolution. If the capabilities dialog box is still open, click Refresh.

Your default screen resolution is restored when you close the program.


DirectDraw Test

Description

The DirectDraw Test application allows you to create and manipulate surfaces, blit between surfaces, time certain operations, and perform a variety of other tests.

Path

Executable: (SDK root)\Bin\DXUtils\DDTest.exe

User's Guide

First click Options select a device, then click Connect in order to connect to the DirectDraw system. Create one or more surfaces by clicking the Create button and selecting the desired capabilities. Note that an error appears in the message list if creation was not successful.

Select a surface from the drop-down list and manipulate it by using the various buttons. Choose Blt in order to blit from one surface to another using various flags.

Perform timing tests by clicking Timing. You can check the speed of operations at different screen resolutions by clicking Set Mode and choosing a different resolution before running the test.


DirectX Texture Tool

Description

The purpose of this tool is to allow developers to create texture maps that use the new DXTn compression formats. Creating a compressed texture is actually not that difficult to do: the IDirectDrawSurface7::Blt method can do the conversion for you. Advanced developers will probably want to write their own tools that meet their specific needs, but this tool provides the following useful basic functionality:

  • Opens BMP and DDS files (See the User's Guide section for a description of the DDS file format).
  • Opens BMP files as alpha channel.
  • Saves textures in DDS format.
  • Supports conversion to all five DXTn compression formats.
  • Supports generation of mipmaps (using a box filter).
  • Supports visualization of alpha channel as a gray-scale image or by means of a user-selectable background color.
  • Supports easy visual comparison of image quality between formats.

Path

Source: (SDK root)\Samples\Multimedia\DDraw\Src\DXTex

Executable: (SDK root)\Bin\DxUtils\Dxtex.exe

User's Guide

DirectX Texture Tool uses a multidocument interface. Each texture map is a document, and several documents can be open at a time.

Each open document can hold the texture in either one format or two formats at once. For instance, you could import a BMP file, which would automatically create a 32-bit ARGB texture. You could then choose to convert the texture to DXT1 format. The document now remembers the image in both formats, and the user can flip between the formats by clicking in the window or by choosing Original or New from the View menu. This makes it easy for the user to spot any artifacts introduced by image compression, and to try several different compression formats without progressive degradation of the image

If this technique were not used and the user converted an image from ARGB to DXT1, all but one bit of alpha would be lost. If the user then decided to convert to DXT2, there would still be only two alpha levels. With the system used by Direct Texture Tool, the second conversion is done from the original ARGB format, and the DXT2 image will contain all 16 levels of alpha supported by DXT2. When the image is saved, the original format is discarded, and only the new format is stored.

This system has a few consequences that must be remembered:

  • If no format conversion has been requested since the document was opened, the one format is the "original" format and that is the format in which the image will be written when the document is saved.
  • If format conversion has been requested since the document was opened, the converted format is the "new" format and that is the format in which the image will be written when the document is saved.
  • If a second format conversion is requested, the "new" format from the first conversion is replaced with the second format. The "original" format will be unchanged.
  • Generating of mipmaps applies to both formats simultaneously.
  • If the original format has multiple mipmaps, and conversion to a new format is requested, the new format will automatically have multiple mipmaps as well.

To create mipmaps, choose Generate MipMaps from the Format menu. The width and height of the source image must both be powers of 2. Filtering is done by a simple box filter—that is, the four nearest pixels are averaged to produce each destination pixel.

DirectX Texture Tool fully supports alpha in textures. When importing a BMP file, if two files exist and one has an "_a" at the end of the name (for example, tex.bmp and tex_a.bmp), the second file will be loaded as an alpha channel. The blue channel of the second .bmp is stored in the alpha channel.

Once a document is open, the user can explicitly load a .bmp file as the alpha channel by using Open As Alpha Channel on the File menu.

To view the alpha channel directly without the RGB channels, choose Alpha Channel Only from the View menu. The alpha channel will appear as a gray-scale image. Note that if no alpha channel has been loaded, the alpha channel will be 100 percent throughout and the image will appear solid white when Alpha Channel Only is selected.

In the normal view, the effect of the alpha channel is visible because the window has a solid background color which shows through the texture where the alpha channel is less than 100 percent. The user can change this background color by choosing Change Background Color from the View menu. This choice does not affect the texture itself or the data that is written when the file is saved.

The DXT2 and DXT4 formats use premultiplied alpha, which means that the red, green, and blue values stored in the surface are already multiplied by the corresponding alpha value. DirectDraw cannot blit from a surface containing premultiplied alpha to one containing non-premultiplied alpha, so some operations (Open as Alpha Channel, conversion to DXT3, and conversion to DXT5) are not possible on DXT2 and DXT4 formats. Supporting textures using these formats is difficult on Direct3D devices which do not support DXTn textures, because DirectDraw cannot handle blitting them to a traditional ARGB surface either (unless that ARGB surface uses premultiplied alpha as well, which is rare). So you may find it easier to use DXT3 rather than DXT2 and DXT5 rather than DXT4 when possible.

Command-line options can be used to pass input files, an output file name, and processing options to DirectX Texture Tool. If an output file name is specified, the program exits automatically after writing the output file, and no user interface is presented.

dxtex [infilename] [-a alphaname] [-m] [DXT1|DXT2|DXT3|DXT4|DXT5] [outfilename]
infilename
The name of the file to load. This can be a .bmp or .dds file.
-a alphaname
If "-a" is specified, the next parameter is the name of a .bmp file to load as the alpha channel. If no alpha filename is specified, the application will still look for a file named infilename_a.bmp and, if it exists, use that as the alpha channel.
-m
If this option is specified, mipmaps are generated.
DXT1 | DXT2 | DXT3 | DXT4 | DXT5
Specifies compression format. If no format is specified, the image will be in ARGB-8888.
outfilename
Specifies the name of the destination file. If this is not specified, the user interface will show the current file and all requested operations. If an outfilename is specified, the application will exit after saving the processed file without presenting a user interface.

See Also

For more information on the DDS file format, see Compress Sample.


KillHelp

Description

KillHelp shuts down Ddhelp.exe, which in turn unloads Ddraw.dll from memory.

Path

Executable: (SDK root)\Bin\DXUtils\Killhelp.exe

User's Guide

This program should be used only by developers of device drivers.

When Ddraw.dll is first loaded by a DirectDraw application, it in turn loads Ddhelp.exe, which enables DirectDraw to restore the proper screen resolution and perform other cleanup tasks in the event that an application fails to do so. KillHelp is the only way to remove Ddraw.dll and Ddhelp.exe from memory without actually restarting the system.


DirectDraw C/C++ Samples

[Visual Basic]

This section pertains only to application development in C and C++. See DirectDraw Visual Basic Samples.

[C++]

This section gives brief descriptions of sample applications in the DirectX SDK primarily intended to demonstrate the DirectDraw component. The following sample programs are included:

  • DDEnum Sample
  • DDEx1 Sample
  • DDEx2 Sample
  • DDEx3 Sample
  • DDEx4 Sample
  • DDEx5 Sample
  • DDOverlay Sample
  • Font Sample
  • FSWindow Sample
  • ModeTest Sample
  • Mosquito Sample
  • Multimon Sample
  • Space Donuts Sample
  • Stretch Sample
  • Switcher Sample
  • Wormhole Sample

Although DirectX samples include Microsoft® Visual C++® project workspace files, you might need to verify other settings in your development environment to ensure that the samples compile properly. For more information, see Compiling DirectX Samples and Other DirectX Applications.


DDEnum Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectDraw Visual Basic Samples.

[C++]

Description

This sample shows how to enumerate the current DirectDraw devices and how to get information using the IDirectDraw7::GetDeviceIdentifier method.

Path

Source: (SDK root)\Samples\Multimedia\DDraw\Src\DDEnum

Executable: (SDK root)\Samples\Multimedia\DDraw\Bin\DDEnum.exe

User's Guide

The user interface is a simple dialog box. Two buttons, Prev and Next, display information for the previous or next device that was enumerated. Click the Close button to exit the application.


DDEx1 Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectDraw Visual Basic Samples.

[C++]

Description

DDEx1 demonstrates the tasks required to initialize and run a DirectDraw application.

Path

Source: (SDK root)\Samples\Multimedia\DDraw\Src\Ddex1

Executable: (SDK root)\Samples\Multimedia\DDraw\Bin\Ddex1.exe

User's Guide

DDEx1 requires no user input. Press the F12 key or the ESC key to quit the program.

Programming Notes

This program shows how to initialize DirectDraw and create a DirectDraw surface. It creates a back buffer and uses page flipping to alternately display the contents of the front and back buffers. Other techniques demonstrated include color fills and using GDI functions on a DirectDraw surface.


DDEx2 Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectDraw Visual Basic Samples.

[C++]

Description

The DDEx2 program is an extension of DDEx1 that adds a bitmap.

Path

Source: (SDK root)\Samples\Multimedia\DDraw\Src\Ddex2

Executable: (SDK root)\Samples\Multimedia\DDraw\Bin\Ddex2.exe

User's Guide

DDEx2 requires no user input. Press F12 or ESC to quit the program.

Programming Notes

DDEx2 shows how to set a palettized video mode. Routines in DDutil.cpp load a bitmap file and copy it to a DirectDraw surface.


DDEx3 Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectDraw Visual Basic Samples.

[C++]

Description

The DDEx3 program is an extension of DDEx2. This example demonstrates the use of off-screen surfaces.

Path

Source: (SDK root)\Samples\Multimedia\DDraw\Src\Ddex3

Executable: (SDK root)\Samples\Multimedia\DDraw\Bin\Ddex3.exe

User's Guide

DDEx3 requires no user input. Press F12 or ESC to quit the program.

The program requires at least 1.2 MB of video RAM.

Programming Notes

In addition to the front and back buffers, the program creates two off-screen surfaces and loads bitmaps into them. It calls the IDirectDrawSurface7::BltFast method to copy the contents of an off-screen surface to the back buffer, alternating the source surface on each frame. After it blits the bitmap to the back buffer, DDEx3 flips the front and back buffers.


DDEx4 Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectDraw Visual Basic Samples.

[C++]

Description

The DDEx4 program is an extension of DDEx3. It demonstrates a simple animation technique.

Path

Source: (SDK root)\Samples\Multimedia\DDraw\Src\Ddex4

Executable: (SDK root)\Samples\Multimedia\DDraw\Bin\Ddex4.exe

User's Guide

DDEx4 requires no user input. Press F12 or ESC to quit the program.

This program requires at least 1.2 MB of video RAM.

Programming Notes

Unlike DDEx3, the DDEx4 program creates only one off-screen surface. It loads a bitmap containing a series of animation images onto this surface. To create the animation, it blits portions of the off-screen surface to the back buffer, then flips the front and back buffers.

The blitting routines illustrate the use of a source color key to create a sprite with a transparent background.


DDEx5 Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectDraw Visual Basic Samples.

[C++]

Description

The DDEx5 program is an extension of DDEx4. It demonstrates a simple palette manipulation.

Path

Source: (SDK root)\Samples\Multimedia\DDraw\Src\Ddex5

Executable: (SDK root)\Samples\Multimedia\DDraw\Bin\Ddex5.exe

User's Guide

DDEx4 requires no user input. Press F12 or ESC to quit the program.

This program requires at least 1.2 MB of video RAM.

Programming Notes

The program uses IDirectDrawPalette::GetEntries to read a palette, modifies the entries, and then uses IDirectDrawPalette::SetEntries to update the palette.


DDOverlay Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectDraw Visual Basic Samples.

[C++]

Description

This sample application demonstrates the use of overlays in a windowed DirectDraw application.

Path

Source: (SDK root)\Samples\Multimedia\DDraw\Src\DDovrly

Executable: (SDK root)\Samples\Multimedia\DDraw\Bin\Ddovrly.exe

User's Guide

Your hardware must support overlays in order for the program to run.

Try moving, resizing, and minimizing and restoring the window. Press ALT+F4 or click the Close button to quit.

Programming Notes

The program checks for overlay support, loads a bitmap into an overlay surface, and updates the window from the overlay surface in response to Windows messages.


Font Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectDraw Visual Basic Samples.

[C++]

Description

This sample program shows how to directly lock and access video memory, using text generated from a GDI font. There are much better ways to draw text into a DirectDrawSurface, and the only point of this sample is to show exactly how to lock and access the video memory directly.

Path

Source: (SDK root)\Samples\Multimedia\DDraw\Src\Font

Executable: (SDK root)\Samples\Multimedia\DDraw\Bin\Font.exe

User's Guide

The program repeatedly updates a text string in the Arial font and moves it randomly about the screen. No user input is required. Quit by closing the window.

Programming Notes

The program creates a font in a memory device context and a DIB section, and uses them to get access to the pixels once GDI has drawn them. The text bitmap is then put on the primary surface with a straight memory copy. It could easily be moved instead to an off-screen surface which could then be blitted as needed, transparently or not.


FSWindow Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectDraw Visual Basic Samples.

[C++]

Description

This sample shows how you can bring up a dialog box, or any other type of window, while your application is running DirectDraw in full-screen exclusive mode. Even devices that are non-GDI are detected and supported by creating a bitmap from their window contents and then blitting that to the device.

Path

Source: (SDK root)\Samples\Multimedia\DDraw\Src\FSWindow

Executable: (SDK root)\Samples\Multimedia\DDraw\Bin\FSWindow.exe

User's Guide

If you have more than one device, the sample starts by displaying a dialog box so that you can select which device to run the sample on. It then switches to full-screen exclusive mode and displays a dialog box and the mouse cursor.

Click on the Cancel or OK button to close the dialog and hide the mouse cursor. Press the F1 key to bring the dialog and cursor back. Press the Esc key to exit the program when the dialog is no longer displayed.

Programming Notes

Most of the important code is in the Fswindow.cpp file.

The sample uses just the dynamic content mode, which constantly refreshes the dialog box to show which controls have focus, text in the edit field, and so on. The static content mode consumes less CPU time and would be good for pop-up windows that display help messages, for example.

It is important to understand that the content window can be any type of window. It could be an HTML Help window, or a window with a rich edit control to display formatted text. The window does not need to have a square clipping region; it could have a complex clipping region that fits the shape of the window you want to display.


ModeTest Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectDraw Visual Basic Samples.

[C++]

Description

This example demonstrates basic usage of the IDirectDraw7::StartModeTest and IDirectDraw7::EvaluateMode methods. Together, these methods allow an application to explore what display modes and refresh rates the monitor connected to the display device is able to display Applications can use these methods when they are interested in using higher refresh rates.

Path

Source: (SDK root)\Samples\Multimedia\DDraw\Src\ModeTest

Executable: (SDK root)\Samples\Multimedia\DDraw\Bin\ModeTest.exe

User's Guide

The user interface is a simple dialog box. First select the DirectDraw display device. Then select one or more modes from the left-hand list box and click Test. Each display mode is tested, and you can specify whether the mode appears correctly or note. If you make a mistake, click Reset and try again. Click Close to exit the application.

Programming Notes

DirectDraw sets up a list of modes to be tested, based on the list the application passed in, and then sequentially tests them under application control.

The application calls IDirectDraw7::EvaluateMode continuously. DirectDraw takes care of setting the modes. All the application has to do is set the cooperative level beforehand, and then handle surface loss and drawing the interface that asks the user if the current mode is displaying correctly. DirectDraw returns enough information from EvalulateMode to allow the application to know when to do these things, and when to stop testing.

The application can pass a flag to EvaluateMode if the user approves the mode, which will cause DirectDraw to mark the mode as good and move on. DirectDraw may also decide that time has run out and give up on a certain mode.

DirectDraw uses information at its disposal from any automated means to make the testing process as short as possible, and applications only need to test modes they are interested in.


Mosquito Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectDraw Visual Basic Samples.

[C++]

Description

This program demonstrates DirectDraw animation using overlays.

Path

Source: (SDK root)\Samples\Multimedia\DDraw\Src\Mosquito

Executable: (SDK root)\Samples\Multimedia\DDraw\Bin\Mosquito.exe

User's Guide

To run the Mosquito application, you must have a display adapter that supports overlays. On a computer with overlay support, the program creates a large mosquito that flies around the screen. If your display adapter card doesn't support source color keying for overlays, you'll see an ugly, black, rectangular background around the mosquito.

Some cards have better overlay support in certain resolutions that others. If you know your card has overlay support through DirectDraw, but the Mosquito program is having problems creating or displaying the overlay, try switching to a lower screen resolution or color depth and restarting the application.

Programming Notes

The program creates a complex overlay surface and animates by flipping.


Multimon Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectDraw Visual Basic Samples.

[C++]

Description

This program demonstrates some of the techniques that can be used in writing an application that takes advantage of multiple monitors.

Path

Source: (SDK root)\Samples\Multimedia\DDraw\Src\Multimon

Executable: (SDK root)\Samples\Multimedia\DDraw\Bin\Multimon.exe

User's Guide

The application does not require input. Click anywhere or press ESC to quit.

Programming Notes

To use the multimonitor functions such as GetMonitorInfo and MonitorFromRect on Windows 95, you can include the file Multimon.h. In addition, in one of the C or C++ files, you need to define COMPILE_MULTIMON_STUBS before including Multimon.h. This allows the multimon functions to return reasonable values when running on Windows 95.

When enumerating DirectDraw devices, you can use either DirectDrawEnumerate or DirectDrawEnumerateEx. DirectDrawEnumerateEx is available on Windows 98 systems with DirectX 5.0 and later, and all other systems with DirectX 6.0 or later.

Because not all systems can be assumed to have DirectDrawEnumerateEx, DirectDraw was formerly set up so developers had to use LoadLibrary and GetProcAddress to check for its presence. In DirectX 7.0 this restriction has been removed, so you can call DirectDrawEnumerateEx directly, but you should note that this will prevent your program from running on a system which does not have DirectX 7.0 or later installed. This sample shows how to do the LoadLibrary/GetProcAddress technique, and how to fall back on DirectDrawEnumerate if DirectDrawEnumerateEx is not available.

Full-screen, multimonitor applications need to deal with focus and device windows. The focus window receives user input messages, and the device windows are used to cover each screen. This program shows how to call IDirectDraw7::SetCooperativeLevel to properly create and assign these windows.

Each screen gets its own DirectDraw interface, and DirectDrawSurfaces created on one DirectDraw interface cannot be used by any other DirectDraw interface. So creating graphics that span multiple monitors takes some extra work.

This sample demonstrates two techniques. For best performance, video memory surfaces should be used. A separate video memory DirectDrawSurface must be created on each screen. For the cases where a system memory surface is required or desired, one must still create separate DirectDrawSurfaces for each screen, but they can be configured to point to the same surface data memory. The IDirectDrawSurface7::SetSurfaceDesc method can be used to accomplish this. Doing this has no performance impact, but it avoids unnecessary consumption of system memory.

IDirectDrawSurface7::Blt calls usually fail when they would cause data to be written outside the borders of the destination surface. This failure can be avoided by attaching clipper objects to the destinations. This sample shows how to create a clipper for each screen and attach it to the front and back buffers so that the sprite surfaces can be blitted without being manually clipped by the application first.


Space Donuts Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectDraw Visual Basic Samples.

[C++]

Description

This simple game shows how to combine DirectDraw, DirectInput, and DirectSound. Although it demonstrates other DirectX components, it is primarily intended to show how to animate multiple sprites.

Path

Source: (SDK root)\Samples\Multimedia\DDraw\Src\Donuts

Executable: (SDK root)\Samples\Multimedia\DDraw\Bin\Donuts.exe

User's Guide

Input is from the keyboard by default, but you can select a joystick from the Game menu.

The commands are listed on the opening screen. All numbers must be entered from the numeric keypad. "Joy" refers to a joystick button.

Key | Command
ESC, F12 | Quit
4 | Turn left
6 | Turn right
5 (Joy 3) | Stop
8 | Accelerate forward
2 | Accelerate backward
7 (Joy 2) | Shield
SPACEBAR (Joy 1) | Fire
ENTER | Start game
F1 | Toggle trailing afterimage effect on/off
F3 | Turn audio on/off
F5 | Toggle frame rate display on/off
F10 | Main menu

Space Donuts defaults to 640x480 at 256 colors. You can specify a different resolution and pixel depth on the command line.

The game uses the following command line switches, which are case-sensitive:

e | Use software emulation, not hardware acceleration
t | Test mode, no input required
x | Stress mode. Never stop if you can help it
S | Turn sound off/on

These switches may be followed by three option numbers representing x-resolution, y-resolution, and bits per pixel. For example:

donuts -S 800 600 16

Programming Notes

This game demonstrates many of the features of DirectDraw. It takes advantage of hardware acceleration if it is supported by the driver.

The program requires less than 1 MB of video RAM.

The sound code is deliberately designed to stress the DirectSound API. It is not intended to be a demonstration of how to use DirectSound API efficiently. For example, each bullet on the screen uses a different sound buffer. Space Donuts creates over 70 sound buffers (including duplicates), and between 20 to 25 may be playing at any time.

The sounds are implemented using the helper functions in Dsutil.h and Dsutil.c (found in the Sdk\Samples\Misc directory). These functions might help you to add sound to your application quickly and easily.


Stretch Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectDraw Visual Basic Samples.

[C++]

Description

The Stretch sample application program illustrates stretching and clipping while blitting a bitmap image.

Path

Source: (SDK root)\Samples\Multimedia\DDraw\Src\Stretch

Executable: (SDK root)\Samples\Multimedia\DDraw\Bin\Stretch.exe

User's Guide

Stretch must be run in a video mode that uses 8 bits per pixel. It will not work properly in other video modes.

The program displays a red torus moving in its client window. Control the rotational speed with the Stop, Slow, and Fast options in the Rotation menu. Alter the size of the window by selecting items from the Size menu, or by resizing the window with the mouse.

Programming Notes

Any time you resize the Stretch program window to a size other than 1x1, you are using the image stretching capabilities of the DirectDraw blitting methods.

The clipper for the primary surface is set to the client window. To demonstrate clipping, partially overlap another window over the Stretch program's window. When Stretch blits the bitmap, the portion of the bitmap that would fall within the other window is clipped.


Switcher Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectDraw Visual Basic Samples.

[C++]

Description

This sample shows how to switch between the normal and exclusive cooperative levels in DirectDraw.

Path

Source: (SDK root)\Samples\Multimedia\DDraw\Src\Switcher

Executable: (SDK root)\Samples\Multimedia\DDraw\Bin\Switcher.exe

User's Guide

Press ALT+ENTER to switch between full-screen and windowed mode. Quit the program by pressing ESC.

Programming Notes

In normal (windowed) mode, the sample assigns a clipper, shows the mouse cursor, and handles window moves, WM_PAINT messages, and pausing caused by losing focus to other applications. In exclusive (full-screen) mode it uses page flipping rather than blitting to update the scene.


Wormhole Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectDraw Visual Basic Samples.

[C++]

Description

This sample program shows how palette changes can create an animated effect.

Path

Source: (SDK root)\Samples\Multimedia\DDraw\Src\Wormhole

Executable: (SDK root)\Samples\Multimedia\DDraw\Bin\Wormhole.exe

User's Guide

Press F12 or ESC to quit the program.

Programming Notes

Imagine a 4x4 display using 4 colors. We could set the colors up to look something like this:

Now we can cycle all of the colors in each row to the right. The one on the right will wrap around to the left.

If we continue this cycling we would get animated lines moving to the right. The same can be done to animate the lines going down:

Now if we expand our palette to 16 color we can combine moving down and right at the same time.

Move right:

Move down:

Move right and down:

Now if you tile these 4x4 blocks end to end and cycle the colors as shown, you get a moving checkerboard. Wormhole does the same thing, except that it uses 15x15 blocks (225 colors) and instead of tiling the blocks end to end on a flat plane, it tiles them in 3-D converging at the center of the wormhole.

The following code will generate the 3-D wormhole using the aforementioned 15x15 grids:

//Do all the work!
//convert r,theta,z to x,y,x to screen x,y
//plot the point
//z=-1.0+(log(2.0*j/DIVS) is the line that sets the math eqn for plot
//Feel free to try other functions!
//Cylindrical coordinates, e.g. z=f(r,theta)

#define STRETCH 25
#define PI      3.14159265358979323846
#define XCENTER 160
#define YCENTER 50
#define DIVS    1200
#define SPOKES  2400

void transarray(void)
    {
    float x,y,z;
    int i,j,color;
    for(j=1;j<DIVS+1;j++)
        for(i=0;i<SPOKES;i++)
            {
            z=-1.0+(log(2.0*j/DIVS));
            x=(320.0*j/DIVS*cos(2*PI*i/SPOKES));
            y=(240.0*j/DIVS*sin(2*PI*i/SPOKES));
            y=y-STRETCH*z;
            x+=XCENTER;
            y+=YCENTER;
            color=((i/8)%15)+15*((j/6)%15)+1;
            if ((x>=0)&&(x<=320)&&(y>=0)&&(y<=200))
                plot((int) x,(int) y,color);
            }
    }

After loading the bitmap to a DirectDraw surface, all that is left to do is rotate the colors and you have a wormhole.


DirectDraw Visual Basic Samples

[C++]

This section pertains only to application development in Visual Basic. See DirectDraw C/C++ Samples.

[Visual Basic]

This section gives brief descriptions of sample applications intended to demonstrate the DirectDraw component of DirectX for Visual Basic. The following sample programs are included:

  • DDBlend Sample
  • Fire Sample

In addition, the SDK includes five very simple tutorial applications. For more information on these samples, see DirectDraw Visual Basic Tutorials.


DDBlend Sample

[C++]

This topic pertains only to application development in Visual Basic. See DirectDraw C/C++ Samples.

[Visual Basic]

Description

The DDBlend sample demonstrates full-screen DirectDraw support, direct surface manipulation and 8-bit palette scrolling.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DDraw\Src\DDBlend

Executable: (SDK root)\Samples\Multimedia\VBSamples\DDraw\Bin\DDBlend.exe

User's Guide

Change the point of origin of the swirling colors by moving the mouse. Cycle forward through the screen resolutions by pressing INSERT or backward by pressing DELETE. Increase the number of particles by pressing HOME, or remove particles by pressing END. Increase the amount of blur by pressing PAGE UP or decrease it with PAGE DOWN. Use the spacebar to switch palettes.

Programming Notes

DDBlend is a full-screen sample, showing off the ability of DirectX to access surface memory directly. It also demonstrates 8-bit palette scrolling as well as on-the-fly video mode switching.


Fire Sample

[C++]

This topic pertains only to application development in Visual Basic. See DirectDraw C/C++ Samples.

[Visual Basic]

Description

The Fire sample demonstrates how to manipulate the video memory directly by using DirectDraw.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DDraw\Src\Fire

Executable: (SDK root)\Samples\Multimedia\VBSamples\DDraw\Bin\Fire.exe

User's Guide

No input is required. Press ESC to quit the program.

Programming Notes

The sample uses DirectDrawSurface7.GetLockedArray to get the display memory into an array of bytes, Pict, where they can be manipulated individually.


DirectInput

This section provides information about the DirectInput® component of the Microsoft® DirectX® application programming interface (API). The information is divided into the following topics:

  • About DirectInput
  • Why Use DirectInput?
  • DirectInput Architecture
  • DirectInput Essentials
  • DirectInput Tutorials
  • DirectInput Reference
  • DirectInput Tools and Samples


About DirectInput

DirectInput is an API for input devices including the mouse, keyboard, joystick, and other game controllers, as well as for force-feedback (input/output) devices.


Why Use DirectInput?

Aside from providing new services for devices not supported by the Microsoft® Win32® API, DirectInput gives faster access to input data by communicating directly with the hardware drivers, rather than relying on Microsoft® Windows® messages.

DirectInput enables an application to retrieve data from input devices even when the application is in the background. It also provides full support for any type of input device, as well as for force feedback.

The extended services and improved performance of DirectInput make it a valuable tool for games, simulations, and other real-time interactive applications running under Windows.


DirectInput Architecture

This section covers the basic structure of DirectInput and how it works with both the Windows operating system and input hardware. For practical information on how to implement the elements of DirectInput introduced here, see DirectInput Essentials.

  • Architectural Overview of DirectInput
  • Integration with Windows
  • Human Interface Device


Architectural Overview of DirectInput

[C++]

The basic architecture of a DirectInput implementation consists of the DirectInput object, which supports the IDirectInput7 COM interface, and an object for each input device that provides data. Each device in turn has device object instances or more simply device objects, which are individual controls or switches such as keys, buttons, or axes.

Note The word object is used to describe both a code object and one of the individual controls on an input device. In this documentation, device object means an input device control, rather than a code object that instantiates the IDirectInputDevice7 interface. Code objects representing whole devices are referred to as DirectInputDevice objects.

Each DirectInputDevice object represents one input device, such as a mouse, keyboard, or joystick. A piece of hardware that is really a combination of different types of input devices, such as a keyboard with a touchpad, can be represented by two or more DirectInputDevice objects. A force-feedback device is represented by a single joystick object that handles both input and output.

DirectInputDevice objects instantiate the IDirectInputDevice7 interface.

The application ascertains the number and type of device objects available by using the IDirectInputDevice7::EnumObjects method. Individual device objects are not encapsulated as code objects, but are described in DIDEVICEOBJECTINSTANCE structures.

Force-feedback effects are represented by the IDirectInputEffect interface. Methods of this interface are used to create, modify, start, and stop effects.

All DirectInput interfaces are available in ANSI and Unicode versions. If "UNICODE" is defined during compilation, the Unicode versions are used.

[Visual Basic]

The basic architecture of a DirectInput implementation consists of a single DirectInput object and a DirectInputDevice object for each input device that is being used by the application. The DirectInputDevice object is used for retrieving the input data.

Any available device, regardless of whether it is being used by DirectInput, can also be represented by a DirectInputDeviceInstance object, which can be used to retrieve miscellaneous information about that device.

Each DirectInputDevice object represents one input device, such as a mouse, keyboard, or joystick. (In this documentation, the term joystick includes all game controllers other than a mouse or keyboard.) A piece of hardware that is really a combination of different types of input devices, such as a keyboard with a touchpad, can be represented by two or more DirectInputDevice objects. A force-feedback device is represented by a single joystick object that handles both input and output.

Each device in turn has device objects, which are individual controls or switches, such as keys, buttons, or axes. Each device object is represented by an instance of the DirectInputDeviceObjectInstance class, whose methods can be used to retrieve information about the device object. (The input data, however, is always retrieved by DirectInputDevice.)

Note The word object is used to describe both a code object and one of the individual controls on an input device. In this documentation, device object means an input device control, rather than a DirectInputDevice object.

Devices and device objects can be enumerated, and the resulting collections are represented by DirectInputEnumDevices and DirectInputEnumDeviceObjects objects.


Integration with Windows

Because DirectInput works directly with the device drivers, it either suppresses or ignores mouse and keyboard messages. When using the mouse in exclusive mode, DirectInput suppresses mouse messages, and therefore Windows is unable to show the standard cursor.

DirectInput also ignores mouse and keyboard settings made by the user in Control Panel.

For the keyboard, character repeat settings are not used by DirectInput. When using buffered data, DirectInput interprets each press and release as a single event, with no repetition. When using immediate data, DirectInput is concerned only with the present physical state of the keys, not with keyboard events as interpreted by Windows.

For the mouse, DirectInput ignores Control Panel settings such as acceleration and swapped buttons. Again, DirectInput works directly with the mouse driver, bypassing the subsystem of Windows that interprets mouse data for windowed applications.

Note Settings in the driver itself are recognized by DirectInput. For example, if the user has a three-button mouse and uses the driver-utility software to make the middle button a double-click shortcut, DirectInput reports a click of the middle button as two clicks of the primary button.

For a joystick or other game controller, DirectInput does use the calibrations set by the user in Control Panel.


Human Interface Device

Human Interface Device (HID) is a class under the universal serial bus (USB) standard. DirectInput provides full support for devices that conform with HID.

Getting data from HID devices is substantially the same as from traditional devices. In addition, HID devices can accept output: for example, you can turn the keyboard LEDs on and off.

By querying a HID device, DirectInput can determine its usage page and usage. These are predefined codes that give information about the type and subtype of the device.

HID controls are grouped in collections. Collections can be nested.

For more information about HID, see http://www.usb.org.


DirectInput Essentials

This section is a practical guide to the concepts and components of DirectInput and provides enough information for you to get started in implementing the DirectInput system in your application. For a broader overview, see DirectInput Architecture.

The following topics are discussed:

  • Creating DirectInput
  • DirectInput Device Enumeration
  • DirectInput Devices
  • DirectInput Device Data
  • Force Feedback
  • Designing for Previous Versions of DirectInput


Creating DirectInput

[C++]

The first step in any DirectInput application is obtaining the IDirectInput7 interface. You can do this most easily by calling the DirectInputCreateEx function.

You should create a single DirectInput object and not release it until the application terminates.

[Visual Basic]

The first step in any DirectInput application is creating the DirectInput object. Do this by using the DirectX7.DirectInputCreate method.

You should create a single DirectInput object and not destroy it until the application terminates.


DirectInput Device Enumeration

DirectInput can query the system for all available input devices, determine whether they are connected, and return information about them. This process is called enumeration.

[C++]

If your application is using only the standard keyboard or mouse, or both, you do not need to enumerate the available input devices. As explained under Creating the DirectInput Device, you can use predefined global variables when calling the IDirectInput7::CreateDeviceEx method.

For all other input devices, and for systems with multiple keyboards or mouse devices, call IDirectInput7::EnumDevices to obtain at least the instance globally unique identifiers (GUIDs) so that DirectInputDevice objects can be created. You might also want to enumerate to give the user a choice of available devices.

The following is a sample implementation of the IDirectInput7::EnumDevices method:

/* lpdi is a valid IDirectInput7 interface pointer. */

GUID              KeyboardGUID = GUID_SysKeyboard;

lpdi->EnumDevices(DIDEVTYPE_KEYBOARD,
                  DIEnumDevicesCallback,
                  &KeyboardGUID,
                  DIEDFL_ATTACHEDONLY);

The first parameter determines what types of devices are to be enumerated. It is NULL if you want to enumerate all devices, regardless of type; otherwise, it is one of the DIDEVTYPE_* values described in DIDEVICEINSTANCE.

The second parameter is a pointer to a callback function to be called once for each device enumerated. This function can be called by any name; the documentation uses the placeholder name DIEnumDevicesCallback.

The third parameter to the EnumDevices method is any 32-bit value that you want to pass into the callback function. In this example, it is a pointer to a variable of type GUID, passed in so that the callback can assign a keyboard instance GUID.

The fourth parameter is a flag to request enumeration of either all devices or only those that are attached (DIEDFL_ALLDEVICES or DIEDFL_ATTACHEDONLY).

If your application is using more than one input device, the callback function is a good place to initialize each device as it is enumerated. (For an example, see Tutorial 3: Using the Joystick.) You obtain the instance GUID of the device from the callback function. You can also perform other processing here, such as looking for particular subtypes of devices or adding the device name to a list box.

The following code example checks for the presence of an enhanced keyboard and stops the enumeration as soon as it finds one. It assigns the instance GUID of the last keyboard found to the KeyboardGUID variable (passed in as pvRef by the previous example of a EnumDevices call), which can then be used in a call to IDirectInput7::CreateDeviceEx.

BOOL          hasEnhanced;

BOOL CALLBACK DIEnumKbdCallback(LPCDIDEVICEINSTANCE lpddi,
                            LPVOID pvRef)
{
  *(GUID*) pvRef = lpddi->guidInstance;
  if (GET_DIDEVICE_SUBTYPE(lpddi->dwDevType) ==
                       DIDEVTYPEKEYBOARD_PCENH)
  {
    hasEnhanced = TRUE;
    return DIENUM_STOP;
  }
  return DIENUM_CONTINUE;
} // End of callback

The first parameter points to a structure containing information about the device. This structure is created for you by DirectInput.

The second parameter points to data passed in from EnumDevices. In this case, it is a pointer to the variable KeyboardGUID. This variable was assigned a default value earlier, but it is given a new value each time that a device is enumerated. It is not important what instance GUID you use for a single keyboard, but the code example illustrates a technique for retrieving an instance GUID from the callback.

The return value in this case indicates that enumeration is to stop if the sought-for device has been found, or otherwise that it is to continue. Enumeration automatically stops as soon as all devices have been enumerated.

[Visual Basic]

If your application is using only the standard keyboard or mouse, or both, you do not need to enumerate the available input devices. As explained under Creating a DirectInput Device, you can use predefined GUID aliases when calling the DirectInput.CreateDevice method.

For all other input devices, and for systems with multiple keyboards or mouse devices, call DirectInput.GetDIEnumDevices to build a collection of available devices. This method returns a DirectInputEnumDevices object representing the collection. Each device in the collection can be retrieved as a DirectInputDeviceInstance object by using the DirectInputEnumDevices.GetItem method.

At the very least, you must retrieve the unique identifier for a nonstandard device by calling DirectInputDeviceInstance.GetGuidInstance before you can create a DirectInputDevice object for that device. You might also want to enumerate devices to look for particular types and subtypes (by using DirectInputDeviceInstance.GetDevType) or to populate a list box that allows the user to select a game controller.

You might even want to search for a device with particular capabilities. To do this, you must create a DirectInputDevice object for each candidate to examine it further by using the DirectInputDevice.GetCapabilities method.


DirectInput Devices

This section contains information about the code objects that represent devices such as a mouse, keyboards, and joysticks. The following topics are covered:

  • Device Setup
  • Creating a DirectInput Device
  • Device Capabilities
  • Cooperative Levels
  • Device Object Enumeration
  • Device Data Formats
  • Device Properties
  • Acquiring Devices
  • Recognizing Device Changes

For information on how to retrieve and interpret data from devices, see DirectInput Device Data.


Device Setup

Your application must create an object for each device from which it expects input. It must also prepare each device for use, which requires, at the very least, setting the data format and acquiring the device. You might also want to carry out other preparatory tasks, such as getting information about the devices and changing their properties.

The following tasks are part of the setup process. Certain steps are always required; others are only necessary if you need further information about devices or need to change default values.

  1. Create the DirectInput device (required). See Creating a DirectInput Device.
  2. Get the device capabilities (optional).
  3. Enumerate the keys, buttons, and axes on the device (optional). See Device Object Enumeration.
  4. Set the cooperative level (highly recommended).
  5. Set the data format (required).
  6. Set the device properties (you must at least set the buffer size if you intend to get buffered data).
  7. When ready to read data, acquire the device (required). See Acquiring Devices.


Creating a DirectInput Device

To get input data from a device, you first have to create an object to represent that device.

[C++]

The IDirectInput7::CreateDeviceEx method is used to obtain a pointer to the IDirectInputDevice7 interface. Methods of this interface are then used to manipulate the device and obtain data.

The code following example, where lpdi is a pointer to the IDirectInput7 interface, creates a keyboard device:

LPDIRECTINPUTDEVICE7  lpdiKeyboard;
lpdi->CreateDeviceEx(GUID_SysKeyboard, IID_IDirectInputDevice7,
        (void**)&lpdiKeyboard, NULL);

The first parameter in IDirectInput7::CreateDeviceEx is an instance GUID that identifies the instance of the device for which the interface is to be created. DirectInput has two predefined GUIDs, GUID_SysMouse and GUID_SysKeyboard, which represent the system mouse and keyboard. You can pass these identifiers into the CreateDeviceEx method. The global variable GUID_Joystick should not be used as a parameter for CreateDeviceEx because it is a product GUID, not an instance GUID.

Note If the computer has more than one mouse, input from all of them is combined to form the system device. The same is true for multiple keyboards.

DirectInput provides four other predefined GUIDs primarily for testing. These are GUID_SysKeyboardEm, GUID_SysKeyboardEm2, GUID_SysMouseEm, and GUID_SysMouseEm2. Passing one of these GUIDs to CreateDeviceEx grants access to the system keyboard or mouse through an emulation layer, at either level 1 or level 2. These GUIDs always represent the system mouse or keyboard. They are aliases for GUID_SysKeyboard and GUID_SysMouse, so they are not enumerated by IDirectInput7::EnumDevices unless the DIEDFL_INCLUDEALIASES flag is passed.

For devices other than the system mouse or keyboard, use the instance GUID for the device returned by IDirectInput7::EnumDevices. The instance GUID for a device is always the same. You can allow the user to select a device from a list of those enumerated, then save the GUID to a configuration file and use it again in future sessions.

[Visual Basic]

The DirectInput.CreateDevice method is used to obtain a DirectInputDevice object. Methods of this interface are then used to manipulate the device and obtain data.

The following code example, where di is the DirectInput object, creates a keyboard device:

Dim diDev As DirectInputDevice
Set diDev = di.CreateDevice("GUID_SysKeyboard")

The parameter is an alias for a GUID that identifies the instance of the device for which the interface is to be created. DirectInput provides two predefined GUIDs, GUID_SysMouse and GUID_SysKeyboard, which represent the system mouse and keyboard, and you can pass either of these to the CreateDevice method.

Note If the computer has more than one mouse, input from all of them is combined to form the system device. The same is true for multiple keyboards.

For devices other than the system mouse or keyboard, use the instance GUID for the device obtained from DirectInputDeviceInstance.GetGuidInstance. The instance GUID for a device is always the same. You can allow the user to select a device from a list of those enumerated, then save the GUID to a configuration file and use it again in future sessions.

In the following code example, it is presumed that the application has enumerated devices and found a suitable one, diDevInstance, which is to be created as a DirectInputDevice:

Dim guid As String
guid = diDevInstance.GetGuidInstance
Set diDev = di.CreateDevice(guid)

For more information on obtaining the DirectInputDeviceInstance object, see DirectInput Device Enumeration.


Device Capabilities

Before you begin asking for input from a device, you need to find out something about its capabilities. Does the joystick have a point-of-view hat? Is the mouse currently attached to the user's computer?

[C++]

Such questions are answered with a call to the IDirectInputDevice7::GetCapabilities method, which returns the data in a DIDEVCAPS structure. As with other such structures in DirectX, you must initialize the dwSize member before passing this structure to the method.

Note To optimize speed or memory usage, you can use the smaller DIDEVCAPS_DX3 structure instead.

The following code example checks whether the mouse is attached and whether it has a third axis (presumably a wheel):

//  LPDIRECTINPUTDEVICE7  lpdiMouse;  // initialized previously

DIDEVCAPS  DIMouseCaps;
HRESULT    hr;
BOOLEAN    WheelAvailable;

DIMouseCaps.dwSize = sizeof(DIDEVCAPS);
hr = lpdiMouse->GetCapabilities(&DIMouseCaps);
WheelAvailable = ((DIMouseCaps.dwFlags & DIDC_ATTACHED)
        && (DIMouseCaps.dwAxes > 2));

Another way to check for a button or axis is to call IDirectInputDevice7::GetObjectInfo for that object. If the call returns DIERR_OBJECTNOTFOUND, the object is not present. The following code example determines whether there is a z-axis, even if it is not the third axis:

DIDEVICEOBJECTINSTANCE  didoi;

didoi.dwSize = sizeof(DIDEVICEOBJECTINSTANCE);
hr = lpdiMouse->GetObjectInfo(&didoi,DIMOFS_Z, DIPH_BYOFFSET);
WheelAvailable = SUCCEEDED(hr);
[Visual Basic]

Such questions are answered with a call to the DirectInputDevice.GetCapabilities method, which returns the data in a DIDEVCAPS type.

The following code example checks whether the mouse is attached and whether it has a third axis (presumably a wheel):

/* diMouse is a valid DirectInputDevice object. */

Dim WheelAvailable As Boolean
Dim dicaps as DIDEVCAPS

Call diDev.GetCapabilities(dicaps)
WheelAvailable = ((dicaps.lFlags And DIDC_ATTACHED) _
        And (dicaps.lAxes > 2))

Another way to check for a certain button or axis is to call DirectInputDevice.GetObjectInfo for that object. If the call raises error DIERR_NOTFOUND, the object is not present. The following code example determines whether there is a z-axis, even if it is not the third axis:

Dim didoi As DirectInputDeviceObjectInstance
On Error GoTo NOTFOUND
Set didoi = diDev.GetObjectInfo(DIMOFS_Z, DIPH_BYOFFSET)
On Error GoTo 0
.
.
.
NOTFOUND:
If Err.Number = DIERR_NOTFOUND Then
  MsgBox "No z-axis found."
End If


Cooperative Levels

[C++]

The cooperative level of a device determines how the input is shared with other applications and with the Windows system. You set it by using the IDirectInputDevice7::SetCooperativeLevel method, as in the following code example:

/* hwnd is the top-level window handle. */
lpdiDevice->SetCooperativeLevel(hwnd,
        DISCL_NONEXCLUSIVE | DISCL_FOREGROUND)

The parameters are the handle to the top-level window associated with the device (generally the application window) and one or more flags.

[Visual Basic]

The cooperative level of a device determines how the input is shared with other applications and with the Windows system. You set it by using the DirectInputDevice.SetCooperativeLevel method, as in the following code example:

diDevice.SetCooperativeLevel(hWnd,
        DISCL_NONEXCLUSIVE Or DISCL_FOREGROUND)

The parameters are the handle to the top-level window associated with the device (generally the application window) and one or more flags. The hWnd property of a form does not become valid until the form is shown. If you are initializing the DirectInput device in the Load method of the application's main form, you must call Show before attempting to set the cooperative level.

Note Although DirectInput provides a default setting, you should still explicitly set the cooperative level because this is the only way to give DirectInput the window handle. Without this handle, DirectInput cannot react to situations that involve window messages, such as joystick recalibration.

The valid flag combinations are shown in the following table:

Flags | Notes
DISCL_NONEXCLUSIVE DISCL_BACKGROUND | The default setting
DISCL_NONEXCLUSIVE DISCL_FOREGROUND |
DISCL_EXCLUSIVE DISCL_FOREGROUND |
DISCL_EXCLUSIVE DISCL_BACKGROUND | Not valid for keyboard or mouse

[C++]

For the keyboard, you can also include DISCL_NOWINKEY in combination with DISCL_NONEXCLUSIVE. This flag disables the Windows key so that users cannot inadvertently break out of the application. In exclusive mode, the Windows key is always disabled.

The cooperative level has two main components: whether the device is being used in the foreground or the background, and whether it is being used exclusively or nonexclusively.

Foreground vs. Background

A foreground cooperative level means that the input device is available only when the application is in the foreground or, in other words, has the input focus. If the application moves to the background, the device is automatically unacquired, or made unavailable.

A background cooperative level really means foreground and background. A device with a background cooperative level can be acquired and used by an application at any time.

You will usually want to have foreground access only, since most applications are not interested in input that takes place when another program is in the foreground.

While developing an application, it is useful to employ conditional compilation so that the background cooperative level is always set for debugging. This prevents your application from losing access to the device every time that it moves to the background as you switch to the debugging environment.

Exclusive vs. Nonexclusive

The fact that your application is using a device at the exclusive level does not mean that other applications cannot get data from the device. However, it does mean that no other application can also acquire the device exclusively.

Take the example of a music player that accepts input from a hand-held remote-control device, even when the application is running in the background. If you run a similar application that plays movies in response to signals from the same remote control, what happens when the user presses Play? Both programs start playing, which is probably not what the user wants. To prevent this from happening, each application should have the DISCL_EXCLUSIVE flag set so that only one of them can be running at a time.

To use force-feedback effects, an application must have exclusive access to the device.

Windows itself requires exclusive access to the mouse because mouse events such as a click on an inactive window could force an application to unacquire the device, with potentially harmful results, such as a loss of data from the input buffer. Therefore, when an application has exclusive access to the mouse, Windows is not allowed any access at all. No mouse messages are generated. A further side effect is that the cursor disappears.

When an application has exclusive access to the keyboard, DirectInput suppresses all keyboard messages except CTRL+ALT+DEL and, on Windows 95 and Windows 98, ALT+TAB.


Device Object Enumeration

It might be necessary for your application to determine what buttons or axes are available on a given device. To do this, you enumerate the device objects in much the same way that you enumerate devices.

[C++]

To some extent, IDirectInputDevice7::EnumObjects overlaps the functionality of IDirectInputDevice7::GetCapabilities. Either method can be used to determine how many buttons or axes are available. However, EnumObjects is intended for cataloging all the available objects, rather than checking for a particular one. The DirectInput QuickTest application provided with the DirectX SDK, for example, uses EnumObjects to populate the list on the Objects tabbed page for the selected device.

Like IDirectInput7::EnumDevices, the EnumObjects method has a callback function that allows you to do other processing on each object—for example, adding it to a list or creating a corresponding element on a user interface.

The following code example extracts the name of each object so that it can be added to a string list or array. This standard callback is documented under the placeholder name DIEnumDeviceObjectsCallback, but you can give it any name that you like. Remember, this function is called once for each object enumerated.

char  szName[MAX_PATH];

BOOL CALLBACK DIEnumDeviceObjectsCallback(
                      LPCDIDEVICEOBJECTINSTANCE lpddoi,
                      LPVOID pvRef)
{
  lstrcpy(szName, lpddoi->tszName);
  // Now, add szName to a list or array.
  .
  .
  .
  return DIENUM_CONTINUE;
}

The first parameter points to a structure containing information about the object. This structure is created for you by DirectInput.

The second parameter is an application-defined pointer to data, equivalent to the second parameter to EnumObjects. In the example, this parameter is not used.

The return value in this case indicates that enumeration is to continue as long as there are objects to be enumerated.

The following code example calls the EnumObjects method, which puts the callback function to work.

lpdiMouse->EnumObjects(DIEnumDeviceObjectsCallback,
                       NULL, DIDFT_ALL);

The first parameter is the address of the callback function.

The second parameter can be a pointer to any data that you want to use or modify in the callback. The example does not use this parameter and, therefore, passes NULL.

The third parameter is a flag to indicate which type or types of objects are to be included in the enumeration. In the example, all objects are to be enumerated. To restrict the enumeration, you can use one or more of the other DIDFT_* flags listed in IDirectInput7::EnumDevices.

Note Some of the DIDFT_* flags are combinations of others; for example, DIDFT_AXIS is equivalent to DIDFT_ABSAXIS | DIDFT_RELAXIS.

[Visual Basic]

You enumerate device objects by calling DirectInputDevice.GetDeviceObjectsEnum, which returns an instance of the DirectInputEnumDeviceObjects class representing the collection of available device objects that match the requested parameters.

The following code example enumerates axes on a device:

' diDev is a DirectInputDevice object.

Dim diEnumObjects As DirectInputEnumDeviceObjects
Set diEnumObjects = diDev.GetDeviceObjectsEnum(DIDFT_AXIS)

The parameter is a flag to indicate which type or types of objects are to be included in the enumeration.

Note Some of the CONST_DIDFTFLAGS flags are combinations of others; for example, DIDFT_AXIS is equivalent to DIDFT_ABSAXIS OR DIDFT_RELAXIS.

To obtain information about a particular device object, call the methods of a DirectInputDeviceObjectInstance object obtained by calling DirectInputEnumDeviceObjects.GetItem. Information available for a device object includes its name, its type, and its offset in the data structure for the device.

The following code example lists the names of the axes enumerated in the previous example:

Dim diDevEnumObjects As DirectInputEnumDeviceObjects
Set diDevEnumObjects = diDev.GetDeviceObjectsEnum(DIDFT_AXIS)

Dim diDevObjInstance As DirectInputDeviceObjectInstance
Dim i As Integer
For i = 1 To diEnumObjects.GetCount
  Set diDevObjInstance = diEnumObjects.GetItem(i)
  Call List1.AddItem(diDevObjInstance.GetName)
Next i


Device Data Formats

Setting the data format for a device is an essential step before you can acquire and begin using the device. This is true even if you do not intend to retrieve immediate (state) data from the device. DirectInput uses the data format in many methods to identify particular device objects.

[C++]

The IDirectInputDevice7::SetDataFormat method tells DirectInput what device objects will be used and how the data will be arranged.

The examples in the reference for the DIDATAFORMAT and DIOBJECTDATAFORMAT structures show how to set up custom data formats for nonstandard devices. Fortunately, this step is not necessary for the joystick, keyboard, and mouse. DirectInput provides five global variables, c_dfDIJoystick, c_dfDIJoystick2, c_dfDIKeyboard, c_dfDIMouse, and c_dfDIMouse2, which can be passed in to SetDataFormat to create a standard data format for these devices.

In the following code example, lpdiMouse is an initialized pointer to the mouse DirectInputDevice object:

lpdiMouse->SetDataFormat(&c_dfDIMouse);

Note You cannot change the dwFlags member in the predefined DIDATAFORMAT global variables (for example, to change the property of an axis), because they are const variables. To change properties, use the IDirectInputDevice7::SetProperty method after setting the data format, but before acquiring the device.

[Visual Basic]

The DirectInputDevice.SetCommonDataFormat and DirectInputDevice.SetDataFormat methods tell DirectInput what device objects will be used and how the data will be arranged.

For standard devices—the mouse, keyboard, and any game controller whose input data can be described in a DIJOYSTATE or DIJOYSTATE2 type—you can set the data format by calling the SetCommonDataFormat method, passing in a constant from the CONST_DICOMMONDATAFORMATS enumeration. The common data formats are adequate for most applications.

For specialized devices, you must pass a description of the data format to the SetDataFormat method. The following code example sets the data format for a device with two axes, both of which require a Long for their data, and no buttons:

Dim dx As New DirectX7
Dim di As DirectInput
Dim did As DirectInputDevice
Dim fD As DIDATAFORMAT
Dim fDA(1) As DIOBJECTDATAFORMAT

Private Sub Form_Load()
    Set di = dx.DirectInputCreate()

    Set did = di.CreateDevice("GUID_SysMouse")

    fDA(0).lFlags = DIDOI_POLLED
    fDA(0).lOfs = 0
    fDA(0).lType = DIDFT_RELAXIS
    fDA(0).strGuid = "GUID_XAxis"

    fDA(1).lFlags = DIDOI_POLLED
    fDA(1).lOfs = 4
    fDA(1).lType = DIDFT_RELAXIS
    fDA(1).strGuid = "GUID_YAxis"

    fD.dataSize = 8
    fD.lFlags = DIDF_RELAXIS
    fD.lObjSize = 4
    fD.numObjs = 2

    did.SetDataFormat fD, fDA()

End Sub


Device Properties

Properties of DirectInput devices include the size of the data buffer, the range and granularity of values returned from an axis, whether axis data is relative or absolute, and the dead zone and saturation values for a joystick axis, which affect the relationship between the physical position of the stick and the reported data. Specialized devices can have other properties, as well.

With one exception—the gain property of a force-feedback device—properties can be changed only when the device is in an unacquired state.

[C++]

Before calling the IDirectInputDevice7::SetProperty or the IDirectInputDevice7::GetProperty method, set up a property structure, which consists of a DIPROPHEADER structure and one or more elements for data. There are potentially a great variety of properties for input devices, and SetProperty must be able to work with all sorts of structures defining those properties. The purpose of the DIPROPHEADER structure is to define the size of the property structure and how the data is to be interpreted.

DirectInput includes the following predefined property structures:

  • DIPROPDWORD defines a structure containing a DIPROPHEADER and a DWORD data member for properties that require a single value, such as a buffer size.
  • DIPROPRANGE is for range properties, which require two values (maximum and minimum). It consists of a DIPROPHEADER and two LONG data members.
  • DIPROPGUIDANDPATH is a specialized property structure allowing applications to perform operations on an HID that are not supported by DirectInput. The structure consists of a DIPROPHEADER, a GUID, and a Unicode string for the path.
  • DIPROPSTRING is for Unicode string properties. The structure comprises a DIPROPHEADER and a Unicode string.

For SetProperty, the data members of the property structure are the values that you want to set. For GetProperty, the current value is returned in these members.

Before the call to GetProperty or SetProperty, the DIPROPHEADER structure must be initialized with the following:

  • The size of the property structure.
  • The size of the DIPROPHEADER structure itself.
  • An object identifier.
  • A dwHow member indicating the way that the object identifier should be interpreted.

When getting or setting properties for a whole device, the object identifier dwObj is 0, and the dwHow member is DIPH_DEVICE. If you want to get or set properties for a device object (for example, a particular axis), the combination of dwObj and dwHow values identifies the object. For details, see DIPROPHEADER structure.

After setting up the property structure, pass the address of its header into GetProperty or SetProperty, along with an identifier for the property that you want to obtain or change.

The following values are used to identify the property passed to SetProperty and GetProperty. For more information, see IDirectInputDevice7::GetProperty.

  • DIPROP_BUFFERSIZE. See also Buffered and Immediate Data.
  • DIPROP_AXISMODE. See also Relative and Absolute Axis Coordinates.
  • DIPROP_CALIBRATIONMODE
  • DIPROP_GRANULARITY
  • DIPROP_FFGAIN
  • DIPROP_FFLOAD
  • DIPROP_AUTOCENTER
  • DIPROP_RANGE
  • DIPROP_DEADZONE
  • DIPROP_SATURATION

For more information about the last three properties, see also Interpreting Joystick Axis Data.

The following code example sets the buffer size for a device to hold 10 data items:

DIPROPDWORD  dipdw;
HRESULT      hres;
dipdw.diph.dwSize = sizeof(DIPROPDWORD);
dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
dipdw.diph.dwObj = 0;
dipdw.diph.dwHow = DIPH_DEVICE;
dipdw.dwData = 10;
hres = lpdiDevice->SetProperty(DIPROP_BUFFERSIZE, &dipdw.diph);
[Visual Basic]

The DirectInputDevice.SetProperty or DirectInputDevice.GetProperty methods take two parameters: a GUID alias in string form that identifies the property being set, and data of type Any. The data is passed in one of the following types:

  • DIPROPLONG is for properties that require a single value, such as a buffer size. The property data consists of a single Long.
  • DIPROPRANGE is for range properties, which require two values (maximum and minimum). The property data consists of two Long data members.

For SetProperty, the data members of the property types are the values that you want to set. For GetProperty, the current value is returned in these members.

In addition to the actual property data, both these types contain three other members: lHow, lObj, and lSize.

The values in lHow and lObj work together, with lHow signifying the system that is used to identify the device object whose property is being set or retrieved, and lObj identifying the device object.

If lHow is DIPH_BYID, the device object is described by a unique numerical identifier in lObj. This ID can be extracted from the value returned by DirectInputDeviceObjectInstance.GetType after device objects have been enumerated.

For most applications, it is simpler to identify the device object by its offset within the data structure established by DirectInputDevice.SetCommonDataFormat or DirectInputDevice.SetDataFormat. In this case, lHow is DIPH_BYOFFSET, and lObj is the offset, in bytes. For the keyboard, mouse, and any game controller whose data can be returned in a DIJOYSTATE type, the device object can be identified by a predefined constant. See CONST_DIKEYFLAGS, CONST_DIMOUSEOFS, and CONST_DIJOYSTICKOFS.

The lHow member can also contain DIPH_DEVICE, which means that the property belongs to the entire device, rather than a single device object. Buffer size is an example of such a property. When lHow is DIPH_DEVICE, lObj is 0.

Finally, the lSize member of the property type must be initialized to the size of the type. This step is necessary because GetProperty or SetProperty do not know what type is being passed.

The following strings are used to identify the property passed to SetProperty and GetProperty. For more information, see DirectInputDevice.GetProperty.

  • DIPROP_AXISMODE. See also Relative and Absolute Axis Coordinates.
  • DIPROP_BUFFERSIZE. See also Buffered and Immediate Data.
  • DIPROP_DEADZONE
  • DIPROP_GRANULARITY
  • DIPROP_RANGE
  • DIPROP_SATURATION

For more information about dead zone, range, and saturation, see also Interpreting Joystick Axis Data.

The following code example sets the buffer size for a device:

' diDev is a DirectInputDevice whose data format has been set.

Dim diProp As DIPROPLONG
diProp.lHow = DIPH_DEVICE
diProp.lObj = 0
diProp.lData = 10
diProp.lSize = Len(diProp)
Call diDev.SetProperty("DIPROP_BUFFERSIZE", diProp)


Acquiring Devices

Acquiring a DirectInput device means giving your application access to it. As long as a device is acquired, DirectInput is making its data available to your application. If the device is not acquired, you can manipulate its characteristics, but not obtain any data.

Acquisition is not permanent. Your application can acquire and unacquire a device many times.

In certain cases, depending on the cooperative level, a device can be unacquired automatically whenever the application moves to the background. The mouse is automatically unacquired when the user clicks on a menu, because at this point Windows takes over the device.

You must unacquire a device before changing its properties. The only exception is that you can change the gain for a force-feedback device while it is in an acquired state.

The acquisition mechanism is needed for two reasons:

First, DirectInput must be able to tell the application when the flow of data from the device has been interrupted by the system. For instance, if the user has switched to another application with ALT+TAB and used the input device in that application, your application needs to know that the input no longer belongs to it and that the state of the buffers might have changed. Consider an application with the DISCL_FOREGROUND cooperative level. The user presses the SHIFT key, and while continuing to press it, switches to another application. Then, the user releases the key and switches back to the first application. As far as the first application is concerned, the SHIFT key is still down. The acquisition mechanism, by telling the application that input was lost, allows it to recover from these conditions.

Second, because your application can alter the properties of the device, without safeguards DirectInput would have to check the properties each time that you wanted to retrieve data. This would be very inefficient. Even worse, this could cause a hardware interrupt accessing a data buffer when the buffer size is being changed. Therefore, DirectInput requires your application to unacquire the device before changing properties. When you reacquire it, DirectInput checks the properties and decides on the optimal way of transferring data from the device to the application. This is done only once, so the data retrieval methods can be very fast.

[C++]

Since the most common cause of losing a device is that your application moves to the background, you might want to reacquire devices whenever your application is activated. Be careful, however, about relying on a WM_ACTIVATE handler at startup time. The first WM_ACTIVATE message will probably arrive when your window is being initialized, before DirectInput has been set up. To ensure that the device is acquired at startup, call IDirectInputDevice7::Acquire as soon as the device has been initialized.

Even acquiring the device on activation of your program window might not cover all cases in which a device is unacquired, especially for devices other than the standard mouse or keyboard. Because your application might unacquire a device unexpectedly, you need a mechanism for checking the acquisition state before attempting to get data from the device. The Scrawl sample application does this in the Scrawl_OnMouseInput function, in which a DIERR_INPUTLOST error triggers a message to reacquire the mouse. (See also Tutorial 2: Using the Mouse.)

[Visual Basic]

Because your application might unacquire a device unexpectedly, especially if you have set the exclusive cooperative level, ensure that the application tracks the state of acquisition. One technique is to check for the DIERR_INPUTLOST error after attempting to retrieve data. If this error is raised, you know the device has been unacquired. If your application is getting input in response to event notification, an event is signaled when acquisition is lost.

See the ScrawlB sample for more information about how to manage device acquisition in exclusive mode.

Attempting to reacquire a device that is already acquired does no harm. Redundant calls to Acquire are ignored, and the device can always be unacquired with a single call to Unacquire.

[C++]

Windows does not have access to the mouse when your application is using it in exclusive mode. If you want to let Windows have the mouse, you must release it. There is an example in the Scrawl sample that responds to a click of the right button by unacquiring the mouse, putting the Windows cursor in the same spot as its own, popping up a context menu, and letting Windows handle the input until a menu choice is made.

[Visual Basic]

Windows does not have access to the mouse when your application is using it in exclusive mode. If you want to let Windows have the mouse, you must release it. There is an example in the ScrawlB sample that responds to a click of the right button by unacquiring the mouse, putting the Windows cursor in the same spot as its own, popping up a context menu, and letting Windows handle the input until a menu choice is made.


Recognizing Device Changes

[Visual Basic]

This topic pertains only to applications written in C++.

[C++]

Because universal serial bus (USB) devices can be added to and removed from the system without rebooting, you might want your application to be able to respond to a new configuration of input devices. For example, you might allow a new player to join a game in progress by plugging in another controller.

To receive a message when a device is changed, you must first register for notification, as in the following code example:

PVOID hNotifyDevNode;

void RegisterForDevChange(HWND hDlg, PVOID *hNotifyDevNode)
{
    DEV_BROADCAST_DEVICEINTERFACE *pFilterData =
           (DEV_BROADCAST_DEVICEINTERFACE*)
           _alloca(sizeof(DEV_BROADCAST_DEVICEINTERFACE));
    ASSERT (pFilterData);

    ZeroMemory(pFilterData, sizeof(DEV_BROADCAST_DEVICEINTERFACE));

    pFilterData->dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
    pFilterData->dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
    pFilterData->dbcc_classguid  = GUID_CLASS_INPUT;

    *hNotifyDevNode = RegisterDeviceNotification(hDlg, pFilterData,
            DEVICE_NOTIFY_WINDOW_HANDLE);
}

Then, in your main window procedure, check for messages announcing that a device has been attached, is about to be removed, or has been removed, as follows:

MyWindowProc(HWND hWnd, UINT nMsg, WPARAM wParam, LPARAM lParam)
{
    switch (nMsg)
    {
        case WM_DEVICECHANGE:
        {
            switch (wParam)
            {
                case DBT_DEVICEARRIVAL:
                    // Handle device arrival
                    break;

                case DBT_DEVICEQUERYREMOVE:
                    // Handle device removal request
                    break;

                case DBT_DEVICEREMOVECOMPLETE:
                    // Handle device removal
                    break;
            }
        }
.
.
.
    }
}

In response to a DBT_DEVICEARRIVAL event, obtain the instance GUID of the device by using IDirectInput7::FindDevice, and pass this value to IDirectInput7::CreateDeviceEx.

For more information, see Device Management in the the Platform SDK.


DirectInput Device Data

This section covers the basic concepts of getting data from DirectInput devices.

  • Buffered and Immediate Data
  • Time Stamps and Sequence Numbers
  • Polling and Events
  • Relative and Absolute Axis Coordinates

Specific details about mouse, keyboard, and joystick input data, and about output data, are given in the following sections:

  • Mouse Data
  • Keyboard Data
  • Joystick Data
  • Output Data


Buffered and Immediate Data

DirectInput supplies two types of data: buffered and immediate. Buffered data is a record of events that are stored until an application retrieves them. Immediate data is a snapshot of the current state of a device.

You might use immediate data in an application that is concerned only with the current state of a device—for example, a flight combat simulation that responds to the current position of the joystick and the state of one or more buttons. Buffered data might be the better choice where events are more important than states—for example, in an application that responds to movement of the mouse and button clicks. You can also use both types of data, as you might for example if you wanted to get immediate data for joystick axes but buffered data for the buttons.

The DirectInput QuickTest application supplied with the DirectX SDK lets you see both immediate and buffered data from a device. After you create the device in the application window, set its properties on the Mode tabbed page. On the Data tabbed page, you then see immediate data on the left and buffered data on the right.

[C++]

An application retrieves immediate data by calling the IDirectInputDevice7::GetDeviceState method. As the name implies, this method returns the current state of the device: for example, whether each button is up or down. The method provides no data about what has happened with the device since the last call, apart from implicit information that you can derive by comparing the current state with the last one. If the user has pressed and released a button between two calls to GetDeviceState, your application does not know anything about it. On the other hand, if the user is holding a button down, GetDeviceState continues reporting button down until the user releases it.

This way of reporting the device state is different from the way that Windows reports events with one-time messages such as WM_LBUTTONDOWN; it is more like the results from the Win32 GetKeyboardState function. If you are polling a device with GetDeviceState, you are responsible for determining what constitutes a button click, a double-click, a single keystroke, and so on, and for ensuring that your application does not keep responding to a button-down or key-down state when it is not appropriate to do so.

With buffered data, events are stored until you are ready to deal with them. Every time a button or key is pressed or an axis is moved, information about the event is placed in a DIDEVICEOBJECTDATA structure in the buffer. If the buffer overflows, new data is lost. Your application reads the buffer with a call to IDirectInputDevice7::GetDeviceData. You can read any number of items at a time.

Reading an item normally deletes it from the buffer, but you also have the choice of peeking without deleting.

To get buffered data, you must first set the buffer size with the IDirectInputDevice7::SetProperty method. (See the example in Device Properties.) Set the buffer size before acquiring the device for the first time. For reasons of efficiency, the default size of the buffer is 0, and you cannot obtain buffered data unless you change this value. The size of the buffer is measured in items of data for that type of device, not in bytes or WORDs.

Check the value of the pdwInOut parameter after a call to the GetDeviceData method. The number of items retrieved from the buffer is returned in this variable.

Note For devices that do not generate interrupts, such as analog joysticks, DirectInput does not obtain any data until you call the IDirectInputDevice7::Poll method. For more information, see Polling and Events.

For examples of retrieving buffered data, see IDirectInputDevice7::GetDeviceData.

[Visual Basic]

An application retrieves immediate data by calling one of the following methods:

  • DirectInputDevice.GetDeviceStateKeyboard. For devices that retrieve data in a DIKEYBOARDSTATE type. (For this and the following three methods, the data format must have been set by using DirectInputDevice.SetCommonDataFormat.)
  • DirectInputDevice.GetDeviceStateMouse. For devices that retrieve data in a DIMOUSESTATE type.
  • DirectInputDevice.GetDeviceStateJoystick. For devices that retrieve data in a DIJOYSTATE type.
  • DirectInputDevice.GetDeviceStateJoystick2. For devices that retrieve data in a DIJOYSTATE2 type.
  • DirectInputDevice.GetDeviceState. For devices that use custom data formats, as set by using DirectInputDevice.SetDataFormat.

As the names imply, each of these methods returns the current state of the device: for example, whether each button is up or down. The method provides no data about what has happened with the device since the last call, apart from implicit information that you can derive by comparing the current state with the last one. If the user has pressed and released a button between two calls to the method, your application does not know anything about it. On the other hand, if the user is holding a button down, the method continues reporting button down until the user releases it.

This way of reporting the device state is different from the way Visual Basic reports events with one-time events like Click and Keydown. If you are polling a device with one of the GetDeviceState methods, you are responsible for determining what constitutes a button click, a double-click, a single keystroke, and so on, and for ensuring that your application does not keep responding to a button-down or key-down state when it is not appropriate to do so.

With buffered data, events are stored until you are ready to deal with them. Every time a button or key is pressed or an axis is moved, information about the event is placed in a DIDEVICEOBJECTDATA type in the buffer. Your application reads the buffer with a call to DirectInputDevice.GetDeviceData. You can read any number of items at a time.

Reading an item normally deletes it from the buffer, but you also have the choice of retrieving without deleting by setting the DIGDD_PEEK flag.

To get buffered data, you must first set the buffer size by using the DirectInputDevice.SetProperty method. (See the example under Device Properties.) Set the buffer size before acquiring the device for the first time. For reasons of efficiency, the default size of the buffer is 0, and you cannot obtain buffered data unless you change this value. The size of the buffer is measured in items of data for that type of device, not in bytes or WORDs.

The return value of GetDeviceData tells you the number of items retrieved from the buffer. If the buffer has overflowed, no data is returned, and GetDeviceData raises an error, which the application should trap.

Note For devices that do not generate interrupts, such as analog joysticks, DirectInput does not obtain any data until you call the DirectInputDevice.Poll method. For more information, see Polling and Events.

See also:

  • Time Stamps and Sequence Numbers
  • Mouse Data
  • Keyboard Data
  • Joystick Data


Time Stamps and Sequence Numbers

[C++]

When DirectInput input data is buffered (see Buffered and Immediate Data), each DIDEVICEOBJECTDATA structure contains not only information about the type of event and the device object associated with it, but also a time stamp and a sequence number.

The dwTimeStamp member contains the system time, in milliseconds, at which the event took place. This is equivalent to the value that would have been returned by the Win32 GetTickCount function, but at a higher resolution.

The dwSequence member contains a sequence number assigned by DirectInput. The DirectInput system keeps a single sequence counter, which is incremented by each nonsimultaneous buffered event from any device. Use this number to compare events from different devices and see which came first. The DISEQUENCE_COMPARE macro takes wrap around into account.

[Visual Basic]

When DirectInput input data is buffered (see Buffered and Immediate Data), each DIDEVICEOBJECTDATA type contains not only information about the type of event and the device object associated with it, but also a time stamp and a sequence number.

The lTimeStamp member contains the system time, in milliseconds, at which the event took place. This is equivalent to the value that would have been returned by the Win32 GetTickCount function, but at a higher resolution.

The lSequence member contains a sequence number assigned by DirectInput. The DirectInput system keeps a single sequence counter, which is incremented by each nonsimultaneous buffered event from any device. Use this number to compare events from different devices and see which came first.

Simultaneous events are assigned the same sequence number. If a mouse or joystick is moved diagonally, for example, the changes in the x-axis and the y-axis have the same sequence number.

Note Events are always placed in the buffer in chronological order, so you do not need to check the sequence numbers to sort the events from a single device.


Polling and Events

There are two ways to find out whether input data is available: polling and event notification.

Polling a device means regularly getting the current state of the device objects or checking the contents of the event buffer. Polling is typically used by real-time games that are never idle, but are constantly updating and rendering the game world.

[C++]

In a C++ application, polling would typically be done within the message loop.

Event notification is suitable for applications like the Scrawl sample that wait for input before doing anything. To use event notification, set up a thread-synchronization object with the Win32 CreateEvent function, and then associate this event with the device by passing its handle to the IDirectInputDevice7::SetEventNotification method. The event is then signaled by DirectInput whenever the state of the device changes. Your application can receive notification of the event with a Win32 function such as WaitForSingleObject, and then respond by checking the input buffer to find out what the event was. For code examples, see the Scrawl sample and IDirectInputDevice7::SetEventNotification.

Some joysticks and other game devices, or particular objects on them, do not generate hardware interrupts and do not return any data or signal any events until you call the IDirectInputDevice7::Poll method. (This behind-the-scenes polling is not to be confused with the kind of application polling just discussed. Poll does not retrieve any data, but merely makes data available.)

To find out whether it is necessary to call Poll each time that you want to retrieve data, first set the data format for the device, then call the IDirectInputDevice7::GetCapabilities method, and check for the DIDC_POLLEDDATAFORMAT flag in the DIDEVCAPS structure.

Do not confuse the DIDC_POLLEDDATAFORMAT flag with the DIDC_POLLEDDEVICE flag. The latter is set if any object on the device requires polling. You can then find out whether this is the case for a particular object by calling the IDirectInputDevice7::GetObjectInfo method and checking for the DIDOI_POLLED flag in the DIDEVICEOBJECTINSTANCE structure.

The DIDC_POLLEDDEVICE flag describes the worst case for the device, not the actual situation. For example, an HID mouse with software-controllable resolution might be marked as DIDC_POLLEDDEVICE because reading the resolution information requires polling. Polling the device under these conditions is pointless if all that you want is the standard button and axis data.

Nevertheless, it does not hurt to call the IDirectInputDevice7::Poll method for any input device. If the call is unnecessary, it has no effect and is very fast.

[Visual Basic]

In a Visual Basic application, polling would typically be done in the Sub Main procedure.

Event notification is suitable for applications such as the ScrawlB sample that wait for input before doing anything. To use event notification, implement DirectXEvent in the form or module in which you want to retrieve data. Then, create an event handle by using DirectX7.CreateEvent, and pass this handle to DirectInputDevice.SetEventNotification. Now, whenever an input event occurs on the device, the DirectXEvent.DXCallback method is called, and in your implementation of this method you can retrieve either the device state or buffered data as you would if you were doing so in Sub Main.

Some joysticks and other game devices, or particular objects on them, do not generate hardware interrupts and do not return any data or signal any events until you call the DirectInputDevice.Poll method. (This behind-the-scenes polling is not to be confused with the kind of application polling just discussed. Poll does not retrieve any data, but merely makes data available.)

To find out whether it is necessary to call Poll each time that you want to retrieve data, first set the data format for the device, then call the DirectInputDevice.GetCapabilities method, and check for the DIDC_POLLEDDATAFORMAT flag in the DIDEVCAPS type.

Do not confuse the DIDC_POLLEDDATAFORMAT flag with the DIDC_POLLEDDEVICE flag. The latter is set if any object on the device requires polling. You can then find out whether this is the case for a particular object by calling the IDirectInputDevice7::GetObjectInfo method to get a DirectInputDeviceObjectInstance object, and then checking for the DIDOI_POLLED flag in the valued returned by DirectInputDeviceObjectInstance.GetFlags.

The DIDC_POLLEDDEVICE flag describes the worst case for the device, not the actual situation. For example, an HID mouse with software-controllable resolution might be marked as DIDC_POLLEDDEVICE because reading the resolution information requires polling. Polling the device under these conditions is pointless if all that you want is the standard button and axis data.

Nevertheless, it does not hurt to call the Poll method for any input device. If the call is unnecessary, it has no effect and is very fast.


Relative and Absolute Axis Coordinates

Axis coordinates can be returned as relative values—that is, the amount by which they have changed since the application last retrieved the device state or, in the case of buffered input, since the last item was put in the buffer.

Absolute axis coordinates are a running total of all the relative coordinates returned by the system since the device was acquired; in other words, they show the position of the axis in relation to a fixed point.

By default, mouse axes are reported as relative coordinates and joystick axes as absolute coordinates. You can change the coordinate system for a device by setting a property. For more information, see Device Properties.


Mouse Data

[C++]

To set up the mouse device for data retrieval, first call the IDirectInputDevice7::SetDataFormat method with the c_dfDIMouse or c_dfDIMouse2 global variable as the parameter value. Use c_dfDIMouse2 if you want to support more than four mouse buttons.

For maximum performance in a full-screen application, set the cooperative level to DISCL_EXCLUSIVE | DISCL_FOREGROUND. The exclusive setting causes the Windows cursor to disappear. The DISCL_FOREGROUND setting causes the application to lose access to the mouse when you switch to a debugging window. Changing to DISCL_BACKGROUND allows you to debug the application more easily, at a cost in performance.

[Visual Basic]

To set up the mouse device for data retrieval, first call the DirectInputDevice.SetCommonDataFormat method with DIFORMAT_MOUSE as the parameter value.

For maximum performance in a full-screen application, set the cooperative level to DISCL_EXCLUSIVE Or DISCL_FOREGROUND. The exclusive setting causes the Windows cursor to disappear. The DISCL_FOREGROUND setting causes the application to lose access to the mouse when you switch to the Visual Basic development environment. Changing to DISCL_BACKGROUND allows you to debug the application more easily, at a cost in performance.

The following sections give more information about getting and interpreting immediate and buffered mouse data:

  • Immediate Mouse Data
  • Buffered Mouse Data
  • Interpreting Mouse Axis Data
  • Checking for Lost Mouse Input

See also

Device Data Formats, Cooperative Levels


Immediate Mouse Data

[C++]

To retrieve the current state of the mouse, call IDirectInputDevice7::GetDeviceState with a pointer to a DIMOUSESTATE or a DIMOUSESTATE2 structure, depending on the data format. The mouse state returned in the structure includes axis data and the state of each of the buttons.

The first three members of the structure hold the axis coordinates. (See Interpreting Mouse Axis Data.)

The rgbButtons member is an array of bytes, one for each of four or eight buttons. For a traditional mouse, the first element in the array is generally the left button, the second is the right button, and the third is the middle button. The high bit is set if the button is down, and clear if the button is up or not present.

[Visual Basic]

To retrieve the current state of the mouse, call DirectInputDevice.GetDeviceStateMouse, passing in a DIMOUSESTATE type. The mouse state returned in the type includes axis data and the state of each of the buttons.

The x, y, and z members of the DIMOUSESTATE type hold the axis coordinates. (See Interpreting Mouse Axis Data.) The buttons member is an array of bytes, one for each of four buttons. The first element in the array is generally the left button, the second is the right button, the third is the middle button, and the fourth is any other button. The high bit is set if the button is down, and clear if the button is up or not present.

See also

Buffered and Immediate Data


Buffered Mouse Data

To retrieve buffered data from the mouse, you must first set the buffer size (see Device Properties). The default size of the buffer is 0, so this step is essential.

[C++]

You must also declare an array of DIDEVICEOBJECTDATA structures. This array can have up to the same number of elements as the buffer size. You do not have to retrieve the entire contents of the buffer with a single call; if you want, you can have just one element in the array and retrieve events one at a time until the buffer is empty.

After acquiring the device, you can examine and flush events in the buffer at any time by using the IDirectInputDevice7::GetDeviceData method. (See Buffered and Immediate Data.) On return, each element in the DIDEVICEOBJECTDATA array represents a change in state for a single object on the mouse. For example, if the user presses button 0 and moves the mouse diagonally, the array passed to GetDeviceData (if it has at least three elements, and pdwInOut is at least 3) has three elements filled in—an element for button 0 being pressed, an element for the change in the x-axis, and an element for the change in the y-axis—and the value of pdwInOut is set to 3.

You can determine which object an element in the array refers to by checking the dwOfs member of the DIDEVICEOBJECTDATA structure against the values returned by the following macros:

  • DIMOFS_BUTTON0 to DIMOFS_BUTTON3
  • DIMOFS_X
  • DIMOFS_Y
  • DIMOFS_Z

Each of these values is derived from the offset of the data for the object in a DIMOUSESTATE or DIMOUSESTATE2 structure. For example, DIMOFS_BUTTON0 is equivalent to the offset of rgbButtons[0] in the DIMOUSESTATE structure. With the macros you can use simple comparisons to determine which device object is associated with an item in the buffer. For example:

DIDEVICEOBJECTDATA  *lpdidod;
int                 n;
.
.
.
/* MouseBuffer is an array of DIDEVICEOBJECTDATA structures
   that has been set by a call to GetDeviceData.
   n is incremented in a loop that examines all filled elements
   in the array. */
lpdidod = &MouseBuffer[n];
if (( (int) lpdidod->dwOfs == DIMOFS_BUTTON0)
      && (lpdidod->dwData & 0x80))
{
 ;  // Do something in response to left button press.
}

The data for the change of state of the device object is located in the dwData member of the DIDEVICEOBJECTDATA structure. For axes, the coordinate value is returned in this member. For button objects, only the low byte of dwData is significant; the high bit of this byte is set if the button was pressed, and clear if the button was released. In other words, the button was pressed if (dwData & 0x80) is nonzero.

For more information on the other members of the DIDEVICEOBJECTDATA structure, see Time Stamps and Sequence Numbers.

[Visual Basic]

You must also declare an array of DIDEVICEOBJECTDATA types. This array can have up to the same number of elements as the buffer size. You do not have to retrieve the entire contents of the buffer with a single call; if you want, you can have just one element in the array and retrieve events one at a time until the buffer is empty.

After acquiring the device, you can examine and flush the buffer at any time by using the DirectInputDevice.GetDeviceData method. (See Buffered and Immediate Data.) On return, each element in the DIDEVICEOBJECTDATA array represents a change in state for a single object on the mouse. For instance, if the user presses button 0 and moves the mouse diagonally, the array passed to GetDeviceData (if it has at least three elements) has three elements filled in—an element for button 0 being pressed, an element for the change in the x-axis, and an element for the change in the y-axis—and the return value of the method is 3.

You can determine which object an element in the array refers to by checking the lOfs member of the DIDEVICEOBJECTDATA type against the constants in the CONST_DIMOUSEOFS enumeration. Each of these values is derived from the offset of the data for the object in a DIMOUSESTATE type. For example, DIMOFS_BUTTON0 is equivalent to the offset of buttons(0) in the DIMOUSESTATE type.

The data for the change of state of the device object is located in the lData member of the DIDEVICEOBJECTDATA type. For axes, the coordinate value is returned in this member. For button objects, only the low byte of lData is significant; the high bit of this byte is set if the button was pressed, and clear if the button was released. In other words, the button was pressed if (lData & 0x80) is nonzero.

For more information on the other members of the DIDEVICEOBJECTDATA type, see Time Stamps and Sequence Numbers.

The following code example retrieves the entire contents of the buffer (which contains BufferSize elements) and responds to various events:

' objDIDev is a DirectInputDevice object.
Dim diDeviceData(1 To BufferSize) As DIDEVICEOBJECTDATA
Dim NumEvents As Integer
Dim i As Integer

NumEvents = objDIDev.GetDeviceData(diDeviceData, 0)
For i = 1 To NumEvents
    Select Case diDeviceData(i).lOfs
        Case DIMOFS_X
           ' Respond to x-axis movement.

         Case DIMOFS_Y
           ' Respond to y-axis movement.

         Case DIMOFS_BUTTON0
           If diDeviceData(i).lData And &H80 Then
             ' Respond to left button pressed.
           Else
             ' Respond to left button released.
           End If

    End Select
Next i


Interpreting Mouse Axis Data

The data returned for the x-axis and y-axis of a mouse indicates the movement of the mouse itself, not the cursor. The units of measurement are based on the values returned by the mouse hardware and have nothing to do with pixels or any other form of screen measurement. Because DirectInput communicates directly with the mouse driver, the values for mouse speed and acceleration set by the user in Control Panel do not affect this data.

Axis data returned from the mouse can be either relative or absolute. (See Relative and Absolute Axis Coordinates.) Because a mouse is a relative device—unlike a joystick, it does not have a home position—relative data is returned by default.

[C++]

The axis mode, which specifies whether relative or absolute data should be returned, is a property that can be changed before the device is acquired. (See Device Properties.) To set the axis mode to absolute, call IDirectInputDevice7::SetProperty with the DIPROP_AXISMODE value in the rguidProp parameter and with DIPROPAXISMODE_ABS in the dwData member of the DIPROPDWORD structure.

[Visual Basic]

The axis mode, which specifies whether relative or absolute data should be returned, is a property that can be changed before the device is acquired. (See Device Properties.) To set the axis mode to absolute, call DirectInputDevice.SetProperty with "DIPROP_AXISMODE" in the guid parameter and with DIPROPAXISMODE_ABS in the lData member of the DIPROPLONG type.

When the axis mode for the mouse is set to relative, the axis coordinate represents the number of units that the device has been moved along the axis since the last value was returned. A negative value indicates that the mouse was moved to the left for the x-axis, or away from the user for the y-axis, or that the z-axis (the wheel) was rotated toward the user. Positive values indicate movement in the opposite direction.

When the axis mode is set to absolute, the coordinates are simply a running total of all relative motions received by DirectInput. The axis coordinates are not initialized to any particular value when the device is acquired, so your application should treat absolute values as relative to an unknown origin. You can record the current absolute position whenever the device is acquired and save it as the virtual origin. This virtual origin can then be subtracted from subsequent absolute coordinates retrieved from the device to compute the relative distance that the mouse has moved from the point of acquisition.

The data returned for the axis coordinates is also affected by the granularity property of the device. For the x-axis and y-axis of the mouse, granularity is normally 1, meaning that the minimum change in value is 1. For the wheel axis, it can be larger.


Checking for Lost Mouse Input

[C++]

Because Windows might force your application to unacquire the mouse when you have set the cooperative level to DISCL_FOREGROUND and the focus switches to another application, or even to the menu in your own application, you should check for the DIERR_INPUTLOST return value from the IDirectInputDevice7::GetDeviceData or the IDirectInputDevice7::GetDeviceState method, and attempt to reacquire the mouse if necessary. (See Acquiring Devices.)

Note You should not attempt to reacquire the mouse on getting a DIERR_NOTACQUIRED error. If you do, you could get caught in an infinite loop: acquisition would fail, you would get another DIERR_NOTACQUIRED error, and so on.

[Visual Basic]

Because Windows might force your application to unacquire the mouse when you have set the cooperative level to DISCL_FOREGROUND and the focus switches to another application, or even to the menu in your own application, you should check for the DIERR_INPUTLOST return value from the DirectInputDevice.GetDeviceData or the DirectInputDevice.GetDeviceStateMouse method, and attempt to reacquire the mouse if necessary. (See Acquiring Devices.)

Note You should not attempt to reacquire the mouse on getting a DIERR_NOTACQUIRED error. If you do, you could get caught in an infinite loop: acquisition would fail, you would get another DIERR_NOTACQUIRED error, and so on.


Keyboard Data

As far as DirectInput is concerned, the keyboard is not a text input device, but a game pad with many buttons. When your application requires text input, do not use DirectInput methods; it is far easier to retrieve the data from the normal Windows messages, in which you can take advantage of services such as character repeat and translation of physical keys to virtual keys. This is particularly important for languages other than English, which can require special translation of key presses.

[C++]

To set up the keyboard device for data retrieval, you must first call the IDirectInputDevice7::SetDataFormat method with the c_dfDIKeyboard global variable as the parameter. (See Device Data Formats.)

[Visual Basic]

To set up the keyboard device for data retrieval, you must first call the DirectInputDevice.SetCommonDataFormat method with DIFORMAT_KEYBOARD as the parameter.

The following sections give more information about obtaining and interpreting keyboard data:

  • Immediate Keyboard Data
  • Buffered Keyboard Data
  • Interpreting Keyboard Data
  • Checking for Lost Keyboard Input


Immediate Keyboard Data

[C++]

To retrieve the current state of the keyboard, call the IDirectInputDevice7::GetDeviceState method with a pointer to an array of 256 bytes to hold the returned data.

The GetDeviceState method behaves in the same way as the Win32 GetKeyboardState function, returning a snapshot of the current state of the keyboard. Each key is represented by a byte in the array of 256 bytes whose address was passed as the lpvData parameter. If the high bit of the byte is set, the key is down. The array is most conveniently indexed with the DirectInput Keyboard Device Constants. (See also Interpreting Keyboard Data.)

The following code example does something in response to the fact that the ESC key is down:

// LPDIRECTINPUTDEVICE  lpdiKeyboard;  // previously initialized
                                       // and acquired

BYTE  diKeys[256];
if (lpdiKeyboard->GetDeviceState(256, diKeys) == DI_OK)
{
  if (diKeys[DIK_ESCAPE] & 0x80) DoSomething();
}
[Visual Basic]

To retrieve the current state of the keyboard, call the DirectInputDevice.GetDeviceStateKeyboard method, passing a DIKEYBOARDSTATE type.

The GetDeviceState method returns a snapshot of the current state of the keyboard. Each key is represented by an element in the array of 256 bytes that makes up the DIKEYBOARDSTATE type. If the high bit of the byte is set, the key is down. The array is most conveniently indexed with the members of the CONST_DIKEYFLAGS enumeration. (See also Interpreting Keyboard Data.)

The following code example determines whether the ESC key is currently being pressed:

' objDIDev is a DirectInputDevice object.
Dim dev As DirectInputDevice
Dim KeyState As DIKEYBOARDSTATE

Call objDIDev.GetDeviceStateKeyboard(KeyState)
If (KeyState.Key(DIK_ESCAPE) And &H80) Then
    ' Key is down.
End If


Buffered Keyboard Data

To retrieve buffered data from the keyboard, you must first set the buffer size (see Device Properties). This step is essential because the default size of the buffer is 0.

[C++]

You must also declare an array of DIDEVICEOBJECTDATA structures. This array can have up to the same number of elements as the buffer size. You do not have to retrieve the entire contents of the buffer with a single call; if you want, you can have just one element in the array and retrieve events one at a time until the buffer is empty.

After acquiring the keyboard device, you can examine and flush the buffer at any time by using the IDirectInputDevice7::GetDeviceData method. (See Buffered and Immediate Data.)

Each element in the DIDEVICEOBJECTDATA array represents a change in state for a single key; that is, a press or release. Because DirectInput gets the data directly from the keyboard, any settings for character repeat in Control Panel are ignored. This means that a keystroke is counted only once, no matter how long the key is held down.

You can determine which key an element in the array refers to by checking the dwOfs member of the DIDEVICEOBJECTDATA structure against the DirectInput Keyboard Device Constants. (See also Interpreting Keyboard Data.)

The data for the change of state of the key is located in the dwData member of the DIDEVICEOBJECTDATA structure. Only the low byte of dwData is significant; the high bit of this byte is set if the key was pressed and clear if it was released. In other words, the key was pressed if (dwData & 0x80) is nonzero.

[Visual Basic]

You must also declare an array of DIDEVICEOBJECTDATA types. This array can have up to the same number of elements as the buffer size. You do not have to retrieve the entire contents of the buffer with a single call; if you want, you can have just one element in the array and retrieve events one at a time until the buffer is empty.

After acquiring the keyboard device, you can examine and flush the buffer at any time by using the DirectInputDevice.GetDeviceData method. (See Buffered and Immediate Data.)

Each element in the DIDEVICEOBJECTDATA array represents a change in state for a single key; that is, a press or release. Because DirectInput gets the data directly from the keyboard, any settings for character repeat in Control Panel are ignored. This means that a keystroke is counted only once, no matter how long the key is held down.

You can determine which key an element in the array refers to by checking the lOfs member of the DIDEVICEOBJECTDATA type against the constants in the CONST_DIKEYFLAGS enumeration. (See also Interpreting Keyboard Data.)

The data for the change of state of the key is located in the lData member of the DIDEVICEOBJECTDATA type. Only the low byte of lData is significant; the high bit of this byte is set if the key was pressed and clear if it was released. In other words, the key was pressed if (lData And &H80) is nonzero.


Interpreting Keyboard Data

[C++]

This section covers the identification of keys for which data is reported by the IDirectInputDevice7::GetDeviceState and IDirectInputDevice7::GetDeviceData methods. For more information on interpreting the data from GetDeviceData, see Time Stamps and Sequence Numbers.

[Visual Basic]

This section covers the identification of keys for which data is reported by the DirectInputDevice.GetDeviceState and DirectInputDevice.GetDeviceData methods. For more information on interpreting the data from GetDeviceData, see Time Stamps and Sequence Numbers.

In one important respect, DirectInput differs from other ways of reading the keyboard in Windows. Keyboard data refers not to virtual keys but to the actual physical keys—that is, the scan codes. DIK_ENTER, for example, refers to the ENTER key on the main keyboard, but not to the one on the numerical keypad.

DirectInput defines a constant for each key on the enhanced keyboard, as well as the additional keys found on international keyboards. Because NEC keyboards support different scan codes than the PC-enhanced keyboards, DirectInput translates NEC key scan codes into PC-enhanced scan codes where possible.

Not all PC-enhanced keyboards have the Windows keys (DIK_LWIN, DIK_RWIN, and DIK_APPS). There is no way to determine whether the keys are physically available.

Laptops and other small computers often do not implement a full set of keys. Instead, some keys (typically numeric keypad keys) are multiplexed with other keys, selected by an auxiliary mode key, which does not generate a separate scan code.

If the keyboard subtype indicates a PC XT or PC AT keyboard, the following keys are not available: DIK_F11, DIK_F12, and all the extended keys (DIK_* values greater than 0x7F). Furthermore, the PC XT keyboard lacks DIK_SYSRQ.

Japanese keyboards, particularly the NEC PC-98 keyboards, contain a substantially different set of keys than U.S. keyboards. For more information, see DirectInput and Japanese Keyboards.


Checking for Lost Keyboard Input

[C++]

Because Windows might force your application to unacquire the keyboard when you have set the cooperative level to DISCL_FOREGROUND and the focus switches to another application, you should check for the DIERR_INPUTLOST return value from the IDirectInputDevice7::GetDeviceData or IDirectInputDevice7::GetDeviceState methods and attempt to reacquire the keyboard, if necessary. (See Acquiring Devices.)

Note You should not attempt to reacquire the keyboard on getting a DIERR_NOTACQUIRED error. If you do, you could get caught in an infinite loop: acquisition would fail, you would get another DIERR_NOTACQUIRED error, and so on.

[Visual Basic]

Because Windows might force your application to unacquire the keyboard when you have set the cooperative level to DISCL_FOREGROUND and the focus switches to another application, you should check for the DIERR_INPUTLOST return value from the DirectInputDevice.GetDeviceData or the DirectInputDevice.GetDeviceStateKeyboard method and attempt to reacquire the keyboard, if necessary. (See Acquiring Devices.)

Note You should not attempt to reacquire the keyboard on getting a DIERR_NOTACQUIRED error. If you do, you could get caught in an infinite loop: acquisition would fail, you would get another DIERR_NOTACQUIRED error, and so on.


Joystick Data

[C++]

To set up the joystick device for data retrieval, first call the IDirectInputDevice7::SetDataFormat method with the c_dfDIJoystick or the c_dfDIJoystick2 global variable as the parameter value. (See Device Data Formats.)

Because some device drivers do not notify DirectInput of changes in state until explicitly asked to do so, you should always call the IDirectInputDevice7::Poll method before attempting to retrieve data from the joystick. For more information, see Polling and Events.

[Visual Basic]

To set up the joystick device for data retrieval, first call the DirectInputDevice.SetCommonDataFormat method with DIFORMAT_JOYSTICK or DIFORMAT_JOYSTICK2 as the parameter value. (See Device Data Formats.)

Because some device drivers do not notify DirectInput of changes in state until explicitly asked to do so, you should always call the DirectInputDevice.Poll method before attempting to retrieve data from the joystick. For more information, see Polling and Events.

The following sections cover getting and interpreting data from a joystick or other similar input device, such as a game pad or steering wheel:

  • Immediate Joystick Data
  • Buffered Joystick Data
  • Interpreting Joystick Axis Data
  • Checking for Lost Joystick Input


Immediate Joystick Data

[C++]

To retrieve the current state of the joystick, call the IDirectInputDevice7::GetDeviceState method with a pointer to a DIJOYSTATE or a DIJOYSTATE2 structure, depending on whether the data format was set with c_dfDIJoystick or c_dfDIJoystick2. (See Device Data Formats.) The joystick state returned in the structure includes the coordinates of the axes, the state of the buttons, and the state of the point-of-view controllers.

The first seven members of the DIJOYSTATE structure hold the axis coordinates. The last of these seven, rglSlider, is an array of two values. (See Interpreting Joystick Axis Data.)

The rgdwPOV member contains the position of up to four point-of-view controllers in hundredths of a degree clockwise from north (or forward). The center position is reported as –1. For controllers that have only five positions, the position is one of the following values:

  • –1
  • 0
  • 90 * DI_DEGREES
  • 180 * DI_DEGREES
  • 270 * DI_DEGREES.

Some drivers report a value of 65,535, instead of –1, for the neutral position. You should check for a centered POV indicator as follows:

BOOL POVCentered = (LOWORD(dwPOV) == 0xFFFF);

The rgbButtons member is an array of bytes, one for each of 32 or 128 buttons, depending on the data format. For each button, the high bit is set if the button is down, and clear if the button is up or not present.

The DIJOYSTATE2 structure has additional members for information about the velocity, acceleration, force, and torque of the axes.

[Visual Basic]

To retrieve the current state of the joystick, call the DirectInputDevice.GetDeviceStateJoystick or the DirectInputDevice.GetDeviceStateJoystick2 method, depending on whether the data format was set with DIFORMAT_JOYSTICK or DIFORMAT_JOYSTICK2. (See Device Data Formats.) The joystick state returned in the state parameter includes the coordinates of the axes, the state of the buttons, and the state of the point-of-view controllers.

The POV member of the DIJOYSTATE or the DIJOYSTATE2 type contains the position of up to four point-of-view controllers in hundredths of a degree clockwise from north (or forward). The center position is reported as –1. For controllers that have only five positions, the position is one of the following values:

  • –1
  • 0
  • 9000
  • 18000
  • 27000

Some drivers report a value of 65,535, instead of –1, for the neutral position. You should check for a centered POV indicator as follows:

Dim POVCentered As Boolean
POVCentered = (dwPOV And &HFFFF) = &HFFFF;

The buttons member is an array of bytes, one for each of 32 or 128 buttons, depending on the data type. For each button, the high bit is set if the button is down, and clear if the button is up or not present.

The DIJOYSTATE2 type has additional members for information about the velocity, acceleration, force, and torque of the axes.

For more information, see Interpreting Joystick Axis Data.

See also

Buffered and Immediate Data


Buffered Joystick Data

[C++]

To retrieve buffered data from the joystick, first set the buffer size (see Device Properties), and declare an array of DIDEVICEOBJECTDATA structures. This array can have up to the same number of elements as the buffer size. You do not have to retrieve the entire contents of the buffer with a single call; if you want, you can have just one element in the array and retrieve events one at a time until the buffer is empty.

After acquiring the device, you can examine and flush the buffer at any time with the IDirectInputDevice7::GetDeviceData method. (See Buffered and Immediate Data.)

Each element in the DIDEVICEOBJECTDATA array represents a change in state for a single object on the joystick. For instance, if the user presses button 0 and moves the stick diagonally, the array passed to GetDeviceData (if it has at least three elements, and pdwInOut is at least 3) has three elements filled in—an element for button 0 being pressed, an element for the change in the x-axis, and an element for the change in the y-axis—and the value of pdwInOut is set to 3.

You can determine which object an element in the array refers to by checking the dwOfs member of the DIDEVICEOBJECTDATA structure against the following values:

  • DIJOFS_X
  • DIJOFS_Y
  • DIJOFS_Z
  • DIJOFS_Rx
  • DIJOFS_Ry
  • DIJOFS_Rz
  • DIJOFS_BUTTON0 to DIJOFS_BUTTON31 or DIJOFS_BUTTON(n)
  • DIJOFS_POV(n)
  • DIJOFS_SLIDER(n)

Each of these values is equivalent to the offset of the data for the object in a DIJOYSTATE structure. For example, DIJOFS_BUTTON0 is equivalent to the offset of rgbButtons[0] in the DIJOYSTATE structure. You can use simple comparisons to determine which device object is associated with an item in the buffer. For example:

DIDEVICEOBJECTDATA  *lpdidod;
int                 n;
.
.
.
/* JoyBuffer is an array of DIDEVICEOBJECTDATA structures
   that has been set by a call to GetDeviceData.
   n is incremented in a loop that examines all filled elements
   in the array. */
lpdidod = &JoyBuffer[n];
if (( (int) lpdidod->dwOfs == DIJOFS_BUTTON0)
   && (lpdidod->dwData & 0x80))
{
 ;  // Do something in response to press of primary button.
}

If the data format was set with c_dfDIJoystick2, you can use the predefined offsets for all the device objects that exist in DIJOYSTATE, but you must supply your own offsets for device objects represented in the extra members of DIJOYSTATE2.

The data for the change of state of the device object is located in the dwData member of the DIDEVICEOBJECTDATA structure. For axes, the coordinate value is returned in this member. For button objects, only the low byte of dwData is significant; the high bit of this byte is set if the button is pressed, and clear if the button is released.

For the other members, see Time Stamps and Sequence Numbers.

[Visual Basic]

To retrieve buffered data from the joystick, first set the buffer size (see Device Properties), and declare an array of DIDEVICEOBJECTDATA types. This array can have up to the same number of elements as the buffer size. You do not have to retrieve the entire contents of the buffer with a single call; if you want, you can have just one element in the array and retrieve events one at a time until the buffer is empty.

After acquiring the device, you can examine and flush the buffer at any time with the DirectInputDevice.GetDeviceData method. (See Buffered and Immediate Data.)

Each element in the DIDEVICEOBJECTDATA array represents a change in state for a single object on the joystick. For instance, if the user presses button 0 and moves the stick diagonally, the array passed to GetDeviceData (if it has at least three elements) has three elements filled in—an element for button 0 being pressed, an element for the change in the x-axis, and an element for the change in the y-axis—and the return value of the method is 3.

You can determine which object an element in the array refers to by checking the lOfs member of the DIDEVICEOBJECTDATA type against the constants of the CONST_DIJOYSTICKOFS enumeration. Each of these values is equivalent to the offset of the data for the object in a DIJOYSTATE type. For example, DIJOFS_BUTTON0 is equivalent to the offset of buttons(0) in the DIJOYSTATE type.

If the data format was set with DIFORMAT_JOYSTICK2, you can use the offset constants for all the device objects that exist in DIJOYSTATE, but you must supply your own offsets for device objects represented in the extra members of DIJOYSTATE2. The internal organization of this type is the same as that of the equivalent C++ structure in the Dinput.h header file.

The data for the change of state of the device object is located in the lData member of the DIDEVICEOBJECTDATA type. For axes, the coordinate value is returned in this member. For button objects, only the low byte of lData is significant; the high bit of this byte is set if the button is pressed, and clear if the button is released.

For the other members, see Time Stamps and Sequence Numbers.


Interpreting Joystick Axis Data

Axis values for the joystick are like those for the mouse: the value returned for the x-axis is greater as the stick moves to the right, and the value for the y-axis increases as the stick moves toward the user.

Data is in arbitrary units determined by the range property of the axis. For example, if the range for the stick's x-axis is from 0 through 10,000, a unit is one ten-thousandth of the stick's left-right travel, and the center position is 5,000. For some axes, the granularity property might be greater than 1, in which case values are rounded off. For example, if the granularity is 10, values are reported as 0, 10, 20, and so on.

Axis data is also affected by the dead zone, a region around the center position in which motion is ignored. The dead zone provides tolerance for a slight deviation from the true center position for either or both axes of the stick. An axis value within the range of the dead zone is reported as true center.

The saturation property of an axis is a zone of tolerance at the minimum and maximum of the range. An axis value within this zone is reported as the minimum or maximum value. The purpose of the saturation property is to allow for slight differences between, for example, the minimum x-axis value reported at the top left and bottom left positions of the stick.

The following illustration shows the effect of the dead zone and the saturation zones. The vertical axis represents the returned axis values, where min and max are the lower and upper limits of the reported range and ctr is the reported center. The horizontal axis shows the physical position of the stick, where pmin and pmax are the extremes of the physical range, pctr is neutral position of the axis, dmin and dmax are the limits of the dead zone, and smin and smax are the boundaries of the lower and upper saturation zones. The lower saturation zone lies between pmin and smin, the upper saturation zone lies between smax and pmax, and the dead zone lies between dmin and dmax.

[C++]

For more information on joystick properties, see the following:

  • IDirectInputDevice7::GetProperty
  • IDirectInputDevice7::SetProperty
  • DIPROPRANGE
[Visual Basic]

For more information on joystick properties, see the following:

  • DirectInputDevice.GetProperty
  • DirectInputDevice.SetProperty
  • DIPROPRANGE

Axis coordinates from the joystick can be either relative or absolute. (See Relative and Absolute Axis Coordinates.) Because a joystick is an absolute device–unlike a mouse, it cannot travel infinitely far along any axis–absolute data is returned by default. When the axis mode for the joystick is set to relative, the axis coordinate represents the number of units of movement along the axis since the last value was returned.

[C++]

The axis mode, which specifies whether relative or absolute data should be returned, is a property that can be changed before the device is acquired. (See Device Properties.) To set the axis mode to relative, call the IDirectInputDevice7::SetProperty method with the DIPROP_AXISMODE value in the rguidProp parameter and with DIPROPAXISMODE_REL in the dwData member of the DIPROPDWORD structure.

[Visual Basic]

The axis mode, which specifies whether relative or absolute data should be returned, is a property that can be changed before the device is acquired. (See Device Properties.) To set the axis mode to absolute, call DirectInputDevice.SetProperty with "DIPROP_AXISMODE" in the guid parameter and with DIPROPAXISMODE_ABS in the lData member of the DIPROPLONG type.


Checking for Lost Joystick Input

If you are using the joystick in foreground mode (see Cooperative Levels), you might lose the device when the focus shifts to another application.

[C++]

You should check for the DIERR_INPUTLOST return value from the IDirectInputDevice7::GetDeviceData or the IDirectInputDevice7::GetDeviceState method and attempt to reacquire the joystick, if necessary. (See Acquiring Devices.)

Note You should not attempt to reacquire the joystick on getting a DIERR_NOTACQUIRED error. If you do, you could get caught in an infinite loop: acquisition would fail, you would get another DIERR_NOTACQUIRED error, and so on.

Because access to the joystick is not lost except when your application moves to the background—unlike the mouse and keyboard, the joystick is never used by the Windows system—an alternative method is to reacquire the device in response to a WM_ACTIVATE message.

[Visual Basic]

You should check for the DIERR_INPUTLOST return value from the DirectInputDevice.GetDeviceData or the DirectInputDevice.GetDeviceStateKeyboard method and attempt to reacquire the keyboard, if necessary. (See Acquiring Devices.)

Note You should not attempt to reacquire the keyboard on getting a DIERR_NOTACQUIRED error. If you do, you could get caught in an infinite loop: acquisition would fail, you would get another DIERR_NOTACQUIRED error, and so on.


Output Data

[C++]

Human Interface Devices can accept output, as well as generating input. The IDirectInputDevice7::SendDeviceData method is used to send packets of data to such devices.

SendDeviceData can be viewed as IDirectInputDevice7::GetDeviceData in reverse. Like that method, it uses the DIDEVICEOBJECTDATA structure as the basic unit of data. In this case, however, the dwOfs member contains the instance ID of the device object associated with the data, rather than its offset in the data format for the device. (Because offset identifiers exist only for device objects that provide input in the selected data format, an object that accepts only output might not even have an offset.) The dwData member contains whatever data is appropriate for the object. The dwTimeStamp and dwSequence members are not used and must be set to 0.

To send data to the device, first set up an array of DIDEVICEOBJECTDATA structures, fill the required number of elements with data, and then pass its address and the number of elements used to SendDeviceData. Data for different device objects is combined into a single packet that is then sent to the device.

The form of the data packet is specific to the device, as is the treatment of unused fields in the packet. Some devices treat fields as optional, meaning that if no data is supplied, the state of the object remains unchanged. More commonly, all fields are significant, even when you do not specifically supply data for them. For example, if you send data to a single keyboard LED, it is assumed that the data for the other two LEDs is 0, and they are turned off. However, you can override this behavior by using the DISDD_CONTINUE flag, in which case the data for the other two LEDs is the value you most recently sent them.

The following code example, when run repeatedly, causes the LEDs on the keyboard, as represented by the IDirectInputDevice7 interface pdev, to flash in a recurring pattern. The device object identifiers, NumLockID, CapsLockID, and ScrollLockID, have previously been obtained from the dwType member of the DIDEVICEOBJECTINSTANCE structure, either during enumeration of device objects or by calling IDirectInputDevice7::GetObjectInfo. It is assumed that the high bit of the data byte determines the state of the LED.

void FlashLEDs(void)
    {
    static int         rgiBits[] = { 1, 2, 4, 2 };
    static int         iLooper = 0;
    DWORD              cdod = 3;                  // Number of items
    DIDEVICEOBJECTDATA rgdod[3];
    HRESULT            hres;

    // Must clear dwTimeStamp and dwSequence
    ZeroMemory(rgdod, sizeof(rgdod));

    rgdod[0].dwOfs = NumLockID;
    rgdod[1].dwOfs = CapsLockID
    rgdod[2].dwOfs = ScrollLockID;

    rgdod[0].dwData = (rgiBits[iLooper] & 1) ? 0x80 : 0;
                                           // 1,0,0,0,...
    rgdod[1].dwData = (rgiBits[iLooper] & 2) ? 0x80 : 0;
                                           // 0,1,0,1,...
    rgdod[2].dwData = (rgiBits[iLooper] & 4) ? 0x80 : 0;
                                           // 0,0,1,0,...

    iLooper = (iLooper + 1) % ARRAYSIZE(rgiBits); // Loops from 0 to 3

    hres = IDirectInputDevice7_SendDeviceData(pdev,
            sizeof(DIDEVICEOBJECTDATA),
            rgdod, &cdod, 0);
    }
[Visual Basic]

Human Interface Devices can accept output, as well as generating input. The DirectInputDevice.SendDeviceData method is used to send packets of data to such devices.

SendDeviceData can be viewed as DirectInputDevice.GetDeviceData in reverse. Like that method, it uses the DIDEVICEOBJECTDATA type as the basic unit of data. In this case, however, the lOfs member contains the instance ID of the device object associated with the data, rather than its offset in the data format for the device. This ID can be extracted from the value returned by DirectInputDeviceObjectInstance.GetType after device objects have been enumerated. (Because offset identifiers exist only for device objects that provide input in the selected data format, an object that accepts only output might not even have an offset.) The lData member contains whatever data is appropriate for the object. The lTimeStamp and lSequence members are not used and must be set to 0.

To send data to the device, first set up an array of DIDEVICEOBJECTDATA types, fill the required number of elements with data, and then pass its address and the number of elements used to SendDeviceData. Data for different device objects is combined into a single packet that is then sent to the device.

The form of the data packet is specific to the device, as is the treatment of unused fields in the packet. Some devices treat fields as optional, meaning that if no data is supplied, the state of the object remains unchanged. More commonly, all fields are significant, even when you do not specifically supply data for them. For example, if you send data to a single keyboard LED, it is assumed that the data for the other two LEDs is 0, and they are turned off. However, you can override this behavior by using the DISDD_CONTINUE flag, in which case the data for the other two LEDs is the value you most recently sent them.


Force Feedback

Force feedback is the generation of push or resistance in an input/output device, for example by motors mounted in the base of a joystick. DirectInput allows you to generate force-feedback effects for devices that have compatible drivers.

The following sections introduce the elements of force feedback:

  • Basic Concepts of Force Feedback
  • Effect Enumeration
  • Loading Effects from a File
  • Information About a Supported Effect
  • Creating an Effect
  • Effect Direction
  • Envelopes and Offsets
  • Effect Playback
  • Downloading and Unloading Effects
  • Changing an Effect
  • Gain
  • Force-Feedback State
  • Effect Object Enumeration
  • Effect Types


Basic Concepts of Force Feedback

A particular instance of force feedback is called an effect, and the push or resistance is called the force. Most effects fall into one of the following categories:

  • Constant force. A steady force in a single direction.
  • Ramp force. A force that steadily increases or decreases in magnitude.
  • Periodic effect. A force that pulsates according to a defined wave pattern.
  • Condition. A force that occurs only in response to input by the user. Two examples are a friction effect that generates resistance to movement of the joystick, and a spring effect that tends to move the stick back to a certain position after it has been moved from that position.

The strength of the force is called its magnitude. Magnitude is measured in units ranging from 0 (no force) through 10,000 (maximum force for the device, defined for C/C++ in Dinput.h as DI_FFNOMINALMAX). A negative value indicates force in the opposite direction. Magnitudes are linear: a force of 10,000 is twice as great as one of 5,000.

Ramp forces have a beginning and ending magnitude. For a periodic effect, the basic magnitude is the force at the peak of the wave.

The direction of a force is the direction from which it comes; a positive force on a given axis pushes from the positive toward the negative.

Effects also have duration, measured in microseconds. Periodic effects have a period, or the duration of one cycle, also measured in microseconds. The phase of a periodic effect is the point along the wave at which playback begins.

The following illustration represents a sawtooth periodic effect with a magnitude of 5,000, or half the maximum force for the device. The horizontal axis represents the duration of the effect, and the vertical axis represents the magnitude. Points above the center line represent positive force in the direction defined for the effect, and points below the center line represent negative force, or force in the opposite direction.

A force can be further shaped by an envelope. An envelope defines an attack value and a fade value, which modify the beginning and ending magnitude of the effect. Attack and fade also have duration, which determines how long the magnitude takes to reach or fall away from the sustain value, the magnitude in the middle portion of the effect.

The following illustration shows an envelope. The attack level is set to 8,000, and the fade level to 1,000. The sustain level is defined by the basic magnitude of the force to which the envelope is being applied; in the example, it is 5,000. In this case, the attack is greater than the sustain, giving the effect an initial strong kick. Both the attack and the fade level can be either greater or less than the sustain level.

The following illustration shows the result of the envelope being applied to the periodic effect in the first illustration. The envelope is mirrored on the negative side of the magnitude. An attack value of 8,000 means that the initial magnitude of the force in either direction is 80 percent of the maximum possible.

Periodic effects and conditions can also be modified by the addition of an offset, which defines the amount by which the waveform is shifted up or down from the base level. The practical effect of applying a positive offset to the sawtooth example would be to strengthen the positive force and weaken the negative one—in other words, the force would peak more strongly in one direction than in the other.

Finally, the overall magnitude of an effect can be scaled by gain, which is analogous to a volume control in audio. A single gain value can be applied to all effects for a device; you might want to do this to compensate for stronger or weaker forces on different hardware or to accommodate the user's preferences.


Effect Enumeration

[C++]

The IDirectInputDevice7::EnumEffects method returns information about the support offered by the device for various kinds of effects.

It is important to distinguish between supported effects and created effects, or effect objects. A supported effect might be a constant force that can be shaped by an envelope. However, this effect has no properties such as magnitude, direction, duration, attack, or fade. You set these properties when you create an effect object in your application. A supported effect can be represented by many effect objects, each with different parameters—for example, several constant forces, each with different duration, magnitude, and direction.

For information on enumerating created effects, see Effect Object Enumeration.

Like other DirectInput enumerations, the IDirectInputDevice7::EnumEffects method requires a callback function; this is documented with the placeholder name DIEnumEffectsCallback, but you can use a different name if you want. This function is called for each effect enumerated. Within the function, you can obtain the GUID for each effect, get information about the extent of hardware support, and create one or more effect objects whose methods you can use to manipulate the effect.

The following code example calls the IDirectInputDevice7::EnumEffects method that sets the enumeration in motion. The pvRef parameter of the callback can be any 32-bit value; in this case, it is a pointer to the device interface, used for getting information about effects supported by the device and for creating effect objects.

HRESULT  hr;
// LPDIRECTINPUTDEVICE lpdid2;   // already initialized

BOOL CALLBACK DIEnumEffectsCallback(LPCDIEFFECTINFO pdei,
                                LPVOID pvRef)
{
    LPDIRECTINPUTDEVICE2 lpdid = pvRef;   // Pointer to calling device
    LPDIRECTINPUTEFFECT  lpdiEffect;      // Pointer to created effect
    DIEFFECT             diEffect;        // Params for created effect
    DICONSTANTFORCE      diConstantForce; // Type-specific parameters
                                          // for diEffect

    if (DIEF_GETTYPE(pdei->dwEffType) == DIEFFT_CONSTANTFORCE)
    {
       /* Here you can extract information about support for the
          effect type (from pdei), and tailor your effects
          accordingly. For example, the device might not support
          envelopes for this type of effect. */
       .
       .
       .
       // Create one or more constant force effects.
       // For each, you have to initialize a DICONSTANTFORCE
       // and a DIEFFECT structure.
       // See detailed example at Creating an Effect.
       .
       .
       .
        hr = pdid->CreateEffect(pdei->guid,
                                &diEffect,
                                &lpdiEffect,
                                NULL);
       .
       .
       .
    }
    // And so on for other types of effect
   .
   .
   .

    return DIENUM_CONTINUE;
}  // End of callback
.
.
.
// Set the callback in motion.
hr = lpdid2->EnumEffects(&EnumEffectsCallback,
                        lpdid2, DIEFT_ALL);

For more information on how to initialize an effect, see Creating an Effect.

[Visual Basic]

The DirectInputDevice.GetEffectsEnum method enumerates effects supported by the device. It returns a DirectInputEnumEffects object representing the collection of supported effects. Methods of DirectInputEnumEffects can be used to get information about a particular effect.

It is important to distinguish between supported effects and created effects, or effect objects. A supported effect might be a constant force that can be shaped by an envelope. However, this effect has no properties such as magnitude, direction, duration, attack, or fade. You set these properties when you create an effect object in your application. A supported effect can be represented by many effect objects, each with different parameters—for example, several constant forces, each with different duration, magnitude, and direction.

The following code example shows how an application could enumerate hardware-specific effects, looking for a particular one supported by the Microsoft® SideWinder® joystick. If the desired effect is not found, the application substitutes one of the standard effects:

Const BasketballDribble = _
        "{E84CD1AC-81FA-11D0-94AB-0080C74C7E95}"
Dim diEnumEffects as DirectInputEnumEffects
Dim EffGuid As String
Dim i as Integer

' diDev is a DirectInputDevice object.
Set diEnumEffects = didev.GetEffectsEnum(DIEFT_HARDWARE)
For i = 1 To diEnumEffects.GetCount
  If diEnumEffects.GetEffectGuid(i) = BasketballDribble Then
    EffGuid = BasketballDribble
    Exit For
  End If
Next i
If EffGuid <> BasketballDribble Then
  EffGuid = "GUID_Sine"
  ' Set parameters for emulated dribble here
End If

' Ultimately pass EffGuid to DirectInputDevice.CreateEffect.


Loading Effects from a File

[Visual Basic]

This topic pertains only to applications developed in C++. DirectX for Visual Basic does not support effect files.

[C++]

Using the Force Editor supplied with the DirectX SDK, or another application that uses the same file format, you can design effects and save them in a file. You can then use these effects in any application by loading them at run time.

To load effects, call the IDirectInputDevice7::EnumEffectsInFile method. By default, the enumeration is limited to the standard DirectInput effects, but you can enumerate other effects by setting the DIFEF_INCLUDENONSTANDARD flag. By setting the DIFEF_MODIFYIFNEEDED flag, you can also instruct DirectInput to modify the parameters of effects, if necessary, so that they work on the device. (For example, an effect authored for two axes can be made to work on a single-axis steering wheel.)

In the following code example, the first three standard effects are loaded from a file and created as DirectInputEffect objects.

// g_lpdid7 is a valid IDirectInputDevice7 pointer to a
// force feedback device.

// The array of effect pointers is declared globally.
LPDIRECTINPUTEFFECT pEff[3];
.
.
.
g_lpdid7->EnumEffectsInFile("FEdit1.ffe", EnumEffectsInFileProc,
        NULL, DIFEF_MODIFYIFNEEDED);
.
.
.

The following callback procedure is called once for each effect in the file or until it returns DIENUM_STOP.

BOOL CALLBACK EnumEffectsInFileProc(LPCDIFILEEFFECT lpdife,
        LPVOID pvRef)

    {
    HRESULT     hr;
    static int  i;

// Because the DIFEF_MODIFYIFNEEDED flag was passed, the
// effect parameters might be modified in lpdife->lpDiEffect.

    hr = g_lpdid7->CreateEffect(lpdife->GuidEffect,
            lpdife->lpDiEffect,
            &pEff[i], NULL);
    if (FAILED(hr))
        {
        // Error handling
        }
    if (++i > 2) return DIENUM_STOP;
    else return DIENUM_CONTINUE;
    }


Information About a Supported Effect

[C++]

The IDirectInputDevice7::GetEffectInfo method can be used to retrieve information about the device's support for an effect whose GUID is known. It retrieves the same information that is returned in the DIEFFECTINFO structure during enumeration. For more information, see Effect Enumeration.

The following code example fetches information about an effect whose GUID is stored in the EffectGuid variable and determines whether the direction of the effect can be changed without stopping and restarting it:

DIEFFECTINFO diEffectInfo;
diEffectInfo.dwSize = sizeof(DIEFFECTINFO);
lpdid2->GetEffectInfo(&diEffectInfo, EffectGuid);
if (diEffectInfo.dwDynamicParams & DIEP_DIRECTION)
{
  // Can reset parameter dynamically
}
[Visual Basic]

In DirectX for Visual Basic, information about a supported effect must be obtained from the DirectInputEnumEffects enumeration object. See Effect Enumeration.

The following code example gets information about the first enumerated effect and determines whether the direction of the effect can be changed without stopping and restarting it:

' diEnumEffects is an initialized DirectInputEnumEffects object.
Dim params As Long
params = diEnumEffects.GetDynamicParams(1)
If params And DIEP_DIRECTION Then
  Debug.Print "Direction is dynamic."
End If


Creating an Effect

[C++]

Create an effect object by using the IDirectInputDevice7::CreateEffect method, as in the following code example, where pdev2 points to an instance of the interface. This example creates a very simple effect that pulls the joystick away from the user at full force for half a second.

HRESULT  hr;
LPDIRECTINPUTEFFECT lpdiEffect;  // receives pointer to created effect
DIEFFECT diEffect;               // parameters for created effect

DWORD    dwAxes[2] = { DIJOFS_X, DIJOFS_Y };
LONG     lDirection[2] = { 18000, 0 };

DICONSTANTFORCE diConstantForce;

diConstantForce.lMagnitude = DI_FFNOMINALMAX;   // Full force

diEffect.dwSize = sizeof(DIEFFECT);
diEffect.dwFlags = DIEFF_POLAR | DIEFF_OBJECTOFFSETS;
diEffect.dwDuration = 0.5 * DI_SECONDS;
diEffect.dwSamplePeriod = 0;               // = default
diEffect.dwGain = DI_FFNOMINALMAX;         // No scaling
diEffect.dwTriggerButton = DIEB_NOTRIGGER; // Not a button response
diEffect.dwTriggerRepeatInterval = 0;      // Not applicable
diEffect.cAxes = 2;
diEffect.rgdwAxes = &dwAxes;
diEffect.rglDirection = &lDirection;
diEffect.lpEnvelope = NULL;
diEffect.cbTypeSpecificParams = sizeof(DICONSTANTFORCE);
diEffect.lpvTypeSpecificParams = &diConstantForce;

hr = pdev2->CreateEffect(GUID_ConstantForce,
                         &diEffect,
                         &lpdiEffect,
                         NULL);

In the method call, the first parameter identifies the supported effect with which the created effect is to be associated. The example uses one of the predefined GUIDs found in Dinput.h. If you use a predefined GUID, the call fails if the device does not support the effect.

The second parameter sets the parameters as specified in the DIEFFECT structure.

The third parameter receives a pointer to the effect object if the call is successful.

The DIEFF_POLAR flag specifies the type of coordinates used for the direction of the force. (See Effect Direction.) It is combined with DIEFF_OBJECTOFFSETS, which indicates that any buttons or axes used in other members are identified by their offsets within the DIDATAFORMAT structure for the device. The alternative is to use the DIEFF_OBJECTIDS flag, signifying that buttons and axes are identified by the dwType member of the DIDEVICEOBJECTINSTANCE structure returned for the object when it was enumerated with the IDirectInputDevice7::EnumObjects method.

For more information on the members of the DIEFFECT structure, see Effect Direction.

[Visual Basic]

You create an effect object by using the DirectInputDevice.CreateEffect method, as in the following code example, where didev is a DirectInputDevice object. This example creates a very simple effect that pulls the joystick away from the user at full force for half a second.

Dim effectInfo As DIEFFECT
Dim objDIEffect As DirectInputEffect

With effectInfo

  .constantForce.lMagnitude = 10000
  .lGain = 10000
  .lDuration = 500000
  .x = 18000
  .lTriggerButton = -1  ' No trigger button
End With

didev.Acquire
Set objDIEffect = didev.CreateEffect("GUID_ConstantForce", effectInfo)

The first parameter can be one of the predefined GUID aliases, or an actual GUID in string form known from hardware documentation or retrieved for an enumerated effect by using the DirectInputEnumEffects.GetEffectGuid method.

The relevant members of the DIEFFECT type vary according to the kind of effect. Constant forces are the simplest kind, requiring only a single type-specific parameter. The lGain, lDuration, and lTriggerButton members should be set for all effects, since the default values of 0 are not usually suitable.

By default, the direction of the effect is expressed in polar coordinates, meaning that DIEFFECT.x holds the direction from which the force comes, in hundredths of a degree, and DIEFFECT.y must be 0.

Effects are automatically downloaded to the device when created, provided the device is not full and is acquired at the exclusive cooperative level.


Effect Direction

[C++]

Directions can be defined for one or more axes. As with the mouse and joystick, the x-axis increases from left to right, and the y-axis increases from far to near. For three-dimensional devices, the z-axis increases from up to down.

The direction of an effect is the direction from which it comes. An effect with a direction along the negative y-axis tends to push the stick along the positive y-axis (toward the user). It is somewhat easier to visualize the axis values of a direction if you imagine the user exerting a counteracting force on the device. If the user must push the stick toward the left to counteract an effect, the effect has a left direction; that is, it lies on the negative x-axis.

Direction can be expressed in polar, spherical, or Cartesian coordinates.

Polar coordinates are expressed as a single angle, in hundredths of a degree clockwise from whatever zero-point, or true north, has been established for the effect. Normally this is the negative y-axis; that is, away from the user. Thus an effect with a polar coordinate of 9,000 normally has a direction of east, or to the user's right, and the user must exert force to the right to counteract it.

Spherical coordinates are also in hundredths of a degree, but can contain two or more angles; for each angle, the direction is rotated in the positive direction of the next axis. For a 3-D device, the first angle would normally be rotated from the positive x-axis toward the positive y-axis (clockwise from east), and the second angle would be rotated toward the positive z-axis (down). Thus a force with a direction of (0, 0) would be to the user's right and parallel to the tabletop. A direction of 27,000 for the first angle and 4,500 for the second would be directly away from the user (270 degrees clockwise from east) and angling toward the floor (45 degrees downward from the tabletop); to counteract a force with this direction, the user would have to push forward and down.

Cartesian coordinates are similar to 3-D vectors. If you draw a straight line on graph paper with an origin of (0, 0) at the center of the page, the direction of the line can be defined by the coordinates of any intersection that it crosses, regardless of the distance from the origin. A direction of (1, –2) and a direction of (5, –10) are exactly the same.

Note The coordinates used in creating force-feedback effects define only direction, not magnitude or distance.

When an effect is created or modified, the cAxes, rgdwAxes, and rglDirection members of the DIEFFECT structure are used to specify the direction of the force.

The cAxes member specifies the number of elements in the arrays pointed to by the next two members.

The array pointed to by rgdwAxes identifies the axes. If the DIEFF_OBJECTOFFSETS flag has been set, the axes are identified by the offsets within the data format structure. These offsets are most readily identified by using the DIJOFS_* defines. (For a list of these values, see Joystick Device Constants.)

Finally, the rglDirection member specifies the direction of the force.

Note The cAxes and rgdwAxes members cannot be modified once they have been set. An effect always has the same axis list.

Regardless of whether you are using Cartesian, polar, or spherical coordinates, you must provide exactly as many elements in rglDirection as there are axes in the array pointed to by rgdwAxes.

In the polar coordinate system, north (0 degrees) lies along the vector (0, –1), where the elements of the vector correspond to the elements in the axis list pointed to by rgdwAxes. Normally those axes are x and y, so north is directly along the negative y-axis; that is, away from the user. The last element of rglDirection must be 0.

In the example in Creating an Effect, the direction of a two-dimensional force is defined in polar coordinates. The force has a south direction—it comes from the direction of the user, so the user has to pull the stick to counteract it. The direction is 180 degrees clockwise from north, and can be assigned as follows:

LONG  lDirection[2] = { 18000, 0 };

For greater clarity, the assignment could also be expressed as follows:

LONG  lDirection[2] = { 180 * DI_DEGREES, 0 };

For spherical coordinates, presuming that you are working with a three-axis device, the same direction is assigned as follows:

LONG  lDirection[3] = { 90 * DI_DEGREES, 0, 0 }

In the DIEFFECT structure, the first angle is measured in hundredths of a degree from the (1, 0) direction, rotated in the direction of (0, 1); the second angle is measured in hundredths of a degree toward (0, 0, 1). The elements of the vector notation again correspond to elements in the array pointed to by the rgdwAxes member. Assume that the elements of this array represent the x, y, and z axes, in that order. The point of origin is at x = 1 and y = 0; that is, to the user's right. The direction of rotation is toward the positive y-axis (0, 1); that is, toward the user, or clockwise. The force in the example is 90 degrees clockwise from the right; that is, south. Because the second element of lDirection is 0, there is no rotation on the third axis.

How do you accomplish the same thing with Cartesian coordinates? Presuming that you have used the DIEFF_CARTESIAN flag in the dwFlags member, you would specify the direction as follows:

LONG     lDirection[2] = { 0, 1 };

Here again, the elements of the array correspond to the axes listed in the array pointed to by rgdwAxes. The example sets the x-axis to 0 and the y-axis to 1; that is, the direction lies directly along the positive y-axis, or to the south.

The theory of effect directions can be difficult to grasp, but the practice is fairly straightforward. For code examples, see Examples of Setting Effect Direction.

[Visual Basic]

DirectX for Visual Basic supports two-axis effects on the x-axis and y-axis.

The direction of an effect is the direction from which it comes. An effect with a direction along the negative y-axis tends to push the stick along the positive y-axis (toward the user). It is somewhat easier to visualize the axis values of a direction if you imagine the user exerting a counteracting force on the device. If the user must push the stick toward the left in order to counteract an effect, the effect has a left direction; that is, it lies on the negative x-axis.

Direction can be expressed in polar or Cartesian coordinates. By default, polar coordinates are used, and the direction is specified in the x member of the DIEFFECT type, with y always 0. To use Cartesian coordinates, you must specify DIEFF_CARTESIAN in the lFlags member and supply values in both x and y.

Polar coordinates are expressed as a single angle, in hundredths of a degree clockwise from whatever zero-point, or true north, has been established for the effect. Normally, this is the negative y-axis; that is, away from the user. Thus an effect with a polar coordinate of 9,000 normally has a direction of east, or to the user's right, and the user must exert force to the right to counteract it.

Cartesian coordinates are similar to 3-D vectors and are most useful for matching a force to the user's orientation in a 3-D environment. If you draw a straight line on graph paper with an origin of (0, 0) at the center of the page, the direction of the line can be defined by the coordinates of any intersection that it crosses, regardless of the distance from the origin. A direction of (1, –2) and a direction of (5, –10) are exactly the same.

Note Cartesian coordinates used in creating force-feedback effects define only direction, not magnitude or distance.

The following code example reverses the direction of a force represented by the DirectInputEffect object dieff, which was created using the global DIEFFECT type effectinfo:

effectinfo.lFlags = DIEFF_CARTESIAN
effectinfo.X = effectinfo.X * -1
effectinfo.Y = effectinfo.Y * -1
Call dieff.SetParameters(effectinfo, DIEP_DIRECTION)

DirectX for Visual Basic does not support setting direction for conditions.


Examples of Setting Effect Direction

[Visual Basic]

This topic pertains only to applications developed in C++.

[C++]

Single-Axis Effects

Setting up the direction for a single-axis effect is extremely simple because there is really nothing to specify. Put the DIEFF_CARTESIAN flag in the dwFlags member of the DIEFFECT structure, and set rglDirection to point to a single LONG containing the value 0.

The following code example sets up the direction and axis parameters for an x-axis effect:

DIEFFECT eff;
LONG     lZero = 0;                        // No direction
DWORD    dwAxis = DIJOFS_X;                // X-axis effect

ZeroMemory(&eff, sizeof(DIEFFECT));
eff.cAxes = 1;                             // One axis
eff.dwFlags =
    DIEFF_CARTESIAN | DIEFF_OBJECTOFFSETS; // Flags
eff.rglDirection = &lZero;                 // Direction
eff.rgdwAxes = &dwAxis;                    // Axis for effect

Two-Axis Effects with Polar Coordinates

Setting up the direction for a polar two-axis effect is only a little more complicated. Set the DIEFF_POLAR flag in dwFlags, and set rglDirection to point to an array of two LONGs. The first element in this array is the direction from which you want the effect to come. The second element in the array must be 0.

The following code example sets up the direction and axis parameters for a two-axis effect coming from the east:

DIEFFECT eff;
LONG     rglDirection = { 90 * DI_DEGREES, 0 }; // 90 degrees from
                                                // north, that is,   east
DWORD    rgdwAxes[2] = { DIJOFS_X, DIJOFS_Y };  // X- and y-axis

ZeroMemory(&eff, sizeof(DIEFFECT));
eff.cAxes = 2;                                  // Two axes
eff.dwFlags =
    DIEFF_POLAR | DIEFF_OBJECTOFFSETS;          // Flags
eff.rglDirection = rglDirection;                // Direction
eff.rgdwAxes = rgdwAxes;                        // Axis for effect

Two-Axis Effects with Cartesian Coordinates

Setting up the direction for a Cartesian two-axis effect is a little more complicated. Set the DIEFF_CARTESIAN flag in dwFlags, and again set rglDirection to point to an array of two LONGs. This time the first element in the array is the x-coordinate of the direction vector, and the second is the y-coordinate.

The following code example sets up the direction and axis parameters for a two-axis effect coming from the east:

DIEFFECT eff;
LONG     rglDirection = { 1, 0 };               // Positive x = east
DWORD    rgdwAxes[2] = { DIJOFS_X, DIJOFS_Y };  // X- and y-axis

ZeroMemory(&eff, sizeof(DIEFFECT));
eff.cAxes = 2;                                  // Two axes
eff.dwFlags =
    DIEFF_CARTESIAN | DIEFF_OBJECTOFFSETS;      // Flags
eff.rglDirection = rglDirection;                // Direction
eff.rgdwAxes = rgdwAxes;                        // Axis for effect


Envelopes and Offsets

You can modify the basic magnitude of some effects by applying an envelope and an offset. For an overview, see Basic Concepts of Force Feedback.

[C++]

To apply an envelope when creating or modifying an effect, initialize a DIENVELOPE structure, and put a pointer to it in the lpEnvelope member of the DIEFFECT structure.

The device driver determines which effects support envelopes. Typically, you can apply an envelope to a constant force, a ramp force, or a periodic effect, but not to a condition. To determine whether a particular effect supports an envelope, call the IDirectInputDevice7::GetEffectInfo method, and check for the DIEP_ENVELOPE flag in the dwStaticParams member of the DIEFFECTINFO structure.

To apply an offset, set the lOffset member of the DIPERIODIC or the DICONDITION structure pointed to by the lpvTypeSpecificParams member of the DIEFFECT structure. For periodic effects, the absolute value of the offset plus the magnitude of the effect must not exceed DI_FFNOMINALMAX.

You cannot apply an offset to a constant force or ramp force. In these cases, the same effect can be achieved by altering the magnitude.

[Visual Basic]

To apply an envelope when creating or modifying an effect, set the bUseEnvelope member of the DIEFFECT type to True, and initialize the envelope member, which is a DIENVELOPE type.

The device driver determines which effects support envelopes. Typically, you can apply an envelope to a constant force, a ramp force, or a periodic effect, but not to a condition. To determine whether a particular effect supports an envelope, call the DirectInputEnumEffects.GetStaticParams method, and check for the DIEP_ENVELOPE flag in the returned value.

To apply an offset, set the lOffset member of the DIPERIODICFORCE or the DICONDITION type used in the periodic or condition member of DIEFFECT. For periodic effects, the absolute value of the offset plus the magnitude of the effect must not exceed 10,000.

You cannot apply an offset to a constant force or ramp force. In these cases, the same effect can be achieved by altering the magnitude.


Effect Playback

[C++]

There are two principal ways to start playback of an effect: manually by a call to the IDirectInputEffect::Start method, or automatically in response to a button press. Playback also starts when you change an effect by calling the IDirectInputEffect::SetParameters method with the DIEP_START flag.

Passing INFINITE in the dwIterations parameter has the effect of playing the effect repeatedly, with the envelope being applied each time. If you want to repeat an effect without repeating the envelope—for example, to begin with a strong kick, then settle down to a steady throb—set dwIterations to 1, and set the dwDuration member of the DIEFFECT structure to INFINITE. (This is the structure passed to the IDirectInputDevice7::CreateEffect method.)

Note Some devices do not support multiple iterations of an effect and accept only the value 1 in the dwIterations parameter to the Start method. Always check the return value from Start to be sure the effect played successfully.

To associate an effect with a button press, set the dwTriggerButton member of the DIEFFECT structure. Also set the dwTriggerRepeatInterval member to the desired delay between playbacks when the button is held down; this is the interval, in microseconds, between the end of one playback and the start of the next.

Note On some devices, multiple effects cannot be triggered by the same button; if you associate more than one effect with a button; the last effect downloaded is the one triggered. Also, trigger repeat interval might not be supported.

To dissociate an effect from its trigger button, either call the IDirectInputEffect::Unload method, or set the parameters for the effect with dwTriggerButton set to DIEB_NOTRIGGER.

Triggered effects, like all others, are lost when the application loses access to the device. To make them active again, download them as soon as the application reacquires the device. This step is not necessary for effects not associated with a trigger because they are automatically downloaded if necessary whenever the Start method is called.

If an effect has a finite duration and is started by a call to the Start method, it stops playing when the time has elapsed. If its duration was set to INFINITE, playback ends only when the IDirectInputEffect::Stop method is called. An effect associated with a trigger button starts when the button is pressed, and stops when the button is released or the duration has elapsed, whichever comes sooner.

[Visual Basic]

There are two principal ways to start playback of an effect: manually by a call to the DirectInputEffect.Start method, or automatically in response to a button press. Playback also starts when you change an effect by calling the DirectInputEffect.SetParameters method with the DIEP_START flag.

Passing –1 in the iterations parameter of Start has the effect of playing the effect repeatedly, with the envelope being applied each time. If you want to repeat an effect without repeating the envelope—for example, to begin with a strong kick, then settle down to a steady throb—set iterations to 1, and set the lDuration member of the DIEFFECT type to –1. (This is the type passed to the DirectInputDevice.CreateEffect method.)

Note Some devices do not support multiple iterations of an effect and accept only the value 1 in the iterations parameter to the Start method.

To associate an effect with a button press, set the lTriggerButton member of the DIEFFECT type. Also set the lTriggerRepeatInterval member to the desired delay between playbacks when the button is held down; this is the interval, in microseconds, between the end of one playback and the start of the next.

Note On some devices, multiple effects cannot be triggered by the same button; if you associate more than one effect with a button; the last effect downloaded is the one triggered. Also, trigger repeat interval might not be supported.

To dissociate an effect from its trigger button, either call the DirectInputEffect.Unload method, or set the parameters for the effect with lTriggerButton set to -1.

Triggered effects, like all others, are lost when the application loses access to the device. To make them active again, download them as soon as the application reacquires the device. This step is not necessary for effects not associated with a trigger because they are automatically downloaded if necessary whenever the Start method is called.

If an effect has a finite duration and is started by a call to the Start method, it stops playing when the time has elapsed. If its duration was set to –1, playback ends only when the DirectInputEffect.Stop method is called. An effect associated with a trigger button starts when the button is pressed, and stops when the button is released or the duration has elapsed, whichever comes sooner.


Downloading and Unloading Effects

Before an effect can be played, it must be downloaded to the device. Downloading an effect means telling the driver to prepare the effect for playback. It is entirely up to the driver to determine how this is done. Generally the driver places the parameters of the effect in hardware memory to minimize the subsequent transfer of data between the device and the system. The consequent reduction in latency is particularly important for conditions and for effects played in response to a trigger, such as a fire button. Ideally the device does not have to communicate with the system at all to respond to axis movements and button presses.

Downloading is done automatically when you create an effect, provided the device is not full and is acquired at the exclusive cooperative level. By default, it is also done when you start the effect or change its parameters.

[C++]

If you specify the DIEP_NODOWNLOAD flag when changing parameters, you must subsequently use the IDirectInputEffect::Download method to download or update the effect.

When the device is unacquired—for example, when it has been acquired with the exclusive foreground cooperative level and the application moves to the background—effects are unloaded and must be downloaded again when the application regains the foreground. As previously stated, this is done automatically when you call the IDirectInputEffect::Start method, but you can choose to download all effects immediately on reacquiring the device. You always have to download effects associated with a trigger button, since the Start method is not normally called for such effects.

If your application gets the DIERR_DEVICEFULL error when downloading an effect, you must make room for the new effect by unloading an old one. You can remove an effect from the device by calling the IDirectInputEffect::Unload method. You can also remove all effects by resetting the device through a call to the IDirectInputDevice7::SendForceFeedbackCommand method.

[Visual Basic]

If you specify the DIEP_NODOWNLOAD flag when changing parameters, you must subsequently use the DirectInputEffect.Download method to download or update the effect.

When the device is unacquired—for example, when it has been acquired with the exclusive foreground cooperative level and the application moves to the background—effects are unloaded and must be downloaded again when the application regains the foreground. As previously stated, this is done automatically when you call the DirectInputEffect.Start method, but you can choose to download all effects immediately on reacquiring the device. You always have to download effects associated with a trigger button, since the Start method is not normally called for such effects.

If your application gets the DIERR_DEVICEFULL error when downloading an effect, you must make room for the new effect by unloading an old one. You can remove an effect from the device by calling the DirectInputEffect.Unload method. You can also remove all effects by resetting the device through a call to the DirectInputDevice.SendForceFeedbackCommand method.

When you create a force-feedback device, the hardware and driver are reset, so any existing effects are cleared.


Changing an Effect

[C++]

You can modify the parameters of an effect, in some cases even while the effect is playing. You do this by using the IDirectInputEffect::SetParameters method.

The dwDynamicParams member of the DIEFFECTINFO structure tells you which effect parameters can be changed while an effect is playing. If you attempt to modify an effect parameter that cannot be modified while the effect is playing and the effect is still playing, DirectInput normally stops the effect, updates the parameters, and restarts the effect. You can override this default behavior by passing the DIEP_NORESTART flag.

The following code example changes the magnitude of the constant force that was set in the example under Creating an Effect.

DIEFFECT        diEffect;           // Parameters for effect
DICONSTANTFORCE diConstantForce;
  // type-specific parameters.

diConstantForce.lMagnitude = 5000;
diEffect.dwSize = sizeof(DIEFFECT);
diEffect.cbTypeSpecificParams = sizeof(DICONSTANTFORCE);
diEffect.lpvTypeSpecificParams = &diConstantForce;
hr = lpdiEffect->SetParameters(&diEffect, DIEP_TYPESPECIFICPARAMS);

The flag ensures that the transfer of data from the DIEFFECT structure is restricted to the relevant members so that you do not have to initialize the entire structure and so that the minimum possible amount of data needs to be sent to the device.

[Visual Basic]

You can modify the parameters of an effect, in some cases even while the effect is playing. You do this by using the DirectInputEffect.SetParameters method.

To find out which effect parameters can be changed while an effect is playing, call the DirectInputEnumEffects.GetDynamicParams method.

If you attempt to modify an effect parameter that cannot be modified while the effect is playing and the effect is still playing, DirectInput normally stops the effect, updates the parameters, and restarts the effect. You can override this default behavior by passing the DIEP_NORESTART flag to SetParameters.

The following code example changes the magnitude of a constant force represented by the DirectInputEffect object dieff, which was created using the global DIEFFECT type effectinfo:

effectinfo.constantForce.lMagnitude = 5000
Call dieff.SetParameters(effectinfo, DIEP_TYPESPECIFICPARAMS)

You must set the DIEP_TYPESPECIFICPARAMS flag if you are changing the condition, constantforce, periodicforce, or rampforce members of DIEFFECT.


Gain

You might want to scale the force of your effects according to the force exerted by different devices. For example, if an application's effects feel right on a device that puts out a maximum force of n Newtons on a given axis, you might want to adjust the gain for a device that puts out more force. (You cannot use the gain to increase the maximum force of the axis, so you should set the basic effect magnitudes to values suitable for devices that put out less force.)

Gain can also be used to decrease the magnitude of a hardware-defined effect.

[C++]

The force generated by a device object such as an axis or button is returned in the dwFFMaxForce member of the DIDEVICEOBJECTINSTANCE structure when objects are enumerated. (See Device Object Enumeration.)

You can set the gain for the entire device by using the IDirectInputDevice7::SetProperty method.

You must set the gain for individual effects when creating them by putting a value in the dwGain member of the DIEFFECT structure. (If dwGain is 0, the effect is not felt.) You can change this value later by using IDirectInputEffect::SetParameters, passing DIEP_GAIN in the dwFlags parameter.

[Visual Basic]

You can set the gain for the entire device by using the DirectInputDevice.SetProperty method.

You must set the gain for individual effects when creating them by putting a value in the lGain member of the DIEFFECT type. (If lGain is 0, the effect is not felt.) You can change this value later by using DirectInputEffect.SetParameters, passing DIEP_GAIN in the flags parameter.

The purpose of setting the device gain is to allow your application to have control over the strength of all effects all at once. For example, you might have a slider control in your application to allow the user to specify how strong the force-feedback effects should be, like the master volume control on a sound mixer. When the device gain is set, your application does not need to adjust the gain of each individual effect to suit the user's preferences.

A gain value can be in the range from 0 through 10,000, where 10,000 indicates that magnitudes are not to be scaled, 7,500 means that forces are to be scaled to 75 percent of their nominal magnitudes, and so on.


Force-Feedback State

[C++]

The IDirectInputDevice7::SendForceFeedbackCommand method allows you to turn off the device's actuators (effectively causing it to ignore any effects that are being played), pause or stop playback of effects, and reset the device so that all downloaded effects are removed.

To retrieve the current force-feedback state, use the IDirectInputDevice7::GetForceFeedbackState method. This method returns information about whether the actuators are active, whether playback is paused, and whether the device has been reset. It also retrieves information about various switches and about whether the device is currently powered.

[Visual Basic]

The DirectInputDevice.SendForceFeedbackCommand method allows you to turn off the device's actuators (effectively causing it to ignore any effects that are being played), pause or stop playback of effects, and reset the device so that all downloaded effects are removed.

To retrieve the current force-feedback state, use the DirectInputDevice.GetForceFeedbackState method. This method returns information about whether the actuators are active, whether playback is paused, and whether the device has been reset. It also retrieves information about various switches and about whether the device is currently powered.


Effect Object Enumeration

[Visual Basic]

This topic pertains only to applications developed in C++. DirectX for Visual Basic does not support enumeration of created effects.

[C++]

Whenever you need to examine or manipulate all the effects you have created, use the IDirectInputDevice7::EnumCreatedEffectObjects method. Since no flags are currently defined for this method, you cannot restrict the enumeration to particular kinds of effects; all effects are enumerated.

Note This method enumerates created effects, not effects supported by a device. For more information on the distinction between the two, see Effect Enumeration.

Like other DirectInput enumerations, the EnumCreatedEffectObjects method requires a callback function. This standard callback is documented with the placeholder name DIEnumCreatedEffectObjectsCallback, but you can use a different name. The function is called for each effect enumerated. Within the function you can perform any processing that you want; however, it is not safe to create a new effect while enumeration is going on.

The following is a code example of the callback function and the call to the EnumCreatedEffectObjects method. The pvRef parameter of the callback can be any 32-bit value; in this case, it is a pointer to the device interface.

HRESULT  hr;
// LPDIRECTINPUTDEVICE lpdid;   // already initialized

BOOL CALLBACK DIEnumCreatedEffectObjectsCallback(
                     LPDIRECTINPUTEFFECT peff, LPVOID pvRef);
{
    LPDIRECTINPUTDEVICE  pdid = pvRef; // Pointer to calling device
    DIEFFECT            diEffect;      // Params for created effect

    diEffect.dwSize = sizeof(DIEFFECTINFO);
    peff->GetParameters(&diEffect, DIEP_ALLPARAMS);
    // Check or set parameters, or do anything else.
    .
    .
    .
}  // End of callback

// Set the callback in motion.
hr = lpdid->EnumCreatedEffectObjects(&EnumCreatedEffectObjectsCallback,
                                     &lpdid, 0);


Effect Types

This section contains information specific to the following types of force-feedback effects:

  • Constant Forces
  • Ramp Forces
  • Periodic Effects
  • Conditions
  • Custom Forces
  • Device-Specific Effects


Constant Forces

A constant force is a force with a defined magnitude and duration.

You can apply an envelope to a constant force to give it shape. For example, suppose you have an effect with a nominal magnitude of 2,000 and a duration of 2 seconds. Then you apply an envelope with the following values:

Attack time | 0.5 second
Initial attack level | 5,000
Fade time | 1 second
Fade level | 0

When you play the effect, you get the following:

Elapsed time | Magnitude
0.0 | 5,000
0.1 | 4,400
0.2 | 3,800
0.3 | 3,200
0.4 | 2,600
0.5 | 2,000
(Duration of sustain) | 2,000
1.0: | 2,000
1.1 | 1,800
1.2 | 1,600
1.3 | 1,400
1.4 | 1,200
1.5 | 1,000
1.6 | 800
1.7 | 600
1.8 | 400
1.9 | 200
2.0 | 0

You cannot apply an offset to a constant force.

[C++]

To create a constant force, pass GUID_ConstantForce to the IDirectInputDevice7::CreateEffect method. You can also pass any other GUID obtained by the IDirectInputDevice7::EnumEffects method, provided the low byte of the dwEffType member of the DIEFFECTINFO structure (DIEFT_GETTYPE(dwEfftype)) is equal to DIEFT_CONSTANTFORCE. In this way, you can use hardware-specific forces designed by the manufacturer, such as a "constant" force that actually varies in magnitude in a seemingly random fashion to simulate turbulence.

A constant force uses a DICONSTANTFORCE structure to define the magnitude. A negative magnitude has the effect of reversing the direction of the force.

[Visual Basic]

To create a constant force, pass "GUID_ConstantForce" to the DirectInputDevice.CreateEffect method. You can also pass any other GUID obtained by the DirectInputEnumEffects.GetEffectGuid method, provided the low byte of the value returned by DirectInputEnumEffects.GetType is equal to DIEFT_CONSTANTFORCE. In this way, you can use hardware-specific forces designed by the manufacturer, such as a "constant" force that actually varies in magnitude in a seemingly random fashion to simulate turbulence.

The magnitude of a constant force is contained in a DICONSTANTFORCE type in the constantForce member of DIEFFECT. A negative magnitude has the effect of reversing the direction of the force.


Ramp Forces

A ramp force is a force with defined starting and ending magnitudes and a finite duration. A ramp force can continue in a single direction, or it can start as a strong push in one direction, weaken, stop, and then strengthen in the opposite direction.

The following illustration shows a ramp force that starts at a magnitude of -5,000 and ends at 5,000:

You can apply an envelope to a ramp force to shape it further. The following diagram shows the effect of applying an envelope, shown in green, to the ramp force in the previous diagram.

During the sustain portion of the envelope, the magnitude of the effect follows the same straight line as before the envelope was applied. For the duration of the attack and fade, the slope of the ramp is modified by the attack and fade levels.

You cannot apply an offset to a ramp force.

[C++]

To create a ramp force, pass GUID_RampForce to the IDirectInputDevice7::CreateEffect method. You can also pass any other GUID obtained by the IDirectInputDevice7::EnumEffects method, provided the low byte of the dwEffType member of the DIEFFECTINFO structure (DIEFT_GETTYPE(dwEfftype)) is equal to DIEFT_RAMPFORCE. In this way, you can use hardware-specific ramp forces designed by the manufacturer.

A ramp force uses a DIRAMPFORCE structure to define the starting and ending magnitude of the force, whereas the duration is taken from the DIEFFECT structure. Duration must never be set to INFINITE.

[Visual Basic]

To create a ramp force, pass "GUID_RampForce" to the DirectInputDevice.CreateEffect method. You can also pass any other GUID obtained by the DirectInputEnumEffects.GetEffectGuid method, provided the low byte of the value returned by DirectInputEnumEffects.GetType is equal to DIEFT_RAMPFORCE. In this way, you can use hardware-specific ramp forces designed by the manufacturer.

The starting and ending magnitude of the force are defined in a DIRAMPFORCE type in the rampForce member of DIEFFECT. The duration cannot be infinite, and therefore DIEFFECT.lDuration must be a positive value.


Periodic Effects

Periodic effects are waveform effects. DirectInput defines the following forms:

  • Square.
  • Sine.
  • Cosine.
  • Triangle.
  • SawtoothUp. The waveform drops vertically after it reaches maximum positive force. See the example in Basic Concepts of Force Feedback.
  • SawtoothDown. The waveform rises vertically after it reaches maximum negative force.

An envelope can be applied to periodic effects. See the example at Basic Concepts of Force Feedback.

The phase of a periodic effect is the point along the waveform where the effect begins. Phase is measured in hundredths of a degree, from 0 to 35,999. The following table indicates where selected phase values (in degrees) lie along the various waveforms. Max is the top (+) or bottom (–) of the wave and Mid is the midpoint, at which no force is applied in either direction.

 | 0 | 90 | 180 | 270
Square | +Max | +Max | –Max | –Max
Sine | Mid | +Max | Mid | –Max
Triangle | +Max | Mid | –Max | Mid
SawtoothUp | –Max | –Max/2 | Mid | +Max/2 (reaches +Max just before the cycle repeats)
SawtoothDown | +Max | +Max/2 | Mid | –Max/2 (reaches –Max just before the cycle repeats)

A driver can round off a phase value to the nearest supported value. For example, for a sine effect some drivers support only values in the range from 0 through 9,000 (to create a cosine); for other effects, only values in the range from 0 through 18,000 are supported.

[C++]

To create a periodic force, pass one of the following values in the rguid parameter of the IDirectInputDevice7::CreateEffect method:

  • GUID_Square
  • GUID_Sine
  • GUID_Triangle
  • GUID_SawtoothUp
  • GUID_SawtoothDown

You can also pass any other GUID obtained by the IDirectInputDevice7::EnumEffects method, provided the low byte of the dwEffType member of the DIEFFECTINFO structure (DIEFT_GETTYPE(dwEfftype)) is equal to DIEFT_PERIODIC. In this way, you can use hardware-specific forces designed by the manufacturer. For example, a hardware device might support a periodic effect that rotates the stick in a small circle.

The type-specific structure for periodic effects is DIPERIODIC.

Do not confuse the period of a periodic effect (DIPERIODIC.dwPeriod) with the sample period (DIEFFECT.dwSamplePeriod). The period is the length of time that it takes to go through a complete wave cycle. The sample period, as for all effects, is the minimum time between actual adjustments of magnitude.

[Visual Basic]

To create a periodic force, pass one of the following values in the guid parameter of the DirectInputDevice.CreateEffect method:

  • "GUID_Square"
  • "GUID_Sine"
  • "GUID_Triangle"
  • "GUID_SawtoothUp"
  • "GUID_SawtoothDown"

You can also pass any other GUID obtained by the DirectInputEnumEffects.GetEffectGuid method, provided the low byte of the value returned by DirectInputEnumEffects.GetType is equal to DIEFT_PERIODIC. In this way, you can use hardware-specific periodic forces designed by the manufacturer.

The type-specific parameters for periodic effects are contained in a DIPERIODICFORCE type in the periodicForce member of DIEFFECT.

Do not confuse the period of a periodic effect (DIEFFECT.periodic.lPeriod) with the sample period (DIEFFECT.lSamplePeriod). The period is the length of time it takes to go through a complete wave cycle. The sample period, as for all effects, is the minimum time between actual adjustments of magnitude.


Conditions

Conditions are forces applied in response to current sensor values within the device. In other words, conditions require information about device motion, such as position or velocity of a joystick handle.

In general, conditions are not associated with individual events during a game or other application. They represent ambient phenomena, such as the stiffness or looseness of a flight stick, or the tendency of a steering wheel to return to a straight-ahead position.

A condition does not have a predefined magnitude; the magnitude is scaled in proportion to the movement or position of the input object.

DirectInput defines the following types of condition effects:

  • Friction. The force is applied when the axis is moved and depends on the defined friction coefficient.
  • Damper. The force increases in proportion to the velocity with which the user moves the axis.
  • Inertia. The force increases in proportion to the acceleration of the axis.
  • Spring. The force increases in proportion to the distance of the axis from a defined neutral point.

Most hardware devices do not support the application of envelopes to conditions.

Conditions have the following type-specific parameters:

Offset
The offset from the 0 reading of the appropriate sensor value at which the condition begins to be applied. For a spring effect, the neutral point—that is, the point along the axis at which the spring would be considered at rest—would be defined by the offset for the condition. For a damper, the offset would define the greatest velocity value for which damping force is 0. Offset is not normally used for inertia or friction effects.
Coefficient
A multiplier that scales the effect. For some devices, you can set separate coefficients for the positive and negative direction along the axis associated with the condition. For example, a flight stick controlling a damaged aircraft might move more easily to the right than to the left.
Saturation
In force feedback, saturation is an expression of the maximum possible force for an effect. For example, suppose a flight stick has a spring condition on the x-axis. The offset is 0, and the coefficient is 10,000, so the maximum force is normally exerted when the stick is furthest from the center. But if you define a positive and negative saturation of 5,000, the force does not increase after the stick has been moved halfway to the right or left.

Not all devices support saturation.

Deadband
The deadband is a zone around the offset of an axis at which the condition is not active. In the case of a spring that is at rest in the middle of an axis, the deadband enlarges this area of rest.

Not all devices support saturation.

Conditions can have duration, although in most cases, you would probably want to set the duration to infinite (–1) and stop the effect only in response to some event in the application.

[C++]

To create a condition, pass one of the following values in the rguid parameter of the IDirectInputDevice7::CreateEffect method:

  • GUID_Spring
  • GUID_Damper
  • GUID_Inertia
  • GUID_Friction

You can also pass any other GUID obtained by the IDirectInputDevice7::EnumEffects method, provided the low byte of the dwEffType member of the DIEFFECTINFO structure (DIEFT_GETTYPE(dwEfftype)) is equal to DIEFT_CONDITION. In this way, you can use hardware-specific conditions designed by the manufacturer.

The type-specific structure for conditions is DICONDITION. For multiple-axis conditions, you can provide an array of such structures, one for each axis, or a single structure that defines the condition in the specified direction. In either case, you must set the cbTypeSpecificParams member of the DIEFFECT structure to the number of bytes used; that is, to sizeof(DICONDITION) * n, where n is the number of structures provided. For more information on how to use either single or multiple structures, see the Remarks for the DICONDITION structure.

An application should call the IDirectInputDevice7::GetEffectInfo method or the IDirectInputDevice7::EnumEffects method and examine the dwEffectType member of the DIEFFECTINFO structure to determine whether both a positive and a negative coefficient and saturation for the effect are supported on the device. If the effect does not return the DIEFT_POSNEGCOEFFICIENTS flag, it ignores the value in the lNegativeCoefficient member, and the value in lPositiveCoefficient is applied to the entire axis. Likewise, if the effect does not return the DIEFT_POSNEGSATURATION flag, it ignores the value in dwNegativeSaturation, and the value in dwPositiveSaturation is used as the negative saturation level. Finally, if the effect does not return the DIEFT_SATURATION flag, it ignores both the dwPositiveSaturation and dwNegativeSaturation values, and no saturation is applied.

You can set a coefficient to a negative value, and this has the effect of generating the force in the opposite direction. For example, for a spring effect, it would cause the spring to push away from the offset point, rather than pulling toward it.

You should also check DIEFFECTINFO.dwEffectType for the DIEFT_DEADBAND flag, to see if deadband is supported for the condition. If it is not supported, the value in the lDeadBand member of the DICONDITION structure is ignored.

[Visual Basic]

To create a condition, pass one of the following values in the rguid parameter of the IDirectInputDevice7::CreateEffect method:

  • "GUID_Spring"
  • "GUID_Damper"
  • "GUID_Inertia"
  • "GUID_Friction"

You can also pass any other GUID obtained by the DirectInputEnumEffects.GetEffectGuid method, provided the low byte of the value returned by DirectInputEnumEffects.GetType is equal to DIEFT_CONDITION. In this way, you can use hardware-specific conditions designed by the manufacturer.

The type-specific parameters for a condition are described in a DICONDITION type in the condition member of the DIEFFECT type.

An application should call the DirectInputEnumEffects.GetType method and examine the return value member to determine whether both a positive and a negative coefficient and saturation for the effect are supported on the device. If the effect does not return the DIEFT_POSNEGCOEFFICIENTS flag, it ignores the value in DICONDITION.lNegativeCoefficient, and the value in lPositiveCoefficient is applied to the entire axis. Likewise, if the effect does not return the DIEFT_POSNEGSATURATION flag, it ignores the value in lNegativeSaturation, and the value in lPositiveSaturation is used as the negative saturation level. Finally, if the effect does not return the DIEFT_SATURATION flag, it ignores both the lPositiveSaturation and lNegativeSaturation values, and no saturation is applied.

You can set a coefficient to a negative value, and this has the effect of generating the force in the opposite direction. For example, for a spring effect, it would cause the spring to push away from the offset point, rather than pulling toward it.

You should also check the value returned by GetType for the DIEFT_DEADBAND flag, to see if deadband is supported for the condition. If it is not supported, the value in the lDeadBand member of the DICONDITION type is ignored.

To create a single-axis effect, set the coefficients for the unused axis to 0 in the conditionX or conditionY member of the DIEFFECT type.

DirectX for Visual Basic does not support rotation of conditions.


Custom Forces

Application writers can create their own effects by creating a custom force. A custom force is an array of constant force values played back by the device.

[C++]

The type-specific structure for custom waveform effects is DICUSTOMFORCE.

Set the dwSamplePeriod member of the DICUSTOMFORCE structure and the dwSamplePeriod member of the DIEFFECT structure to the same value. This is the length of time, in milliseconds, for which each element in the array of forces is played.

The custom force is played repeatedly until the time set in the dwDuration member of the DIEFFECT structure has elapsed.

[Visual Basic]

To create a custom force, first define an array of magnitudes, all in the range from –10,000 through 10,000. Then pass this array to the DirectInputDevice.CreateCustomEffect method.

Set the samplePeriod parameter and the lSamplePeriod member of the DIEFFECT type to the same value. This is the length of time, in milliseconds, for which each element in the array of forces is played.

The custom force is played repeatedly until the time set in the DIEFFECT.lDuration has elapsed.


Device-Specific Effects

Hardware drivers can support special effects that do not fit into the categories defined by DirectInput. The type-specific parameters for these effects can be hard-coded or modifiable by the application.

[C++]

If type-specific parameters are modifiable, the application developer must obtain a header file declaring the data structure required by the effect.

The hardware vendor must provide a GUID identifying the device-specific effect and might provide a custom structure for the type-specific parameters of the effect. Your application then must initialize a DIEFFECT structure and a type-specific structure, as with any other effect. You then call the IDirectInputDevice7::CreateEffect method, passing the device-specific GUID and a pointer to the DIEFFECT structure.

When you obtain information about a device-specific effect in a DIEFFECTINFO structure, the low byte of the dwEffType member (DIEFT_GETTYPE(dwEfftype)) indicates into which of the predefined DirectInput effect categories (constant force, ramp force, periodic, or condition) the effect falls. If it does not fall into any of the predefined categories, the value is DIEFT_HARDWARE.

If a device-specific effect falls into one of the predefined categories, the lpvTypeSpecificParams member of the DIEFFECT structure must point to the corresponding DICONSTANTFORCE, DIRAMPFORCE, DIPERIODIC, or DICONDITION structure, and the cbTypeSpecificParams member must be equal to the size of that structure.

If the (DIEFT_GETTYPE(dwEfftype) == DIEFT_HARDWARE), the values of the lpvTypeSpecificParams and cbTypeSpecificParams members depend on whether the effect requires custom type-specific parameters. If it does, these values must refer to the appropriate structure defined in the manufacturer's header file and declared and initialized by your application. If the effect does not require custom parameters—that is, if the dwStaticParms member of the DIEFFECTINFO structure for the hardware effect does not have the DIEP_TYPESPECIFICPARAMS flag—lpvTypeSpecificParams must be NULL and cbTypeSpecificParams must be 0.

DirectInput passes the GUID and the DIEFFECT structure to the device driver for verification. If the GUID is unknown, the device returns DIERR_DEVICENOTREG. If the GUID is known but the type-specific data is incorrect for that effect, the device returns DIERR_INVALIDPARAM.

[Visual Basic]

DirectX for Visual Basic does not support hardware effects that require custom type-specific parameters.

The hardware vendor must provide a GUID identifying the device-specific effect. Your application then must initialize a DIEFFECT type, as with any other effect. You then pass this type, along with the GUID, to the DirectInputDevice.CreateEffect method.

When you obtain information about a device-specific effect in a DirectInputEnumEffects enumeration, the low byte of the return value of DirectInputEnumEffects.GetType indicates into which of the predefined DirectInput effect categories (constant force, ramp force, periodic, or condition) the effect falls. If it does not fall into any of the predefined categories, the value is DIEFT_HARDWARE.

If a device-specific effect falls into one of the predefined categories, the DIEFFECT type must be initialized, as it would be for a standard force of that category. For example, if the effect type is DIEFT_CONSTANTFORCE, the constantForce member must be initialized.

DirectInput passes the GUID and the DIEFFECT structure to the device driver for verification. If the GUID is unknown, the device returns DIERR_DEVICENOTREG. If the GUID is known but the type-specific data is incorrect for that effect, the device returns DIERR_INVALIDPARAM.


Designing for Previous Versions of DirectInput

[Visual Basic]

This topic pertains only to applications developed in C++.

[C++]

In several places, DirectInput requires you to pass a version number to a method. This parameter specifies which version of DirectX the DirectInput subsystem should emulate.

Applications designed for the latest version of DirectInput should pass the value DIRECTINPUT_VERSION as defined in Dinput.h.

Applications designed to run under previous versions should pass a value corresponding to the version of DirectInput for which they were designed, with the main version number in the high-order byte. For example, an application that was designed to run on DirectInput 3 should pass a value of 0x0300.

If you define DIRECTINPUT_VERSION as 0x0300 before including the Dinput.h header file, the header file generates structure definitions compatible with DirectInput 3.0.

If you do not define DIRECTINPUT_VERSION before including the Dinput.h header file, the header file generates structure definitions compatible with the current version of DirectInput. However, the DirectX 3–compatible structures are available under the same names with "_DX3" appended. For example, the DirectX 3–compatible DIDEVCAPS structure is called DIDEVCAPS_DX3.

You must also use the appropriate versions of the DirectInput and DirectInputDevice interfaces. For versions of DirectX prior to DirectX 7.0, you must use IDirectInput and either IDirectInputDevice or IDirectInputDevice2 (the latter is available for DirectX 5.0 or later.)


DirectInput Tutorials

The following sections contain tutorials providing step-by-step instructions for implementing basic Microsoft® DirectInput® functionality:

  • DirectInput C/C++ Tutorials
  • DirectInput Visual Basic Tutorials


DirectInput C/C++ Tutorials

[Visual Basic]

The information in this topic pertains only to applications written in C++. See DirectInput Visual Basic Tutorials.

[C++]

This section contains four tutorials, each providing step-by-step instructions for implementing basic DirectInput functionality in a C or C++ application.

  • Tutorial 1: Using the Keyboard

    The first tutorial shows how to add DirectInput keyboard support to an existing application.

  • Tutorial 2: Using the Mouse

    The next tutorial takes you through the steps of providing DirectInput mouse support in an application. The tutorial is based on the Scrawl sample, and focuses on buffered data.

  • Tutorial 3: Using the Joystick

    This tutorial shows how to enumerate all the joysticks connected to a system, how to create and initialize DirectInputDevice objects for each of them in a callback function, and how to retrieve immediate data. Sample code is based on the Space Donuts sample.

  • Tutorial 4: Using Force Feedback

    The final tutorial illustrates the creation and manipulation of a simple effect on a force-feedback joystick.


Tutorial 1: Using the Keyboard

[Visual Basic]

The information in this topic pertains only to applications written in C++. See DirectInput Visual Basic Tutorials.

[C++]

To prepare for keyboard input, you first create an instance of a DirectInput object. Then you use the IDirectInput7::CreateDeviceEx method to create an instance of an IDirectInputDevice7 interface. The IDirectInputDevice7 interface methods are used to manipulate the device, set its behavior, and retrieve data.

The tutorial breaks down the required tasks into the following steps:

  • Step 1: Create the DirectInput Object
  • Step 2: Create the DirectInput Keyboard Device
  • Step 3: Set the Keyboard Data Format
  • Step 4: Set the Keyboard Behavior
  • Step 5: Gain Access to the Keyboard
  • Step 6: Retrieve Data from the Keyboard
  • Step 7: Close Down the DirectInput System

Adding DirectInput keyboard support to an application is relatively simple, so this tutorial is not accompanied by a complete sample application. All of the tutorial steps are illustrated by code within the text. The related steps for initializing the system are gathered in Sample Function 1: DI_Init. Another function, Sample Function 2: DI_Term, is called whenever the system needs to be closed down.


Step 1: Create the DirectInput Object

[Visual Basic]

The information in this topic pertains only to applications written in C++. See DirectInput Visual Basic Tutorials.

[C++]

The first step in setting up the DirectInput system is to create a single DirectInput object as overall manager. This is done with a call to the DirectInputCreateEx function.

// HINSTANCE  hinst; // initialized earlier
HRESULT         hr;
LPDIRECTINPUT7  g_lpdi;

hr = DirectInputCreateEx(hinst, DIRECTINPUT_VERSION,
        IID_IDirectInput7, (void**)&g_lpdi, NULL);
if FAILED(hr)
{
  // DirectInput not available; take appropriate action
}

The first parameter for DirectInputCreateEx is the instance handle to the application or DLL that is creating the object.

The second parameter tells the DirectInput object which version of the DirectInput system should be used. You can design your application to be compatible with earlier versions of DirectInput. For more information, see Designing for Previous Versions of DirectInput.

The third parameter determines which interface is returned. Most applications will obtain the most recent version, by passing IID_IDirectInput7.

The fourth parameter is the address of a variable that will be initialized with a valid interface pointer if the call succeeds.

The last parameter specifies the address of the controlling object's IUnknown interface for use in COM aggregation. Most applications will not be using aggregation and so will pass NULL.

Next: Step 2: Create the DirectInput Keyboard Device


Step 2: Create the DirectInput Keyboard Device

[Visual Basic]

The information in this topic pertains only to applications written in C++. See DirectInput Visual Basic Tutorials.

[C++]

After creating the DirectInput object, your application must create the keyboard object—the device—and retrieve a pointer to an IDirectInputDevice7 interface. The device will perform most of the keyboard-related tasks, using the methods of the interface.

To do this your application must call the IDirectInput7::CreateDeviceEx method, as shown in Sample Function 1: DI_Init. CreateDeviceEx accepts four parameters.

The first parameter is the GUID for the device being created. Since the system keyboard will be used, your application should pass the GUID_SysKeyboard predefined global variable.

The second parameter is the GUID for the desired interface. Most applications will obtain the most recent version, by passing IID_IDirectInputDevice7.

The third parameter is the address of a variable that will be initialized with the interface pointer if the call succeeds.

The fourth parameter specifies the address of the controlling object's IUnknown interface for use in COM aggregation. Your application will likely not use aggregation, in which case the parameter is NULL.

The following example attempts to retrieve a pointer to an IDirectInputDevice7 interface. If this fails, it calls the DI_Term application-defined sample function to deallocate existing DirectInput objects, if any.

Note In all the examples, g_lpdi is the initialized pointer to the DirectInput object. The method calls are in the C++ form.

HRESULT               hr;
LPDIRECTINPUTDEVICE7  g_lpDIDEVICE

hr = g_lpDI->CreateDeviceEx(GUID_SysKeyboard, IID_IDirectInputDevice7,
        (void**)&g_lpDIDevice, NULL);
if FAILED(hr)
{
    DI_Term();
    return FALSE;
}

Next: Step 3: Set the Keyboard Data Format


Step 3: Set the Keyboard Data Format

[Visual Basic]

The information in this topic pertains only to applications written in C++. See DirectInput Visual Basic Tutorials.

[C++]

After retrieving an IDirectInputDevice7 pointer, your application must set the device's data format, as shown in Sample Function 1: DI_Init. For keyboards, this is a very simple task. Call the IDirectInputDevice7::SetDataFormat method, specifying the data format provided for your convenience by DirectInput in the c_dfDIKeyboard global variable.

The following example attempts to set the data format. If this fails, it calls the DI_Term sample function to deallocate existing DirectInput objects, if any.

hr = g_lpDIDevice->SetDataFormat(&c_dfDIKeyboard);

if FAILED(hr){
    DI_Term();
    return FALSE;
}

Next: Step 4: Set the Keyboard Behavior


Step 4: Set the Keyboard Behavior

[Visual Basic]

The information in this topic pertains only to applications written in C++. See DirectInput Visual Basic Tutorials.

[C++]

Before your application can gain access to the keyboard, it must set the device's behavior using the IDirectInputDevice7::SetCooperativeLevel method, as shown in Sample Function 1: DI_Init. This method accepts the handle to the window to be associated with the device and a combination of flags that determine the cooperative level. In this case the application is requesting foreground, nonexclusive access.

The following example attempts to set the device's cooperative level. If this fails, it calls the DI_Term application-defined sample function to deallocate existing DirectInput objects, if any.

// Set the cooperative level
hr = g_lpDIDevice->SetCooperativeLevel(g_hwndMain,
                   DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);

if FAILED(hr){
    DI_Term();
    return FALSE;
}

Next: Step 5: Gain Access to the Keyboard


Step 5: Gain Access to the Keyboard

[Visual Basic]

The information in this topic pertains only to applications written in C++. See DirectInput Visual Basic Tutorials.

[C++]

After your application sets the keyboard's behavior, it can acquire access to the device by calling the IDirectInputDevice7::Acquire method. The application must acquire the device before retrieving data from it. The Acquire method accepts no parameters.

The following line of code acquires the keyboard device that was created in Step 2: Create the DirectInput Keyboard Device:

if (g_lpDIDevice) g_lpDIDevice->Acquire();

Next: Step 6: Retrieve Data from the Keyboard


Step 6: Retrieve Data from the Keyboard

[Visual Basic]

The information in this topic pertains only to applications written in C++. See DirectInput Visual Basic Tutorials.

[C++]

Once a device is acquired, your application can start retrieving data from it. The simplest way to do this is to call the IDirectInputDevice7::GetDeviceState method, which takes a snapshot of the device's state at the time of the call.

The GetDeviceState method accepts two parameters: the size of a buffer to be filled with device state data, and a pointer to that buffer. For keyboards, always declare a buffer of 256 unsigned bytes.

The following sample attempts to retrieve the state of the keyboard. If this fails, it calls an application-defined sample function to deallocate existing DirectInput objects, if any. (See Sample Function 2: DI_Term.)

After retrieving the keyboard's current state, your application may respond to specific keys that were down at the time of the call. Each element in the buffer represents a key. If an element's high bit is on, the key was down at the moment of the call; otherwise, the key was up. To check the state of a given key, use the DirectInput Keyboard Device Constants to index the buffer for a given key.

The following skeleton function, called from the main loop of a hypothetical spaceship game, uses the IDirectInputDevice7::GetDeviceState method to poll the keyboard. It then checks to see if the LEFT ARROW, RIGHT ARROW, UP ARROW or DOWN ARROW keys were pressed when the device state was retrieved. This is accomplished with the KEYDOWN macro defined in the body of the function. The macro accepts a buffer's variable name and an index value, then checks the byte at the specified index to see if the high bit is set and returns TRUE if it is.

void WINAPI ProcessKBInput()
{
    #define KEYDOWN(name,key) (name[key] & 0x80)

    char     buffer[256];
    HRESULT  hr;

    hr = g_lpDIDevice->GetDeviceState(sizeof(buffer),(LPVOID)&buffer);
    if FAILED(hr)
    {
         // If it failed, the device has probably been lost.
         // We should check for (hr == DIERR_INPUTLOST)
         // and attempt to reacquire it here.
         return;
    }

    // Turn the ship right or left
    if (KEYDOWN(buffer, DIK_RIGHT));
        // Turn right.
    else if(KEYDOWN(buffer, DIK_LEFT));
        // Turn left.

    // Thrust or stop the ship
    if (KEYDOWN(buffer, DIK_UP)) ;
        // Move the ship forward.
    else if (KEYDOWN(buffer, DIK_DOWN));
        // Stop the ship.
}

Next: Step 7: Close Down the DirectInput System


Step 7: Close Down the DirectInput System

[Visual Basic]

The information in this topic pertains only to applications written in C++. See DirectInput Visual Basic Tutorials.

[C++]

When an application is about to close, it should destroy all DirectInput objects. This is a three-step process:

  • Unacquire all DirectInput devices (IDirectInputDevice7::Unacquire)
  • Release all DirectInput devices (IDirectInputDevice7::Release)
  • Release the DirectInput object (IDirectInput7::Release)

For a sample function that closes down the DirectInput system, see Sample Function 2: DI_Term.


Sample Function 1: DI_Init

[Visual Basic]

The information in this topic pertains only to applications written in C++. See DirectInput Visual Basic Tutorials.

[C++]

This application-defined sample function creates a DirectInput object, initializes it, and retrieves the necessary interface pointers, assigning them to global variables. When initialization is complete, it acquires the device.

If any part of the initialization fails, this function calls the DI_Term application-defined sample function to deallocate DirectInput objects and interface pointers in preparation for terminating the program. (See Sample Function 2: DI_Term.)

Besides creating the DirectInput object, the DI_Init function performs the tasks discussed in the following tutorial steps:

  • Step 2: Create the DirectInput Keyboard Device
  • Step 3: Set the Keyboard Data Format
  • Step 4: Set the Keyboard Behavior
  • Step 5: Gain Access to the Keyboard

Here is the DI_Init function:

/ * The following variables are presumed initialized:
HINSTANCE             g_hinst;    // application instance
HWND                  g_hwndMain; // application window
*/
LPDIRECTINPUT7        g_lpDI;
LPDIRECTINPUTDEVICE7  g_lpDIDevice;

BOOL WINAPI DI_Init()
{
    HRESULT hr;

    // Create the DirectInput object.
    hr = DirectInputCreateEx(g_hinst, DIRECTINPUT_VERSION,
                           IID_IDirectInput7, (void**)&g_lpDI, NULL);
    if FAILED(hr) return FALSE;

    // Retrieve a pointer to an IDirectInputDevice7 interface
    hr = g_lpDI->CreateDeviceEx(GUID_SysKeyboard,
            IID_IDirectInputDevice7, (void**)&g_lpDIDevice, NULL);
    if FAILED(hr)
    {
        DI_Term();
        return FALSE;
    }

// Now that you have an IDirectInputDevice7 interface, get
// it ready to use.

    // Set the data format using the predefined keyboard data
    // format provided by the DirectInput object for keyboards.
    hr = g_lpDIDevice->SetDataFormat(&c_dfDIKeyboard);
    if FAILED(hr)
    {
        DI_Term();
        return FALSE;
    }

    // Set the cooperative level
    hr = g_lpDIDevice->SetCooperativeLevel(g_hwndMain,
                       DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
    if FAILED(hr)
    {
        DI_Term();
        return FALSE;
    }

    // Get access to the input device.
    hr = g_lpDIDevice->Acquire();
    if FAILED(hr)
    {
        DI_Term();
        return FALSE;
    }

    return TRUE;
}


Sample Function 2: DI_Term

[Visual Basic]

The information in this topic pertains only to applications written in C++. See DirectInput Visual Basic Tutorials.

[C++]

This application-defined sample function deallocates existing DirectInput interface pointers in preparation for program shutdown or in the event of a failure to properly initialize a device.

/* The following variables are presumed initialized:
LPDIRECTINPUT7        g_lpDI;
LPDIRECTINPUTDEVICE7  g_lpDIDevice;
*/

void WINAPI DI_Term()
{
    if (g_lpDI)
    {
        if (g_lpDIDevice)
        {
            /*
Always unacquire device before calling Release().              */
             g_lpDIDevice->Unacquire();
             g_lpDIDevice->Release();
             g_lpDIDevice = NULL;
        }
        g_lpDI->Release();
        g_lpDI = NULL;
    }
}


Tutorial 2: Using the Mouse

[Visual Basic]

The information in this topic pertains only to applications written in C++. See DirectInput Visual Basic Tutorials.

[C++]

This tutorial guides you through the process of setting up a mouse device and retrieving buffered input data. The examples are based on the Scrawl sample.

To prepare for mouse input, you first create an instance of a DirectInput object. Then you use the IDirectInput7::CreateDeviceEx method to create an instance of an IDirectInputDevice7 interface. The IDirectInputDevice7 interface methods are used to manipulate the device, set its behavior, and retrieve data.

The preliminary step of setting up the DirectInput system and the final step of closing it down are the same for any application and are covered in Tutorial 1: Using the Keyboard.

This tutorial breaks down the required tasks into the following steps:

  • Step 1: Create the DirectInput Mouse Device
  • Step 2: Set the Mouse Data Format
  • Step 3: Set the Mouse Behavior
  • Step 4: Prepare for Buffered Input from the Mouse
  • Step 5: Manage Access to the Mouse
  • Step 6: Retrieve Buffered Data from the Mouse

Note When an application acquires the mouse at the exclusive cooperative level, Windows does not show a mouse pointer on the screen. For this, your application needs a simple sprite engine. The Scrawl sample application uses the Win32 function DrawIcon to display a crosshair cursor.


Step 1: Create the DirectInput Mouse Device

[Visual Basic]

The information in this topic pertains only to applications written in C++. See DirectInput Visual Basic Tutorials.

[C++]

After creating the DirectInput object, your application should retrieve a pointer to an IDirectInputDevice7 interface, which will be used to perform most mouse-related tasks. To do this, call the IDirectInput7::CreateDeviceEx method.

The first parameter of CreateDeviceEx is the globally unique identifier (GUID) for the device your application is creating. In this case, since the system mouse will be used, your application should pass the predefined global variable GUID_SysMouse.

The second parameter is the GUID of the desired DirectInputDevice interface. Most applications will want the latest interface and so will pass IID_IDirectInputDevice7.

The third parameter is the address of a variable that will be initialized with a valid IDirectInputDevice7 interface pointer if the call succeeds.

The fourth parameter specifies the address of the controlling object's IUnknown interface for use in COM aggregation. Your application probably won't be using aggregation, in which case the parameter will be NULL.

The following sample code attempts to retrieve a pointer to an IDirectInputDevice7 interface. If the call fails, FALSE is returned. It is assumed that g_pdi is a valid pointer to IDirectInput7.

LPDIRECTINPUTDEVICE g_pMouse;
HRESULT             hr;

hr = g_pdi->CreateDeviceEx(GUID_SysMouse, IID_IDirectInputDevice7,
        (void**)&g_pMouse, NULL);

if (FAILED(hr)) {
    return FALSE;
}

Next: Step 2: Set the Mouse Data Format


Step 2: Set the Mouse Data Format

[Visual Basic]

The information in this topic pertains only to applications written in C++. See DirectInput Visual Basic Tutorials.

[C++]

After retrieving an IDirectInputDevice7 pointer, your application must set the device's data format. For mouse devices, this is a very simple task. Call the IDirectInputDevice7::SetDataFormat method, specifying the data format provided for your convenience by DirectInput in the c_dfDIMouse global variable.

The following code attempts to set the device's data format. If the call fails, FALSE is returned.

hr = g_pMouse->SetDataFormat(&c_dfDIMouse);

if (FAILED(hr)) {
    return FALSE;
}

Next: Step 3: Set the Mouse Behavior


Step 3: Set the Mouse Behavior

[Visual Basic]

The information in this topic pertains only to applications written in C++. See DirectInput Visual Basic Tutorials.

[C++]

Before it can gain access to the mouse, your application must set the mouse device's behavior using the IDirectInputDevice7::SetCooperativeLevel method. This method accepts the handle to the window to be associated with the device. In Scrawl, the DISCL_EXCLUSIVE flag is included to ensure that this application is the only one that can have exclusive access to the device. This flag is combined with DISCL_FOREGROUND because Scrawl is not interested in what the mouse is doing when another application is in the foreground.

The following code attempts to set the device's cooperative level. If this attempt fails, FALSE is returned.

hr = g_pMouse->SetCooperativeLevel(hwnd,
               DISCL_EXCLUSIVE | DISCL_FOREGROUND);

if (FAILED(hr)) {
    return FALSE;
}

Next: Step 4: Prepare for Buffered Input from the Mouse


Step 4: Prepare for Buffered Input from the Mouse

[Visual Basic]

The information in this topic pertains only to applications written in C++. See DirectInput Visual Basic Tutorials.

[C++]

The Scrawl application demonstrates how to use event notification to find out about mouse activity, and how to read buffered input from the mouse. Both these techniques require some setup. You can perform these steps at any time after creating the mouse device and before acquiring it.

First, create an event and associate it with the mouse device. You are instructing DirectInput to notify the mouse device object whenever a hardware interrupt indicates that new data is available.

This is how it's done in Scrawl, where g_hevtMouse is a global HANDLE.

g_hevtMouse = CreateEvent(0, 0, 0, 0);

if (g_hevtMouse == NULL) {
    return FALSE;
}

hr = g_pMouse->SetEventNotification(g_hevtMouse);

if (FAILED(hr)) {
    return FALSE;
}

Now you need to set the buffer size so that DirectInput can store any input data until you're ready to look at it. Remember, by default the buffer size is zero, so this step is essential if you want to use buffered data.

It's not necessary to used buffered data with event notification; if you prefer, you can retrieve immediate data when an event is signaled.

To set the buffer size you need to initialize a DIPROPDWORD structure with information about itself and about the property you wish to set. Most of the values are boilerplate; the key value is the last one, dwData, which is initialized with the number of items you want the buffer to hold.

#define DINPUT_BUFFERSIZE  16

DIPROPDWORD dipdw =
    {
        // the header
        {
            sizeof(DIPROPDWORD),        // diph.dwSize
            sizeof(DIPROPHEADER),       // diph.dwHeaderSize
            0,                          // diph.dwObj
            DIPH_DEVICE,                // diph.dwHow
        },
        // the data
        DINPUT_BUFFERSIZE,              // dwData
    };

You then pass the address of the header (the DIPROPHEADER structure within the DIPROPDWORD structure), along with the identifier of the property you want to change, to the IDirectInputDevice7::SetProperty method, as follows:

hr = g_pMouse->SetProperty(DIPROP_BUFFERSIZE, &dipdw.diph);

if (FAILED(hr)) {
    return FALSE;
 }

The setup is now complete, and you're ready to acquire the mouse and start collecting data.

Next: Step 5: Manage Access to the Mouse


Step 5: Manage Access to the Mouse

[Visual Basic]

The information in this topic pertains only to applications written in C++. See DirectInput Visual Basic Tutorials.

[C++]

DirectInput provides the IDirectInputDevice7::Acquire and IDirectInputDevice7::Unacquire methods to manage device access. Your application must call the Acquire method to gain access to the device before requesting mouse information with the IDirectInputDevice7::GetDeviceState and IDirectInputDevice7::GetDeviceData methods.

Most of the time your application will have the device acquired. However, if you have only foreground access the mouse will automatically be unacquired whenever your application moves to the background. You are responsible for reacquiring it when you get the focus back again. This can be done in response to a WM_ACTIVATE message.

Scrawl handles this message by setting a global variable, g_fActive, according to whether the application is gaining or losing the focus. It then calls a helper function, Scrawl_SyncAcquire, which acquires the mouse if g_fActive is TRUE and unacquires it otherwise.

case WM_ACTIVATE:
        g_fActive = wParam == WA_ACTIVE || wParam == WA_CLICKACTIVE;
        Scrawl_SyncAcquire(hwnd);
        break;

If you have exclusive access, your application may need to let go of the mouse to let the user interact with Windows—for example, to access a menu or a dialog box. In Scrawl this can happen when the user opens the system menu with ALT+SPACEBAR.

The Scrawl window procedure has a handler for WM_ENTERMENULOOP that responds by setting the global variable g_fActive to FALSE and calling the Scrawl_SyncAcquire function. This handler allows Windows to have the mouse and display its own cursor.

When the user is done using a menu, Windows sends the application a WM_EXITMENULOOP message. In this case, the Scrawl window process posts an application-defined message, WM_SYNCACQUIRE, to its own message queue. This allows other pending messages to be processed before the mouse is reacquired with the Scrawl_SyncAcquire function.

Scrawl also unacquires the mouse in response to a right button click, which opens up a context menu. Although the mouse would get unacquired later, in the WM_ENTERMENULOOP handler, it's done here first so that the position of the Windows cursor can be set before the menu appears.

Finally, Scrawl tries to reacquire the mouse if it receives a DIERR_INPUTLOST error after an attempt to retrieve data. This is just in case the device has been unacquired by some mechanism not covered elsewhere; for instance, if the user has pressed CTRL+ALT+DEL.

In summary, your application needs to acquire the mouse before it can get data from it. This needs to be done only once, as long as nothing happens to force your application to give up access to it. In exclusive mode, you are responsible for giving up control of the mouse when Windows needs it. You are also responsible for reacquiring the mouse whenever your program needs access to it after losing it to Windows or another application.

Next: Step 6: Retrieve Buffered Data from the Mouse


Step 6: Retrieve Buffered Data from the Mouse

[Visual Basic]

The information in this topic pertains only to applications written in C++. See DirectInput Visual Basic Tutorials.

[C++]

Once the mouse is acquired, your application can begin to retrieve data from it.

In the Scrawl sample, retrieval is triggered by a signaled event. In the WinMain function, the application sleeps until MsgWaitForMultipleObjects indicates that there is either a signal or a message. If there's a signal associated with the mouse, the Scrawl_OnMouseInput function is called. This function is a good illustration of how buffered input is handled, so we'll look at it in detail.

First the function makes sure the old cursor position will be cleaned up. Remember, Scrawl is maintaining its own cursor and is wholly responsible for drawing and erasing it.

void Scrawl_OnMouseInput(HWND hwnd)
{
    /* Invalidate the old cursor so it will be erased */
    InvalidateCursorRect(hwnd);

Now the function enters a loop to read and respond to the entire contents of the buffer. Because it retrieves just one item at a time, it needs only a single DIDEVICEOBJECTDATA structure to hold the data.

Another way to go about handling input would be to read the entire buffer at once and then loop through the retrieved items, responding to each one in turn. In that case, dwElements would be the size of the buffer, and od would be an array with the same number of elements.

    while (!fDone) {
        DIDEVICEOBJECTDATA od;
        DWORD dwElements = 1;   // number of items to be retrieved

The application calls the IDirectInputDevice7::GetDeviceData method in order to fetch the data. The second parameter tells DirectInput where to put the data, and the third tells it how many items are wanted. The final parameter would be DIGDD_PEEK if the data was to be left in the buffer, but in this case the data is not going to be needed again, so it is removed.

        HRESULT hr = g_pMouse->GetDeviceData(
                             sizeof(DIDEVICEOBJECTDATA),
                             &od,
                             &dwElements, 0);

Now the application checks to see if access to the device has been lost and, if so, tells itself to try to reacquire the mouse at the first opportunity. This step was discussed in Step 5: Manage Access to the Mouse.

        if (hr == DIERR_INPUTLOST) {
            PostMessage(hwnd, WM_SYNCACQUIRE, 0, 0L);
            break;
        }

Next the application makes sure the call to the GetDeviceData method succeeded and that there was actually data to be retrieved. Remember, after the call to GetDeviceData the dwElements variable shows how many items were actually retrieved.

        /* Unable to read data or no data available */
        if (FAILED(hr) || dwElements == 0) {
            break;
        }

If execution has proceeded to this point, everything is fine: the call succeeded and there is an item of data in the buffer. Now the application looks at the dwOfs member of the DIDEVICEOBJECTDATA structure to determine which object on the device reported a change of state, and calls helper functions to respond appropriately. The value of the dwData member, which gives information about what happened, is passed to these functions.

        /* Look at the element to see what happened */

        switch (od.dwOfs) {

        /* DIMOFS_X: Mouse horizontal motion */
        case DIMOFS_X: UpdateCursorPosition(od.dwData, 0); break;

        /* DIMOFS_Y: Mouse vertical motion */
        case DIMOFS_Y: UpdateCursorPosition(0, od.dwData); break;

        /* DIMOFS_BUTTON0: Button 0 pressed or released */
        case DIMOFS_BUTTON0:

            if (od.dwData & 0x80) { /* Button pressed */
                fDone = 1;
                Scrawl_OnButton0Down(hwnd); /* Go into button-down
                                               mode */
            }
            break;

        /* DIMOFS_BUTTON1: Button 1 pressed or released */
        case DIMOFS_BUTTON1:

            if (!(od.dwData & 0x80)) {    /* Button released */
                fDone = 1;
                Scrawl_OnButton1Up(hwnd); /* Context menu time */
            }
        }

    }

Finally, the Scrawl_OnMouseInput sample function invalidates the screen rectangle occupied by the cursor, in case the cursor has been moved by one of the helper functions.

    /* Invalidate the new cursor so it will be drawn */
    InvalidateCursorRect(hwnd);
}

Scrawl also collects mouse data in the Scrawl_OnButton0Down function. This is where the application keeps track of mouse movements while the primary button is being held down—that is, while the user is drawing. This function does not rely on event notification, but repeatedly polls the DirectInput buffer until the button is released.

A key point to note in the Scrawl_OnButton0Down function is that no actual drawing is done until all pending data has been read. The reason is that each horizontal or vertical movement of the mouse is reported as a separate event. (Both events are, however, placed in the buffer at the same time.) If a line were immediately drawn in response to each separate axis movement, a diagonal movement of the mouse would produce two lines at right angles.

Another way you can be sure that the movement in both axes is taken into account before responding in your application is to check the sequence numbers of the x-axis item and the y-axis item. If the numbers are the same, the two events took place simultaneously. For more information, see Time Stamps and Sequence Numbers.


Tutorial 3: Using the Joystick

[Visual Basic]

The information in this topic pertains only to applications written in C++. See DirectInput Visual Basic Tutorials.

[C++]

This tutorial shows you how to enumerate joysticks on a system and set up two or more joysticks for input. Code samples are based on the Space Donuts sample. The method calls are in the C form.

The preliminary step of setting up the DirectInput system and the final step of closing it down are the same for any application and are covered in Tutorial 1: Using the Keyboard.

The first step in the tutorial is to enumerate devices; that is, to see what joysticks are available. As part of this process you initialize each joystick device and set its desired characteristics. You then use the IDirectInputDevice7 interface methods to retrieve data from each joystick.

The tutorial breaks down the required tasks into the following steps:

  • Step 1: Enumerate the Joysticks
  • Step 2: Create the DirectInput Joystick Device
  • Step 3: Set the Joystick Data Format
  • Step 4: Set the Joystick Behavior
  • Step 5: Gain Access to the Joystick
  • Step 6: Retrieve Data from the Joystick


Step 1: Enumerate the Joysticks

[Visual Basic]

The information in this topic pertains only to applications written in C++. See DirectInput Visual Basic Tutorials.

[C++]

After creating the DirectInput system, call the IDirectInput7::EnumDevices method to enumerate the joysticks. The following code accomplishes this.

// pdi is an initialized pointer to IDirectInput7

pdi->lpVtbl->EnumDevices(pdi, DIDEVTYPE_JOYSTICK,
                         InitJoystickInput, pdi, DIEDFL_ATTACHEDONLY);

The method call is in the C form. Note that you could use the IDirectInput7_EnumDevices macro to simplify the call. All DirectInput methods have corresponding macros defined in Dinput.h that expand to the appropriate C or C++ syntax.

The DIDEVTYPE_JOYSTICK constant, passed as the second parameter, specifies the type of device to be enumerated.

InitJoystickInput is the address of a callback function to be called each time a joystick is found. This is where the individual devices will be initialized in the following steps of the tutorial.

The fourth parameter can be any 32-bit value that you want to make available to the callback function. In this case it's a pointer to the DirectInput interface, which the callback function needs to know so it can call the IDirectInput7::CreateDeviceEx method.

The last parameter, DIEDFL_ATTACHEDONLY, is a flag that restricts enumeration to devices that are attached to the computer.

Next: Step 2: Create the DirectInput Joystick Device


Step 2: Create the DirectInput Joystick Device

[Visual Basic]

The information in this topic pertains only to applications written in C++. See DirectInput Visual Basic Tutorials.

[C++]

After creating the DirectInput object, the application must retrieve a pointer to an IDirectInputDevice7 interface, which will be used to perform most joystick-related tasks. In the Space Donuts sample, this is done in the callback function InitJoystickInput, which is called each time a joystick is enumerated.

Here is the first part of the callback function:

BOOL FAR PASCAL InitJoystickInput(LPCDIDEVICEINSTANCE pdinst,
                                  LPVOID pvRef)
{
   LPDIRECTINPUT7 pdi = pvRef;
   LPDIRECTINPUTDEVICE7 pdev;

   // Create the DirectInput joystick device.
   if (pdi->lpVtbl->CreateDeviceEx(pdi, &pdinst->guidInstance,
          IID_IDirectInputDevice7, (void**)&pdev, NULL) != DI_OK)
   {
      OutputDebugString("IDirectInput7::CreateDeviceEx FAILED\n");
      return DIENUM_CONTINUE;
   }

The parameters to the callback function InitJoystickInput are:

  • A pointer to the device instance, supplied by the DirectInput system when the device is enumerated.
  • A pointer to the DirectInput interface, which you supplied as an parameter to IDirectInput7::EnumDevices. This parameter could have been any 32-bit value but in this case you want the DirectInput interface so that you can call the IDirectInput7::CreateDeviceEx method.

The InitJoystickInput sample function declares a local pointer to the DirectInput object, pdi, and assigns it the value passed into the callback. It also declares a local pointer to a DirectInput device, pdev, which is initialized when the device is created.

The first task of the callback function, then, is to create the device. The IDirectInput7::CreateDeviceEx method accepts four parameters.

The first, unnecessary in C++, is a this pointer to the calling DirectInput interface.

The second parameter is a reference to the globally unique identifier (GUID) for the instance of the device. In this case, the GUID is taken from the DIDEVICEINSTANCE structure supplied by DirectInput when it enumerated the device.

The third parameter is the address of the variable that will be initialized with a valid interface pointer if the call succeeds.

The fourth parameter specifies the address of the controlling object's IUnknown interface for use in COM aggregation. Space Donuts doesn't use aggregation, so the parameter is NULL.

Note that if for some reason the device interface cannot be created, DIENUM_CONTINUE is returned from the callback function. This flag instructs DirectInput to keep enumerating as long as there are devices to be enumerated.

Next: Step 3: Set the Joystick Data Format


Step 3: Set the Joystick Data Format

[Visual Basic]

The information in this topic pertains only to applications written in C++. See DirectInput Visual Basic Tutorials.

[C++]

Now that the application has a pointer to a DirectInput device, it can call the IDirectInputDevice7 methods to manipulate that device. The first step, which is an essential one, is to set the data format for the joystick. This step tells DirectInput how to format the input data.

The Space Donuts sample performs this action inside the callback function introduced in the previous step.

   if (pdev->lpVtbl->SetDataFormat(pdev, &c_dfDIJoystick) != DI_OK)
   {
      OutputDebugString("IDirectInputDevice7::SetDataFormat FAILED\n");
      pdev->lpVtbl->Release(pdev);
      return DIENUM_CONTINUE;
   }

The pdev variable is a pointer to the device interface created by IDirectInput7::CreateDeviceEx.

The IDirectInputDevice7::SetDataFormat method takes two parameters. The first is a this pointer to the calling instance of the interface and is unnecessary in C++. The second is a pointer to a DIDATAFORMAT structure containing information about how the data for the device is to be formatted. For the joystick, the predefined global variable c_dfDIJoystick can be used here.

As in the previous step, the callback function returns DIENUM_CONTINUE if it fails to initialize the device. This flag instructs DirectInput to keep enumerating as long as there are devices to be enumerated.

Next: Step 4: Set the Joystick Behavior


Step 4: Set the Joystick Behavior

[Visual Basic]

The information in this topic pertains only to applications written in C++. See DirectInput Visual Basic Tutorials.

[C++]

The joystick device has been created, and its data format has been set. The next step is to set its cooperative level. In the Space Donuts sample, this is done in the callback function called when the device is enumerated. As in the previous step, pdev is a pointer to the device interface.

   if(pdev->lpVtbl->SetCooperativeLevel(pdev, hWndMain,
      DISCL_NONEXCLUSIVE | DISCL_FOREGROUND) != DI_OK)
   {
      OutputDebugString("IDirectInputDevice7::SetCooperativeLevel
                         FAILED\n");
      pdev->lpVtbl->Release(pdev);
      return DIENUM_CONTINUE;
   }

Once again, the first parameter to IDirectInputDevice7::SetCooperativeLevel is a this pointer.

The second parameter is a window handle. In this case the handle to the main program window is passed in.

The final parameter is a combination of flags describing the desired cooperative level. Space Donuts requires input from the joystick only when it is the foreground application, and does not care whether another program is using the joystick in exclusive mode, so the flags are set to DISCL_NONEXCLUSIVE | DISCL_FOREGROUND. (See Cooperative Levels for a full explanation of these flags.)

The final step carried out for each joystick enumerated in the callback function is to set the properties of the device. In the sample, the properties changed include the range and the dead zone for both the x-axis and y-axis.

By setting the range, you are telling DirectInput what maximum and minimum values you want returned for an axis. If you set a range of -1,000 to +1,000 for the x-axis, as in the example, you are asking that a value of -1,000 be returned when the stick is at the extreme left, +1,000 when it is at the extreme right, and zero when it is in the middle.

The dead zone is a region of tolerance in the middle of the axis, measured in ten-thousandths of the physical range of axis travel. If you set a dead zone of 1,000 for the x-axis, you are saying that the stick can travel one-tenth of its range to the left or right of center before a non-center value will be returned. For more information on the dead zone, see Interpreting Joystick Axis Data.

Here's the code to set the range of the x-axis:

   DIPROPRANGE diprg;

   diprg.diph.dwSize       = sizeof(diprg);
   diprg.diph.dwHeaderSize = sizeof(diprg.diph);
   diprg.diph.dwObj        = DIJOFS_X;
   diprg.diph.dwHow        = DIPH_BYOFFSET;
   diprg.lMin              = -1000;
   diprg.lMax              = +1000;

   if FAILED(pdev->lpVtbl->SetProperty(pdev,
                   DIPROP_RANGE, &diprg.diph))
   {
      OutputDebugString("IDirectInputDevice7::SetProperty(DIPH_RANGE)
                         FAILED\n");
      pdev->lpVtbl->Release(pdev);
      return FALSE;
   }

The first task here is to set up the DIPROPRANGE structure diprg, whose address will be passed into the IDirectInputDevice7::SetProperty method. Actually, it's not the address of the structure itself that is passed but rather the address of its first member, which is a DIPROPHEADER structure. For more information, see Device Properties.

The property header is initialized with the following values:

  • The size of the property structure
  • The size of the header structure
  • The value returned by the DIJOFS_X joystick device constant macro, which points to the object whose property is being changed
  • A flag to indicate how the third parameter is to be interpreted

The lmin and lmax members of the DIPROPRANGE structure are assigned the desired range values.

The application now calls the IDirectInputDevice7::SetProperty method. As usual, the first parameter is a this pointer. The second parameter is a flag indicating which property is being changed. The third parameter is the address of the DIPROPHEADER member of the property structure.

Setting the dead zone of the x-axis requires a similar procedure. The Space Donuts sample uses a helper function, SetDIDwordProperty, to initialize a DIPROPDWORD property structure. Unlike DIPROPRANGE, this structure contains only one data member, which in the example is set to 5,000, indicating that the stick must move half of its range from the center before the axis is reported to be off-center.

   // set X axis dead zone to 50% (to avoid accidental turning)
   if FAILED(SetDIDwordProperty(pdev, DIPROP_DEADZONE, DIJOFS_X,
                                DIPH_BYOFFSET, 5000))
   {
      OutputDebugString("IDirectInputDevice7::
                           SetProperty(DIPH_DEADZONE) FAILED\n");
      pdev->lpVtbl->Release(pdev);
      return FALSE;
   }

Next: Step 5: Gain Access to the Joystick


Step 5: Gain Access to the Joystick

[Visual Basic]

The information in this topic pertains only to applications written in C++. See DirectInput Visual Basic Tutorials.

[C++]

After your application sets a joystick's behavior, it can acquire access to the device by calling the IDirectInputDevice7::Acquire method. The application must acquire the device before retrieving data from it. The Acquire method accepts no parameters.

The Space Donuts application takes care of acquisition in the ReacquireInput function. This function does double duty, serving both to acquire the device on startup and to reacquire it if for some reason a DIERR_INPUTLOST error is returned when the application tries to get input data.

In the following code, g_pdevCurrent is a global pointer to whatever DirectInput device is currently in use.

BOOL ReacquireInput(void)
{
    HRESULT hRes;

    // if we have a current device
    if (g_pdevCurrent)
    {
        // acquire the device
        hRes = IDirectInputDevice_Acquire(g_pdevCurrent);
        // The call above is a macro that expands to:
        // g_pdevCurrent->lpVtbl->Acquire(g_pdevCurrent);

        if (SUCCEEDED(hRes))
        {
            // acquisition successful
            return TRUE;
        }
        else
        {
            // acquisition failed
            return FALSE;
        }
    }
    else
    {
        // we don't have a current device
        return FALSE;
    }
}

In this example, acquisition is effected by a call to IDirectInputDevice7_Acquire, a macro defined in Dinput.h that simplifies the C call to the IDirectInputDevice7::Acquire method.

Next: Step 6: Retrieve Data from the Joystick


Step 6: Retrieve Data from the Joystick

[Visual Basic]

The information in this topic pertains only to applications written in C++. See DirectInput Visual Basic Tutorials.

[C++]

Since your application is more likely concerned with the position of the joystick axes than with their movement, you will probably want to retrieve immediate rather than buffered data from the device. You can do this by polling with IDirectInputDevice7::GetDeviceState. Remember, not all device drivers will notify DirectInput when the state of the device changes, so it's always good policy to call the IDirectInputDevice7::Poll method before checking the device state.

The Space Donuts application calls the following function on each pass through the rendering loop, provided the joystick is the active input device.

DWORD ReadJoystickInput(void)
{
    DWORD                   dwKeyState;
    HRESULT                 hRes;
    DIJOYSTATE              js;

    // poll the joystick to read the current state
    hRes = IDirectInputDevice7_Poll(g_pdevCurrent);

    // get data from the joystick
    hRes = IDirectInputDevice7_GetDeviceState(g_pdevCurrent,
                                            sizeof(DIJOYSTATE), &js);

    if (hRes != DI_OK)
    {
        // did the read fail because we lost input for some reason?
        // if so, then attempt to reacquire. If the second acquire
        // fails, then the error from GetDeviceData will be
        // DIERR_NOTACQUIRED, so we won't get stuck an infinite loop.
        if(hRes == DIERR_INPUTLOST)
            ReacquireInput();

        // return the fact that we did not read any data
        return 0;
    }

    // Now study the position of the stick and the buttons.

    dwKeyState = 0;
    if (js.lX < 0) {
        dwKeyState |= KEY_LEFT;
    } else if (js.lX > 0) {
        dwKeyState |= KEY_RIGHT;
    }

    if (js.lY < 0) {
        dwKeyState |= KEY_UP;
    } else if (js.lY > 0) {
          dwKeyState |= KEY_DOWN;
   }

    if (js.rgbButtons[0] & 0x80) {
        dwKeyState |= KEY_FIRE;
    }

    if (js.rgbButtons[1] & 0x80) {
        dwKeyState |= KEY_SHIELD;
    }

    if (js.rgbButtons[2] & 0x80) {
        dwKeyState |= KEY_STOP;
    }

    return dwKeyState;
}

Note the calls to IDirectInputDevice7_Poll and IDirectInputDevice7_GetDeviceState. These are macros that expand to C calls to the corresponding methods, similar to the macro in the previous step of this tutorial. The parameters to the macro are the same as those you would pass to the method. Here is what the call to GetDeviceState looks like:

    hRes = IDirectInputDevice7_GetDeviceState(g_pdevCurrent,
                                             sizeof(DIJOYSTATE), &js);

The first parameter is the this pointer; that is, a pointer to the calling object. The second parameter is the size of the structure in which the data will be returned, and the last parameter is the address of this structure, which is of type DIJOYSTATE. This structure holds data for up to six axes, 32 buttons, and a point-of-view hat. The sample program looks at the state of two axes and three buttons.

If the position of an axis is reported as nonzero, that axis is outside the dead zone, and the function responds by setting the dwKeyState variable appropriately. This variable holds the current set of user commands as entered with either the keyboard or the joystick. For example, if the x-axis of the stick is greater than zero, that is considered the same as the RIGHT ARROW key being down.

Joystick buttons work just like keys or mouse buttons: if the high bit of the returned byte is set, the button is down.


Tutorial 4: Using Force Feedback

[Visual Basic]

The information in this topic pertains only to applications written in C++. See DirectInput Visual Basic Tutorials.

[C++]

This tutorial takes you through the process of creating, playing, and modifying a simple effect on a force-feedback joystick. The effect is something like a balky chain saw that you're trying to get started. The sample code uses C++ syntax.

The preliminary step of setting up the DirectInput system and the final step of closing it down are essentially the same for any application and are covered in Tutorial 1: Using the Keyboard. However, when closing down the DirectInput force-feedback system you must take the additional step of releasing any effects you have created.

The tutorial breaks down the required tasks into the following steps:

  • Step 1: Enumerate Force-Feedback Devices
  • Step 2: Create the DirectInput Force-Feedback Device
  • Step 3: Enumerate Supported Effects
  • Step 4: Create an Effect
  • Step 5: Play an Effect
  • Step 6: Change an Effect


Step 1: Enumerate Force-Feedback Devices

[Visual Basic]

The information in this topic pertains only to applications written in C++. See DirectInput Visual Basic Tutorials.

[C++]

The first step is to ensure that a force-feedback device is available on the system. You do this by calling the IDirectInput7::EnumDevices method. In the following example, the global pointer to the game device interface is initialized only if the enumeration has succeeded in finding at least one suitable device:

LPDIRECTINPUTDEVICE7  g_lpdid7 = NULL;

lpdi->EnumDevices(DIDEVTYPE_JOYSTICK,
                  DIEnumDevicesProc,
                  NULL,
                  DIEDFL_FORCEFEEDBACK | DIEDFL_ATTACHEDONLY);
if (g_lpdid7 == NULL)
  {
  // No force-feedback joystick available; take appropriate action.
  }

In the example, lpdi is an initialized pointer to the IDirectInput7 interface. The first parameter to EnumDevices restricts the enumeration to joystick-type devices. The second parameter is the callback function that's going to be called each time DirectInput identifies a device that qualifies for enumeration. The third parameter is for user-defined data to be passed in or out of the callback function; in this case it's not used. Finally, the flags restrict the enumeration further to devices actually attached to the system that support force feedback.

The callback function is a convenient place to initialize the device as soon as it has been found. (It's assumed that the first device found is the one you want to use.) You'll do this next in Step 2: Create the DirectInput Force-Feedback Device.


Step 2: Create the DirectInput Force-Feedback Device

[Visual Basic]

The information in this topic pertains only to applications written in C++. See DirectInput Visual Basic Tutorials.

[C++]

In order to have DirectInput enumerate devices, you must create a callback function of the same type as DIEnumDevicesCallback. In Step 1 you passed the address of this function to the IDirectInput7::EnumDevices method.

DirectInput passes into the callback, as the first parameter, a pointer to a DIDEVICEINSTANCE structure that tells you what you need to know about the device. The structure member of chief interest in the example is guidInstance, the unique identifier for the particular piece of hardware on the user's system. You will need to pass this GUID to the IDirectInput7::CreateDeviceEx method.

Here's the first part of the callback, which extracts the GUID and creates the device object:

BOOL CALLBACK DIEnumDevicesProc(LPCDIDEVICEINSTANCE lpddi,
                                LPVOID pvRef)
  {
  HRESULT hr;
  GUID DeviceGuid = lpddi->guidInstance;

  // Create game device.

  hr = lpdi->CreateDeviceEx(DeviceGuid, IID_IDirectInputDevice7,
          (void**)&g_lpdid7, NULL);

  if (FAILED(hr))
    {
    OutputDebugString("Failed to create device.\n");
    return DIENUM_STOP;
    }

The next steps, still within the callback function, are similar to those for setting up any input device. Note that you need the exclusive cooperative level for any force-feedback device. You also need to set the data format.

  // Set cooperative level.
  if (FAILED(g_lpdid7->SetCooperativeLevel(hMainWindow,
         DISCL_EXCLUSIVE | DISCL_FOREGROUND)))
    {
    OutputDebugString(
      "Failed to set cooperative level.\n");
    g_lpdid7->Release();
    g_lpdid7 = NULL;
    return DIENUM_STOP;
    }

  // set game data format
  if (FAILED(g_lpdid7->SetDataFormat(&c_dfDIJoystick)))
    {
    OutputDebugString("Failed to set game device data format.\n");
    g_lpdid7->Release();
    g_lpdid7 = NULL;
    return DIENUM_STOP;
    }

Finally. you may want to turn off the device's autocenter feature. Autocenter is essentially a condition effect that uses the motors to simulate the springs in a standard joystick. It's a good idea to turn it off so that it doesn't interfere with other effects.

  DIPROPDWORD DIPropAutoCenter;

  DIPropAutoCenter.diph.dwSize = sizeof(DIPropAutoCenter);
  DIPropAutoCenter.diph.dwHeaderSize = sizeof(DIPROPHEADER);
  DIPropAutoCenter.diph.dwObj = 0;
  DIPropAutoCenter.diph.dwHow = DIPH_DEVICE;
  DIPropAutoCenter.dwData = 0;

  if (FAILED(lpdid7->SetProperty(DIPROP_AUTOCENTER,
          &DIPropAutoCenter.diph)))
    {
    OutputDebugString("Failed to change device property.\n");
    }

  return DIENUM_STOP;   // One is enough.
  } // end DIEnumDevicesProc

Before using the device, you must acquire it. See Step 5: Gain Access to the Joystick in the previous tutorial for an example of how to handle acquisition.

Next: Step 3: Enumerate Supported Effects


Step 3: Enumerate Supported Effects

[Visual Basic]

The information in this topic pertains only to applications written in C++. See DirectInput Visual Basic Tutorials.

[C++]

Now that you've successfully enumerated and created a force-feedback device, you can enumerate the effect types it supports.

Effect enumeration is not strictly necessary if you want to create only standard effects that will be available on any device, such as constant forces. When creating the effect object, you can identify the desired effect type simply by using one of the predefined GUIDs, such as GUID_ConstantForce. (For a complete list of these identifiers, see IDirectInputDevice7::CreateEffect.)

Another, more flexible approach is to enumerate supported effects of a particular type, and obtain the GUID for the effect from the callback function. This is the approach taken in the FFDonuts sample, and you'll adopt it here as well. You could, of course, use the callback to obtain more information about the device's support for the effect— for example, whether it supports an envelope—but in this tutorial you'll get only the effect GUID.

First, create the callback function that will be called by DirectInput for each effect enumerated. For information on this standard callback, see DIEnumEffectsCallback. You can give the function any name you like.

BOOL  EffectFound = FALSE;  // global flag

BOOL CALLBACK DIEnumEffectsProc(LPCDIEFFECTINFO pei, LPVOID pv)
  {
  *((GUID *)pv) = pei->guid;
  EffectFound = TRUE;
  return DIENUM_STOP;  // one is enough
  }

The GUID variable pointed to by the application-defined value pv is assigned the value passed in the DIEFFECTINFO structure created by DirectInput for the effect.

In order to obtain the effect GUID, you set the callback in motion by calling the IDirectInputDevice7::EnumEffects method, as follows:

HRESULT  hr;
GUID     guidEffect;

hr = g_lpdid7->EnumEffects(
     (LPDIENUMEFFECTSCALLBACK) DIEnumEffectsProc,
     &guidEffect,
     DIEFT_PERIODIC);
if (FAILED(hr))
  {
  OutputDebugString("Effect enumeration failed\n");
  // Note: success doesn't mean any effects were found,
  // only that the process went smoothly.
  }

Note that you pass the address of a GUID variable, guidEffect, to the EnumEffects method. This address is passed in turn to the callback as the pv parameter. You also restrict the enumeration to periodic effects by setting the flag DIEFT_PERIODIC.

Next: Step 4: Create an Effect


Step 4: Create an Effect

[Visual Basic]

The information in this topic pertains only to applications written in C++. See DirectInput Visual Basic Tutorials.

[C++]

If the EffectFound value is no longer FALSE after effect enumeration, you can safely assume that DirectInput has found support for at least one effect of the type you requested. (Of course, in real life you would probably not be content with finding just any periodic effect; you would want to use a particular kind such as a sine or sawtooth.) Armed with the effect GUID, you can now create the effect object.

Before calling the IDirectInputDevice7::CreateEffect method, you need to set up the following arrays and structures:

  • An array of axes that will be involved in the effect. For a joystick this array will normally consist of the identifiers for the x-axis and the y-axis.
  • An array of values for setting the direction. The values will differ according to the number of axes, and according to whether you want to use polar, spherical, or Cartesian coordinates. For a full explanation of this rather complicated business, see Effect Direction.
  • A structure of type-specific parameters. In the example, since you are creating a periodic effect, this will be of type DIPERIODIC.
  • A DIENVELOPE structure for defining the envelope to be applied to the effect.
  • Finally, a DIEFFECT structure to contain the basic parameters for the effect.

First, declare the arrays and structures. You can initialize the arrays at the same time:

DWORD      dwAxes[2] = { DIJOFS_X, DIJOFS_Y };
LONG       lDirection[2] = { 0, 0 };

DIPERIODIC diPeriodic;      // type-specific parameters
DIENVELOPE diEnvelope;      // envelope
DIEFFECT   diEffect;        // general parameters

Now initialize the type-specific parameters. If you use the values in the example, you will create a full-force periodic effect with a period of one-twentieth of a second.

diPeriodic.dwMagnitude = DI_FFNOMINALMAX;
diPeriodic.lOffset = 0;
diPeriodic.dwPhase = 0;
diPeriodic.dwPeriod = (DWORD) (0.05 * DI_SECONDS);

To get the effect of the chain-saw motor trying to start, briefly coughing into life, and then slowly dying, you will set an envelope with an attack time of half a second and a fade time of one second. You'll get to the sustain value in a moment.

diEnvelope.dwSize = sizeof(DIENVELOPE);
diEnvelope.dwAttackLevel = 0;
diEnvelope.dwAttackTime = (DWORD) (0.5 * DI_SECONDS);
diEnvelope.dwFadeLevel = 0;
diEnvelope.dwFadeTime = (DWORD) (1.0 * DI_SECONDS);

Now you set up the basic effect parameters. These include flags to determine how the directions and device objects (buttons and axes) are identified, the sample period and gain for the effect, and pointers to the other data that you have just prepared. You also associate the effect with the fire button of the joystick, so that it will automatically be played whenever that button is pressed.

diEffect.dwSize = sizeof(DIEFFECT);
diEffect.dwFlags = DIEFF_POLAR | DIEFF_OBJECTOFFSETS;
diEffect.dwDuration = (DWORD) (2 * DI_SECONDS);

diEffect.dwSamplePeriod = 0;               // = default
diEffect.dwGain = DI_FFNOMINALMAX;         // no scaling
diEffect.dwTriggerButton = DIJOFS_BUTTON0;
diEffect.dwTriggerRepeatInterval = 0;
diEffect.cAxes = 2;
diEffect.rgdwAxes = dwAxes;
diEffect.rglDirection = &lDirection[0];
diEffect.lpEnvelope = &diEnvelope;
diEffect.cbTypeSpecificParams = sizeof(diPeriodic);
diEffect.lpvTypeSpecificParams = &diPeriodic;

So much for the setup. At last you can create the effect:

LPDIEFFECT  g_lpdiEffect;  // global effect object

HRESULT hr = g_lpdid7->CreateEffect(
                 guidEffect,     // GUID from enumeration
                 &diEffect,      // where the data is
                 &g_lpdiEffect,  // where to put interface pointer
                 NULL);          // no aggregation
if (FAILED(hr))
  {
  OutputDebugString("Failed to create periodic effect");
  }

Remember that, by default, the effect is downloaded to the device as soon as it has been created, provided that the device is in an acquired state at the exclusive cooperative level. So if everything has gone according to plan, you should be able to compile, run, press the "fire" button, and feel the sputtering of a chain saw that's out of gas.

Next: Step 5: Play an Effect


Step 5: Play an Effect

[Visual Basic]

The information in this topic pertains only to applications written in C++. See DirectInput Visual Basic Tutorials.

[C++]

The effect created in the previous step starts in response to the press of a button. In order to create an effect that is to be played in response to an explicit call, you need to go back to Step 4 and modify the dwTriggerButton member of the DIEFFECT structure, as follows:

diEffect.dwTriggerButton = DIEB_NOTRIGGER;

Now, suppose you want to make a chain saw that actually starts and keeps going. This is simply a matter of changing the dwDuration member as follows:

diEffect.dwDuration = INFINITE;

Starting the effect is very simple:

g_lpdiEffect->Start(1, 0);

The effect will keep running until you stop it:

g_lpdiEffect->Stop();

Note that you don't need to change the envelope you created in the previous step. The attack is played as the effect starts, but the fade value is ignored.

Next: Step 6: Change an Effect


Step 6: Change an Effect

[Visual Basic]

The information in this topic pertains only to applications written in C++. See DirectInput Visual Basic Tutorials.

[C++]

Your chain saw is merrily rattling away, and now you want to modify the effect to simulate the slowing down of the engine as the saw bites into wood. Fortunately, DirectInput lets you modify the parameters of an effect while it is playing.

To change the effect, you need to set up a DIEFFECT structure or have access to the one you used to create the effect. If you are setting up a new structure with local scope, you need to initialize only the dwSize member and any members that contain or point to data that is to be changed.

In this case you want to change a type-specific parameter—the period of the effect—so you need to have access to the DIPERIODIC structure you used when creating the effect, or else create a local copy with all members initialized. Make sure that the address of the DIPERIODIC structure is in the lpvTypeSpecificParams member of the DIEFFECT structure.

Now set the new period of the effect:

diPeriodic.dwPeriod = (DWORD) (0.08 * DI_SECONDS);

Then call the method that actually makes the changes:

HRESULT hr = g_lpdiEffect->SetParameters(&diEffect,
                           DIEP_TYPESPECIFICPARAMS)

Note the flag that restricts the changes to a single member of the DIEFFECT structure.

You can control the way changes are handled by using other flags. For example, by using the DIEP_NODOWNLOAD flag you could change the parameters immediately after starting the effect but delay the implementation until the user actually started cutting wood. Then you would call the IDirectInputEffect::Download method. For more information on how to use the various control flags, see IDirectInputEffect::SetParameters.


DirectInput Visual Basic Tutorials

[C++]

This section pertains only to application development in Visual Basic. See DirectInput C/C++ Tutorials.

[Visual Basic]

This section contains the following tutorials, each providing step-by-step instructions for implementing DirectInput in a Visual Basic application:

  • Tutorial 1: Using the Keyboard

    The first tutorial shows how to add DirectInput keyboard support to an existing application, using event polling.

  • Tutorial 2: Using the Mouse

    The next tutorial takes you through the steps of providing DirectInput mouse support in an application, using the exclusive cooperative level and event notification. The tutorial is based on the ScrawlB sample, and focuses on buffered data.

  • Tutorial 3: Using the Joystick

    This tutorial shows how to enumerate all the joysticks connected to a system, how to create and initialize DirectInputDevice objects for each of them in a callback function, and how to retrieve immediate data.

  • Tutorial 4: Using Force Feedback

    The final tutorial shows how to implement simple force-feedback effects in an application.


Tutorial 1: Using the Keyboard

[C++]

This topic pertains only to application development in Visual Basic. See DirectInput C/C++ Tutorials.

[Visual Basic]

To prepare for keyboard input, you first create a DirectInput object. Then you create a DirectInputDevice object representing the keyboard. The DirectInputDevice class methods are used to set the behavior of the device and retrieve data.

The tutorial breaks down the required tasks into the following steps:

  • Step 1: Create DirectInput and the Keyboard Device
  • Step 2: Set the Keyboard Parameters
  • Step 3: Gain Access to the Keyboard
  • Step 4: Retrieve Immediate Data from the Keyboard


Step 1: Create DirectInput and the Keyboard Device

[C++]

This topic pertains only to application development in Visual Basic. See DirectInput C/C++ Tutorials.

[Visual Basic]

The first step in setting up the DirectInput system is to create a single DirectInput object as overall manager. This is done with a call to the DirectX7.DirectInputCreate method, typically in the Load event handler for the main form or in Sub Main:

Dim dx As New DirectX7
Dim di As DirectInput

Set di = dx.DirectInputCreate()

The keyboard is then created as a standard device by passing the keyboard GUID alias to DirectInput.CreateDevice:

Dim didev As DirectInputDevice
Set didev = di.CreateDevice("GUID_SysKeyboard")

Next: Step 2: Set the Keyboard Parameters


Step 2: Set the Keyboard Parameters

[C++]

This topic pertains only to application development in Visual Basic. See DirectInput C/C++ Tutorials.

[Visual Basic]

After creating a DirectInputDevice, your application must set the device's data format. For keyboards, as with other standard devices, this is a very simple task. Call the DirectInputDevice.SetCommonDataFormat method, specifying the data format provided for your convenience by DirectInput when you pass DIFORMAT_KEYBOARD as the parameter.

Call didev.SetCommonDataFormat(DIFORMAT_KEYBOARD)

Remember, you have to set the data format even if you intend to retrieve buffered data. DirectInput identifies the device objects by their offset within the data format. In the case of the keyboard, keys are identified by their offsets within the DIKEYBOARDSTATE type.

Before your application can gain access to the keyboard, it must set the device's behavior using the DirectInputDevice.SetCooperativeLevel method, as follows:

didev.SetCooperativeLevel Me.hWnd, _
        DISCL_NONEXCLUSIVE Or DISCL_BACKGROUND

This method accepts the handle to the window to be associated with the device, and exactly two flags (one of DISCL_EXCLUSIVE and DISCL_NONEXCLUSIVE, and one of DISCL_FOREGROUND and DISCL_BACKGROUND), indicating the desired cooperative level. DirectInput does not support exclusive access to keyboard devices, so the DISCL_NONEXCLUSIVE flag must be included in this case.

The example also sets the background cooperative level, so input will be available regardless of whether the form is in the foreground. Note also that keystrokes continue to be passed through to whatever application has the focus. Most applications don't need input when they're in the background, and in such cases the DISCL_FOREGROUND flag should be set instead.

Next: Step 3: Gain Access to the Keyboard


Step 3: Gain Access to the Keyboard

[C++]

This topic pertains only to application development in Visual Basic. See DirectInput C/C++ Tutorials.

[Visual Basic]

After your application sets the keyboard's behavior, it can acquire access to the device by calling the DirectInputDevice.Acquire method. The application must acquire the device before retrieving data from it. The Acquire method accepts no parameters.

Call didev.Acquire

In the sample, the application is unlikely to fail to acquire the keyboard, or to lose it later, because it is using the background, nonexclusive cooperative level. However, in general it is good practice to handle errors on calls to Acquire as well as when attempting to retrieve data.

Next: Step 4: Retrieve Immediate Data from the Keyboard


Step 4: Retrieve Immediate Data from the Keyboard

[C++]

This topic pertains only to application development in Visual Basic. See DirectInput C/C++ Tutorials.

[Visual Basic]

Once a device is acquired, your application can start retrieving data from it. The simplest way to do this is to call the DirectInputDevice.GetDeviceStateKeyboard method, which takes a snapshot of the device's state at the time of the call.

The GetDeviceStateKeyboard method accepts as its single parameter a DIKEYBOARDSTATE type, which simply contains an array of 256 bytes.

The following sample retrieves the state of the keyboard:

Dim state As DIKEYBOARDSTATE
Call didev.GetDeviceStateKeyboard(state)

After retrieving the keyboard's current state, your application may respond to specific keys that were down at the time of the call. Each element in the buffer represents a key. If an element's high bit is on, the key was down at the moment of the call; otherwise, the key was up. To check the state of a given key, use the constants of the CONST_DIKEYFLAGS enumeration to index the buffer for a given key.

The following sample code shows how an application might move a vehicle around in response to the arrow keys:

If state.Key(DIK_UP) And &H80 Then
  ' Move the vehicle up
End If
if state.Key(DIK_DOWN) And &H80 Then
  ' Move the vehicle down
End If
' And so on.

The following works just as well:

If state.Key(DIK_UP)
  ' Move the vehicle up
End If

The value of the key state is 0 if the key is up, as is the case with all buttons in the current version of DirectInput. However, future versions might support "analog" keys with more than two states and hence more than a single nonzero value, so this shorter version of the code should be used with caution, especially for devices other than the keyboard.

Remember also that DIK_UP is a single key, the dedicated up arrow key. DirectInput treats the 8 key on the numerical keypad as a distinct key, and gives it the same identifier regardless of whether NUM LOCK is on. In order to allow input from either of the arrow keys, you would have to write code like this:

If state.Key(DIK_UP) Or state.Key(DIK_NUMPAD8) Then
  ' Move the vehicle up
End If


Tutorial 2: Using the Mouse

[C++]

This topic pertains only to application development in Visual Basic. See DirectInput C/C++ Tutorials.

[Visual Basic]

This tutorial focuses on using the mouse at the exclusive cooperative level and shows how to retrieve buffered data in response to notifications. The sample code is based on the ScrawlB sample.

The tutorial is divided into the following steps:

  • Step 1: Set Up the Mouse
  • Step 2: Set Up Notifications
  • Step 3: Manage Exclusive Access to the Mouse
  • Step 4: Retrieve Buffered Data from the Mouse


Step 1: Set Up the Mouse

[C++]

This topic pertains only to application development in Visual Basic. See DirectInput C/C++ Tutorials.

[Visual Basic]

First steps in setting up the mouse for use under DirectInput are similar to those taken in Tutorial 1: Using the Keyboard. In the ScrawlB sample, initialization takes place in Sub Main after some global declarations:

Public objDX As New DirectX7
Public objDI As DirectInput
.
.
.
Set objDIDev = objDI.CreateDevice("guid_SysMouse")
Call objDIDev.SetCommonDataFormat(DIFORMAT_MOUSE)
Call objDIDev.SetCooperativeLevel(frmCanvas.hwnd, _
        DISCL_FOREGROUND Or DISCL_EXCLUSIVE)

This time the device takes exclusive control of the device. The result is that as long as the application has the mouse in the acquired state, Windows does not generate mouse messages or display the system cursor. Note that DISCL_EXCLUSIVE must be combined with DISCL_FOREGROUND; it is not possible for an application to have exclusive access to the mouse and also receive input when it loses the focus.

Because the ScrawlB sample application is taking over full responsibility for the mouse, it must also track the position of its private cursor and also must scale movement of the cursor to movements of the mouse. The following global variables are used to store the cursor coordinates (in pixels relative to the upper left corner of the main form) and movement scaling:

Public g_cursorx As Long
Public g_cursory As Long
Public g_Sensitivity

Back in Sub Main, the application sets the buffer size so that it can receive buffered data, using the DirectInputDevice.SetProperty method:

Dim diProp As DIPROPLONG
diProp.lHow = DIPH_DEVICE
diProp.lObj = 0
diProp.lData = BufferSize    ' BufferSize is a constant
diProp.lSize = Len(diProp)
Call objDIDev.SetProperty("DIPROP_BUFFERSIZE", diProp)

Next: Step 2: Set Up Notifications


Step 2: Set Up Notifications

[C++]

This topic pertains only to application development in Visual Basic. See DirectInput C/C++ Tutorials.

[Visual Basic]

Rather than polling for mouse input in Sub Main, the ScrawlB sample application relies on DirectInput to notify it whenever a mouse event takes place. As part of initialization, the application gets an event handle and passes it to DirectInputDevice.SetEventNotification:

Dim EventHandle As Long
EventHandle = objDX.CreateEvent(frmCanvas)
Call objDIDev.SetEventNotification(EventHandle)

DirectInput will now notify any object that implements the DirectXEvent class. In the case of ScrawlB, the implementing object is the frmCanvas form, whose declarations section contains the following line:

Implements DirectXEvent

This line causes frmCanvas to inherit all the methods of the DirectXEvent class. As it happens, the only visible method of that class is DirectXEvent.DXCallback, and the inheriting class must implement this method. DirectInput will call this method whenever an input event is signaled.

The implementation of DXCallback is covered under Step 4: Retrieve Buffered Data from the Mouse.

Next: Step 3: Manage Exclusive Access to the Mouse


Step 3: Manage Exclusive Access to the Mouse

[C++]

This topic pertains only to application development in Visual Basic. See DirectInput C/C++ Tutorials.

[Visual Basic]

The ScrawlB sample demonstrates using the mouse with the exclusive foreground cooperative level. At this level, Windows does not track the mouse while it is acquired by the application. There are three major consequences for the application:

  • It is entirely responsible for displaying a cursor if one is needed, and for moving it at an appropriate speed in response to DirectInput data.
  • It loses acquisition when the user switches to another application by using the keyboard, and must reacquire the mouse when the user switches back.
  • It must provide a means for Windows to get the mouse back whenever the user needs to use the system cursor—for example, to navigate a menu within the application.

ScrawlB handles the first responsibility by keeping a private record of mouse movements, adjusted by a user-defined sensitivity value, and displaying an icon that serves as a cursor for drawing.

ScrawlB loses acquisition of the mouse involuntarily whenever the application window moves to the background. When it comes to the foreground again, the application automatically reacquires the mouse by calling DirectInputDevice.Acquire in the MouseMove event handler, which is called whenever Windows sends a mouse message to the application. This happens as soon as the system cursor moves over the client window, or the client window gains the focus under the system cursor. Once ScrawlB reacquires the mouse, of course, no more Windows mouse messages are sent, so the Form_MouseMove method is not called in response to subsequent mouse events.

In order to let the user navigate the context menu, or to display the system cursor for some other purpose such as resizing the window, ScrawlB calls the DirectInputDevice.Unacquire method whenever the user opens the menu. When the menu is closed, Form_MouseMove is called and the mouse is reacquired, unless the user has chosen Suspend from the menu, in which case a flag is set. This flag prevents Form_MouseMove from reacquiring, so that the user can continue using the system cursor.

The sample application demonstrates one more technique for releasing the mouse. If the user opens the system menu by pressing ALT+SPACE, Windows sends a WM_ENTERMENULOOP message. This message is intercepted by a subclassed window procedure, which then unacquires the mouse. As long as Windows is using the system cursor for navigating the menu or allowing the user to move or resize the window, it sends no mouse messages to frmCanvas, so the application doesn't attempt to reacquire the mouse in Form_MouseMove. A similar technique could be used for intercepting other Windows messages such as WM_ACTIVATE or WM_ACTIVATEAPP, so that the application could fully control acquisition and unacquisition of the mouse in response to gaining and losing the focus.

Next: Step 4: Retrieve Buffered Data from the Mouse


Step 4: Retrieve Buffered Data from the Mouse

[C++]

This topic pertains only to application development in Visual Basic. See DirectInput C/C++ Tutorials.

[Visual Basic]

The ScrawlB sample retrieves buffered mouse data inside the DirectXEvent.DXCallback method implemented by frmCanvas. This method is called each time an input event is signaled.

The method declares a buffer of the same size as the buffer DirectInput is using to store the data. This is the size that was set previously by a call to DirectInputDevice.SetProperty.

Dim diDeviceData(1 To BufferSize) As DIDEVICEOBJECTDATA

Also required are a variable to receive the number of items actually retrieved, a loop counter, and a variable to track the previous sequence number of an event:

Dim NumItems As Integer
Dim i As Integer
Static OldSequence As Long

The application now retrieves all the data available, in a single call to DirectInputDevice.GetDeviceData:

On Error GoTo INPUTLOST
NumItems = objDIDev.GetDeviceData(diDeviceData, 0)
On Error GoTo 0

Note the error trap. One of the events that DirectInput will signal is loss of acquisition. If the user switches to another application, for instance, ScrawlB will no longer have the mouse in the acquired state. An event will be signaled and this method will be called, but GetDeviceData will fail, because data can only be retrieved from an acquired device.

The application now iterates through the retrieved items and examines the data in the DIDEVICEOBJECTDATA type, comparing the lOfs member with the constants for the various buttons and axes that are of interest. For the x-axis, for instance, the application extracts the change in axis position from the lData member and uses this to adjust the cursor position, taking into account the user-defined sensitivity:

For i = 1 To NumItems
    Select Case diDeviceData(i).lOfs
        Case DIMOFS_X
           g_cursorx = g_cursorx + diDeviceData(i).lData * _
               g_Sensitivity

The application also examines the sequence number and compares it with the previous one. If two axis events have the same sequence number, the mouse has been moved diagonally, and it's not desirable to update the cursor position or draw a line until both movements have been taken into account.

           If OldSequence <> diDeviceData(i).lSequence Then
             UpdateCursor  ' Move cursor and maybe draw line
             OldSequence = diDeviceData(i).lSequence
           Else
             OldSequence = 0
           End If

For the buttons, the method determines the kind of event by checking the appropriate bit in lData. If the bit is set, the mouse button was pressed; otherwise, it was released. Remember, GetDeviceData does not return the current state of the device, so it is up to the application to keep a private record of whether a button is being held down. For the left button, ScrawlB keeps this information in the Drawing Boolean variable.

         Case DIMOFS_BUTTON0
           If diDeviceData(i).lData And &H80 Then
             Drawing = True

             ' Keep record for Line function
             CurrentX = g_cursorx
             CurrentY = g_cursory

             ' Draw point in case button-up follows immediately
             PSet (g_cursorx, g_cursory)
           Else
             Drawing = False
           End If
.
.
.
    End Select
Next i


Tutorial 3: Using the Joystick

[C++]

This topic pertains only to application development in Visual Basic. See DirectInput C/C++ Tutorials.

[Visual Basic]

This tutorial shows how to create a joystick device, set its properties, and retrieve immediate data. The example code is based on the Joystick sample.

The tutorial breaks down the required tasks into the following steps:

  • Step 1: Enumerate and Create the Joystick
  • Step 2: Get Joystick Capabilities
  • Step 3: Set Joystick Properties
  • Step 4: Retrieve Immediate Data from the Joystick


Step 1: Enumerate and Create the Joystick

[C++]

This topic pertains only to application development in Visual Basic. See DirectInput C/C++ Tutorials.

[Visual Basic]

Because there is no system joystick, in the sense that there can be a system keyboard or mouse, in order to create a DirectInputDevice object for a joystick you first need to obtain an instance GUID, or globally unique identifier. Generally this is done by enumerating the available joysticks, presenting the user with a choice, and then obtaining the information for the selected device.

The following function initializes DirectInput and enumerates attached joysticks:

Dim dx As New DirectX7
Dim di As DirectInput
Dim diDev As DirectInputDevice
Dim diDevEnum As DirectInputEnumDevices

Sub InitDirectInput()
    On Error GoTo Error_Out

    Set di = dx.DirectInputCreate()
    Set diDevEnum = di.GetDIEnumDevices( _
            DIDEVTYPE_JOYSTICK, DIEDFL_ATTACHEDONLY)
    If diDevEnum.GetCount = 0 Then
        MsgBox "No joystick attached."
        Unload Me
    End If

    'Add attached joysticks to the listbox
    Dim i As Integer
    For i = 1 To diDevEnum.GetCount
        Call lstJoySticks.AddItem( _
                diDevEnum.GetItem(i).GetInstanceName)
    Next

    ' Get an event handle to associate with the device
    EventHandle = dx.CreateEvent(Me)
    Exit Sub

Error_Out:
    MsgBox "Error initializing DirectInput."
    Unload Me

End Sub

When the user selects a joystick from the list, the device is created and initialized in the lstJoySticks_Click procedure:

Set diDev = di.CreateDevice(diDevEnum.GetItem( _
        lstJoySticks.ListIndex + 1).GetGuidInstance)
diDev.SetCommonDataFormat DIFORMAT_JOYSTICK
diDev.SetCooperativeLevel Me.hWnd, _
        DISCL_FOREGROUND Or DISCL_NONEXCLUSIVE

The call to DirectInput.CreateDevice takes as its parameter the GUID for a DirectInputDeviceInstance object obtained from the enumeration. Note that like all enumerated collections in DirectX for Visual Basic, the device enumeration is 1-based, so the index is one greater than the index of the selected item in the list box. The list box must also be unsorted.

You must set the data format before attempting to enumerate objects on the device or manipulate its properties.

Next: Step 2: Get Joystick Capabilities


Step 2: Get Joystick Capabilities

[C++]

This topic pertains only to application development in Visual Basic. See DirectInput C/C++ Tutorials.

[Visual Basic]

Getting basic information about the buttons, axes, and point-of-view controllers on the device requires a simple call to DirectInputDevice.GetCapabilities:

Dim joyCaps As DIDEVCAPS
Call diDev.GetCapabilities joyCaps

The Joystick sample is interested only in the number of buttons and point-of-view controllers on the device. Although the DIDEVCAPS type also reports the number of axes on the device, it does not reveal anything about what those axes are. For this information, the sample calls the IdentifyAxes procedure:

Sub IdentifyAxes(diDev As DirectInputDevice)

   Dim didoEnum As DirectInputEnumDeviceObjects
   Dim dido As DirectInputDeviceObjectInstance
   Dim i As Integer

   For i = 1 To 8
     AxisPresent(i) = False
   Next

After declaring a few variables and clearing out the AxisPresent array (which stores Boolean values for each possible axis), the procedure goes on to enumerate all device objects:

   Set didoEnum = diDev.GetDeviceObjectsEnum(DIDFT_AXIS)

It then queries each DirectInputDeviceObjectInstance for its offset within the data format that was established earlier by the call to DirectInputDevice.SetCommonDataFormat. This offset identifies the conventional role or type of the axis; for instance, you know that a DIJOFS_RZ axis likely corresponds to a twisting motion on the main stick. Keep in mind, though, that device drivers are free to assign any designation to an axis. It is always a good idea to allow users to change the mapping of the axes to actions within your application.

    For i = 1 To didoEnum.GetCount
        Set dido = didoEnum.GetItem(i)
        Select Case dido.GetOfs
            Case DIJOFS_X
                AxisPresent(1) = True
            Case DIJOFS_Y
                AxisPresent(2) = True
' and so on
.
.
.
        End Select
    Next
End Sub

The application now passes the event handle created earlier to the device, so that notifications will be sent to the form when an input event takes place.

Call diDev.SetEventNotification(EventHandle)

Next: Step 3: Set Joystick Properties


Step 3: Set Joystick Properties

[C++]

This topic pertains only to application development in Visual Basic. See DirectInput C/C++ Tutorials.

[Visual Basic]

Property changes are made through the DirectInputDevice.SetProperty method, and must be made after the data format of the device is established, but before it is acquired.

Because different devices might return different ranges of axis values, it is a good idea to set a range that will apply to all devices. The Joystick sample requests that all axis values be within the range 0 to 10,000.

Dim DiProp_Range As DIPROPRANGE

With DiProp_Range
    .lHow = DIPH_DEVICE  ' Set for all axes
    .lSize = Len(DiProp_Range)
    .lMin = 0
    .lMax = 10000
End With
diDev.SetProperty "DIPROP_RANGE", DiProp_Range

Note that you must specify the length of the DIPROPRANGE type within its lSize member, because the method can handle parameters of different types, and must know how much memory to allocate. If you're used to programming in C++, you should also note that Len(DIPROPRANGE) is not valid, because it returns zero.

The Joystick sample also sets the dead zone and saturation zones for the stick. In this case, it's not desirable to set these values for other axes such as a throttle or rudder, so the lHow member of the property type is set to indicated that the property change applies to a device object identified by its offset within the data format, and the lObj member is set to that offset value.

Dim DiProp_Dead As DIPROPLONG

With DiProp_Dead
    .lData = 1000
    .lObj = DIJOFS_X
    .lSize = Len(DiProp_Dead)
    .lHow = DIPH_BYOFFSET
' Set for x-axis
    .lObj = DIJOFS_X
    diDev.SetProperty "DIPROP_DEADZONE", DiProp_Dead
' Set for y-axis
    .lObj = DIJOFS_Y
    diDev.SetProperty "DIPROP_DEADZONE", DiProp_Dead
End With

The value in lData is the proportion of the range of travel, in units of 10,000, that is set up as a dead zone. The value of 1000 used in the example specifies that the middle 10 percent of the range of travel on the x-axis and y-axis will be reported as 5000, which happens to be the center of the range set in the previous step.

Note Dead zone and saturation values are always in units of 10,000, regardless of the range of values reported by the device.

The saturation zones for the device are set similarly. In this case lData is 9500, because it represents the proportion of the range of travel that lies outside the saturation zones at the extremities. In other words, the bottom and top 5 percent of the raw values returned by the stick will be reported as the minimum or maximum range value set for the device (in this case, 0 or 10,000).

Next: Step 4: Retrieve Immediate Data from the Joystick


Step 4: Retrieve Immediate Data from the Joystick

[C++]

This topic pertains only to application development in Visual Basic. See DirectInput C/C++ Tutorials.

[Visual Basic]

Now that the necessary properties have been set, the device can be acquired and data can be collected from the joystick. In the Joystick sample, the device is polled in a loop after its properties have been set. In a real-world multimedia application, polling would take place in the main game loop or rendering loop.

diDev.Acquire

While DoEvents
    diDev.Poll
Wend

The sample application does not actually retrieve immediate data each time the device is polled. To avoid unnecessary screen updates, it relies on notification, and the call to Poll is only to ensure that notifications are issued by devices that do not generate interrupts. Polling is not necessary for some game devices (such as HIDs), but it is just as efficient to make a redundant call to DirectInputDevice.Poll as it would be to check a flag for the device before calling Poll.

Notifications are handled, as usual, in the implementation of the DirectXEvent.DXCallback method. Each time this procedure is called, the application knows that some joystick event has occurred. At this point it could call DirectInputDevice.GetDeviceData to retrieve any pending axis changes or button events. However, with a game controller it would be more usual to retrieve the state of the entire device, so the sample uses DirectInputDevice.GetDeviceStateJoystick.

Dim js As DIJOYSTATE

diDev.GetDeviceStateJoystick js

The values in the DIJOYSTATE type now tell the application everything it needs to know about the state of the device objects. Since it knows from Step 2: Get Joystick Capabilities what buttons, axes, and point-of-view controllers are actually present, it also knows which members of the type to ignore.


Tutorial 4: Using Force Feedback

[C++]

This topic pertains only to application development in Visual Basic. See DirectInput C/C++ Tutorials.

[Visual Basic]

This tutorial shows how to test for the presence of a force-feedback device, how to create and play an effect, and how to change the parameters of an effect as it is playing.

The tutorial breaks down the tasks into the following steps:

  • Step 1: Initialize the Force-Feedback Device
  • Step 2: Set Device Properties
  • Step 3: Create an Effect
  • Step 4: Modify an Effect


Step 1: Initialize the Force-Feedback Device

[C++]

This topic pertains only to application development in Visual Basic. See DirectInput C/C++ Tutorials.

[Visual Basic]

In order to implement force feedback, you must first determine whether an appropriate device is available, and if so, create a DirectInputDevice object for it. Let's presume that your application requires a device that can play effects on the x-axis and y-axis.

The following example starts by creating a DirectInput object, then using that to enumerate the available devices in a DirectInputEnumDevices object. The enumeration is restricted to attached devices of type DIDEVTYPE_JOYSTICK, since all force-feedback devices are of this type.

' dx is the global DirectX object, already initialized
' di is the global DirectInput object

Dim diDevInst As DirectInputDeviceInstance
Dim diDevObjEnum As DirectInputEnumDeviceObjects
Dim devobj As DirectInputDeviceObjectInstance

Dim devcaps As DIDEVCAPS
Dim ForceX As Boolean, ForceY As Boolean
Dim FoundForce As Boolean
Dim efftype As Long
Dim strObjGuid As String

Dim i As Integer, iAxes As Integer

Set di = dx.DirectInputCreate
Set diEnumDev = di.GetDIEnumDevices(DIDEVTYPE_JOYSTICK, _
        DIEDFL_ATTACHEDONLY)

The example now iterates through the available devices till it finds one that has force-feedback capabilities.

For i = 1 To diEnumDev.GetCount
  Set diDevInst = diEnumDev.GetItem(i)
  Set didev = di.CreateDevice(diDevInst.GetGuidInstance)
  Call didev.GetCapabilities(devcaps)
  If devcaps.lFlags And DIDC_FORCEFEEDBACK Then

Now the example enumerates the axes on the device in a DirectInputEnumDeviceObjects collection:

    Set diDevObjEnum = didev.GetDeviceObjectsEnum(DIDFT_AXIS)
    ForceX = False
    ForceY = False

It then goes through the axes looking for the x-axis and y-axis, and checks to see whether they support force-feedback effects:

    For iAxes = 1 To diDevObjEnum.GetCount
      Set devobj = diDevObjEnum.GetItem(iAxes)
      strObjGuid = devobj.GetGuidType
      If strObjGuid = "GUID_XAxis" Then
        If devobj.GetFlags And DIDOI_FFACTUATOR Then
          ForceX = True
        End If
      ElseIf strObjGuid = "GUID_YAxis" Then
        If devobj.GetFlags And DIDOI_FFACTUATOR Then
          ForceY = True
        End If
      End If
    Next iAxes
    FoundForce = ForceX And ForceY
    if FoundForce Then Exit For
  End If
Next i

If Not FoundForce Then
  MsgBox "Two force feedback axes required."
End

Next: Step 2: Set Device Properties


Step 2: Set Device Properties

[C++]

This topic pertains only to application development in Visual Basic. See DirectInput C/C++ Tutorials.

[Visual Basic]

Presuming you have found a suitable force-feedback device, the DirectInputDevice object created in the last step in order to check capabilities can be left in place. It requires some further initialization, as covered in Tutorial 3: Using the Joystick: setting the data format and cooperative level, and setting the range properties for input. Note that the cooperative level must include DISCL_EXCLUSIVE. Although you probably won't need background access to the device, the DISCL_BACKGROUND flag makes debugging easier, because you won't keep losing acquisition when you switch to the code window.

Call didev.SetCommonDataFormat(DIFORMAT_JOYSTICK2)
Call didev.SetCooperativeLevel(Me.hWnd, _
        DISCL_BACKGROUND Or DISCL_EXCLUSIVE)
' Set range properties...
.
.
.

For force feedback, you might also want to disable the autocenter property of the device, so that the default spring action will not interfere with effects you create:

Dim prop As DIPROPLONG
prop.lData = 0
prop.lHow = DIPH_DEVICE
prop.lObj = 0
prop.lSize = Len(prop)
Call didev.SetProperty("DIPROP_AUTOCENTER", prop)

didev.Acquire

Next: Step 3: Create an Effect


Step 3: Create an Effect

[C++]

This topic pertains only to application development in Visual Basic. See DirectInput C/C++ Tutorials.

[Visual Basic]

Let's suppose that in your application you wish to simulate the pull of a stationary object (say a magnet) on a movable object (say an iron ball) controlled by the joystick. At the beginning of the simulation, the iron ball is due south of the magnet and experiencing one-half the maximum possible pull.

You will simulate the pull of the magnet by a constant force. First you set up the DIEFFECT type that describes the force:

Dim EffectInfo as DIEFFECT
With EffectInfo
  .constantForce.lMagnitude = 5000
  .lDuration = -1       ' Infinite
  .x = 18000
  .lGain = 10000        ' Play at full magnitude
  .lTriggerButton = -1  ' No trigger button
End With

All the other members of DIEFFECT are either not relevant to a constant force or are valid as 0.

Now create the effect:

Dim di_effect As DirectInputEffect
Set di_effect = didev.CreateEffect("GUID_ConstantForce", EffectInfo)

If the device is in an acquired state at this time, the effect is automatically downloaded. If not, the effect will be downloaded when it is started.

di_effect.Start(1, 0)

Only one iteration of the effect is needed, since it has infinite duration, and no flags are required in this case.

Next: Step 4: Modify an Effect


Step 4: Modify an Effect

[C++]

This topic pertains only to application development in Visual Basic. See DirectInput C/C++ Tutorials.

[Visual Basic]

As the user moves the iron ball around, the application will adjust the direction and magnitude of the effect. First of all, though, you may want to check whether the device allows you to change the direction of the effect without stopping and restarting it. DirectInput will stop and restart the effect automatically if necessary, but you might want to modify the behavior of your application to avoid breaks in continuity.

In order to examine the capabilities for any effect, you need to enumerate supported effects and then look for the particular one you are interested in.

Dim diEnumEffects As DirectInputEnumEffects
Dim params As Long
Dim i As Long

' Enumerate constant forces

Set diEnumEffects = didev.GetEffectsEnum(DIEFT_CONSTANTFORCE)

For i = 1 To diEnumEffects.GetCount

  ' Look for the standard constant force. There could be others.

  If diEnumEffects.GetEffectGuid(i) = "GUID_ConstantForce" Then
    params = diEnumEffects.GetDynamicParams(i)
    Exit For
  End If

Next i

If Not (params And DIEP_DIRECTION) Then
  ' Cannot change direction dynamically. Take remedial action such
  ' as limiting points at which modifications will be made.
End If

Similarly, to learn whether you can change the magnitude of the effect dynamically, perform the following check:

if Not (params And DIEP_TYPESPECIFICPARAMS)
   ' Can't change type-specific parameters dynamically.
End If

Now you wish to modify the effect each time the device has been polled for input and the iron ball has moved. Let's presume that you have calculated the new magnitude in CurrentMag and the new direction (in degrees) in CurrentBearing. In order to make the necessary changes, you need to initialize only those members of DIEFFECT that are relevant.

EffectInfo.constantForce.lMagnitude = CurrentMag
EffectInfo.x = CurrentBearing * 100

You now pass the DIEFFECT type to DirectInputEffect.SetParameters along with flags indicating which members contain valid data:

di_effect.SetParameters(EffectInfo, _
        DIEP_DIRECTION Or DIEP_TYPESPECIFICPARAMS)

The DIEP_TYPESPECIFICPARAMS flag indicates that any member containing information particular to that type of effect is valid. In the case of a constant force, this means the constantForce member.


DirectInput Reference

This section contains reference information for the application programming interface (API) elements provided by Microsoft® DirectInput® in C/C++ and Microsoft® Visual Basic® development systems. Reference material is organized by language:

  • DirectInput C/C++ Reference
  • DirectInput Visual Basic Reference


DirectInput C/C++ Reference

Reference material for the DirectInput C/C++ API is divided into the following categories:

  • Interfaces
  • Functions
  • Callback Functions
  • Macros
  • Structures
  • Device Constants
  • Return Values


Interfaces

This section contains references for methods of the following DirectInput interfaces:

  • IDirectInput7
  • IDirectInputDevice7
  • IDirectInputEffect

Note All DirectInput methods have corresponding macros that expand to C or C++ syntax depending on which language is defined. These macros are found in the Dinput.h header file and are not documented separately.


IDirectInput7

Applications use the methods of the IDirectInput7 interface to enumerate, create, and retrieve the status of DirectInput devices, initialize the DirectInput object, and invoke an instance of the Windows Control Panel.

The IDirectInput7 interface is obtained by using the DirectInputCreateEx function.

IDirectInput7 supersedes the IDirectInput interface used in earlier versions of DirectX.

The methods of the IDirectInput7 interface can be organized into the following groups.

Device Management | CreateDevice
 | CreateDeviceEx
 | EnumDevices
 | FindDevice
 | GetDeviceStatus
Miscellaneous | Initialize
 | RunControlPanel

The IDirectInput interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECTINPUT type is defined as a pointer to the IDirectInput7 interface:

typedef struct IDirectInput7    *LPDIRECTINPUT7;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.


IDirectInput7::CreateDevice

The IDirectInput7::CreateDevice method creates and initializes an instance of a device based on a given GUID, and obtains an IDirectInputDevice interface. This method has been superseded by IDirectInput7::CreateDeviceEx.

HRESULT CreateDevice(
  REFGUID rguid,
  LPDIRECTINPUTDEVICE *lplpDirectInputDevice,
  LPUNKNOWN pUnkOuter
);

Parameters

rguid
Reference to (C++) or address of (C) the instance GUID for the desired input device (see Remarks). The GUID is retrieved through the IDirectInput7::EnumDevices method, or it can be one of the following predefined GUIDs:
GUID_SysKeyboard
The default system keyboard.
GUID_SysMouse
The default system mouse.

For the preceding GUID values to be valid, your application must define INITGUID before all other preprocessor directives at the beginning of the source file, or link to Dxguid.lib.

lplpDirectInputDevice
Address of a variable to receive the IDirectInputDevice interface pointer if successful.
pUnkOuter
Address of the controlling object's IUnknown interface for COM aggregation, or NULL if the interface is not aggregated. Most callers pass NULL.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following:

DIERR_DEVICENOTREG
DIERR_INVALIDPARAM
DIERR_NOINTERFACE
DIERR_NOTINITIALIZED
DIERR_OUTOFMEMORY

Remarks

In C++ the rguid parameter must be passed by reference; in C, which does not permit passing by reference, it must be passed by address. The following is an example of a C++ call:

lpdi->CreateDevice(GUID_SysKeyboard, &pdev, NULL);

The following shows the same call in C:

lpdi->lpVtbl->CreateDevice(lpdi, &GUID_SysKeyboard, &pdev, NULL);

Calling this method with pUnkOuter = NULL is equivalent to creating the object by CoCreateInstance(&CLSID_DirectInputDevice, NULL, CLSCTX_INPROC_SERVER, riid, lplpDirectInputDevice) and then initializing it with Initialize.

Calling this method with pUnkOuter != NULL is equivalent to creating the object by CoCreateInstance(&CLSID_DirectInputDevice, punkOuter, CLSCTX_INPROC_SERVER, &IID_IUnknown, lplpDirectInputDevice). The aggregated object must be initialized manually.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.


IDirectInput7::CreateDeviceEx

The IDirectInput7::CreateDeviceEx method creates and initializes an instance of a device based on a given GUID, and obtains an IDirectInputDevice, IDirectInputDevice2, or IDirectInputDevice7 interface.

HRESULT CreateDeviceEx(
  REFGUID rguid,
  REFIID riid,
  LPVOID *pvOut,
  LPUNKNOWN pUnkOuter
);

Parameters

rguid
Reference to (C++) or address of (C) the instance GUID for the desired input device (see Remarks). The GUID is retrieved through the IDirectInput7::EnumDevices method, or it can be one of the following predefined GUIDs:
GUID_SysKeyboard
The default system keyboard.
GUID_SysMouse
The default system mouse.

For the preceding GUID values to be valid, your application must define INITGUID before all other preprocessor directives at the beginning of the source file, or link to Dxguid.lib.

riid
Unique identifier for the desired interface. Currently accepted values are IID_IDirectInputDevice, IID_IDirectInputDevice2, and IID_IDirectInputDevice7.
pvOut
Address of a variable to receive the interface pointer if successful.
pUnkOuter
Address of the controlling object's IUnknown interface for COM aggregation, or NULL if the interface is not aggregated. Most callers pass NULL.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following:

DIERR_DEVICENOTREG
DIERR_INVALIDPARAM
DIERR_NOINTERFACE
DIERR_NOTINITIALIZED
DIERR_OUTOFMEMORY

Remarks

In C++ the rguid parameter must be passed by reference; in C, which does not permit passing by-reference, it must be passed by address. The following is an example of a C++ call:

lpdi->CreateDevice(GUID_SysKeyboard, &pdev, NULL);

The following shows the same call in C:

lpdi->lpVtbl->CreateDevice(lpdi, &GUID_SysKeyboard, &pdev, NULL);

Most applications will want to pass IID_IDirectInputDevice7 in the riid parameter to obtain the IDirectInputDevice7 interface.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.


IDirectInput7::EnumDevices

The IDirectInput7::EnumDevice method enumerates devices that are either currently attached or could be attached to the computer.

HRESULT EnumDevices(
  DWORD dwDevType,
  LPDIENUMCALLBACK lpCallback,
  LPVOID pvRef,
  DWORD dwFlags
);

Parameters

dwDevType
Device type filter. If this parameter is 0, all device types are enumerated. Otherwise, it is a DIDEVTYPE_* value (see DIDEVICEINSTANCE), indicating the device type that should be enumerated.
lpCallback
Address of a callback function to be called with a description of each DirectInput device.
pvRef
Application-defined 32-bit value to be passed to the enumeration callback each time it is called.
dwFlags
Flag value that specifies the scope of the enumeration. This parameter can be one or more of the following values:
DIEDFL_ALLDEVICES
All installed devices are enumerated. This is the default behavior.
DIEDFL_ATTACHEDONLY
Only attached and installed devices.
DIEDFL_FORCEFEEDBACK
Only devices that support force feedback.
DIEDFL_INCLUDEALIASES
Include devices that are aliases for other devices.
DIEDFL_INCLUDEPHANTOMS
Include phantom (placeholder) devices.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED

Remarks

All installed devices can be enumerated, even if they are not present. For example, a flight stick might be installed on the system, but not currently plugged into the computer. Set the dwFlags parameter to indicate whether only attached or all installed devices should be enumerated. If the DIEDFL_ATTACHEDONLY flag is not present, all installed devices are enumerated.

A preferred device type can be passed as a dwDevType filter so that only the devices of that type are enumerated.

The lpCallback parameter specifies the address of a callback function of the type documented as DIEnumDevicesCallback. DirectInput calls this function for every device that is enumerated. In the callback, the device type and friendly name, and the product GUID and friendly name, are given for each device. If a single input device can function as more than one DirectInput device type, it is returned for each device type that it supports. For example, a keyboard with a built-in mouse is enumerated as a keyboard and as a mouse. The product GUID would be the same for each device, however.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.


IDirectInput7::FindDevice

The IDirectInput7::FindDeviceStatus method retrieves the instance GUID of a device that has been newly attached to the system. It is called in response to a Win32 device management notification.

HRESULT FindDevice(
  REFGUID rguidClass,
  LPCTSTR ptszName,
  LPGUID pguidInstance
);

Parameters

rguidClass
Unique identifier of the device class for the device that the application is to locate. The application obtains the class GUID from the device arrival notification. (See the documentation for the DBT_DEVICEARRIVAL event in the Platform SDK.)
ptszName
Name of the device. The application obtains the name from the device arrival notification.
pguidInstance
Address of a variable to receive the instance GUID for the device, if the device is found. This value can be passed to IDirectInput7::CreateDeviceEx.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be DIERR_DEVICENOTREG. Failure results if the GUID and name do not correspond to a device class that is registered with DirectInput. For example, they might refer to a storage device, rather than an input device.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.

See Also

Recognizing Device Changes


IDirectInput7::GetDeviceStatus

The IDirectInput7::GetDeviceStatus method retrieves the status of a specified device.

HRESULT GetDeviceStatus(
  REFGUID rguidInstance
);

Parameters

rguidInstance
Instance identifier of the device whose status is being checked.

Return Values

If the method succeeds, the return value is DI_OK if the device is attached to the system, or DI_NOTATTACHED otherwise.

If the method fails, the return value can be one of the following error values:

DIERR_GENERIC
DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.


IDirectInput7::Initialize

The IDirectInput7::Initialize method initializes a DirectInput object. The DirectInputCreate and DirectInputCreateEx functions automatically initialize the DirectInput object after creating it. Applications normally do not need to call this method.

HRESULT Initialize(
  HINSTANCE hinst,
  DWORD dwVersion
);

Parameters

hinst
Instance handle to the application or dynamic-link library (DLL) that is creating the DirectInput object. DirectInput uses this value to determine whether the application or DLL has been certified and to establish any special behaviors that might be necessary for backwards compatibility.

It is an error for a DLL to pass the handle of the parent application. For example, an ActiveX control embedded in a Web page that uses DirectInput must pass its own instance handle, and not the handle of the Web browser. This ensures that DirectInput recognizes the control and can enable any special behaviors that might be necessary.

dwVersion
Version number of DirectInput for which the application is designed. This value is normally DIRECTINPUT_VERSION. Passing the version number of a previous version causes DirectInput to emulate that version. For more information, see Designing for Previous Versions of DirectInput.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_BETADIRECTINPUTVERSION
DIERR_OLDDIRECTINPUTVERSION

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.


IDirectInput7::RunControlPanel

The IDirectInput7::RunControlPanel method runs Control Panel to allow the user to install a new input device or modify configurations.

HRESULT RunControlPanel(
  HWND hwndOwner,
  DWORD dwFlags
);

Parameters

hwndOwner
Handle of the window to be used as the parent window for the subsequent user interface. If this parameter is NULL, no parent window is used.
dwFlags
Currently not used and must be set to 0.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.

See Also

IDirectInputDevice7::RunControlPanel


IDirectInputDevice7

Applications use the methods of the IDirectInputDevice7 interface to gain and release access to DirectInput devices, manage device properties and information, set behavior, perform initialization, create and play force-feedback effects, and invoke a device's control panel.

The IDirectInputDevice7 interface is obtained by using the IDirectInput7::CreateDeviceEx method. For an example, see Creating a DirectInput Device.

IDirectInputDevice7 supersedes the IDirectInputDevice and IDirectInputDevice2 interfaces used in previous versions of DirectX.

The methods of the IDirectInputDevice7 interface can be organized into the following groups.

Accessing input devices | Acquire
 | Unacquire
Device information | GetCapabilities
 | GetDeviceData
 | GetDeviceInfo
 | GetDeviceState
 | Poll
 | SetDataFormat
 | SetEventNotification
Device objects | EnumObjects
 | GetObjectInfo
Device properties | GetProperty
 | SetCooperativeLevel
 | SetProperty
Force feedback | CreateEffect
 | EnumCreatedEffectObjects
 | EnumEffects
 | EnumEffectsInFile
 | Escape
 | GetEffectInfo
 | GetForceFeedbackState
 | SendForceFeedbackCommand
 | WriteEffectToFile
Miscellaneous | Initialize
 | RunControlPanel
 | SendDeviceData

The IDirectInputDevice7 interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECTINPUTDEVICE7 type is defined as a pointer to the IDirectInputDevice interface:

typedef struct IDirectInputDevice7    *LPDIRECTINPUTDEVICE7;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.

See Also

IDirectInputDevice7

Built on Thursday, September 02, 1999


IDirectInputDevice7::Acquire

The IDirectInputDevice7::Acquire method obtains access to the input device.

HRESULT Acquire();

Parameters

None.

Return Values

If the method succeeds, the return value is DI_OK or S_FALSE.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED
DIERR_OTHERAPPHASPRIO

If the method returns S_FALSE, the device has already been acquired.

Remarks

Before a device can be acquired, a data format must be set by using the IDirectInputDevice7::SetDataFormat method.

Devices must be acquired before calling the IDirectInputDevice7::GetDeviceState or IDirectInputDevice7::GetDeviceData methods for that device.

Device acquisition does not use a reference count. Therefore, if an application calls the IDirectInputDevice7::Acquire method twice, then calls the IDirectInputDevice7::Unacquire method once, the device is unacquired.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.


IDirectInputDevice7::CreateEffect

The IDirectInputDevice7::CreateEffect method creates and initializes an instance of an effect identified by the effect GUID.

HRESULT CreateEffect(
  REFGUID rguid,
  LPCDIEFFECT lpeff,
  LPDIRECTINPUTEFFECT * ppdeff,
  LPUNKNOWN punkOuter
);

Parameters

rguid
Identity of the effect to be created. This can be a predefined effect GUID, or it can be a GUID obtained from IDirectInputDevice7::EnumEffects.

The following effect GUIDs are defined:

  • GUID_ConstantForce
  • GUID_RampForce
  • GUID_Square
  • GUID_Sine
  • GUID_Triangle
  • GUID_SawtoothUp
  • GUID_SawtoothDown
  • GUID_Spring
  • GUID_Damper
  • GUID_Inertia
  • GUID_Friction
  • GUID_CustomForce
lpeff
DIEFFECT structure that provides parameters for the created effect. This parameter is optional. If it is NULL, the effect object is created without parameters. The application must then call the IDirectInputEffect::SetParameters method to set the parameters of the effect before it can download the effect.
ppdeff
Address of a variable to receive a pointer to the IDirectInputEffect interface if successful.
punkOuter
Controlling unknown for COM aggregation. The value is NULL if the interface is not aggregated. Most callers pass NULL.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_DEVICENOTREG
DIERR_DEVICEFULL
DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED

If the return value is S_OK, the effect was created, and the parameters of the effect were updated, but the effect was not necessarily downloaded. For it to be downloaded, the device must be acquired in exclusive mode.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.


IDirectInputDevice7::EnumCreatedEffectObjects

The IDirectInputDevice7::EnumCreatedEffectObjects method enumerates all the currently created effects for this device. Effects created by IDirectInputDevice7::CreateEffect are enumerated.

HRESULT EnumCreatedEffectObjects(
  LPDIENUMCREATEDEFFECTOBJECTSCALLBACK lpCallback,
  LPVOID pvRef,
  DWORD fl
);

Parameters

lpCallback
Address of an application-defined callback function. DirectInput provides the prototype function DIEnumCreatedEffectObjectsCallback.
pvRef
Reference data (context) for callback.
fl
No flags are currently defined. This parameter must be 0.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED

Remarks

The results are unpredictable if you create or destroy an effect while an enumeration is in progress. However, the callback function can safely release the effect passed to it.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.


IDirectInputDevice7::EnumEffects

The IDirectInputDevice7::EnumEffects method enumerates all the effects supported by the force-feedback system on the device. The enumerated GUIDs can represent predefined effects, as well as effects peculiar to the device manufacturer.

HRESULT EnumEffects(
  LPDIENUMEFFECTSCALLBACK lpCallback,
  LPVOID pvRef,
  DWORD dwEffType
);

Parameters

lpCallback
Address of an application-defined callback function. The declaration of this function must conform to that of the DIEnumEffectsCallback prototype.
pvRef
A 32-bit application-defined value to be passed to the callback function. This parameter can be any 32-bit type; it is declared as LPVOID for convenience.
dwEffType
Effect type filter. Use one of the DIEFT_* values to indicate the effect type to be enumerated, or DIEFT_ALL to enumerate all effect types. For a list of these values, see DIEFFECTINFO.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED

If the callback stops the enumeration prematurely, the enumeration is considered to have succeeded.

Remarks

An application can use the dwEffType member of the DIEFFECTINFO structure to obtain general information about the effect, such as its type and which envelope and condition parameters are supported by the effect.

To exploit an effect to its fullest, contact the device manufacturer to obtain information on the semantics of the effect and its effect-specific parameters.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.


IDirectInputDevice7::EnumEffectsInFile

The IDirectInputDevice7::EnumEffectsInFile method enumerates all the effects in a file created by the Force Editor utility or another application using the same file format.

HRESULT EnumEffectsInFile(
  LPCSTR lpszFileName,
  LPENUMEFFECTSINFILECALLBACK pec,
  LPVOID pvRef,
  DWORD dwFlags
);

Parameters

lpszFileName
Name of the RIFF file.
pec
Address of an application-defined callback function. The declaration of this function must conform to that of the DIEnumEffectsInFileCallback prototype.
pvRef
Application-defined value to be passed to the callback function. This parameter can be any 32-bit type.
dwFlags
Can be DIFEF_DEFAULT ( = 0) or one or both of the following values:
DIFEF_INCLUDENONSTANDARD
Include effect types that are not defined by DirectInput.
DIFEF_MODIFYIFNEEDED
Instruct DirectInput to modify the authored effect, if necessary, so that it plays on the current device. For example, by default, an effect authored for two axes does not play on a single-axis device. Setting this flag allows the effect to play on a single axis. The parameters are modified in the DIEFFECT structure pointed to by the lpDiEffect member of the DIFILEEFFECT structure passed to the callback.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED

If the callback stops the enumeration prematurely, the enumeration is considered to have succeeded.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.

See Also

IDirectInputDevice7::WriteEffectToFile, Loading Effects from a File


IDirectInputDevice7::EnumObjects

The IDirectInputDevice7::EnumObjects method enumerates the input and force-feedback objects available on a device.

HRESULT EnumObjects(
  LPDIENUMDEVICEOBJECTSCALLBACK lpCallback,
  LPVOID pvRef,
  DWORD dwFlags
);

Parameters

lpCallback
Address of a callback function that receives DirectInputDevice objects. DirectInput provides a prototype of this function as DIEnumDeviceObjectsCallback.
pvRef
Reference data (context) for callback.
dwFlags
Flags specifying the types of object to be enumerated. Each of the following values restricts the enumeration to objects of the described type:
DIDFT_ABSAXIS
An absolute axis.
DIDFT_ALL
All objects.
DIDFT_AXIS
An axis, either absolute or relative.
DIDFT_BUTTON
A push button or a toggle button.
DIDFT_COLLECTION
An HID link collection. HID link collections do not generate data of their own.
DIDFT_ENUMCOLLECTION(n)
An object that belongs to HID link collection number n.
DIDFT_FFACTUATOR
An object that contains a force-feedback actuator. In other words, forces can be applied to this object.
DIDFT_FFEFFECTTRIGGER
An object that can be used to trigger force-feedback effects.
DIDFT_NOCOLLECTION
An object that does not belong to any HID link collection; in other words, an object for which the wCollectionNumber member of the DIDEVICEOBJECTINSTANCE structure is 0.
DIDFT_NODATA
An object that does not generate data.
DIDFT_OUTPUT
An object to which data can be sent by using the IDirectInputDevice7::SendDeviceData method.
DIDFT_POV
A point-of-view controller.
DIDFT_PSHBUTTON
A push button. A push button is reported as down when the user presses it and as up when the user releases it.
DIDFT_RELAXIS
A relative axis.
DIDFT_TGLBUTTON
A toggle button. A toggle button is reported as down when the user presses it and remains so until the user presses the button a second time.
DIDFT_VENDORDEFINED
An object of a type defined by the manufacturer.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED

Remarks

The DIDFT_FFACTUATOR and DIDFT_FFEFFECTTRIGGER flags in the dwFlags parameter restrict enumeration to objects that meet all the criteria defined by the included flags. For all the other flags, an object is enumerated if it meets the criterion defined by any included flag in this category. For example, (DIDFT_FFACTUATOR | DIDFT_FFEFFECTTRIGGER) restricts enumeration to force-feedback trigger objects, and (DIDFT_FFEFFECTTRIGGER | DIDFT_TGLBUTTON | DIDFT_PSHBUTTON) restricts enumeration to buttons of any kind that can be used as effect triggers.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.


IDirectInputDevice7::Escape

The IDirectInputDevice7::Escape method sends a hardware-specific command to the force-feedback driver.

HRESULT Escape(
  LPDIEFFESCAPE pesc
);

Parameters

pesc
DIEFFESCAPE structure that describes the command to be sent. On success, the cbOutBuffer member contains the number of bytes of the output buffer actually used.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_DEVICEFULL
DIERR_NOTINITIALIZED

Other device-specific error codes are also possible. Ask the hardware manufacturer for details.

Remarks

Since each driver implements different escapes, it is the application's responsibility to ensure that it is sending the escape to the correct driver by comparing the value of the guidFFDriver member of the DIDEVICEINSTANCE structure against the value the application is expecting.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.


IDirectInputDevice7::GetCapabilities

The IDirectInputDevice7::GetCapabilities method obtains the capabilities of the DirectInputDevice object.

HRESULT GetCapabilities(
  LPDIDEVCAPS lpDIDevCaps
);

Parameters

lpDIDevCaps
Address of a DIDEVCAPS structure to be filled with the device capabilities. The dwSize member of this structure must be initialized before calling this method.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED

Remarks

For compatibility with DirectX 3, it is also valid to pass a DIDEVCAPS_DX3 structure with the dwSize member initialized to sizeof(DIDEVCAPS_DX3). For more information, see Designing for Previous Versions of DirectInput.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.


IDirectInputDevice7::GetDeviceData

The IDirectInputDevice7::GetDeviceData method retrieves buffered data from the device.

HRESULT GetDeviceData(
  DWORD cbObjectData,
  LPDIDEVICEOBJECTDATA rgdod,
  LPDWORD pdwInOut,
  DWORD dwFlags
);

Parameters

cbObjectData
Size of the DIDEVICEOBJECTDATA structure, in bytes.
rgdod
Array of DIDEVICEOBJECTDATA structures to receive the buffered data. The number of elements in this array must be equal to the value of the pdwInOut parameter. If this parameter is NULL, the buffered data is not stored anywhere, but all other side-effects take place.
pdwInOut
On entry, the number of elements in the array pointed to by the rgdod parameter. On exit, the number of elements actually obtained.
dwFlags
Flags that control the manner in which data is obtained. This value can be 0 or the following flag:
DIGDD_PEEK
Do not remove the items from the buffer. A subsequent IDirectInputDevice7::GetDeviceData call will read the same data. Normally, data is removed from the buffer after it is read.

Return Values

If the method succeeds, the return value is DI_OK or DI_BUFFEROVERFLOW.

If the method fails, the return value can be one of the following error values:

DIERR_INPUTLOST
DIERR_INVALIDPARAM
DIERR_NOTACQUIRED
DIERR_NOTBUFFERED
DIERR_NOTINITIALIZED

Remarks

Before device data can be obtained, you must set the data format by using the IDirectInputDevice7::SetDataFormat method, set the buffer size with the IDirectInputDevice7::SetProperty method, and acquire the device by using the IDirectInputDevice7::Acquire method.

The following code example reads up to ten buffered data elements, removing them from the device buffer as they are read.

DIDEVICEOBJECTDATA rgdod[10];
DWORD dwItems = 10;
hres = IDirectInputDevice7_GetDeviceData(
    pdid,
    sizeof(DIDEVICEOBJECTDATA),
    rgdod,
    &dwItems,
    0);
if (SUCCEEDED(hres)) {
    // dwItems = number of elements read (could be zero)
    if (hres == DI_BUFFEROVERFLOW) {
    // Buffer had overflowed.
    }
}

Your application can flush the buffer and retrieve the number of flushed items by specifying NULL for the rgdod parameter and a pointer to a variable containing INFINITE for the pdwInOut parameter. The following code example illustrates how this can be done:

dwItems = INFINITE;
hres = IDirectInputDevice7_GetDeviceData(
            pdid,
            sizeof(DIDEVICEOBJECTDATA),
            NULL,
            &dwItems,
            0);
if (SUCCEEDED(hres)) {
    // Buffer successfully flushed
    // dwItems = number of elements flushed
    if (hres == DI_BUFFEROVERFLOW) {
        // Buffer had overflowed.
    }
}

Your application can query for the number of elements in the device buffer by setting the rgdod parameter to NULL, setting pdwInOut to INFINITE and setting dwFlags to DIGDD_PEEK. The following code example illustrates how this can be done:

dwItems = INFINITE;
hres = IDirectInputDevice7_GetDeviceData(
            pdid,
            sizeof(DIDEVICEOBJECTDATA),
            NULL,
            &dwItems,
            DIGDD_PEEK);
if (SUCCEEDED(hres)) {
    // dwItems = number of elements in buffer
    if (hres == DI_BUFFEROVERFLOW) {
        // Buffer overflow occurred; not all data
        // was successfully captured.
    }
}

To query about whether a buffer overflow has occurred, set the rgdod parameter to NULL and the pdwInOut parameter to 0. The following code example illustrates how this can be done:

dwItems = 0;
hres = IDirectInputDevice7_GetDeviceData(
            pdid,
            sizeof(DIDEVICEOBJECTDATA),
            NULL,
            &dwItems,
            0);
if (hres == DI_BUFFEROVERFLOW) {
    // Buffer overflow occurred
}

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.

See Also

IDirectInputDevice7::Poll, Polling and Events


IDirectInputDevice7::GetDeviceInfo

The IDirectInputDevice7::GetDeviceInfo method obtains information about the device's identity.

HRESULT GetDeviceInfo(
  LPDIDEVICEINSTANCE pdidi
);

Parameters

pdidi
Address of a DIDEVICEINSTANCE structure to be filled with information about the device's identity. An application must initialize the structure's dwSize member before calling this method.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED

Remarks

For compatibility with DirectX 3, it is also valid to pass a DIDEVICEINSTANCE_DX3 structure with the dwSize member initialized to sizeof(DIDEVICEINSTANCE_DX3). For more information, see Designing for Previous Versions of DirectInput.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.


IDirectInputDevice7::GetDeviceState

The IDirectInputDevice7::GetDeviceState method retrieves immediate data from the device.

HRESULT GetDeviceState(
  DWORD cbData,
  LPVOID lpvData
);

Parameters

cbData
Size of the buffer in the lpvData parameter, in bytes.
lpvData
Address of a structure that receives the current state of the device. The format of the data is established by a prior call to the IDirectInputDevice7::SetDataFormat method.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INPUTLOST
DIERR_INVALIDPARAM
DIERR_NOTACQUIRED
DIERR_NOTINITIALIZED
E_PENDING

Remarks

Before device data can be obtained, set the cooperative level by using the IDirectInputDevice7::SetCooperativeLevel method, then set the data format by using IDirectInputDevice7::SetDataFormat, and acquire the device by using the IDirectInputDevice7::Acquire method.

The five predefined data formats require corresponding device state structures according to the following table:

Data format | State structure
c_dfDIMouse | DIMOUSESTATE
c_dfDIMouse2 | DIMOUSESTATE2
c_dfDIKeyboard | array of 256 bytes
c_dfDIJoystick | DIJOYSTATE
c_dfDIJoystick2 | DIJOYSTATE2

For example, if you passed the c_dfDIMouse format to the IDirectInputDevice7::SetDataFormat method, you must pass a DIMOUSESTATE structure to the IDirectInputDevice7::GetDeviceState method.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.

See Also

IDirectInputDevice7::Poll, Polling and Events, Buffered and Immediate Data


IDirectInputDevice7::GetEffectInfo

The IDirectInputDevice7::GetEffectInfo method obtains information about an effect.

HRESULT GetEffectInfo(
  LPDIEFFECTINFO pdei,
  REFGUID rguid
);

Parameters

pdei
DIEFFECTINFO structure that receives information about the effect. The caller must initialize the dwSize member of the structure before calling this method.
rguid
Identifier of the effect for which information is being requested.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_DEVICENOTREG
DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED

Remarks

In C++, the rguid parameter must be passed by reference; in C, which does not have pass-by-reference, it must be passed by address. The following is an example of a C++ call:

lpdev2->GetEffectInfo(&dei, GUID_Effect);

The following shows the same call in C:

lpdev2->lpVtbl->GetEffectInfo(lpdev2, &dei, &GUID_Effect);

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.


IDirectInputDevice7::GetForceFeedbackState

The IDirectInputDevice7::GetForceFeedbackState method retrieves the state of the device's force-feedback system.

HRESULT GetForceFeedbackState(
  LPDWORD pdwOut
);

Parameters

pdwOut
Location for flags that describe the current state of the device's force-feedback system.

The value is a combination of the following constants:

DIGFFS_ACTUATORSOFF
The device's force-feedback actuators are disabled.
DIGFFS_ACTUATORSON
The device's force-feedback actuators are enabled.
DIGFFS_DEVICELOST
The device suffered an unexpected failure and is in an indeterminate state. It must be reset either by unacquiring and reacquiring the device, or by sending a DISFFC_RESET command.
DIGFFS_EMPTY
The device has no downloaded effects.
DIGFFS_PAUSED
Playback of all active effects has been paused.
DIGFFS_POWEROFF
The force-feedback system is not currently available. If the device cannot report the power state, neither DIGFFS_POWERON nor DIGFFS_POWEROFF is returned.
DIGFFS_POWERON
Power to the force-feedback system is currently available. If the device cannot report the power state, neither DIGFFS_POWERON nor DIGFFS_POWEROFF is returned.
DIGFFS_SAFETYSWITCHOFF
The safety switch is currently off, meaning that the device cannot operate. If the device cannot report the state of the safety switch, neither DIGFFS_SAFETYSWITCHON nor DIGFFS_SAFETYSWITCHOFF is returned.
DIGFFS_SAFETYSWITCHON
The safety switch is currently on, meaning that the device can operate. If the device cannot report the state of the safety switch, neither DIGFFS_SAFETYSWITCHON nor DIGFFS_SAFETYSWITCHOFF is returned.
DIGFFS_STOPPED
No effects are playing, and the device is not paused.
DIGFFS_USERFFSWITCHOFF
The user force-feedback switch is currently off, meaning that the device cannot operate. If the device cannot report the state of the user force-feedback switch, neither DIGFFS_USERFFSWITCHON nor DIGFFS_USERFFSWITCHOFF is returned.
DIGFFS_USERFFSWITCHON
The user force-feedback switch is currently on, meaning that the device can operate. If the device cannot report the state of the user force-feedback switch, neither DIGFFS_USERFFSWITCHON nor DIGFFS_USERFFSWITCHOFF is returned.

Future versions of DirectInput can define additional flags. Applications should ignore any flags that are not currently defined.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INPUTLOST
DIERR_INVALIDPARAM
DIERR_NOTEXCLUSIVEACQUIRED
DIERR_NOTINITIALIZED
DIERR_UNSUPPORTED

Remarks

The device must be acquired at the exclusive cooperative level for this method to succeed.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.


IDirectInputDevice7::GetObjectInfo

The IDirectInputDevice7::GetObjectInfo method retrieves information about a device object, such as a button or axis.

HRESULT GetObjectInfo(
  LPDIDEVICEOBJECTINSTANCE pdidoi,
  DWORD dwObj,
  DWORD dwHow
);

Parameters

pdidoi
Address of a DIDEVICEOBJECTINSTANCE structure to be filled with information about the object. The structure's dwSize member must be initialized before this method is called.
dwObj
Value that identifies the object whose information is to be retrieved. The value set for this parameter depends on the value specified in the dwHow parameter.
dwHow
Value specifying how the dwObj parameter should be interpreted. This value can be one of the following:
Value | Meaning
DIPH_BYOFFSET | The dwObj parameter is the offset into the current data format of the object whose information is being accessed.
DIPH_BYID | The dwObj parameter is the object type/instance identifier. This identifier is returned in the dwType member of the DIDEVICEOBJECTINSTANCE structure returned from a previous call to the IDirectInputDevice7::EnumObjects method.
DIPH_BYUSAGE | The dwObj parameter contains the HID Usage Page and Usage values of the object, combined by the DIMAKEUSAGEDWORD macro.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED
DIERR_OBJECTNOTFOUND

Remarks

For compatibility with DirectX 3, it is also valid to pass a DIDEVICEOBJECTINSTANCE_DX3 structure with the dwSize member initialized to sizeof(DIDEVICEOBJECTINSTANCE_DX3). For more information, see Designing for Previous Versions of DirectInput.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.


IDirectInputDevice7::GetProperty

The IDirectInputDevice7::GetProperty method retrieves information about the input device.

HRESULT GetProperty(
  REFGUID rguidProp,
  LPDIPROPHEADER pdiph
);

Parameters

rguidProp
Identifier of the property to be retrieved. This can be one of the predefined values or a pointer to a GUID that identifies the property. The following properties are predefined for an input device:
DIPROP_AUTOCENTER
Specifies whether device objects are self-centering. See IDirectInputDevice7::SetProperty for more information.
DIPROP_AXISMODE
Retrieves the axis mode. The retrieved value (DIPROPAXISMODE_ABS or DIPROPAXISMODE_REL) is set in the dwData member of the associated DIPROPDWORD structure. See the description for the pdiph parameter for more information.
DIPROP_BUFFERSIZE
Retrieves the input-buffer size. The retrieved value is set in the dwData member of the associated DIPROPDWORD structure. See the description for the pdiph parameter for more information.

The buffer size determines the amount of data that the buffer can hold between calls to the IDirectInputDevice7::GetDeviceData method before data is lost. This value can be set to 0 to indicate that the application does not be reading buffered data from the device. If the buffer size in the dwData member of the DIPROPDWORD structure is too large to be supported by the device, the largest possible buffer size is set. To determine whether the requested buffer size was set, retrieve the buffer-size property, and compare the result with the value that you previously attempted to set.

DIPROP_DEADZONE
Retrieves a value for the dead zone of a joystick, in the range from 0 through 10,000, where 0 indicates that there is no dead zone, 5,000 indicates that the dead zone extends over 50 percent of the physical range of the axis on both sides of center, and 10,000 indicates that the entire physical range of the axis is dead. When the axis is within the dead zone, it is reported as being at the center of its range.
DIPROP_FFGAIN
Retrieves the gain of the device. See IDirectInputDevice7::SetProperty for more information.
DIPROP_FFLOAD
Retrieves the memory load for the device. This setting applies to the entire device, rather than to any particular object, so the dwHow member of the associated DIPROPDWORD structure must be DIPH_DEVICE.

The dwData member contains a value in the range from 0 through 100, indicating the percentage of device memory in use.

DIPROP_GRANULARITY
Retrieves the input granularity. The retrieved value is set in the dwData member of the associated DIPROPDWORD structure. See the description of the pdiph parameter for more information.

Granularity represents the smallest distance over which the object reports movement. Most axis objects have a granularity of one, meaning that all values are possible. Some axes have a larger granularity. For example, the wheel axis on a mouse can have a granularity of 20, meaning that all reported changes in position are multiples of 20. In other words, when the user turns the wheel slowly, the device reports a position of 0, then 20, then 40, and so on.

This is a read-only property; you cannot set its value by calling the IDirectInputDevice7::SetProperty method.

DIPROP_GUIDANDPATH
Allows the application to access the class GUID and device interface (path) for the device. This property lets advanced applications perform operations on a HID that are not supported by DirectInput. For more information, see the reference for the DIPROPGUIDANDPATH structure.
DIPROP_INSTANCENAME
Retrieves the friendly instance name of the device. For more information, see IDirectInputDevice7::SetProperty.
DIPROP_PRODUCTNAME
Retrieves the friendly product name of the device. For more information, see IDirectInputDevice7::SetProperty.
DIPROP_RANGE
Retrieves the range of values an object can possibly report. The retrieved minimum and maximum values are set in the lMin and lMax members of the associated DIPROPRANGE structure. See the description of the pdiph parameter for more information.

For some devices, this is a read-only property; you cannot set its value by calling the IDirectInputDevice7::SetProperty method.

DIPROP_SATURATION
Retrieves a value for the saturation zones of a joystick, in the range from 0 through 10,000. The saturation level is the point at which the axis is considered to be at its most extreme position. For example, if the saturation level is set to 9,500, the axis reaches the extreme of its range when it has moved 95 percent of the physical distance from its center position (or from the dead zone).
pdiph
Address of the DIPROPHEADER portion of a larger property-dependent structure that contains the DIPROPHEADER structure as a member. When retrieving object range information, this value is the address of the DIPROPHEADER structure contained within the DIPROPRANGE structure. For most other properties, this value is the address of the DIPROPHEADER structure contained within the DIPROPDWORD structure.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED
DIERR_OBJECTNOTFOUND
DIERR_UNSUPPORTED

Remarks

The following C example shows how to obtain the value of the DIPROP_BUFFERSIZE property:

DIPROPDWORD dipdw;  // DIPROPDWORD contains a DIPROPHEADER structure.
HRESULT hr;
dipdw.diph.dwSize       = sizeof(DIPROPDWORD);
dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
dipdw.diph.dwObj        = 0; // device property
dipdw.diph.dwHow        = DIPH_DEVICE;

hr = IDirectInputDevice7_GetProperty(pdid, DIPROP_BUFFERSIZE, &dipdw.diph);
if (SUCCEEDED(hr)) {
    // The dipdw.dwData member contains the buffer size.
}

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.

See Also

IDirectInputDevice7::SetProperty


IDirectInputDevice7::Initialize

The IDirectInputDevice7::Initialize method initializes a DirectInputDevice object. The IDirectInput7::CreateDevice method automatically initializes a device after creating it; applications normally do not need to call this method.

HRESULT Initialize(
  HINSTANCE hinst,
  DWORD dwVersion,
  REFGUID rguid
);

Parameters

hinst
Instance handle to the application or DLL that is creating the DirectInput device object. DirectInput uses this value to determine whether the application or DLL has been certified and to establish any special behaviors that might be necessary for backward compatibility.

It is an error for a DLL to pass the handle to the parent application. For example, an ActiveX control embedded in a Web page that uses DirectInput must pass its own instance handle, and not the handle to the Web browser. This ensures that DirectInput recognizes the control and can enable any special behaviors that may be necessary.

dwVersion
Version number of DirectInput for which the application is designed. This value is normally DIRECTINPUT_VERSION. Passing the version number of a previous version causes DirectInput to emulate that version. For more information, see Designing for Previous Versions of DirectInput.
rguid
Identifier for the instance of the device with which the interface should be associated. The IDirectInput7::EnumDevices method can be used to determine which instance GUIDs are supported by the system.

Return Values

If the method succeeds, the return value is DI_OK or S_FALSE.

If the method fails, the return value can be one of the following error values:

DIERR_ACQUIRED
DIERR_DEVICENOTREG

If the method returns S_FALSE, the device had already been initialized with the instance GUID passed in though rGUID.

Remarks

If this method fails, the underlying object should be considered to be in an indeterminate state and must be reinitialized before use.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.


IDirectInputDevice7::Poll

The IDirectInputDevice7::Poll method retrieves data from polled objects on a DirectInput device. If the device does not require polling, calling this method has no effect. If a device that requires polling is not polled periodically, no new data is received from the device. Calling this method causes DirectInput to update the device state, generate input events (if buffered data is enabled), and set notification events (if notification is enabled).

HRESULT Poll()

Parameters

None.

Return Values

If the method succeeds, the return value is DI_OK, or DI_NOEFFECT if the device does not require polling.

If the method fails, the return value can be one of the following error values:

DIERR_INPUTLOST
DIERR_NOTACQUIRED
DIERR_NOTINITIALIZED

Remarks

Before a device data can be polled, the data format must be set by using the IDirectInputDevice7::SetDataFormat method, and the device must be acquired by using the IDirectInputDevice7::Acquire method.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.

See Also

Polling and Events


IDirectInputDevice7::RunControlPanel

The IDirectInputDevice7::RunControlPanel method runs the DirectInput control panel associated with this device. If the device does not have a control panel associated with it, the default device control panel is launched.

HRESULT RunControlPanel(
  HWND hwndOwner,
  DWORD dwFlags
);

Parameters

hwndOwner
Parent window handle. If this parameter is NULL, no parent window is used.
dwFlags
Not currently used. Zero is the only valid value.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.


IDirectInputDevice7::SendDeviceData

The IDirectInputDevice7::SendDeviceData method sends data to a device that accepts output. The device must be in an acquired state.

HRESULT SendDeviceData(
  DWORD cbObjectData,
  LPCDIDEVICEOBJECTDATA rgdod,
  LPDWORD pdwInOut,
  DWORD fl
);

Parameters

cbObjectData
Size, in bytes, of a single DIDEVICEOBJECTDATA structure.
rgdod
Array of DIDEVICEOBJECTDATA structures containing the data to send to the device. It must consist of *pdwInOut elements.

The dwOfs field of each DIDEVICEOBJECTDATA structure must contain the device object identifier (as obtained from the dwType field of the DIDEVICEOBJECTINSTANCE structure) for the device object to which the data is directed. The dwTimeStamp and dwSequence members must be 0.

pdwInOut
On entry, the variable pointed to by this parameter contains the number of elements in the array pointed to by rgdod. On exit, it contains the number of elements sent to the device.
fl
Flags controlling the manner in which data is sent. This can be 0 or the following value:
DISDD_CONTINUE
The device data sent is overlaid on the previously sent device data. See Remarks.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INPUTLOST
DIERR_NOTACQUIRED
DIERR_REPORTFULL
DIERR_UNPLUGGED

Remarks

There is no guarantee that the individual data elements will be sent in a particular order. However, data sent by successive calls to IDirectInputDevice7::SendDeviceData is not interleaved. Furthermore, if multiple pieces of data are sent to the same object with a single call, it is unspecified which piece of data is sent.

Consider, for example, a device that can be sent data in packets, each packet describing two pieces of information; call them A and B. Suppose the application attempts to send three data elements: B = 2, A = 1, and B = 0.

The actual device is sent a single packet. The A field of the packet contains the value 1, and the B field of the packet is either 2 or 0.

If the data must to be sent to the device exactly as specified, three calls to IDirectInputDevice7::SendDeviceData should be performed, each call sending one data element.

In response to the first call, the device is sent a packet in which the A field is blank and the B field contains the value 2.

In response to the second call, the device is sent a packet in which the A field contains the value 1, and the B field is blank.

Finally, in response to the third call, the device is sent a packet in which the A field is blank and the B field contains the value 0.

If the DISDD_CONTINUE flag is set, the device data sent is overlaid on the previously sent device data. Otherwise, the device data sent starts from scratch.

For example, suppose a device supports two button outputs, Button0 and Button1. If an application first calls IDirectInputDevice7::SendDeviceData passing "Button0 pressed", a packet of the form "Button0 pressed, Button1 not pressed" is sent to the device. If the application then makes another call, passing "Button1 pressed" and the DISDD_CONTINUE flag, a packet of the form "Button0 pressed, Button1 pressed" is sent to the device. However, if the application had not passed the DISDD_CONTINUE flag, the packet sent to the device would have been "Button0 not pressed, Button1 pressed".

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.


IDirectInputDevice7::SendForceFeedbackCommand

The IDirectInputDevice7::SendForceFeedbackCommand method sends a command to the device's force-feedback system.

HRESULT SendForceFeedbackCommand(
  DWORD dwFlags
);

Parameters

dwFlags
Single value indicating the desired change in state. The value can be one of the following:
DISFFC_CONTINUE
Paused playback of all active effects is to be continued. It is an error to send this command when the device is not in a paused state.
DISFFC_PAUSE
Playback of all active effects is to be paused. This command also stops the clock-on effects so that they continue playing to their full duration when restarted.

While the device is paused, new effects cannot be started, and existing ones cannot be modified. Doing so can cause the subsequent DISFFC_CONTINUE command to fail to perform properly.

To abandon a pause and stop all effects, use the DISFFC_STOPALL or DISFCC_RESET commands.

DISFFC_RESET
The device's force-feedback system is to be put in its startup state. All effects are removed from the device, are no longer valid, and must be recreated if they are to be used again. The device's actuators are disabled.
DISFFC_SETACTUATORSOFF
The device's force-feedback actuators are to be disabled. While the actuators are off, effects continue to play but are ignored by the device. Using the analogy of a sound playback device, they are muted, rather than paused.
DISFFC_SETACTUATORSON
The device's force-feedback actuators are to be enabled.
DISFFC_STOPALL
Playback of any active effects is to be stopped. All active effects are reset, but are still being maintained by the device and are still valid. If the device is in a paused state, that state is lost.

This command is equivalent to calling the IDirectInputEffect::Stop method for each effect playing.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INPUTLOST
DIERR_INVALIDPARAM
DIERR_NOTEXCLUSIVEACQUIRED
DIERR_NOTINITIALIZED
DIERR_UNSUPPORTED

Remarks

The device must be acquired at the exclusive cooperative level for this method to succeed.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.


IDirectInputDevice7::SetCooperativeLevel

The IDirectInputDevice7::SetCooperativeLevel method establishes the cooperative level for this instance of the device. The cooperative level determines how this instance of the device interacts with other instances of the device and the rest of the system.

HRESULT SetCooperativeLevel(
  HWND hwnd,
  DWORD dwFlags
);

Parameters

hwnd
Window handle to be associated with the device. This parameter must be a valid top-level window handle that belongs to the process. The window associated with the device must not be destroyed while it is still active in a DirectInput device.
dwFlags
Flags that describe the cooperative level associated with the device. The following flags are defined:
DISCL_BACKGROUND
The application requires background access. If background access is granted, the device can be acquired at any time, even when the associated window is not the active window.
DISCL_EXCLUSIVE
The application requires exclusive access. If exclusive access is granted, no other instance of the device can obtain exclusive access to the device while it is acquired. However, nonexclusive access to the device is always permitted, even if another application has obtained exclusive access.

An application that acquires the mouse or keyboard device in exclusive mode should always unacquire the devices when it receives WM_ENTERSIZEMOVE and WM_ENTERMENULOOP messages. Otherwise, the user cannot manipulate the menu or move and resize the window.

DISCL_FOREGROUND
The application requires foreground access. If foreground access is granted, the device is automatically unacquired when the associated window moves to the background.
DISCL_NONEXCLUSIVE
The application requires nonexclusive access. Access to the device does not interfere with other applications that are accessing the same device.
DISCL_NOWINKEY
Disable the Windows key. Setting this flag ensures that the user cannot inadvertently break out of the application

Applications must specify either DISCL_FOREGROUND or DISCL_BACKGROUND; it is an error to specify both or neither. Similarly, applications must specify either DISCL_EXCLUSIVE or DISCL_NONEXCLUSIVE.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED
E_HANDLE

Remarks

If the system mouse is acquired in exclusive mode, the pointer is removed from the screen until the device is unacquired.

Applications must call this method before acquiring the device by using the IDirectInputDevice7::Acquire method.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.

See Also

Cooperative Levels


IDirectInputDevice7::SetDataFormat

The IDirectInputDevice7::SetDataFormat method sets the data format for the DirectInput device.

HRESULT SetDataFormat(
  LPCDIDATAFORMAT lpdf
);

Parameters

lpdf
Address of a structure that describes the format of the data that the DirectInputDevice should return. An application can define its own DIDATAFORMAT structure or use one of the following predefined global variables:
  • c_dfDIKeyboard
  • c_dfDIMouse
  • c_dfDIMouse2
  • c_dfDIJoystick
  • c_dfDIJoystick2

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_ACQUIRED
DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED

Remarks

The data format must be set before the device can be acquired by using the IDirectInputDevice7::Acquire method. It is necessary to set the data format only once. The data format cannot be changed while the device is acquired.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.

See Also

IDirectInputDevice7::GetDeviceState


IDirectInputDevice7::SetEventNotification

The IDirectInputDevice7::SetEventNotification method sets the event notification status. This method specifies an event that is to be set when the device state changes. It is also used to turn off event notification.

HRESULT SetEventNotification(
  HANDLE hEvent
);

Parameters

hEvent
Handle to the event that is to be set when the device state changes. DirectInput uses the Win32 SetEvent function on the handle when the state of the device changes. If the hEvent parameter is NULL, notification is disabled.

The application can create the handle as either a manual-reset or autoreset event by using the Win32 CreateEvent function. If the event is created as an autoreset event, the operating system automatically resets the event once a wait has been satisfied. If the event is created as a manual-reset event, it is the application's responsibility to call the Win32 ResetEvent function to reset it. DirectInput does not call the Win32 ResetEvent function for event notification handles. Most applications create the event as an automatic-reset event.

Return Values

If the method succeeds, the return value is DI_OK or DI_POLLEDDEVICE.

If the method fails, the return value can be one of the following error values:

DIERR_ACQUIRED
DIERR_HANDLEEXISTS
DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED

Remarks

A device state change is defined as any of the following:

  • A change in the position of an axis
  • A change in the state (pressed or released) of a button
  • A change in the direction of a POV control
  • Loss of acquisition

Do not call the Win32 CloseHandle function on the event while it has been selected into a DirectInputDevice object. You must call this method with the hEvent parameter set to NULL before closing the event handle.

The event notification handle cannot be changed while the device is acquired. If the function is successful, the application can use the event handle like any other Win32 event handle.

The following code example checks whether the handle is currently set without blocking:

dwResult = WaitForSingleObject(hEvent, 0);
if (dwResult == WAIT_OBJECT_0) {
    // Event is set. If the event was created as
    // autoreset, it has also been reset.
}

The following code example illustrates blocking indefinitely until the event is set. This behavior is strongly discouraged because the thread does not respond to the system until the wait is satisfied. In particular, the thread does not respond to Windows messages.

dwResult = WaitForSingleObject(hEvent, INFINITE);
if (dwResult == WAIT_OBJECT_0) {
    // Event has been set. If the event was created
    // as autoreset, it has also been reset.
}

The following code example illustrates a typical message loop for a message-based application that uses two events:.

HANDLE ah[2] = { hEvent1, hEvent2 };

while (TRUE) {

    dwResult = MsgWaitForMultipleObjects(2, ah, FALSE,
                        INFINITE, QS_ALLINPUT);
    switch (dwResult) {
    case WAIT_OBJECT_0:
        // Event 1 has been set. If the event was created as
        // autoreset, it has also been reset.
        ProcessInputEvent1();
        break;

    case WAIT_OBJECT_0 + 1:
        // Event 2 has been set. If the event was created as
        // autoreset, it has also been reset.
        ProcessInputEvent2();
        break;

    case WAIT_OBJECT_0 + 2:
        // A Windows message has arrived. Process
        // messages until there aren't any more.
        while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)){
            if (msg.message == WM_QUIT) {
                goto exitapp;
            }
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
        break;

    default:
        // Unexpected error.
        Panic();
        break;
    }
}

The following code example illustrates a typical application loop for a non-message-based application that uses two events:

HANDLE ah[2] = { hEvent1, hEvent2 };
DWORD dwWait = 0;

while (TRUE) {

    dwResult = MsgWaitForMultipleObjects(2, ah, FALSE,
                                         dwWait, QS_ALLINPUT);
    dwWait = 0;

    switch (dwResult) {
    case WAIT_OBJECT_0:
        // Event 1 has been set. If the event was
        // created as autoreset, it has also
        // been reset.
        ProcessInputEvent1();
        break;

    case WAIT_OBJECT_0 + 1:
        // Event 2 has been set. If the event was
        // created as autoreset, it has also
        // been reset.
        ProcessInputEvent2();
        break;

    case WAIT_OBJECT_0 + 2:
        // A Windows message has arrived. Process
        // messages until there aren't any more.
        while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)){
            if (msg.message == WM_QUIT) {
                goto exitapp;
            }
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
        break;

    default:
        // No input or messages waiting.
        // Do a frame of the game.
        // If the game is idle, tell the next wait
        // to wait indefinitely for input or a message.
        if (!DoGame()) {
            dwWait = INFINITE;
        }
        break;
    }
}

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.

See Also

Polling and Events


IDirectInputDevice7::SetProperty

The IDirectInputDevice7::SetProperty method sets properties that define the device behavior. These properties include input buffer size and axis mode.

HRESULT SetProperty(
  REFGUID rguidProp,
  LPCDIPROPHEADER pdiph
);

Parameters

rguidProp
Identifier of the property to be set. This can be one of the predefined values, or a pointer to a GUID that identifies the property. The following property values are predefined for an input device:
DIPROP_AUTOCENTER
Specifies whether device objects are self-centering. This setting applies to the entire device, rather than to any particular object, so the dwHow member of the associated DIPROPDWORD structure must be DIPH_DEVICE.

The dwData member can be one of the following values:

DIPROPAUTOCENTER_OFF: The device should not automatically center when the user releases the device. An application that uses force feedback should disable the auto-centering spring before playing effects.

DIPROPAUTOCENTER_ON: The device should automatically center when the user releases the device. For example, in this mode, a joystick would engage the self-centering spring.

The use of force-feedback effects can interfere with the auto-centering spring. Some devices disable the auto-centering spring when a force-feedback effect is played.

Not all devices support the auto-center property.

DIPROP_AXISMODE
Sets the axis mode. The value being set (DIPROPAXISMODE_ABS or DIPROPAXISMODE_REL) must be specified in the dwData member of the associated DIPROPDWORD structure. See the description of the pdiph parameter for more information.

This setting applies to the entire device, so the dwHow member of the associated DIPROPDWORD structure must be set to DIPH_DEVICE.

DIPROP_BUFFERSIZE
Sets the input-buffer size. The value being set must be specified in the dwData member of the associated DIPROPDWORD structure. See the description of the pdiph parameter for more information.

This setting applies to the entire device, so the dwHow member of the associated DIPROPDWORD structure must be set to DIPH_DEVICE.

DIPROP_CALIBRATIONMODE
Allows the application to specify whether DirectInput should retrieve calibrated or uncalibrated data from an axis. By default, DirectInput retrieves calibrated data.

Setting the calibration mode for the entire device is equivalent to setting it for each axis individually.

The dwData member of the DIPROPDWORD structure can be one of the following values:

DIPROPCALIBRATIONMODE_COOKED: DirectInput should return data after applying calibration information. This is the default mode.

DIPROPCALIBRATIONMODE_RAW: DirectInput should return raw, uncalibrated data. This mode is typically used only by Control Panel–type applications.

Setting a device into raw mode causes the dead zone, saturation, and range settings to be ignored.

DIPROP_DEADZONE
Sets the value for the dead zone of a joystick, in the range from 0 through 10,000, where 0 indicates that there is no dead zone, 5,000 indicates that the dead zone extends over 50 percent of the physical range of the axis on both sides of center, and 10,000 indicates that the entire physical range of the axis is dead. When the axis is within the dead zone, it is reported as being at the center of its range.

This setting can be applied to either the entire device or to a specific axis.

DIPROP_FFGAIN
Sets the gain for the device. This setting applies to the entire device, rather than to any particular object, so the dwHow member of the associated DIPROPDWORD structure must be DIPH_DEVICE.

The dwData member contains a gain value that is applied to all effects created on the device. The value is an integer in the range from 0 through 10,000, specifying the amount by which effect magnitudes should be scaled for the device. For example, a value of 10,000 indicates that all effect magnitudes are to be taken at face value. A value of 9,000 indicates that all effect magnitudes are to be reduced to 90% of their nominal magnitudes.

Setting a gain value is useful when an application wants to scale down the strength of all force-feedback effects uniformly, based on user preferences.

Unlike other properties, the gain can be set when the device is in an acquired state.

DIPROP_INSTANCENAME
This property exists for advanced applications that want to change the friendly instance name of a device (as returned in the tszInstanceName member of the DIDEVICEINSTANCE structure) to distinguish it from similar devices that are plugged in simultaneously. Most applications should have no need to change the friendly name.

This setting applies to the entire device, so the dwHow member of the associated DIPROPDWORD structure must be set to DIPH_DEVICE.

The pdiph parameter must be a pointer to the diph member of a DIPROPSTRING structure.

DIPROP_PRODUCTNAME
This property exists for advanced applications that want to change the friendly product name of a device (as returned in the tszProductName member of the DIDEVICEINSTANCE structure) to distinguish it from similar devices which are plugged in simultaneously. Most applications should have no need to change the friendly name.

This setting applies to the entire device, so the dwHow member of the associated DIPROPDWORD structure must be set to DIPH_DEVICE.

The pdiph parameter must be a pointer to the diph member of a DIPROPSTRING structure.

DIPROP_RANGE
Sets the range of values an object can possibly report. The minimum and maximum values are taken from the lMin and lMax members of the associated DIPROPRANGE structure.

For some devices, this is a read-only property.

You cannot set a reverse range; lMax must be greater than lMin.

DIPROP_SATURATION
Sets the value for the saturation zones of a joystick, in the range from 0 through 10,000. The saturation level is the point at which the axis is considered to be at its most extreme position. For example, if the saturation level is set to 9,500, the axis reaches the extreme of its range when it has moved 95 percent of the physical distance from its center position (or from the dead zone).

This setting can be applied to either the entire device or a specific axis.

pdiph
Address of the DIPROPHEADER structure contained within the type-specific property structure.

Return Values

If the method succeeds, the return value is DI_OK or DI_PROPNOEFFECT.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED
DIERR_OBJECTNOTFOUND
DIERR_UNSUPPORTED

Remarks

The buffer size determines the amount of data that the buffer can hold between calls to the IDirectInputDevice7::GetDeviceData method before data is lost. This value may be set to 0 to indicate that the application does not read buffered data from the device. If the buffer size in the dwData member of the DIPROPDWORD structure is too large to be supported by the device, the largest possible buffer size is set. To determine whether the requested buffer size was set, retrieve the buffer-size property, and compare the result with the value that you previously attempted to set.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.

See Also

IDirectInputDevice7::GetProperty


IDirectInputDevice7::Unacquire

The IDirectInputDevice7::Unacquire method releases access to the device.

HRESULT Unacquire();

Parameters

None.

Return Values

The return value is DI_OK is the device was unacquired, or DI_NOEFFECT if the device was not in an acquired state.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.


IDirectInputDevice7::WriteEffectToFile

The IDirectInputDevice7::WriteEffectToFile method saves information about one or more force-feedback effects to a file that can be read by using IDirectInputDevice7::EnumEffectsInFile. This method is chiefly of interest to those wanting to write their own force-authoring applications.

HRESULT WriteEffectToFile(
  LPCSTR lpszFileName,
  DWORD dwEntries,
  LPCDIFILEEFFECT rgDiFileEft,
  DWORD dwFlags
);

Parameters

lpszFileName
Name of the RIFF file.
dwEntries
Number of structures in the rgDiFileEft array.
rgDiFileEft
Array of DIFILEEFFECT structures.
dwFlags
Flags which control how the effect should be written. Can be DIFEF_DEFAULT (= 0) or the following value:
DIFEF_INCLUDENONSTANDARD
Includes effects that are not defined by DirectInput. If this flag is not specified, only effects with GUIDs defined in Dinput.h, such as GUID_ConstantForce, are written.

Return Values

If the method succeeds, it returns DI_OK.

If it fails, the return value can be DIERR_INVALIDPARAM.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.

See Also

IDirectInputDevice7::EnumEffectsInFile


IDirectInputEffect

Applications use the methods of the IDirectInputEffect interface to manage effects of force-feedback devices.

The interface is obtained by using the IDirectInputDevice7::CreateEffect method.

The methods of the IDirectInputEffect interface can be organized into the following groups.

Effect information | GetEffectGuid
 | GetEffectStatus
 | GetParameters
Effect manipulation | Download
 | Initialize
 | SetParameters
 | Start
 | Stop
 | Unload
Miscellaneous | Escape

The IDirectInputEffect interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECTINPUTEFFECT type is defined as a pointer to the IDirectInputEffect interface:

typedef struct IDirectInputEffect    *LPDIRECTINPUTEFFECT;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.


IDirectInputEffect::Download

The IDirectinputEffect::Download method places the effect on the device. If the effect is already on the device, the existing effect is updated to match the values set by the IDirectInputEffect::SetParameters method.

HRESULT Download(void);

Parameters

None.

Return Values

If the method succeeds, the return value is DI_OK or S_FALSE.

If the method fails, the return value can be one of the following error values:

DIERR_NOTINITIALIZED
DIERR_DEVICEFULL
DIERR_INCOMPLETEEFFECT
DIERR_INPUTLOST
DIERR_NOTEXCLUSIVEACQUIRED
DIERR_INVALIDPARAM
DIERR_EFFECTPLAYING

If the method returns S_FALSE, the effect has already been downloaded to the device.

Remarks

It is valid to update an effect while it is playing. The semantics of such an operation are explained in the reference for IDirectInputEffect::SetParameters.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.


IDirectInputEffect::Escape

The IDirectInputEffect::Escape method sends a hardware-specific command to the driver.

HRESULT Escape(
  LPDIEFFESCAPE pesc
);

Parameters

pesc
DIEFFESCAPE structure that describes the command to be sent. On success, the cbOutBuffer member contains the number of bytes of the output buffer used.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_NOTINITIALIZED
DIERR_DEVICEFULL

Other device-specific error codes are also possible. Ask the hardware manufacturer for details.

Remarks

Since each driver implements different escapes, it is the application's responsibility to ensure that it is sending the escape to the correct driver by comparing the value of the guidFFDriver member of the DIDEVICEINSTANCE structure against the value the application is expecting.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.


IDirectInputEffect::GetEffectGuid

The IDirectInputEffect::GetEffectGuid method retrieves the GUID for the effect represented by the IDirectInputEffect object.

HRESULT GetEffectGuid(
  LPGUID pguid
);

Parameters

pguid
GUID structure that is filled by the method.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED

Remarks

Additional information about the effect can be obtained by passing the GUID to IDirectInputDevice7::GetEffectInfo.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.


IDirectInputEffect::GetEffectStatus

The IDirectInputEffect::GetEffectStatus method retrieves the status of an effect.

HRESULT GetEffectStatus(
  LPDWORD pdwFlags
);

Parameters

pdwFlags
Status flags for the effect. The value can be 0 or one or more of the following constants:
DIEGES_PLAYING
The effect is playing.
DIEGES_EMULATED
The effect is emulated.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.


IDirectInputEffect::GetParameters

The IDirectInputEffect::GetParameters method retrieves information about an effect.

HRESULT GetParameters(
  LPDIEFFECT peff,
  DWORD dwFlags
);

Parameters

peff
Address of a DIEFFECT structure that receives effect information. The dwSize member must be filled in by the application before calling this method.
dwFlags
Flags specifying which parts of the effect information are to be retrieved. The value can be 0 or one or more of the following constants:
DIEP_ALLPARAMS
The union of all other DIEP_* flags, indicating that all members of the DIEFFECT structure are being requested.
DIEP_ALLPARAMS_DX5
The union of all other DIEP_* flags except the DIEP_STARTDELAY flag.
DIEP_AXES
The cAxes and rgdwAxes members should receive data. The cAxes member on entry contains the size (in DWORDs) of the buffer pointed to by the rgdwAxes member. If the buffer is too small, the method returns DIERR_MOREDATA and sets cAxes to the necessary size of the buffer.
DIEP_DIRECTION
The cAxes and rglDirection members should receive data. The cAxes member on entry contains the size (in DWORDs) of the buffer pointed to by the rglDirection member. If the buffer is too small, the GetParameters method returns DIERR_MOREDATA and sets cAxes to the necessary size of the buffer.

The dwFlags member must include at least one of the coordinate system flags (DIEFF_CARTESIAN, DIEFF_POLAR, or DIEFF_SPHERICAL). DirectInput returns the direction of the effect in one of the coordinate systems you specified, converting between coordinate systems as necessary. On exit, exactly one of the coordinate system flags is set in the dwFlags member, indicating which coordinate system DirectInput used. In particular, passing all three coordinate system flags retrieves the coordinates in exactly the same format in which they were set.

DIEP_DURATION
The dwDuration member should receive data.
DIEP_ENVELOPE
The lpEnvelope member points to a DIENVELOPE structure that should receive data. If the effect does not have an envelope associated with it, the lpEnvelope member is set to NULL.
DIEP_GAIN
The dwGain member should receive data.
DIEP_SAMPLEPERIOD
The dwSamplePeriod member should receive data.
DIEP_STARTDELAY
The dwStartDelay member should receive data.
DIEP_TRIGGERBUTTON
The dwTriggerButton member should receive data.
DIEP_TRIGGERREPEATINTERVAL
The dwTriggerRepeatInterval member should receive data.
DIEP_TYPESPECIFICPARAMS
The lpvTypeSpecificParams member points to a buffer whose size is specified by the cbTypeSpecificParams member. On return, the buffer is filled in with the type-specific data associated with the effect, and the cbTypeSpecificParams member contains the number of bytes copied. If the buffer supplied by the application is too small to contain all the type-specific data, the method returns DIERR_MOREDATA, and the cbTypeSpecificParams member contains the required size of the buffer in bytes.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM
DIERR_MOREDATA
DIERR_NOTINITIALIZED

Remarks

Common errors resulting in a DIERR_INVALIDPARAM error include not setting the dwSize member of the DIEFFECT structure, passing invalid flags, or not setting up the members in the DIEFFECT structure properly in preparation for receiving the effect information. For example, if information is to be retrieved in the dwTriggerButton member, the dwFlags member must be set to either DIEFF_OBJECTIDS or DIEFF_OBJECTOFFSETS so that DirectInput knows how to describe the button.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.


IDirectInputEffect::Initialize

The IDirectInputEffect::Initialize method initializes a DirectInputEffect object.

HRESULT Initialize(
  HINSTANCE hinst,
  DWORD dwVersion,
  REFGUID rguid
);

Parameters

hinst
Instance handle to the application or DLL that is creating the DirectInputEffect object. DirectInput uses this value to determine whether the application or DLL has been certified and to establish any special behaviors that might be necessary for backward compatibility. It is an error for a DLL to pass the handle to the parent application.
dwVersion
Version number of DirectInput for which the application is designed. This value is normally DIRECTINPUT_VERSION. Passing the version number of a previous version causes DirectInput to emulate that version. For more information, see Designing for Previous Versions of DirectInput.
rguid
Identifier of the effect with which the interface is associated. The IDirectInputDevice7::EnumEffects method can be used to determine which effect GUIDs are supported by the device.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be DIERR_DEVICENOTREG.

Remarks

If this method fails, the underlying object should be considered to be an indeterminate state and needs to be reinitialized before it can be subsequently used.

The IDirectInputDevice7::CreateEffect method automatically initializes the effect after creating it. Applications normally do not need to call the Initialize method.

In C++ the rguid parameter must be passed by reference; in C, which does not have pass-by-reference, it must be passed by address. The following is an example of a C++ call:

lpeff->Initialize(g_hinstDll, DIRECTINPUT_VERSION, GUID_Effect);

The following shows the same call in C:

lpeff->lpVtbl->Initialize(lpeff, g_hinstDll,
                          DIRECTINPUT_VERSION, &GUID_Effect);

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.


IDirectInputEffect::SetParameters

The IDirectInputEffect::SetParameters method sets the characteristics of an effect.

HRESULT SetParameters(
  LPCDIEFFECT peff,
  DWORD dwFlags
);

Parameters

peff
DIEFFECT structure that contains effect information. The dwSize member must be filled in by the application before calling this method, as well as any members specified by corresponding bits in the dwFlags parameter.
dwFlags
Flags specifying which portions of the effect information are to be set and how the downloading of the parameters should be handled. The value can be 0 or one or more of the following constants:
DIEP_AXES
The cAxes and rgdwAxes members contain data.
DIEP_DIRECTION
The cAxes and rglDirection members contain data. The dwFlags member specifies (with DIEFF_CARTESIAN or DIEFF_POLAR) the coordinate system in which the values should be interpreted.
DIEP_DURATION
The dwDuration member contains data.
DIEP_ENVELOPE
The lpEnvelope member points to a DIENVELOPE structure that contains data. To detach any existing envelope from the effect, pass this flag and set the lpEnvelope member to NULL.
DIEP_GAIN
The dwGain member contains data.
DIEP_NODOWNLOAD
Suppress the automatic IDirectInputEffect::Download that is normally performed after the parameters are updated. See Remarks.
DIEP_NORESTART
Suppress the stopping and restarting of the effect to change parameters. See Remarks.
DIEP_SAMPLEPERIOD
The dwSamplePeriod member contains data.
DIEP_START
The effect is to be started (or restarted if it is currently playing) after the parameters are updated. By default, the play state of the effect is not altered.
DIEP_STARTDELAY
The dwStartDelay member contains data.
DIEP_TRIGGERBUTTON
The dwTriggerButton member contains data.
DIEP_TRIGGERDELAY
The dwTriggerDelay member contains data.
DIEP_TRIGGERREPEATINTERVAL
The dwTriggerRepeatInterval member contains data.
DIEP_TYPESPECIFICPARAMS
The lpvTypeSpecificParams and cbTypeSpecificParams members of the DIEFFECT structure contain the address and size of type-specific data for the effect.

Return Values

If the method succeeds, the return value is one of the following:

DI_OK
DI_EFFECTRESTARTED
DI_DOWNLOADSKIPPED
DI_TRUNCATED
DI_TRUNCATEDANDRESTARTED

If the method fails, the return value can be one of the following error values:

DIERR_NOTINITIALIZED
DIERR_INCOMPLETEEFFECT
DIERR_INPUTLOST
DIERR_INVALIDPARAM
DIERR_EFFECTPLAYING

Remarks

The dwDynamicParams member of the DIEFFECTINFO structure for the effect specifies which parameters can be dynamically updated while the effect is playing.

The IDirectInputEffect::SetParameters method automatically downloads the effect, but this behavior can be suppressed by setting the DIEP_NODOWNLOAD flag. If automatic download has been suppressed, you can manually download the effect by invoking the IDirectInputEffect::Download method.

If the effect is playing while the parameters are changed, the new parameters take effect as if they were the parameters when the effect started.

For example, suppose a periodic effect with a duration of three seconds is started. After two seconds, the direction of the effect is changed. The effect then continues for one additional second in the new direction. The envelope, phase, amplitude, and other parameters of the effect continue smoothly, as if the direction had not changed.

In the same situation, if after two seconds, the duration of the effect were changed to 1.5 seconds, the effect would stop.

Normally, if the driver cannot update the parameters of a playing effect, the driver is permitted to stop the effect, update the parameters, and then restart the effect. Passing the DIEP_NORESTART flag suppresses this behavior. If the driver cannot update the parameters of an effect while it is playing, the error code DIERR_EFFECTPLAYING is returned, and the parameters are not updated.

No more than one of the DIEP_NODOWNLOAD, DIEP_START, and DIEP_NORESTART flags should be set. (It is also valid to pass none of them.)

These three flags control download and playback behavior as follows:

If DIEP_NODOWNLOAD is set, the effect parameters are updated but not downloaded to the device.

If the DIEP_START flag is set, the effect parameters are updated and downloaded to the device, and the effect is started just as if the IDirectInputEffect::Start method had been called with the dwIterations parameter set to 1 and with no flags. (Combining the update with DIEP_START is slightly faster than calling Start separately, because it requires less information to be transmitted to the device.)

If neither DIEP_NODOWNLOAD nor DIEP_START is set and the effect is not playing, the parameters are updated and downloaded to the device.

If neither DIEP_NODOWNLOAD nor DIEP_START is set and the effect is playing, the parameters are updated if the device supports on-the-fly updating. Otherwise the behavior depends on the state of the DIEP_NORESTART flag. If it is set, the error code DIERR_EFFECTPLAYING is returned. If it is clear, the effect is stopped, the parameters are updated, and the effect is restarted.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.


IDirectInputEffect::Start

The IDirectInputEffect::Start method begins playing an effect. If the effect is already playing, it is restarted from the beginning. If the effect has not been downloaded or has been modified since its last download, it is downloaded before being started. This default behavior can be suppressed by passing the DIES_NODOWNLOAD flag.

HRESULT Start(
  DWORD dwIterations,
  DWORD dwFlags
);

Parameters

dwIterations
Number of times to play the effect in sequence. The envelope is re-articulated with each iteration.

To play the effect exactly once, pass 1. To play the effect repeatedly until explicitly stopped, pass INFINITE. To play the effect until explicitly stopped without re-articulating the envelope, modify the effect parameters with the IDirectInputEffect::SetParameters method, and change the dwDuration member to INFINITE.

dwFlags
Flags that describe how the effect should be played by the device. The value can be 0 or one or more of the following values:
DIES_SOLO
All other effects on the device should be stopped before the specified effect is played. If this flag is omitted, the effect is mixed with existing effects already started on the device.
DIES_NODOWNLOAD
Do not automatically download the effect.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM
DIERR_INCOMPLETEEFFECT
DIERR_NOTEXCLUSIVEACQUIRED
DIERR_NOTINITIALIZED
DIERR_UNSUPPORTED

Remarks

The device must be acquired at the exclusive cooperative level for this method to succeed.

Not all devices support multiple iterations.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.


IDirectInputEffect::Stop

The IDirectInputEffect::Stop method stops playing an effect.

HRESULT Stop(void);

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_NOTEXCLUSIVEACQUIRED
DIERR_NOTINITIALIZED

Remarks

The device must be acquired at the exclusive cooperative level for this method to succeed.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.


IDirectInputEffect::Unload

The IDirectInputEffect::Unload method removes the effect from the device. If the effect is playing, it is automatically stopped before it is unloaded.

HRESULT Unload(void);

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INPUTLOST
DIERR_INVALIDPARAM
DIERR_NOTEXCLUSIVEACQUIRED
DIERR_NOTINITIALIZED

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.


Functions

This section is a reference for DirectInput functions other than COM interface methods and callback functions.

The following functions fall into this category:

  • DirectInputCreate is used to create the DirectInput system and obtain an IDirectInput interface. This function is still supported but has been superseded by DirectInputCreateEx.
  • DirectInputCreateEx is used to create the DirectInput system and obtain an IDirectInput, IDirectInput2, or IDirectInput7 interface.


DirectInputCreate

The DirectInputCreate function creates a DirectInput object that supports the IDirectInput COM interface.

HRESULT WINAPI DirectInputCreate(
  HINSTANCE hinst,
  DWORD dwVersion,
  LPDIRECTINPUT * lplpDirectInput,
  LPUNKNOWN punkOuter
);

Parameters

hinst
Instance handle to the application or DLL that is creating the DirectInput object. DirectInput uses this value to determine whether the application or DLL has been certified and to establish any special behaviors that may be necessary for backward compatibility.

It is an error for a DLL to pass the handle to the parent application. For example, an ActiveX control embedded in a Web page that uses DirectInput must pass its own instance handle, and not the handle to the Web browser. This ensures that DirectInput recognizes the control and can enable any special behaviors that might be necessary.

dwVersion
Version number of DirectInput for which the application is designed. This value is normally DIRECTINPUT_VERSION. Passing the version number of a previous version causes DirectInput to emulate that version. For more information, see Designing for Previous Versions of DirectInput.
lplpDirectInput
Address of a variable to receive a valid IDirectInput interface pointer if the call succeeds.
punkOuter
Pointer to the address of the controlling object's IUnknown interface for COM aggregation, or NULL if the interface is not aggregated. Most callers pass NULL. If aggregation is requested, the object returned in *lplpDirectInput is a pointer to the IUnknown, rather than an IDirectInput interface, as required by COM aggregation.

Return Values

If the function succeeds, the return value is DI_OK.

If the function fails, the return value can be one of the following error values:

DIERR_BETADIRECTINPUTVERSION
DIERR_INVALIDPARAM
DIERR_OLDDIRECTINPUTVERSION
DIERR_OUTOFMEMORY

Remarks

This function has been superseded by DirectInputCreateEx, which can be used to obtain any existing interface to the DirectInput object. It is recommended that you use that function to obtain the IDirectInput7 interface, which has more functionality.

Calling the function with punkOuter = NULL is equivalent to creating the object through CoCreateInstance(&CLSID_DirectInput, punkOuter, CLSCTX_INPROC_SERVER, &IID_IDirectInput, lplpDirectInput), then initializing it with Initialize.

Calling the function with punkOuter != NULL is equivalent to creating the object through CoCreateInstance(&CLSID_DirectInput, punkOuter, CLSCTX_INPROC_SERVER, &IID_IUnknown, lplpDirectInput). The aggregated object must be initialized manually.

There are separate ANSI and Unicode versions of this service. The ANSI version creates an object that supports the IDirectInputA interface, whereas the Unicode version creates an object that supports the IDirectInputW interface. As with other system services that are sensitive to character-set issues, macros in the header file map DirectInputCreate to the appropriate character set variation.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.


DirectInputCreateEx

The DirectInputCreateEx function creates a DirectInput object that supports the IDirectInput, IDirectInput2, or IDirectInput7 COM interfaces.

HRESULT WINAPI DirectInputCreateEx(
  HINSTANCE hinst,
  DWORD dwVersion,
  REFIID riidltf,
  LPVOID * ppvOut,
  LPUNKNOWN punkOuter
);

Parameters

hinst
Instance handle to the application or DLL that is creating the DirectInput object. DirectInput uses this value to determine whether the application or DLL has been certified and to establish any special behaviors that might be necessary for backward compatibility.

It is an error for a DLL to pass the handle to the parent application. For example, an ActiveX control embedded in a Web page that uses DirectInput must pass its own instance handle, and not the handle to the Web browser. This ensures that DirectInput recognizes the control and can enable any special behaviors that might be necessary.

dwVersion
Version number of DirectInput for which the application is designed. This value is normally DIRECTINPUT_VERSION. Passing the version number of a previous version causes DirectInput to emulate that version. For more information, see Designing for Previous Versions of DirectInput.
riidltf
Unique identifier of the desired DirectInput interface. Values supported are IID_IDirectInput, IID_IDirectInput2, and IID_IDirectInput7. If UNICODE is defined during compilation, the Unicode version of the interface is returned; otherwise, it is the ANSI version.
ppvOut
Address of a variable to receive the interface pointer if the call succeeds.
punkOuter
Pointer to the address of the controlling object's IUnknown interface for COM aggregation, or NULL if the interface is not aggregated. Most callers pass NULL. If aggregation is requested, the object returned in *ppvOut is a pointer to IUnknown, rather than an IDirectInput interface, as required by COM aggregation.

Return Values

If the function succeeds, the return value is DI_OK.

If the function fails, the return value can be one of the following error values:

DIERR_BETADIRECTINPUTVERSION
DIERR_INVALIDPARAM
DIERR_OLDDIRECTINPUTVERSION
DIERR_OUTOFMEMORY

Remarks

Calling the function with punkOuter = NULL is equivalent to creating the object through CoCreateInstance(&CLSID_DirectInput, punkOuter, CLSCTX_INPROC_SERVER, &IID_IDirectInput7W, lplpDirectInput), then initializing it with IDirectInput7::Initialize.

Calling the function with punkOuter != NULL is equivalent to creating the object through CoCreateInstance(&CLSID_DirectInput, punkOuter, CLSCTX_INPROC_SERVER, &IID_IUnknown, lplpDirectInput). The aggregated object must be initialized manually.

There are separate ANSI and Unicode versions of this service. The ANSI version creates an object that supports the IDirectInputA interface, whereas the Unicode version creates an object that supports the IDirectInputW interface. As with other system services that are sensitive to character-set issues, macros in the header file map DirectInputCreateEx to the appropriate character set variation.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: Use dinput.lib.


Callback Functions

The following four functions are prototype callback functions for use with various enumeration methods. Applications can declare one of these callback functions under any name and define it in any way, but the parameter and return types must be the same as in the prototype.

  • DIEnumCreatedEffectObjectsCallback
  • DIEnumDeviceObjectsCallback
  • DIEnumDevicesCallback
  • DIEnumEffectsCallback
  • DIEnumEffectsInFileCallback


DIEnumCreatedEffectObjectsCallback

The DIEnumCreatedEffectObjectsCallback function is an application-defined callback function that receives DirectInputDevice effects as a result of a call to the IDirectInputDevice7::EnumCreatedEffectObjects method.

BOOL CALLBACK DIEnumCreatedEffectObjectsCallback(
  LPDIRECTINPUTEFFECT peff,
  LPVOID pvRef
);

Parameters

peff
Address of an effect object that has been created.
pvRef
Application-defined value given in the IDirectInputDevice7::EnumCreatedEffectObjects method.

Return Values

Returns DIENUM_CONTINUE to continue the enumeration or DIENUM_STOP to stop the enumeration.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: User-defined.


DIEnumDeviceObjectsCallback

The DIEnumDeviceObjectsCallback function is an application-defined callback function that receives DirectInputDevice objects as a result of a call to the IDirectInputDevice7::EnumObjects method.

BOOL CALLBACK DIEnumDeviceObjectsCallback(
  LPCDIDEVICEOBJECTINSTANCE lpddoi,
  LPVOID pvRef
);

Parameters

lpddoi
DIDEVICEOBJECTINSTANCE structure that describes the object being enumerated.
pvRef
Application-defined value given in the EnumObjects method.

Return Values

Returns DIENUM_CONTINUE to continue the enumeration or DIENUM_STOP to stop the enumeration.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: User-defined.


DIEnumDevicesCallback

The DIEnumDevicesCallback function is an application-defined callback function that receives DirectInput devices as a result of a call to the IDirectInput7::EnumDevices method.

BOOL CALLBACK DIEnumDevicesCallback(
  LPCDIDEVICEINSTANCE lpddi,
  LPVOID pvRef
);

Parameters

lpddi
Address of a DIDEVICEINSTANCE structure that describes the device instance.
pvRef
Application-defined value given in the EnumDevices method.

Return Values

Returns DIENUM_CONTINUE to continue the enumeration or DIENUM_STOP to stop the enumeration.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: User-defined.


DIEnumEffectsCallback

The DIEnumEffectsCallback function is an application-defined callback function used with the IDirectInputDevice7::EnumEffects method.

BOOL CALLBACK DIEnumEffectsCallback(
  LPCDIEFFECTINFO pdei,
  LPVOID pvRef
);

Parameters

pdei
DIEFFECTINFO structure that describes the enumerated effect.
pvRef
Address of application-defined data given to the EnumEffects method.

Return Values

Returns DIENUM_CONTINUE to continue the enumeration, or DIENUM_STOP to stop it.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: User-defined.


DIEnumEffectsInFileCallback

The DIEnumEffectsInFileCallback function is an application-defined callback function used with the IDirectInputDevice7::EnumEffectsInFile method.

BOOL CALLBACK DIEnumEffectsInFileCallback(
  LPCDIFILEEFFECT lpDiFileEf,
  LPVOID pvRef
);

Parameters

lpDiFileEf
DIFILEEFFECT structure that describes the enumerated effect.
pvRef
Address of application-defined data given to the EnumEffectsInFile method.

Return Values

Returns DIENUM_CONTINUE to continue the enumeration, or DIENUM_STOP to stop it.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.
Import Library: User-defined.


Macros

This section describes the following macros used in DirectInput:

  • DIDFT_GETINSTANCE
  • DIDFT_GETTYPE
  • DIDFT_MAKEINSTANCE
  • DIEFT_GETTYPE
  • DIMAKEUSAGEDWORD
  • DISEQUENCE_COMPARE
  • GET_DIDEVICE_SUBTYPE
  • GET_DIDEVICE_TYPE

Dinput.h also defines macros for C calls to all the methods of the IDirectInput and IDirectInputDevice interfaces. These macros eliminate the need for pointers to method tables. For example, the following is a C call to the IDirectInputDevice7::Release method:

lpdid->lpVtbl->Release(lpdid));

The equivalent macro call looks like this:

IDirectInputDevice7_Release(lpdid);

All these macros take the same parameters as the method calls themselves.


DIDFT_GETINSTANCE

The DIDFT_GETINSTANCE macro extracts the object instance number code from a data format type.

DIDFT_GETINSTANCE(n) LOWORD((n) >> 8)

Parameters

n
DirectInput data format type. The possible values for this parameter are identical to those found in the dwType member of the DIOBJECTDATAFORMAT structure.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.

See Also

DIDFT_MAKEINSTANCE, DIDFT_GETTYPE


DIDFT_GETTYPE

The DIDFT_GETTYPE macro extracts the object type code from a data format type.

DIDFT_GETTYPE(n)  LOBYTE(n)

Parameters

n
DirectInput data format type. The possible values for this parameter are identical to those found in the dwType member of the DIOBJECTDATAFORMAT structure.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.

See Also

DIDFT_GETINSTANCE


DIDFT_MAKEINSTANCE

The DIDFT_MAKEINSTANCE macro creates an instance identifier of a device object for packing in the dwType member of the DIOBJECTDATAFORMAT structure.

DIDFT_MAKEINSTANCE(n) ((WORD)(n) << 8)

Parameters

n
Instance of the object; for example, 1 for button 1 of a mouse.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.

See Also

DIDFT_GETINSTANCE


DIEFT_GETTYPE

The DIEFT_GETTYPE macro extracts the effect type code from an effect format type.

DIEFT_GETTYPE(n)  LOBYTE(n)

Parameters

n
DirectInput effect format type. The possible values for this parameter are identical to those found in the dwEffType member of the DIEFFECTINFO structure.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.


DIMAKEUSAGEDWORD

The DIMAKEUSAGEDWORD macro combines the Usage Page and Usage HID codes for a device object, for passing to the IDirectInputDevice7::GetObjectInfo method.

DWORD DIMAKEUSAGEDWORD(
  WORD UsagePage,
  WORD Usage
);

Parameters

UsagePage
Usage page of the device object.
Usage
Usage of the device object.

Remarks

This macro is declared in Dinput.h as follows:

#define DIMAKEUSAGEDWORD(UsagePage, Usage) \
        ((DWORD)MAKELONG(Usage, UsagePage))

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in dinput.h.


DISEQUENCE_COMPARE

The DISEQUENCE_COMPARE macro compares two DirectInput sequence numbers, compensating for wrap around.

DISEQUENCE_COMPARE(dwSequence1, cmp, dwSequence2) \
                ((int)((dwSequence1) - (dwSequence2)) cmp 0)

Parameters

dwSequence1
First sequence number to compare.
cmp
One of the following comparison operators: ==, !=, <, >, <=, or >=.
dwSequence2
Second sequence number to compare.

Return Values

Returns a nonzero value if the result of the comparison specified by the cmp parameter is true, or 0 otherwise.

Remarks

The following example checks whether the dwSequence1 parameter value precedes the dwSequence2 parameter value chronologically:

BOOL Sooner = (DISEQUENCE_COMPARE(dwSequence1, <, dwSequence2));

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.


GET_DIDEVICE_SUBTYPE

The GET_DIDEVICE_SUBTYPE macro extracts the device subtype code from a device type description code.

GET_DIDEVICE_SUBTYPE(dwDevType)  HIBYTE(dwDevType)

Parameters

dwDevType
DirectInput device type description code. The possible values for this parameter are identical to those found in the dwDevType member of the DIDEVICEINSTANCE structure.

Remarks

The interpretation of the subtype code depends on the primary type.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.

See Also

GET_DIDEVICE_TYPE, DIDEVICEINSTANCE


GET_DIDEVICE_TYPE

The GET_DIDEVICE_TYPE macro extracts the device primary type code from a device type description code.

GET_DIDEVICE_TYPE(dwDevType)  LOBYTE(dwDevType)

Parameters

dwDevType
DirectInput device type description code. Possible values for this parameter are identical to those found in the dwDevType member of the DIDEVICEINSTANCE structure.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.

See Also

GET_DIDEVICE_SUBTYPE, DIDEVICEINSTANCE


Structures

This section contains information on the following structures used with DirectInput:

  • DICONDITION
  • DICONSTANTFORCE
  • DICUSTOMFORCE
  • DIDATAFORMAT
  • DIDEVCAPS
  • DIDEVICEINSTANCE
  • DIDEVICEOBJECTDATA
  • DIDEVICEOBJECTINSTANCE
  • DIEFFECT
  • DIEFFECTINFO
  • DIEFFESCAPE
  • DIENVELOPE
  • DIFILEEFFECT
  • DIJOYSTATE
  • DIJOYSTATE2
  • DIMOUSESTATE
  • DIMOUSESTATE2
  • DIOBJECTDATAFORMAT
  • DIPERIODIC
  • DIPROPDWORD
  • DIPROPGUIDANDPATH
  • DIPROPHEADER
  • DIPROPRANGE
  • DIPROPSTRING
  • DIRAMPFORCE

Note The memory for all DirectX structures must be initialized to 0 before use. In addition, all structures that contain a dwSize member should set the member to the size of the structure, in bytes, before use. The following example performs these tasks on a common structure, DIDEVCAPS:

DIDEVCAPS didevcaps; // Can't use this yet

ZeroMemory(&didevcaps, sizeof(didevcaps));
didevcaps.dwSize = sizeof(didevcaps);

// Now the structure can be used.
.
.


DICONDITION

The DICONDITION structure contains type-specific information for effects that are marked as DIEFT_CONDITION.

A pointer to an array of DICONDITION structures for an effect is passed in the lpvTypeSpecificParams member of the DIEFFECT structure. The number of elements in the array must be either one, or equal to the number of axes associated with the effect.

typedef struct DICONDITION {
    LONG lOffset;
    LONG lPositiveCoefficient;
    LONG lNegativeCoefficient;
    DWORD dwPositiveSaturation;
    DWORD dwNegativeSaturation;
    LONG lDeadBand;
} DICONDITION, *LPDICONDITION;

typedef const DICONDITION *LPCDICONDITION;

Members

lOffset
Offset for the condition, in the range from –10,000 through 10,000.
lPositiveCoefficient
Coefficient constant on the positive side of the offset, in the range from –10,000 through 10,000.
lNegativeCoefficient
Coefficient constant on the negative side of the offset, in the range from –10,000 through 10,000.

If the device does not support separate positive and negative coefficients, the value of lNegativeCoefficient is ignored, and the value of lPositiveCoefficient is used as both the positive and negative coefficients.

dwPositiveSaturation
Maximum force output on the positive side of the offset, in the range from 0 through 10,000.

If the device does not support force saturations, the value of this member is ignored.

dwNegativeSaturation
Maximum force output on the negative side of the offset, in the range from 0 through 10,000.

If the device does not support force saturation, the value of this member is ignored.

If the device does not support separate positive and negative saturation, the value of dwNegativeSaturation is ignored, and the value of dwPositiveSaturation is used as both the positive and negative saturation.

lDeadBand
Region around lOffset in which the condition is not active, in the range from 0 through 10,000. In other words, the condition is not active between lOffset minus lDeadBand and lOffset plus lDeadBand.

Remarks

Different types of conditions interpret the parameters differently, but the basic idea is that force resulting from a condition is equal to A(q - q0) where A is a scaling coefficient, q is some metric, and q0 is the neutral value for that metric.

The preceding simplified formula must be adjusted if a nonzero dead band is provided. If the metric is less than lOffset - lDeadBand, the resulting force is given by the following formula:

force = lNegativeCoefficient * (q - (lOffset - lDeadBand))

Similarly, if the metric is greater than lOffset + lDeadBand, the resulting force is given by the following formula:

force = lPositiveCoefficient * (q - (lOffset + lDeadBand))

A spring condition uses axis position as the metric.

A damper condition uses axis velocity as the metric.

An inertia condition uses axis acceleration as the metric.

If the number of DICONDITION structures in the array is equal to the number of axes for the effect, the first structure applies to the first axis, the second applies to the second axis, and so on. For example, a two-axis spring condition with lOffset set to 0 in both DICONDITION structures would have the same effect as the joystick self-centering spring. When a condition is defined for each axis in this way, the effect must not be rotated.

If there is a single DICONDITION structure for an effect with more than one axis, the direction along which the parameters of the DICONDITION structure are in effect is determined by the direction parameters passed in the rglDirection field of the DIEFFECT structure. For example, a friction condition rotated 45 degrees (in polar coordinates) would resist joystick motion in the northeast-southwest direction but would have no effect on joystick motion in the northwest-southeast direction.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.


DICONSTANTFORCE

The DICONSTANTFORCE structure contains type-specific information for effects that are marked as DIEFT_CONSTANTFORCE.

The structure describes a constant force effect.

A pointer to a single DICONSTANTFORCE structure for an effect is passed in the lpvTypeSpecificParams member of the DIEFFECT structure.

typedef struct DICONSTANTFORCE {
    LONG lMagnitude;
} DICONSTANTFORCE, *LPDICONSTANTFORCE;

typedef const DICONSTANTFORCE *LPCDICONSTANTFORCE;

Members

lMagnitude
The magnitude of the effect, in the range from –10,000 through 10,000. If an envelope is applied to this effect, the value represents the magnitude of the sustain. If no envelope is applied, the value represents the amplitude of the entire effect.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.


DICUSTOMFORCE

The DICUSTOMFORCE structure contains type-specific information for effects that are marked as DIEFT_CUSTOMFORCE.

The structure describes a custom or user-defined force.

A pointer to a DICUSTOMFORCE structure for an effect is passed in the lpvTypeSpecificParams member of the DIEFFECT structure.

typedef struct DICUSTOMFORCE {
    DWORD cChannels;
    DWORD dwSamplePeriod;
    DWORD cSamples;
    LPLONG rglForceData;
} DICUSTOMFORCE, *LPDICUSTOMFORCE;

typedef const DICUSTOMFORCE *LPCDICUSTOMFORCE;

Members

cChannels
Number of channels (axes) affected by this force.

The first channel is applied to the first axis associated with the effect, the second to the second, and so on. If there are fewer channels than axes, nothing is associated with the extra axes.

If there is only a single channel, the effect is rotated in the direction specified by the rglDirection member of the DIEFFECT structure. If there is more than one channel, rotation is not allowed.

Not all devices support rotation of custom effects.

dwSamplePeriod
Sample period, in microseconds.
cSamples
Total number of samples in the rglForceData. It must be an integral multiple of the cChannels.
rglForceData
Pointer to an array of force values representing the custom force. If multiple channels are provided, the values are interleaved. For example, if cChannels is 3, the first element of the array belongs to the first channel, the second to the second, and the third to the third.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.


DIDATAFORMAT

The DIDATAFORMAT structure carries information describing a device's data format. This structure is used with the IDirectInputDevice7::SetDataFormat method.

typedef struct DIDATAFORMAT {
    DWORD dwSize;
    DWORD dwObjSize;
    DWORD dwFlags;
    DWORD dwDataSize;
    DWORD dwNumObjs;
    LPDIOBJECTDATAFORMAT rgodf;
} DIDATAFORMAT, *LPDIDATAFORMAT;

typedef const DIDATAFORMAT *LPCDIDATAFORMAT;

Members

dwSize
Size of this structure, in bytes.
dwObjSize
Size of the DIOBJECTDATAFORMAT structure, in bytes.
dwFlags
Flags describing other attributes of the data format. This value can be one of the following:
DIDF_ABSAXIS
The axes are in absolute mode. Setting this flag in the data format is equivalent to manually setting the axis mode property, using the IDirectInputDevice7::SetProperty method. This cannot be combined with DIDF_RELAXIS flag.
DIDF_RELAXIS
The axes are in relative mode. Setting this flag in the data format is equivalent to manually setting the axis mode property using the IDirectInputDevice7::SetProperty method. This cannot be combined with the DIDF_ABSAXIS flag.
dwDataSize
Size of a data packet returned by the device, in bytes. This value must be a multiple of 4 and must exceed the largest offset value for an object's data within the data packet.
dwNumObjs
Number of objects in the rgodf array.
rgodf
Address to an array of DIOBJECTDATAFORMAT structures. Each structure describes how one object's data should be reported in the device data. Typical errors include placing two pieces of information in the same location and placing one piece of information in more than one location.

Remarks

Applications do not typically need to create a DIDATAFORMAT structure. An application can use one of the predefined global data format variables, c_dfDIMouse, c_dfDIMouse2, c_dfDIKeyboard, c_dfDIJoystick, or c_dfDIJoystick2.

The following code example sets a data format that can be used by applications that need two axes (reported in absolute coordinates) and two buttons:

// Suppose an application uses the following
// structure to read device data.

typedef struct MYDATA {
    LONG  lX;                   // X-axis goes here.
    LONG  lY;                   // Y-axis goes here.
    BYTE  bButtonA;             // One button goes here.
    BYTE  bButtonB;             // Another button goes here.
    BYTE  bPadding[2];          // Must be DWORD multiple in size.
} MYDATA;

// Then, it can use the following data format.

DIOBJECTDATAFORMAT rgodf[ ] = {
  { &GUID_XAxis, FIELD_OFFSET(MYDATA, lX),
    DIDFT_AXIS | DIDFT_ANYINSTANCE, 0, },
  { &GUID_YAxis, FIELD_OFFSET(MYDATA, lY),
    DIDFT_AXIS | DIDFT_ANYINSTANCE, 0, },
  { &GUID_Button, FIELD_OFFSET(MYDATA, bButtonA),
    DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0, },
  { &GUID_Button, FIELD_OFFSET(MYDATA, bButtonB),
    DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0, },
};
#define numObjects (sizeof(rgodf) / sizeof(rgodf[0]))

DIDATAFORMAT df = {
    sizeof(DIDATAFORMAT),       // this structure
    sizeof(DIOBJECTDATAFORMAT), // size of object data format
    DIDF_ABSAXIS,               // absolute axis coordinates
    sizeof(MYDATA),             // device data size
    numObjects,                 // number of objects
    rgodf,                      // and here they are
};

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.


DIDEVCAPS

The DIDEVCAPS structure contains information about a DirectInput device's capabilities. This structure is used with the IDirectInputDevice7::GetCapabilities method.

typedef struct DIDEVCAPS {
    DWORD dwSize;
    DWORD dwFlags;
    DWORD dwDevType;
    DWORD dwAxes;
    DWORD dwButtons;
    DWORD dwPOVs;
    DWORD dwFFSamplePeriod;
    DWORD dwFFMinTimeResolution;
    DWORD dwFirmwareRevision;
    DWORD dwHardwareRevision;
    DWORD dwFFDriverVersion;
} DIDEVCAPS, *LPDIDEVCAPS;

Members

dwSize
Size of this structure, in bytes. This member must be initialized by the application before a call to the IDirectInputDevice7::GetCapabilities method.
dwFlags
Flags associated with the device. This value can be a combination of the following:
DIDC_ALIAS
The device is a duplicate of another DirectInput device. Alias devices are by default not enumerated by IDirectInput7::EnumDevices.
DIDC_PHANTOM
The device does not really exist. It is a placeholder for a device which might exist in the future. Phantom devices are by default not enumerated by IDirectInput7::EnumDevices.
DIDC_ATTACHED
The device is physically attached.
DIDC_DEADBAND
The device supports deadband for at least one force-feedback condition.
DIDC_EMULATED
If this flag is set, the data is coming from a user mode device interface (such as HID) or by some other ring 3 means. If it is not set, the data is coming directly from a kernel mode driver.
DIDC_FORCEFEEDBACK
The device supports force feedback.
DIDC_FFFADE
The force-feedback system supports the fade parameter for at least one effect. If the device does not support fade, the fade level and fade time members of the DIENVELOPE structure are ignored by the device.

After a call to the IDirectInputDevice7::GetEffectInfo method, an individual effect sets the DIEFT_FFFADE flag if fade is supported for that effect.

DIDC_FFATTACK
The force-feedback system supports the attack parameter for at least one effect. If the device does not support attack, the attack level and attack time members of the DIENVELOPE structure are ignored by the device.

After a call to the IDirectInputDevice7::GetEffectInfo method, an individual effect sets the DIEFT_FFATTACK flag if attack is supported for that effect.

DIDC_POLLEDDATAFORMAT
At least one object in the current data format is polled, rather than interrupt-driven. For these objects, the application must explicitly call the IDirectInputDevice7::Poll method to obtain data.
DIDC_POLLEDDEVICE
At least one object on the device is polled, rather than interrupt-driven. For these objects, the application must explicitly call the IDirectInputDevice7::Poll method to obtain data. HID devices can contain a mixture of polled and nonpolled objects.
DIDC_POSNEGCOEFFICIENTS
The force-feedback system supports two coefficient values for conditions (one for the positive displacement of the axis and one for the negative displacement of the axis) for at least one condition. If the device does not support both coefficients, the negative coefficient in the DICONDITION structure is ignored.

After a call to the IDirectInputDevice7::GetEffectInfo method, an individual condition sets the DIEFT_POSNEGCOEFFICIENTS flag if separate positive and negative coefficients are supported for that condition.

DIDC_POSNEGSATURATION
The force-feedback system supports a maximum saturation for both positive and negative force output for at least one condition. If the device does not support both saturation values, the negative saturation in the DICONDITION structure is ignored.

After a call to the IDirectInputDevice7::GetEffectInfo method, an individual condition sets the DIEFT_POSNEGSATURATION flag if separate positive and negative saturation are supported for that condition.

DIDC_SATURATION
The force-feedback system supports the saturation of condition effects for at least one condition. If the device does not support saturation, the force generated by a condition is limited only by the maximum force that the device can generate.

After a call to the IDirectInputDevice7::GetEffectInfo method, an individual condition sets the DIEFT_SATURATION flag if saturation is supported for that condition.

DIDC_STARTDELAY
The force-feedback system supports the start delay parameter for at least one effect. If the device does not support start delays, the dwStartDelay member of the DIEFFECT structure is ignored.
dwDevType
Device type specifier. This member can contain values identical to those in the dwDevType member of the DIDEVICEINSTANCE structure.
dwAxes
Number of axes available on the device.
dwButtons
Number of buttons available on the device.
dwPOVs
Number of point-of-view controllers available on the device.
dwFFSamplePeriod
Minimum time between playback of consecutive raw force commands.
dwFFMinTimeResolution
Minimum time, in microseconds, that the device can resolve. The device rounds any times to the nearest supported increment. For example, if the value of dwFFMinTimeResolution is 1000, the device would round any times to the nearest millisecond.
dwFirmwareRevision
Specifies the firmware revision of the device.
dwHardwareRevision
Hardware revision of the device.
dwFFDriverVersion
Version number of the device driver.

Remarks

The semantics of version numbers are left to the manufacturer of the device. The only guarantee is that newer versions have larger numbers.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.

See Also

DIDEVICEINSTANCE


DIDEVICEINSTANCE

The DIDEVICEINSTANCE structure contains information about an instance of a DirectInput device. This structure is used with the IDirectInput7::EnumDevices and IDirectInputDevice7::GetDeviceInfo methods.

typedef struct DIDEVICEINSTANCE {
    DWORD dwSize;
    GUID  guidInstance;
    GUID  guidProduct;
    DWORD dwDevType;
    TCHAR tszInstanceName[MAX_PATH];
    TCHAR tszProductName[MAX_PATH];
    GUID guidFFDriver;
    WORD wUsagePage;
    WORD wUsage;
} DIDEVICEINSTANCE, *LPDIDEVICEINSTANCE;

typedef const DIDEVICEINSTANCE  *LPCDIDEVICEINSTANCE;

Members

dwSize
Size of this structure, in bytes. This member must be initialized before the structure is used.
guidInstance
Unique identifier for the instance of the device. An application can save the instance GUID into a configuration file and use it at a later time. Instance GUIDs are specific to a particular computer. An instance GUID obtained from one computer is unrelated to instance GUIDs on another.
guidProduct
Unique identifier for the product. This identifier is established by the manufacturer of the device.
dwDevType
Device type specifier. The least-significant byte of the device type description code specifies the device type. The next-significant byte specifies the device subtype. This value can be one of the following types combined with their respective subtypes and optionally with DIDEVTYPE_HID, which specifies a Human Interface Device.
Device Types
DIDEVTYPE_MOUSE
A mouse or mouse-like device (such as a trackball).
DIDEVTYPE_KEYBOARD
A keyboard or keyboard-like device.
DIDEVTYPE_JOYSTICK
A joystick or similar device, such as a steering wheel.
DIDEVTYPE_DEVICE
A device that does not fall into the previous categories.
Mouse subtypes
DIDEVTYPEMOUSE_UNKNOWN
The subtype could not be determined.
DIDEVTYPEMOUSE_TRADITIONAL
The device is a traditional mouse.
DIDEVTYPEMOUSE_FINGERSTICK
The device is a fingerstick.
DIDEVTYPEMOUSE_TOUCHPAD
The device is a touchpad.
DIDEVTYPEMOUSE_TRACKBALL
The device is a trackball.
Keyboard subtypes
DIDEVTYPEKEYBOARD_UNKNOWN
The subtype could not be determined.
DIDEVTYPEKEYBOARD_PCXT
IBM PC/XT 83-key keyboard.
DIDEVTYPEKEYBOARD_OLIVETTI
Olivetti 102-key keyboard.
DIDEVTYPEKEYBOARD_PCAT
IBM PC/AT 84-key keyboard.
DIDEVTYPEKEYBOARD_PCENH
IBM PC Enhanced 101/102-key or Microsoft Natural® keyboard.
DIDEVTYPEKEYBOARD_NOKIA1050
Nokia 1050 keyboard.
DIDEVTYPEKEYBOARD_NOKIA9140
Nokia 9140 keyboard.
DIDEVTYPEKEYBOARD_NEC98
Japanese NEC PC98 keyboard.
DIDEVTYPEKEYBOARD_NEC98LAPTOP
Japanese NEC PC98 laptop keyboard.
DIDEVTYPEKEYBOARD_NEC98106
Japanese NEC PC98 106-key keyboard.
DIDEVTYPEKEYBOARD_JAPAN106
Japanese 106-key keyboard.
DIDEVTYPEKEYBOARD_JAPANAX
Japanese AX keyboard.
DIDEVTYPEKEYBOARD_J3100
Japanese J3100 keyboard.
Joystick Subtypes
DIDEVTYPEJOYSTICK_UNKNOWN
The subtype could not be determined.
DIDEVTYPEJOYSTICK_TRADITIONAL
A traditional joystick.
DIDEVTYPEJOYSTICK_FLIGHTSTICK
A joystick optimized for flight simulation.
DIDEVTYPEJOYSTICK_GAMEPAD
A device whose primary purpose is to provide button input.
DIDEVTYPEJOYSTICK_RUDDER
A device for yaw control.
DIDEVTYPEJOYSTICK_WHEEL
A steering wheel.
DIDEVTYPEJOYSTICK_HEADTRACKER
A device that tracks the movement of the user's head.

Flags in the High Word

DIDEVTYPE_HID
The device uses the Human Interface Device (HID) protocol.
tszInstanceName[MAX_PATH]
Friendly name for the instance. For example, "Joystick 1."
tszProductName[MAX_PATH]
Friendly name for the product.
guidFFDriver
Unique identifier for the driver being used for force feedback. This identifier is established by the manufacturer of the driver.
wUsagePage
If the device is an HID device, this member contains the HID usage page code.
wUsage
If the device is an HID, this member contains the HID usage code.

Remarks

For compatibility with previous versions of DirectX, a DIDEVICEINSTANCE_DX3 structure is also defined, containing only the first six members of the DIDEVICEINSTANCE structure.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.


DIDEVICEOBJECTDATA

The DIDEVICEOBJECTDATA structure contains raw buffered device information. This structure is used with the IDirectInputDevice7::GetDeviceData and the IDirectInputDevice7::SendDeviceData methods.

typedef struct DIDEVICEOBJECTDATA {
    DWORD dwOfs;
    DWORD dwData;
    DWORD dwTimeStamp;
    DWORD dwSequence;
} DIDEVICEOBJECTDATA, *LPDIDEVICEOBJECTDATA;

typedef const DIDEVICEOBJECTDATA *LPCDIDEVICEOBJECTDATA;

Members

dwOfs
For GetDeviceData, the offset into the current data format of the object whose data is being reported; that is, the location in which the dwData would have been stored if the data had been obtained by a call to the IDirectInputDevice7::GetDeviceState method. If the device is accessed as a mouse, keyboard, or joystick, the dwOfs member is one of the mouse device constants, keyboard device constants, or joystick device constants. If a custom data format has been set, it is an offset relative to the custom data format.

For SendDeviceData, the instance ID of the object to which the data is being sent, as obtained from the dwType member of a DIDEVICEOBJECTINSTANCE structure.

dwData
Data obtained from or sent to the device.

For axis input, if the device is in relative axis mode, the relative axis motion is reported. If the device is in absolute axis mode, the absolute axis coordinate is reported.

For button input, only the low byte of dwData is significant. The high bit of the low byte is set if the button went down; it is clear if the button went up.

dwTimeStamp
Tick count at which the input event was generated, in milliseconds. The current system tick count (at a lower resolution) can be obtained by calling the Win32 GetTickCount function. This value wraps around approximately every 50 days.

When the structure is used with the SendDeviceData method, this member must be 0.

dwSequence
DirectInput sequence number for this event. All input events are assigned an increasing sequence number. This allows events from different devices to be sorted chronologically. Since this value can wrap around, care must be taken when comparing two sequence numbers. The DISEQUENCE_COMPARE macro can be used to perform this comparison safely.

When the structure is used with the SendDeviceData method, this member must be 0.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.


DIDEVICEOBJECTINSTANCE

The DIDEVICEOBJECTINSTANCE structure contains information about a device object instance. This structure is used with the IDirectInputDevice7::EnumObjects method to provide the DIEnumDeviceObjectsCallback callback function with information about a particular object associated with a device, such as an axis or button. It is also used with the IDirectInputDevice7::GetObjectInfo method to retrieve information about a device object.

typedef struct DIDEVICEOBJECTINSTANCE {
    DWORD dwSize;
    GUID  guidType;
    DWORD dwOfs;
    DWORD dwType;
    DWORD dwFlags;
    TCHAR tszName[MAX_PATH];
    DWORD dwFFMaxForce;
    DWORD dwFFForceResolution;
    WORD  wCollectionNumber;
    WORD  wDesignatorIndex;
    WORD  wUsagePage;
    WORD  wUsage;
    DWORD dwDimension;
    WORD  wExponent;
    WORD  wReportId;
} DIDEVICEOBJECTINSTANCE, *LPDIDEVICEOBJECTINSTANCE;

typedef const DIDEVICEOBJECTINSTANCE *LPCDIDEVICEOBJECTINSTANCE;

Members

dwSize
Size of the structure, in bytes. During enumeration, the application can inspect this value to determine how many members of the structure are valid. When the structure is passed to the IDirectInputDevice7::GetObjectInfo method, this member must be initialized to sizeof(DIDEVICEOBJECTINSTANCE).
guidType
Unique identifier that indicates the object type. This member is optional. If present, it can be one of the following values:
GUID_XAxis
The horizontal axis. For example, it can represent the left-right motion of a mouse.
GUID_YAxis
The vertical axis. For example, it can represent the forward-backward motion of a mouse.
GUID_ZAxis
The z-axis. For example, it can represent rotation of the wheel on a mouse, or movement of a throttle control on a joystick.
GUID_RxAxis
Rotation around the x-axis.
GUID_RyAxis
Rotation around the y-axis.
GUID_RzAxis
Rotation around the z-axis (often a rudder control).
GUID_Slider
A slider axis.
GUID_Button
A button on a mouse.
GUID_Key
A key on a keyboard.
GUID_POV
A point-of-view indicator.
GUID_Unknown
Unknown.

Other object types might be defined in the future.

dwOfs
Offset within the data format at which data is reported for this object. This value can be used to identify the object in method calls and structures that accept the DIPH_BYOFFSET flag.
dwType
Device type that describes the object. It is a combination of DIDFT_* flags that describe the object type (axis, button, and so on) and contains the object instance number in the middle 16 bits. Use the DIDFT_GETINSTANCE macro to extract the object instance number. For the DIDFT_* flags, see IDirectInputDevice7::EnumObjects.
dwFlags
Flags describing other attributes of the data format. This value can be one of the following:
DIDOI_ASPECTACCEL
The object reports acceleration information.
DIDOI_ASPECTFORCE
The object reports force information.
DIDOI_ASPECTMASK
The bits that are used to report aspect information. An object can represent at most one aspect.
DIDOI_ASPECTPOSITION
The object reports position information.
DIDOI_ASPECTVELOCITY
The object reports velocity information.
DIDOI_FFACTUATOR
The object can have force-feedback effects applied to it.
DIDOI_FFEFFECTTRIGGER
The object can trigger playback of force-feedback effects.
DIDOI_GUIDISUSAGE
The pguid member of the DIOBJECTDATAFORMAT structure is really a (suitably cast) DIMAKEUSAGEDWORD of the usage page and usage that is desired.
DIDOI_POLLED
The object does not return data until the IDirectInputDevice7::Poll method is called.
tszName[MAX_PATH]
Name of the object; for example, "X-Axis" or "Right Shift."
dwFFMaxForce
The magnitude of the maximum force that can be created by the actuator associated with this object. Force is expressed in newtons and measured in relation to where the hand would be during normal operation of the device.
dwFFForceResolution
The force resolution of the actuator associated with this object. The returned value represents the number of gradations, or subdivisions, of the maximum force that can be expressed by the force-feedback system from 0 (no force) to maximum force.
wCollectionNumber
The HID link collection to which the object belongs.
wDesignatorIndex
An index that refers to a designator in the HID physical descriptor. This number can be passed to functions in the HID parsing library (Hidpi.h) to obtain additional information about the device object.
wUsagePage
The HID usage page associated with the object, if known. Human Interface Devices always report a usage page. Non-HID devices can optionally report a usage page; if they do not, the value of this member is 0.
wUsage
The HID usage associated with the object, if known. Human Interface Devices always report a usage. Non-HID devices can optionally report a usage; if they do not, the value of this member is 0.
dwDimension
An HID code for the dimensional units in which the object's value is reported, if known, or 0 if not known.
wExponent
The exponent to associate with the dimension, if known. Dimensional units are always integral, so an exponent might be needed to convert them to nonintegral types.
wReportId
Reserved.

Remarks

Applications can use the wUsagePage and wUsage members to obtain additional information about how the object was designed to be used. For example, if wUsagePage has the value 0x02 (vehicle controls) and wUsage has the value 0xB9 (elevator trim), the object was designed to be the elevator trim control on a flightstick. A flight simulator application can use this information to provide more reasonable defaults for objects on the device. HID usage codes are determined by the USB standards committee.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.


DIEFFECT

The DIEFFECT structure is used by the IDirectInputDevice7::CreateEffect method to initialize a new IDirectInputEffect object. It is also used by the IDirectInputEffect::SetParameters and IDirectInputEffect::GetParameters methods.

typedef struct DIEFFECT {
    DWORD dwSize;
    DWORD dwFlags;
    DWORD dwDuration;
    DWORD dwSamplePeriod;
    DWORD dwGain;
    DWORD dwTriggerButton;
    DWORD dwTriggerRepeatInterval;
    DWORD cAxes;
    LPDWORD rgdwAxes;
    LPLONG rglDirection;
    LPDIENVELOPE lpEnvelope;
    DWORD cbTypeSpecificParams;
    LPVOID lpvTypeSpecificParams;
    DWORD  dwStartDelay;
} DIEFFECT, *LPDIEFFECT;

typedef const DIEFFECT *LPCDIEFFECT;

Members

dwSize
Specifies the size, in bytes, of the structure. This member must be initialized before the structure is used.
dwFlags
Flags associated with the effect. This value can be a combination of one or more of the following values:
DIEFF_CARTESIAN
The values of rglDirection are to be interpreted as Cartesian coordinates.
DIEFF_OBJECTIDS
The values of dwTriggerButton and rgdwAxes are object identifiers as obtained by IDirectInputDevice7::EnumObjects.
DIEFF_OBJECTOFFSETS
The values of dwTriggerButton and rgdwAxes are data format offsets, relative to the data format selected by IDirectInputDevice7::SetDataFormat.
DIEFF_POLAR
The values of rglDirection are to be interpreted as polar coordinates.
DIEFF_SPHERICAL
The values of rglDirection are to be interpreted as spherical coordinates.
dwDuration
The total duration of the effect, in microseconds. If this value is INFINITE, the effect has infinite duration. If an envelope has been applied to the effect, the attack is applied, followed by an infinite sustain.
dwSamplePeriod
The period at which the device should play back the effect, in microseconds. A value of 0 indicates that the default playback sample rate should be used.

If the device is not capable of playing back the effect at the specified rate, it chooses the supported rate that is closest to the requested value.

Setting a custom dwSamplePeriod can be used for special effects. For example, playing a sine wave at an artificially large sample period results in a rougher texture.

dwGain
The gain to be applied to the effect, in the range from 0 through 10,000. The gain is a scaling factor applied to all magnitudes of the effect and its envelope.
dwTriggerButton
The identifier or offset of the button to be used to trigger playback of the effect. The flags DIEFF_OBJECTIDS and DIEFF_OBJECTOFFSETS determine the semantics of the value. If this member is set to DIEB_NOTRIGGER, no trigger button is associated with the effect.
dwTriggerRepeatInterval
The interval, in microseconds, between the end of one playback and the start of the next when the effect is triggered by a button press and the button is held down. Setting this value to INFINITE suppresses repetition.

Support for trigger repeat for an effect is indicated by the presence of the DIEP_TRIGGERREPEATINTERVAL flag in the dwStaticParams member of the DIEFFECTINFO structure.

cAxes
Number of axes involved in the effect. This member must be filled in by the caller if changing or setting the axis list or the direction list.

The number of axes for an effect cannot be changed once it has been set.

rgdwAxes
Pointer to a DWORD array (of cAxes elements) containing identifiers or offsets identifying the axes to which the effect is to be applied. The flags DIEFF_OBJECTIDS and DIEFF_OBJECTOFFSETS determine the semantics of the values in the array.

The list of axes associated with an effect cannot be changed once it has been set.

No more than 32 axes can be associated with a single effect.

rglDirection
Pointer to a LONG array (of cAxes elements) containing either Cartesian coordinates or polar coordinates. The flags DIEFF_CARTESIAN, DIEFF_POLAR, and DIEFF_SPHERICAL determine the semantics of the values in the array.

If Cartesian, each value in rglDirection is associated with the corresponding axis in rgdwAxes.

If polar, the angle is measured in hundredths of degrees from the (0, –1) direction, rotated in the direction of (1, 0). This usually means that north is away from the user, and east is to the user's right. The last element is not used.

If spherical, the first angle is measured in hundredths of a degree from the (1, 0) direction, rotated in the direction of (0, 1). The second angle (if the number of axes is three or more) is measured in hundredths of a degree toward (0, 0, 1). The third angle (if the number of axes is four or more) is measured in hundredths of a degree toward (0, 0, 0, 1), and so on. The last element is not used.

Note The rglDirection array must contain cAxes entries, even if polar or spherical coordinates are given. In these cases, the last element in the rglDirection array is reserved for future use and must be 0.

lpEnvelope
Optional pointer to a DIENVELOPE structure that describes the envelope to be used by this effect. Not all effect types use envelopes. If no envelope is to be applied, the member should be set to NULL.
cbTypeSpecificParams
Number of bytes of additional type-specific parameters for the corresponding effect type.
lpvTypeSpecificParams
Pointer to type-specific parameters, or NULL if there are no type-specific parameters.

If the effect is of type DIEFT_CONDITION, this member contains a pointer to an array of DICONDITION structures that define the parameters for the condition. A single structure may be used, in which case the condition is applied in the direction specified in the rglDirection array. Otherwise, there must be one structure for each axis, in the same order as the axes in rgdwAxes array. If a structure is supplied for each axis, the effect should not be rotated; you should use the following values in the rglDirection array:

  • DIEFF_SPHERICAL: 0, 0, ...
  • DIEFF_POLAR: 9000, 0, ...
  • DIEFF_CARTESIAN: 1, 0, ...

If the effect is of type DIEFT_CUSTOMFORCE, this member contains a pointer to a DICUSTOMFORCE structure that defines the parameters for the custom force.

If the effect is of type DIEFT_PERIODIC, this member contains a pointer to a DIPERIODIC structure that defines the parameters for the effect.

If the effect is of type DIEFT_CONSTANTFORCE, this member contains a pointer to a DICONSTANTFORCE structure that defines the parameters for the constant force.

If the effect is of type DIEFT_RAMPFORCE, this member contains a pointer to a DIRAMPFORCE structure that defines the parameters for the ramp force.

dwStartDelay
Time (in microseconds) that the device should wait after a IDirectInputEffect::Start call before playing the effect. If this value is 0, effect playback begins immediately. This member is not present in versions prior to DirectX 7.0.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.


DIEFFECTINFO

The DIEFFECTINFO structure is used by the IDirectInputDevice7::EnumEffects and IDirectInputDevice7::GetEffectInfo methods to return information about a particular effect supported by a device.

typedef struct DIEFFECTINFO {
    DWORD dwSize;
    GUID guid;
    DWORD dwEffType;
    DWORD dwStaticParams;
    DWORD dwDynamicParams;
    TCHAR tszName[MAX_PATH];
} DIEFFECTINFO, *LPDIEFFECTINFO;

typedef const DIEFFECTINFO  *LPCDIEFFECTINFO;

Members

dwSize
Size of the structure in bytes. During enumeration, the application can inspect this value to determine how many members of the structure are valid. This member must be initialized before the structure is passed to the IDirectInputDevice7::GetEffectInfo method.
guid
Identifier of the effect.
dwEffType
Zero or more of the following values:
DIEFT_ALL
Valid only for IDirectInputDevice7::EnumEffects . Enumerate all effects, regardless of type. This flag cannot be combined with any of the other flags.
DIEFT_CONDITION
The effect represents a condition. When creating or modifying a condition, the lpvTypeSpecificParams member of the DIEFFECT structure must point to an array of DICONDITION structures (one per axis), and the cbTypeSpecificParams member must be set to cAxis * sizeof(DICONDITION).

Not all devices support all the parameters of conditions. Check the effect capability flags to determine which capabilities are available.

The flag can be passed to IDirectInputDevice7::EnumEffects to restrict the enumeration to conditions.

DIEFT_CONSTANTFORCE
The effect represents a constant-force effect. When creating or modifying a constant-force effect, the lpvTypeSpecificParams member of the DIEFFECT must point to a DICONSTANTFORCE structure, and the cbTypeSpecificParams member must be set to sizeof(DICONSTANTFORCE).

The flag can be passed to IDirectInputDevice7::EnumEffects to restrict the enumeration to constant-force effects.

DIEFT_CUSTOMFORCE
The effect represents a custom-force effect. When creating or modifying a custom-force effect, the lpvTypeSpecificParams member of the DIEFFECT structure must point to a DICUSTOMFORCE structure, and the cbTypeSpecificParams member must be set to sizeof(DICUSTOMFORCE).

The flag can be passed to IDirectInputDevice7::EnumEffects to restrict the enumeration to custom-force effects.

DIEFT_DEADBAND
The effect generator for this condition effect supports the lDeadBand parameter.
DIEFT_FFATTACK
The effect generator for this effect supports the attack envelope parameter. If the effect generator does not support attack, the attack level and attack time parameters of the DIENVELOPE structure are ignored by the effect.

If neither DIEFT_FFATTACK nor DIEFT_FFFADE is set, the effect does not support an envelope, and any provided envelope is ignored.

DIEFT_FFFADE
The effect generator for this effect supports the fade parameter. If the effect generator does not support fade, the fade level and fade time parameters of the DIENVELOPE structure are ignored by the effect.

If neither DIEFT_FFATTACK nor DIEFT_FFFADE is set, the effect does not support an envelope, and any provided envelope is ignored.

DIEFT_HARDWARE
The effect represents a hardware-specific effect. For additional information on using a hardware-specific effect, consult the hardware documentation.

The flag can be passed to the IDirectInputDevice7::EnumEffects method to restrict the enumeration to hardware-specific effects.

DIEFT_PERIODIC
The effect represents a periodic effect. When creating or modifying a periodic effect, the lpvTypeSpecificParams member of the DIEFFECT structure must point to a DIPERIODIC structure, and the cbTypeSpecificParams member must be set to sizeof(DIPERIODIC).

The flag can be passed to IDirectInputDevice7::EnumEffects to restrict the enumeration to periodic effects.

DIEFT_POSNEGCOEFFICIENTS
The effect generator for this effect supports two coefficient values for conditions, one for the positive displacement of the axis and one for the negative displacement of the axis. If the device does not support both coefficients, the negative coefficient in the DICONDITION structure is ignored, and the positive coefficient is used in both directions.
DIEFT_POSNEGSATURATION
The effect generator for this effect supports a maximum saturation for both positive and negative force output. If the device does not support both saturation values, the negative saturation in the DICONDITION structure is ignored, and the positive saturation is used in both directions.
DIEFT_RAMPFORCE
The effect represents a ramp-force effect. When creating or modifying a ramp-force effect, the lpvTypeSpecificParams member of the DIEFFECT structure must point to a DIRAMPFORCE structure, and the cbTypeSpecificParams member must be set to sizeof(DIRAMPFORCE).

The flag can be passed to IDirectInputDevice7::EnumEffects to restrict the enumeration to ramp-force effects.

DIEFT_SATURATION
The effect generator for this effect supports the saturation of condition effects. If the effect generator does not support saturation, the force generated by a condition is limited only by the maximum force that the device can generate.
dwStaticParams
Zero or more DIEP_* values describing the parameters supported by the effect. For example, if DIEP_ENVELOPE is set, the effect supports an envelope. For a list of possible values, see IDirectInputEffect::GetParameters.

It is not an error for an application to attempt to use effect parameters that are not supported by the device. The unsupported parameters are ignored.

This information is provided to allow the application to tailor its use of force feedback to the capabilities of the specific device.

dwDynamicParams
Zero or more DIEP_* values denoting parameters of the effect that can be modified while the effect is playing. For a list of possible values, see IDirectInputEffect::GetParameters.

If an application attempts to change a parameter while the effect is playing and the driver does not support modifying that effect dynamically, the driver is permitted to stop the effect, update the parameters, then restart it. For more information, see IDirectInputEffect::SetParameters.

tszName[MAX_PATH]
Name of the effect; for example, "Sawtooth up" or "Constant force".

Remarks

Use the DIEFT_GETTYPE macro to extract the effect type from the dwEffType flags.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.


DIEFFESCAPE

The DIEFFESCAPE structure is used by the IDirectInputDevice7::Escape and IDirectInputEffect::Escape methods to pass hardware-specific data directly to the device driver.

typedef struct DIEFFESCAPE {
    DWORD dwSize;
    DWORD dwCommand;
    LPVOID lpvInBuffer;
    DWORD cbInBuffer;
    LPVOID lpvOutBuffer;
    DWORD cbOutBuffer;
} DIEFFESCAPE, *LPDIEFFESCAPE;

Members

dwSize
Size of the structure in bytes. This member must be initialized before the structure is used.
dwCommand
Driver-specific command number. Consult the driver documentation for a list of valid commands.
lpvInBuffer
Buffer containing the data required to perform the operation.
cbInBuffer
Size, in bytes, of the lpvInBuffer buffer.
lpvOutBuffer
Buffer in which the operation's output data is returned.
cbOutBuffer
On entry, the size in bytes of the lpvOutBuffer buffer. On exit, the number of bytes actually produced by the command.

Remarks

Since each driver implements different escapes, it is the application's responsibility to ensure that it is talking to the correct driver by comparing the guidFFDriver member in the DIDEVICEINSTANCE structure against the value the application is expecting.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.


DIENVELOPE

The DIENVELOPE structure is used by the DIEFFECT structure to specify the optional envelope parameters for an effect. The sustain level for the envelope is represented by the dwMagnitude member of the DIPERIODIC structure and the lMagnitude member of the DICONSTANTFORCE structure. The sustain time is represented by dwDuration member of the DIEFFECT structure.

typedef struct DIENVELOPE {
    DWORD dwSize;
    DWORD dwAttackLevel;
    DWORD dwAttackTime;
    DWORD dwFadeLevel;
    DWORD dwFadeTime;
} DIENVELOPE, *LPDIENVELOPE;

typedef const DIENVELOPE *LPCDIENVELOPE;

Members

dwSize
Size, in bytes, of the structure. This member must be initialized before the structure is used.
dwAttackLevel
Amplitude for the start of the envelope, relative to the baseline, in the range from 0 through 10,000. If the effect's type-specific data does not specify a baseline, the amplitude is relative to 0.
dwAttackTime
The time, in microseconds, to reach the sustain level.
dwFadeLevel
Amplitude for the end of the envelope, relative to the baseline, in the range from 0 through 10,000. If the effect's type-specific data does not specify a baseline, the amplitude is relative to 0.
dwFadeTime
The time, in microseconds, to reach the fade level.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.


DIFILEEFFECT

The DIFILEEFFECT structure describes data for a force-feedback effect stored in a file. It is used in conjunction with the IDirectInputDevice7::EnumEffectsInFile and IDirectInputDevice7::WriteEffectToFile methods.

typedef struct DIFILEEFFECT{
    DWORD       dwSize;
    GUID        GuidEffect;
    LPCDIEFFECT lpDiEffect;
    CHAR        szFriendlyName[MAX_PATH];
}DIFILEEFFECT, *LPDIFILEEFFECT;

Members

dwSize
Size, in bytes, of the structure. This member must be initialized before the structure is used.
GuidEffect
Unique identifier of the effect type. This can be one of the standard GUIDs defined in Dinput.h, such as GUID_ConstantForce, or one created by the designer.
lpDiEffect
Pointer to a DIEFFECT structure containing information about the effect.
szFriendlyName
Name of the effect.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.


DIJOYSTATE

The DIJOYSTATE structure contains information about the state of a joystick device. This structure is used with the IDirectInputDevice7::GetDeviceState method.

typedef struct DIJOYSTATE {
    LONG    lX;
    LONG    lY;
    LONG    lZ;
    LONG    lRx;
    LONG    lRy;
    LONG    lRz;
    LONG    rglSlider[2];
    DWORD   rgdwPOV[4];
    BYTE    rgbButtons[32];
} DIJOYSTATE, *LPDIJOYSTATE;

Members

lX
Information about the joystick x-axis (usually the left-right movement of a stick).
lY
Information about the joystick y-axis (usually the forward-backward movement of a stick).
lZ
Information about the joystick z-axis (often the throttle control). If the joystick does not have this axis, the value is 0.
lRx
Information about the joystick x-axis rotation. If the joystick does not have this, the value is 0.
lRy
Information about the joystick y-axis rotation. If the joystick does not have this axis, the value is 0.
lRz
Information about the joystick z-axis rotation (often called the rudder). If the joystick does not have this axis, the value is 0.
rglSlider[2]
Two additional axis values (formerly called the u-axis and v-axis) whose semantics depend on the joystick. Use the IDirectInputDevice7::GetObjectInfo method to obtain semantic information about these values.
rgdwPOV[4]
The current position of up to four direction controllers (such as point-of-view indicators). The position is indicated in hundredths of a degree clockwise from north (away from the user). The center position is normally reported as –1; but see Remarks. For indicators that have only five positions, the value for a controller is –1, 0, 9,000, 18,000, or 27,000.
rgbButtons[32]
Array of button states. The high-order bit of the byte is set if the corresponding button is down, and clear if the button is up or does not exist.

Remarks

You must prepare the device for joystick-style access by calling the IDirectInputDevice7::SetDataFormat method, passing the c_dfDIJoystick global data format variable.

If an axis is in relative mode, the appropriate member contains the change in position. If it is in absolute mode, the member contains the absolute axis position.

Some drivers report the centered position of the POV indicator as 65,535. Determine whether the indicator is centered as follows:

BOOL POVCentered = (LOWORD(dwPOV) == 0xFFFF);

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.


DIJOYSTATE2

The DIJOYSTATE2 structure contains information about the state of a joystick device with extended capabilities. This structure is used with the IDirectInputDevice7::GetDeviceState method.

typedef struct DIJOYSTATE2 {
    LONG    lX;
    LONG    lY;
    LONG    lZ;
    LONG    lRx;
    LONG    lRy;
    LONG    lRz;
    LONG    rglSlider[2];
    DWORD   rgdwPOV[4];
    BYTE    rgbButtons[128];
    LONG    lVX;
    LONG    lVY;
    LONG    lVZ;
    LONG    lVRx;
    LONG    lVRy;
    LONG    lVRz;
    LONG    rglVSlider[2];
    LONG    lAX;
    LONG    lAY;
    LONG    lAZ;
    LONG    lARx;
    LONG    lARy;
    LONG    lARz;
    LONG    rglASlider[2];
    LONG    lFX;
    LONG    lFY;
    LONG    lFZ;
    LONG    lFRx;
    LONG    lFRy;
    LONG    lFRz;
    LONG    rglFSlider[2];
} DIJOYSTATE2, *LPDIJOYSTATE2;

Members

lX
Information about the joystick x-axis (usually the left-right movement of a stick).
lY
Information about the joystick y-axis (usually the forward-backward movement of a stick).
lZ
Information about the joystick z-axis (often the throttle control). If the joystick does not have this axis, the value is 0.
lRx
Information about the joystick x-axis rotation. If the joystick does not have this, the value is 0.
lRy
Information about the joystick y-axis rotation. If the joystick does not have this axis, the value is 0.
lRz
Information about the joystick z-axis rotation (often called the rudder). If the joystick does not have this axis, the value is 0.
rglSlider[2]
Two additional axis values (formerly called the u-axis and v-axis) whose semantics depend on the joystick. Use the IDirectInputDevice7::GetObjectInfo method to obtain semantic information about these values.
rgdwPOV[4]
The current position of up to four direction controllers (such as point-of-view hats). The position is indicated in hundredths of a degree clockwise from north (away from the user). The center position is normally reported as –1; but see Remarks. For indicators that have only five positions, the value for a controller is –1, 0, 9,000, 18,000, or 27,000.
rgbButtons[128]
Array of button states. The high-order bit of the byte is set if the corresponding button is down, and clear if the button is up or does not exist.
lVX
Information about the x-axis velocity.
lVY
Information about the y-axis velocity.
lVZ
Information about the z-axis velocity.
lVRx
Information about the x-axis angular velocity.
lVRy
Information about the y-axis angular velocity.
lVRz
Information about the z-axis angular velocity.
rglVSlider[2]
Information about extra axis velocities.
lAX
Information about the x-axis acceleration.
lAY
Information about the y-axis acceleration.
lAZ
Information about the z-axis acceleration.
lARx
Information about the x-axis angular acceleration.
lARy
Information about the y-axis angular acceleration.
lARz
Information about the z-axis angular acceleration.
rglASlider[2]
Information about extra axis accelerations.
lFX
Information about the x-axis force.
lFY
Information about the y-axis force.
lFZ
Information about the z-axis force.
lFRx
Information about the x-axis torque.
lFRy
Information about the y-axis torque.
lFRz
Information about the z-axis torque.
rglFSlider[2]
Information about extra axis forces.

Remarks

You must prepare the device for access to a joystick with extended capabilities by calling the IDirectInputDevice7::SetDataFormat method, passing the c_dfDIJoystick2 global data format variable.

The DIJOYSTATE2 structure has no special association with the IDirectInputDevice7 interface. You can use either DIJOYSTATE or DIJOYSTATE2 with either the IDirectInputDevice or the IDirectInputDevice7 interface.

If an axis is in relative mode, the appropriate member contains the change in position. If it is in absolute mode, the member contains the absolute axis position.

Some drivers report the centered position of the POV indicator as 65,535. Determine whether the indicator is centered as follows:

BOOL POVCentered = (LOWORD(dwPOV) == 0xFFFF);

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.


DIMOUSESTATE

The DIMOUSESTATE structure contains information about the state of a mouse device that has up to four buttons, or another device that is being accessed as if it were a mouse device. This structure is used with the IDirectInputDevice7::GetDeviceState method.

typedef struct DIMOUSESTATE {
    LONG lX;
    LONG lY;
    LONG lZ;
    BYTE rgbButtons[4];
} DIMOUSESTATE, *LPDIMOUSESTATE;

Members

lX
Information about the mouse x-axis.
lY
Information about the mouse y-axis.
lZ
Information about the mouse z-axis (typically a wheel). If the mouse does not have a z-axis, the value is 0.
rgbButtons[4]
Array of button states. The high-order bit of the byte is set if the corresponding button is down.

Remarks

You must prepare the device for mouse-style access by calling the IDirectInputDevice7::SetDataFormat method, passing the c_dfDIMouse global data format variable.

The mouse is a relative-axis device, so the absolute axis positions for mouse axes are simply accumulated relative motion. Therefore, the value of the absolute axis position is not meaningful except in comparison with other absolute axis positions.

If an axis is in relative mode, the appropriate member contains the change in position. If it is in absolute mode, the member contains the absolute axis position.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.

See Also

DIMOUSESTATE2


DIMOUSESTATE2

The DIMOUSESTATE2 structure contains information about the state of a mouse device that has up to eight buttons, or another device that is being accessed as if it were a mouse device. This structure is used with the IDirectInputDevice7::GetDeviceState method.

typedef struct DIMOUSESTATE {
    LONG lX;
    LONG lY;
    LONG lZ;
    BYTE rgbButtons[8];
} DIMOUSESTATE, *LPDIMOUSESTATE;

Members

lX
Information about the mouse x-axis.
lY
Information about the mouse y-axis.
lZ
Information about the mouse z-axis (typically a wheel). If the mouse does not have a z-axis, the value is 0.
rgbButtons[8]
Array of button states. The high-order bit of the byte is set if the corresponding button is down.

Remarks

You must prepare the device for mouse-style access by calling the IDirectInputDevice7::SetDataFormat method, passing the c_dfDIMouse2 global data format variable.

The mouse is a relative-axis device, so the absolute axis positions for mouse axes are simply accumulated relative motion. Therefore, the value of the absolute axis position is not meaningful except in comparison with other absolute axis positions.

If an axis is in relative mode, the appropriate member contains the change in position. If it is in absolute mode, the member contains the absolute axis position.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.

See Also

DIMOUSESTATE


DIOBJECTDATAFORMAT

The DIOBJECTDATAFORMAT structure contains information about a device object's data format for use with the IDirectInputDevice7::SetDataFormat method.

typedef struct DIOBJECTDATAFORMAT {
    const GUID * pguid;
    DWORD        dwOfs;
    DWORD        dwType;
    DWORD        dwFlags;
} DIOBJECTDATAFORMAT, *LPDIOBJECTDATAFORMAT;

typedef const DIOBJECTDATAFORMAT *LPCDIOBJECTDATAFORMAT;

Members

pguid
Unique identifier for the axis, button, or other input source. When requesting a data format, making this member NULL indicates that any type of object is permissible.
dwOfs
Offset within the data packet where the data for the input source is stored. This value must be a multiple of 4 for DWORD size data, such as axes. It can be byte-aligned for buttons.
dwType
Device type that describes the object. It is a combination of the following flags describing the object type (axis, button, and so forth) and containing the object-instance number in the middle 16 bits. When requesting a data format, the instance portion must be set to DIDFT_ANYINSTANCE to indicate that any instance is permissible, or to DIDFT_MAKEINSTANCE(n) to restrict the request to instance n. See the examples under Remarks.
DIDFT_ABSAXIS
The object selected by the SetDataFormat method must be an absolute axis.
DIDFT_AXIS
The object selected by the SetDataFormat method must be an absolute or relative axis.
DIDFT_BUTTON
The object selected by the SetDataFormat method must be a push button or a toggle button.
DIDFT_FFACTUATOR
The object selected by the SetDataFormat method must contain a force-feedback actuator; in other words, it must be possible to apply forces to the object.
DIDFT_FFEFFECTTRIGGER
The object selected by the SetDataFormat method must be a valid force-feedback effect trigger.
DIDFT_POV
The object selected by the SetDataFormat method must be a point-of-view controller.
DIDFT_PSHBUTTON
The object selected by the SetDataFormat method must be a push button.
DIDFT_RELAXIS
The object selected by SetDataFormat must be a relative axis.
DIDFT_TGLBUTTON
The object selected by SetDataFormat must be a toggle button.
DIDFT_VENDORDEFINED
The object selected by SetDataFormat must be of a type defined by the manufacturer.
dwFlags
Zero or more of the following values:
DIDOI_ASPECTACCEL
The object selected by SetDataFormat must report acceleration information.
DIDOI_ASPECTFORCE
The object selected by SetDataFormat must report force information.
DIDOI_ASPECTPOSITION
The object selected by SetDataFormat must report position information.
DIDOI_ASPECTVELOCITY
The object selected by SetDataFormat must report velocity information.

Remarks

A data format is made up of several DIOBJECTDATAFORMAT structures, one for each object (axis, button, and so on). An array of these structures is contained in the DIDATAFORMAT structure that is passed to IDirectInputDevice7::SetDataFormat. An application typically does not need to create an array of DIOBJECTDATAFORMAT structures; rather, it can use one of the predefined data formats, c_dfDIMouse, c_dfDIMouse2, c_dfDIKeyboard, c_dfDIJoystick, or c_dfDIJoystick2, which have predefined settings for DIOBJECTDATAFORMAT.

The following object data format specifies that DirectInput should choose the first available axis and report its value in the DWORD at offset 4 in the device data.

DIOBJECTDATAFORMAT dfAnyAxis = {
    0,                              // Wildcard
    4,                              // Offset
    DIDFT_AXIS | DIDFT_ANYINSTANCE, // Any axis is okay.
    0,                              // Don't care about aspect
};

The following object data format specifies that the x-axis of the device should be stored in the DWORD at offset 12 in the device data. If the device has more than one x-axis, the first available one should be selected.

DIOBJECTDATAFORMAT dfAnyXAxis = {
    &GUID_XAxis,                    // Must be an X axis
    12,                             // Offset
    DIDFT_AXIS | DIDFT_ANYINSTANCE, // Any X axis is okay.
    0,                              // Don't care about aspect
};

The following object data format specifies that DirectInput should choose the first available button and report its value in the high bit of the byte at offset 16 in the device data.

DIOBJECTDATAFORMAT dfAnyButton = {
    0,                                // Wildcard
    16,                               // Offset
    DIDFT_BUTTON | DIDFT_ANYINSTANCE, // Any button is okay.
    0,                                // Don't care about aspect
};

The following object data format specifies that button 0 of the device should be reported as the high bit of the byte stored at offset 18 in the device data.

If the device does not have a button 0, the attempt to set this data format fails.

DIOBJECTDATAFORMAT dfButton0 = {
    0,                                    // Wildcard
    18,                                   // Offset
    DIDFT_BUTTON | DIDFT_MAKEINSTANCE(0), // Button zero
    0,                                    // Don't care about aspect
};

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.


DIPERIODIC

The DIPERIODIC structure contains type-specific information for effects that are marked as DIEFT_PERIODIC.

The structure describes a periodic effect.

A pointer to a single DIPERIODIC structure for an effect is passed in the lpvTypeSpecificParams member of the DIEFFECT structure.

typedef struct DIPERIODIC {
    DWORD dwMagnitude;
    LONG  lOffset;
    DWORD dwPhase;
    DWORD dwPeriod;
} DIPERIODIC, *LPDIPERIODIC;

typedef const DIPERIODIC *LPCDIPERIODIC;

Members

dwMagnitude
Magnitude of the effect, in the range from 0 through 10,000. If an envelope is applied to this effect, the value represents the magnitude of the sustain. If no envelope is applied, the value represents the amplitude of the entire effect.
lOffset
Offset of the effect. The range of forces generated by the effect is lOffset minus dwMagnitude to lOffset plus dwMagnitude. The value of the lOffset member is also the baseline for any envelope that is applied to the effect.
dwPhase
Position in the cycle of the periodic effect at which playback begins, in the range from 0 through 35,999. See Remarks.
dwPeriod
Period of the effect, in microseconds.

Remarks

A device driver cannot provide support for all values in the dwPhase member. In this case, the value is rounded off to the nearest supported value.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.


DIPROPDWORD

The DIPROPDWORD is a generic structure used to access DWORD properties.

typedef struct DIPROPDWORD {
    DIPROPHEADER     diph;
    DWORD            dwData;
} DIPROPDWORD, *LPDIPROPDWORD;

typedef const DIPROPDWORD *LPCDIPROPDWORD;

Members

diph
DIPROPHEADER structure that must be initialized as follows:
Member | Value
dwSize | sizeof(DIPROPDWORD)
dwHeaderSize | sizeof(DIPROPHEADER)
dwObj If the dwHow member is DIPH_DEVICE, this member must be 0.

If the dwHow member is DIPH_BYID, this member must be the identifier for the object whose property setting is to be set or retrieved.

If the dwHow member is DIPH_BYOFFSET, this member must be a data format offset for the object whose property setting is to be set or retrieved. For example, if the c_dfDIMouse data format is selected, it must be one of the DIIMOFS_* values.
dwHow | Specifies how the dwObj member should be interpreted. If dwObj is DIPROP_AXISMODE or DIPROP_BUFFERSIZE, dwHow should be DIPH_DEVICE.

dwData
Property-specific value being set or retrieved.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.

See Also

IDirectInputDevice7::GetProperty, IDirectInputDevice7::SetProperty


DIPROPGUIDANDPATH

The DIPROPGUIDANDPATH structure is used to access properties whose values represent a GUID and a path.

typedef struct DIPROPGUIDANDPATH {
    DIPROPHEADER diph;
    GUID         guidClass;
    WCHAR        wszPath[MAX_PATH];
} DIPROPGUIDANDPATH, *LPDIPROPGUIDANDPATH;

Members

diph
DIPROPHEADER structure that must be initialized as follows:
Member | Value
dwSize | sizeof(DIPROPGUIDANDPATH)
dwHeaderSize | sizeof(DIPROPHEADER)
dwObj | Identifier of the object. For devices, must be 0
dwHow | How the dwObj member should be interpreted.

guidClass
Class GUID for the object.
wszPath
Returned path for the object. This is a Unicode string.

Remarks

The DIPROP_GUIDANDPATH property associated with the DIPROPGUIDANDPATH structure allows advanced applications to perform operations on a HID that are not supported by DirectInput.

The application calls the IDirectInputDevice7::GetProperty method with DIPROP_GUIDANDPATH as the rguidProp parameter. The class GUID of the device is returned in the guidClass member of the DIPROPGUIDANDPATH structure, and the device interface path is returned in the wszPath member. The application can then call the CreateFile function on this path to access the device directly.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in dinput.h.


DIPROPHEADER

DIPROPHEADER is a generic structure placed at the beginning of all property structures.

typedef struct DIPROPHEADER {
    DWORD    dwSize;
    DWORD    dwHeaderSize;
    DWORD    dwObj;
    DWORD    dwHow;
} DIPROPHEADER, *LPDIPROPHEADER;

typedef const DIPROPHEADER *LPCDIPROPHEADER;

Members

dwSize
Size of the enclosing structure. This member must be initialized before the structure is used.
dwHeaderSize
Size of the DIPROPHEADER structure.
dwObj
Object for which the property is to be accessed. The value set for this member depends on the value specified in the dwHow member.
dwHow
Value specifying how the dwObj member should be interpreted. This value can be one of the following:
Value | Meaning
DIPH_DEVICE | The dwObj member must be 0.
DIPH_BYOFFSET | The dwObj member is the offset into the current data format of the object whose property is being accessed.
DIPH_BYID | The dwObj member is the object type/instance identifier. This identifier is returned in the dwType member of the DIDEVICEOBJECTINSTANCE structure returned from a previous call to the IDirectInputDevice7::EnumObjects member.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.


DIPROPRANGE

The DIPROPRANGE structure contains information about the range of an object within a device. This structure is used with the DIPROP_RANGE flag set in the IDirectInputDevice7::GetProperty and IDirectInputDevice7::SetProperty methods.

typedef struct DIPROPRANGE {
    DIPROPHEADER diph;
    LONG         lMin;
    LONG         lMax;
} DIPROPRANGE, *LPDIPROPRANGE;

typedef const DIPROPRANGE *LPCDIPROPRANGE;

Members

diph
DIPROPHEADER structure that must be initialized as follows:
Member | Value
dwSize | sizeof(DIPROPRANGE)
dwHeaderSize | sizeof(DIPROPHEADER)
dwObj | Identifier of the object whose range is being retrieved or set.
dwHow | How the dwObj member should be interpreted.

lMin
Lower limit of the range. If the range of the device is unrestricted, this value is DIPROPRANGE_NOMIN when the IDirectInputDevice7::GetProperty method returns.
lMax
Upper limit of the range. If the range of the device is unrestricted, this value is DIPROPRANGE_NOMAX when the IDirectInputDevice7::GetProperty method returns.

Remarks

The range values for devices whose ranges are unrestricted wrap around.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.

See Also

IDirectInputDevice7::GetProperty, IDirectInputDevice7::SetProperty


DIPROPSTRING

The DIPROPSTRING structure is used to access string properties.

typedef struct {
    DIPROPHEADER diph;
    WCHAR wsz;
} DIPROPSTRING;

Members

diph
DIPROPHEADER structure that must be initialized as follows:
Member | Value
dwSize | sizeof(DIPROPSTRING)
dwHeaderSize | sizeof(DIPROPHEADER)
dwObj | Identifier of the object whose property is being retrieved or set.
dwHow | How the dwObj member should be interpreted.

wsz
String itself. This is a Unicode string.

Remarks

The DIPROP_INSTANCENAME and DIPROP_PRODUCTNAME properties associated with the DIPROPSTRING structure allows advanced applications to perform operations on an HID that are not supported by DirectInput.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in dinput.h.


DIRAMPFORCE

The DIRAMPFORCE structure contains type-specific information for effects that are marked as DIEFT_RAMPFORCE. The structure describes a ramp force effect.

A pointer to a single DIRAMPFORCE structure for an effect is passed in the lpvTypeSpecificParams member of the DIEFFECT structure.

typedef struct DIPROPRANGE {
    LONG lStart;
    LONG lEnd;
} DIRAMPFORCE, *LPDIRAMPFORCE;

typedef const DIRAMPFORCE *LPCDIRAMPFORCE;

Members

lStart
Magnitude at the start of the effect, in the range from –10,000 through 10,000.
lEnd
Magnitude at the end of the effect, in the range from –10,000 through 10,000.

Remarks

The dwDuration for a ramp force effect cannot be INFINITE.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dinput.h.


Device Constants

This section is a reference for constants used to interpret data for keys, buttons, and axes.

  • Keyboard Device Constants
  • DirectInput and Japanese Keyboards
  • Mouse Device Constants
  • Joystick Device Constants


Keyboard Device Constants

Keyboard device constants, defined in Dinput.h, represent offsets within a keyboard device's data packet, a 256-byte array. The data at a given offset is associated with a keyboard key. Typically, these values are used in the dwOfs member of the DIDEVICEOBJECTDATA, DIOBJECTDATAFORMAT or DIDEVICEOBJECTINSTANCE structures, or as indices when accessing data within the array using array notation.

The standard keyboard device constants are the following (in ascending order):

Constant | Note
DIK_ESCAPE |
DIK_1 | On main keyboard
DIK_2 | On main keyboard
DIK_3 | On main keyboard
DIK_4 | On main keyboard
DIK_5 | On main keyboard
DIK_6 | On main keyboard
DIK_7 | On main keyboard
DIK_8 | On main keyboard
DIK_9 | On main keyboard
DIK_0 | On main keyboard
DIK_MINUS | On main keyboard
DIK_EQUALS | On main keyboard
DIK_BACK | The BACKSPACE key
DIK_TAB |
DIK_Q |
DIK_W |
DIK_E |
DIK_R |
DIK_T |
DIK_Y |
DIK_U |
DIK_I |
DIK_O |
DIK_P |
DIK_LBRACKET | The [ key
DIK_RBRACKET | The ] key
DIK_RETURN | ENTER key on main keyboard
DIK_LCONTROL | Left CTRL key
DIK_A |
DIK_S |
DIK_D |
DIK_F |
DIK_G |
DIK_H |
DIK_J |
DIK_K |
DIK_L |
DIK_SEMICOLON |
DIK_APOSTROPHE |
DIK_GRAVE | Grave accent (`) key
DIK_LSHIFT | Left SHIFT key
DIK_BACKSLASH |
DIK_Z |
DIK_X |
DIK_C |
DIK_V |
DIK_B |
DIK_N |
DIK_M |
DIK_COMMA |
DIK_PERIOD | On main keyboard
DIK_SLASH | Forward slash on main keyboard
DIK_RSHIFT | Right SHIFT key
DIK_MULTIPLY | The * key on numeric keypad
DIK_LMENU | Left ALT key
DIK_SPACE | SPACEBAR
DIK_CAPITAL | CAPS LOCK key
DIK_F1 |
DIK_F2 |
DIK_F3 |
DIK_F4 |
DIK_F5 |
DIK_F6 |
DIK_F7 |
DIK_F8 |
DIK_F9 |
DIK_F10 |
DIK_NUMLOCK |
DIK_SCROLL | SCROLL LOCK
DIK_NUMPAD7 |
DIK_NUMPAD8 |
DIK_NUMPAD9 |
DIK_SUBTRACT | MINUS SIGN on numeric keypad
DIK_NUMPAD4 |
DIK_NUMPAD5 |
DIK_NUMPAD6 |
DIK_ADD | PLUS SIGN on numeric keypad
DIK_NUMPAD1 |
DIK_NUMPAD2 |
DIK_NUMPAD3 |
DIK_NUMPAD0 |
DIK_DECIMAL | PERIOD (decimal point) on numeric keypad
DIK_OEM_102 | On British and German keyboards.
DIK_F11 |
DIK_F12 |
DIK_F13 |
DIK_F14 |
DIK_F15 |
DIK_KANA | On Japanese keyboard
DIK_ABNT_C1 | On numeric pad of Brazilian keyboards
DIK_CONVERT | On Japanese keyboard
DIK_NOCONVERT | On Japanese keyboard
DIK_YEN | On Japanese keyboard
DIK_ABNT_C2 | On numeric pad of Brazilian keyboards
DIK_NUMPADEQUALS | On numeric keypad (NEC PC98)
DIK_PREVTRACK | Previous track; circumflex on Japanese keyboard
DIK_AT | On Japanese keyboard
DIK_COLON | On Japanese keyboard
DIK_UNDERLINE | On Japanese keyboard
DIK_KANJI | On Japanese keyboard
DIK_STOP | On Japanese keyboard
DIK_AX | On Japanese keyboard
DIK_UNLABELED | On Japanese keyboard
DIK_NEXTTRACK | Next track
DIK_NUMPADENTER |
DIK_RCONTROL | Right CTRL key
DIK_MUTE |
DIK_CALCULATOR |
DIK_PLAYPAUSE |
DIK_MEDIASTOP |
DIK_VOLUMEDOWN |
DIK_VOLUMEUP |
DIK_WEBHOME |
DIK_NUMPADCOMMA | COMMA on NEC PC98 numeric keypad
DIK_DIVIDE | Forward slash on numeric keypad
DIK_SYSRQ |
DIK_RMENU | Right ALT key
DIK_PAUSE |
DIK_HOME
DIK_UP | UP ARROW
DIK_PRIOR | PAGE UP
DIK_LEFT | LEFT ARROW
DIK_RIGHT | RIGHT ARROW
DIK_END |
DIK_DOWN | DOWN ARROW
DIK_NEXT | PAGE DOWN
DIK_INSERT |
DIK_DELETE |
DIK_LWIN | Left Windows key
DIK_RWIN | Right Windows key
DIK_APPS | Application key
DIK_POWER |
DIK_SLEEP |
DIK_WAKE |
DIK_WEBSEARCH |
DIK_WEBFAVORITES |
DIK_WEBREFRESH |
DIK_WEBSTOP |
DIK_WEBFORWARD |
DIK_WEBBACK |
DIK_MYCOMPUTER |
DIK_MAIL |
DIK_MEDIASELECT |

The following alternate names are available:

Alternate name | Regular name | Note
DIK_BACKSPACE | DIK_BACK | BACKSPACE
DIK_NUMPADSTAR | DIK_MULTIPLY | * key on numeric keypad
DIK_LALT | DIK_LMENU | Left ALT
DIK_CAPSLOCK | DIK_CAPITAL | CAPSLOCK
DIK_CIRCUMFLEX | DIK_PREVTRACK | On Japanese keyboards.
DIK_NUMPADMINUS | DIK__SUBTRACT | Minus key on numeric keypad
DIK_NUMPADPLUS | DIK_ADD | Plus key on numeric keypad
DIK_NUMPADPERIOD | DIK_DECIMAL | Period key on numeric keypad
DIK_NUMPADSLASH | DIK__DIVIDE | Forward slash on numeric keypad
DIK_RALT | DIK_RMENU | Right ALT
DIK_UPARROW | DIK_UP | On arrow keypad
DIK_PGUP | DIK_PRIOR | On arrow keypad
DIK_LEFTARROW | DIK_LEFT | On arrow keypad
DIK_RIGHTARROW | DIK_RIGHT | On arrow keypad
DIK_DOWNARROW | DIK_DOWN | On arrow keypad
DIK_PGDN | DIK_NEXT | On arrow keypad

For information on Japanese keyboards, see DirectInput and Japanese Keyboards.


DirectInput and Japanese Keyboards

There are substantial differences between Japanese and U.S. keyboards. The following chart lists the additional keys that are available on each type of Japanese keyboard. It also lists the keys that are available on U.S. keyboards but are missing on the various Japanese keyboards.

On some NEC PC-98 keyboards, the DIK_CAPSLOCK and DIK_KANA keys are toggle buttons and not push buttons. These generate a down event when first pressed, then generate an up event when pressed a second time.

Keyboard | Additional keys | Missing keys
DOS/V 106 Keyboard, NEC PC-98 106 Keyboard | DIK_AT, DIK_CIRCUMFLEX, DIK_COLON, DIK_CONVERT, DIK_KANA, DIK_KANJI, DIK_NOCONVERT, DIK_YEN | DIK_APOSTROPHE, DIK_EQUALS, DIK_GRAVE
NEC PC-98 Standard Keyboard, NEC PC-98 Laptop Keyboard | DIK_AT, DIK_CIRCUMFLEX, DIK_COLON, DIK_F13, DIK_F14, DIK_F15, DIK_KANA, DIK_KANJI, DIK_NOCONVERT, DIK_NUMPADCOMMA, DIK_NUMPADEQUALS, DIK_STOP, DIK_UNDERLINE, DIK_YEN | DIK_APOSTROPHE, DIK_BACKSLASH, DIK_EQUALS, DIK_GRAVE, DIK_NUMLOCK, DIK_NUMPADENTER, DIK_RCONTROL, DIK_RMENU, DIK_RSHIFT, DIK_SCROLL
AX Keyboard | DIK_AX, DIK_CONVERT, DIK_KANJI, DIK_NOCONVERT, DIK_YEN | DIK_RCONTROL, DIK_RMENU
J-3100 Keyboard | DIK_KANA, DIK_KANJI, DIK_NOLABEL, DIK_YEN | DIK_RCONTROL, DIK_RMENU


Mouse Device Constants

Mouse device constants, defined in Dinput.h, represent offsets within a mouse device's data packet, the DIMOUSESTATE or DIMOUSESTATE2 structure. The data at a given offset is associated with a device object (button or axis). Typically, these values are used in the dwOfs member of the DIDEVICEOBJECTDATA, DIOBJECTDATAFORMAT or DIDEVICEOBJECTINSTANCE structures.

The mouse device constants are the following:

DIMOFS_BUTTON0 | Offset of the data representing the state of mouse button 0.
DIMOFS_BUTTON1 | Offset of the data representing the state of mouse button 1.
DIMOFS_BUTTON2 | Offset of the data representing the state of mouse button 2.
DIMOFS_BUTTON3 | Offset of the data representing the state of mouse button 3.
DIMOFS_BUTTON4 | Offset of the data representing the state of mouse button 4. (DIMOUSESTATE2 only.)
DIMOFS_BUTTON5 | Offset of the data representing the state of mouse button 5. (DIMOUSESTATE2 only.)
DIMOFS_BUTTON6 | Offset of the data representing the state of mouse button 6. (DIMOUSESTATE2 only.)
DIMOFS_BUTTON7 | Offset of the data representing the state of mouse button 7. (DIMOUSESTATE2 only.)
DIMOFS_X | Offset of the data representing the mouse's position on the x-axis.
DIMOFS_Y | Offset of the data representing the mouse's position on the y-axis.
DIMOFS_Z | Offset of the data representing the mouse's position on the z-axis.


Joystick Device Constants

Joystick device constants represent offsets within a joystick device's data packet, the DIJOYSTATE structure. The data at a given offset is associated with a device object; that is, a button or axis. Typically, these values are used in the dwOfs member of the DIDEVICEOBJECTDATA, DIOBJECTDATAFORMAT or DIDEVICEOBJECTINSTANCE structures.

The following macros return a constant indicating the offset of the data for a particular button or axis relative to the beginning of the DIJOYSTATE structure:

DIJOFS_BUTTON0 to DIJOFS_BUTTON31 or DIJOFS_BUTTON(n) | A button.
DIJOFS_POV(n) | A point-of-view indicator.
DIJOFS_RX | The x-axis rotation.
DIJOFS_RY | The y-axis rotation.
DIJOFS_RZ | The z-axis rotation (rudder).
DIJOFS_X | The x-axis.
DIJOFS_Y | The y-axis.
DIJOFS_Z | The z-axis.
DIJOFS_SLIDER(n) | A slider axis.


Return Values

This table lists the HRESULT values that can be returned by DirectInput methods and functions. Errors are represented by negative values and cannot be combined.

For a list of the error values each method or function can return, see the individual descriptions. Lists of error codes in the documentation are necessarily incomplete. For example, any DirectInput method can return DIERR_OUTOFMEMORY even though the error code is not explicitly listed as a possible return value in the documentation for that method.

DI_BUFFEROVERFLOW
The device buffer overflowed and some input was lost. This value is equal to the S_FALSE standard COM return value.
DI_DOWNLOADSKIPPED
The parameters of the effect were successfully updated, but the effect could not be downloaded because the associated device was not acquired in exclusive mode.
DI_EFFECTRESTARTED
The effect was stopped, the parameters were updated, and the effect was restarted.
DI_NOEFFECT
The operation had no effect. This value is equal to the S_FALSE standard COM return value.
DI_NOTATTACHED
The device exists but is not currently attached. This value is equal to the S_FALSE standard COM return value.
DI_OK
The operation completed successfully. This value is equal to the S_OK standard COM return value.
DI_POLLEDDEVICE
The device is a polled device. As a result, device buffering does not collect any data and event notifications is not signaled until the IDirectInputDevice7::Poll method is called.
DI_PROPNOEFFECT
The change in device properties had no effect. This value is equal to the S_FALSE standard COM return value.
DI_TRUNCATED
The parameters of the effect were successfully updated, but some of them were beyond the capabilities of the device and were truncated to the nearest supported value.
DI_TRUNCATEDANDRESTARTED
Equal to DI_EFFECTRESTARTED | DI_TRUNCATED.
DIERR_ACQUIRED
The operation cannot be performed while the device is acquired.
DIERR_ALREADYINITIALIZED
This object is already initialized
DIERR_BADDRIVERVER
The object could not be created due to an incompatible driver version or mismatched or incomplete driver components.
DIERR_BETADIRECTINPUTVERSION
The application was written for an unsupported prerelease version of DirectInput.
DIERR_DEVICEFULL
The device is full.
DIERR_DEVICENOTREG
The device or device instance is not registered with DirectInput. This value is equal to the REGDB_E_CLASSNOTREG standard COM return value.
DIERR_EFFECTPLAYING
The parameters were updated in memory but were not downloaded to the device because the device does not support updating an effect while it is still playing.
DIERR_HASEFFECTS
The device cannot be reinitialized because there are still effects attached to it.
DIERR_GENERIC
An undetermined error occurred inside the DirectInput subsystem. This value is equal to the E_FAIL standard COM return value.
DIERR_HANDLEEXISTS
The device already has an event notification associated with it. This value is equal to the E_ACCESSDENIED standard COM return value.
DIERR_INCOMPLETEEFFECT
The effect could not be downloaded because essential information is missing. For example, no axes have been associated with the effect, or no type-specific information has been supplied.
DIERR_INPUTLOST
Access to the input device has been lost. It must be reacquired.
DIERR_INVALIDPARAM
An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard COM return value.
DIERR_MOREDATA
Not all the requested information fit into the buffer.
DIERR_NOAGGREGATION
This object does not support aggregation.
DIERR_NOINTERFACE
The specified interface is not supported by the object. This value is equal to the E_NOINTERFACE standard COM return value.
DIERR_NOTACQUIRED
The operation cannot be performed unless the device is acquired.
DIERR_NOTBUFFERED
The device is not buffered. Set the DIPROP_BUFFERSIZE property to enable buffering.
DIERR_NOTDOWNLOADED
The effect is not downloaded.
DIERR_NOTEXCLUSIVEACQUIRED
The operation cannot be performed unless the device is acquired in DISCL_EXCLUSIVE mode.
DIERR_NOTFOUND
The requested object does not exist.
DIERR_NOTINITIALIZED
This object has not been initialized.
DIERR_OBJECTNOTFOUND
The requested object does not exist.
DIERR_OLDDIRECTINPUTVERSION
The application requires a newer version of DirectInput.
DIERR_OTHERAPPHASPRIO
Another application has a higher priority level, preventing this call from succeeding. This value is equal to the E_ACCESSDENIED standard COM return value. This error can be returned when an application has only foreground access to a device but is attempting to acquire the device while in the background.
DIERR_OUTOFMEMORY
The DirectInput subsystem could not allocate sufficient memory to complete the call. This value is equal to the E_OUTOFMEMORY standard COM return value.
DIERR_READONLY
The specified property cannot be changed. This value is equal to the E_ACCESSDENIED standard COM return value.
DIERR_REPORTFULL
More information was requested to be sent than can be sent to the device.
DIERR_UNPLUGGED
The operation could not be completed because the device is not plugged in.
DIERR_UNSUPPORTED
The function called is not supported at this time. This value is equal to the E_NOTIMPL standard COM return value.
E_HANDLE
The HWND parameter is not a valid top-level window that belongs to the process.
E_PENDING
Data is not yet available.


DirectInput Visual Basic Reference

Reference material for the DirectInput Visual Basic application programming interface is divided into the following categories:

  • Classes
  • Types
  • Enumerations
  • Keyboard Keys
  • Error Codes


Classes

This section contains references for methods of the following DirectInput classes:

  • DirectInput
  • DirectInputDevice
  • DirectInputDeviceInstance
  • DirectInputDeviceObjectInstance
  • DirectInputEffect
  • DirectInputEnumDeviceObjects
  • DirectInputEnumDevices
  • DirectInputEnumEffects


DirectInput

The DirectInput class represents the DirectInput system. An application should have a single object of this class, which is used to enumerate available devices, create devices, and retrieve the status of devices, as well as to invoke an instance of the Windows Control Panel.

The DirectInput object is obtained by using the DirectX7.DirectInputCreate method.

The DirectInput class has the following methods:

Device Management | CreateDevice
 | GetDeviceStatus
 | GetDIEnumDevices
Miscellaneous | RunControlPanel


DirectInput.CreateDevice

The DirectInput.CreateDevice method creates and initializes an instance of a device based on a given GUID.

object.CreateDevice(guid As String) As DirectInputDevice

Parameters

object
Object expression that resolves to a DirectInput object.
guid
The instance GUID for the desired input device. The GUID is retrieved from the DirectInputDeviceInstance object returned by the DirectInputEnumDevices.GetItem method, or it can be one of the following strings:
GUID_SysKeyboard
The default system keyboard.
GUID_SysMouse
The default system mouse.

Return Values

If the method succeeds, a DirectInputDevice object is returned.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following:

DIERR_DEVICENOTREG
DIERR_INVALIDPARAM
DIERR_NOINTERFACE
DIERR_OUTOFMEMORY

See Also

Using GUIDs


DirectInput.GetDeviceStatus

The DirectInput.GetDeviceStatus method determines whether a device is attached to the system.

object.GetDeviceStatus(guid As String) As Boolean

Parameters

object
Object expression that resolves to a DirectInput object.
guid
The instance GUID for the desired input device. The GUID is retrieved by using the DirectInputDeviceInstance.GetGuidInstance method on the object returned by DirectInputEnumDevices.GetItem method, or it can be one of the following strings:
GUID_SysKeyboard
The default system keyboard.
GUID_SysMouse
The default system mouse.

Return Values

The method returns True if the device is attached, and False otherwise.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes:

DIERR_GENERIC
DIERR_INVALIDPARAM

See Also

Using GUIDs


DirectInput.GetDIEnumDevices

The DirectInput.GetDIEnumDevices method returns a DirectInputEnumDevices object which is used to enumerate devices that are either currently attached or could be attached to the computer.

object.GetDIEnumDevices( _
  deviceType As CONST_DIDEVICETYPE, _
  flags As CONST_DIENUMDEVICESFLAGS) _
  As DirectInputEnumDevices

Parameters

object
Object expression that resolves to a DirectInput object.
deviceType
Device type filter. If this parameter is 0, all device types are enumerated. Otherwise, it is one of the following DIDEVTYPE_* constants of the CONST_DIDEVICETYPE enumeration, indicating the device type that should be enumerated.
DIDEVTYPE_MOUSE
A mouse or mouse-like device (such as a trackball).
DIDEVTYPE_KEYBOARD
A keyboard or keyboard-like device.
DIDEVTYPE_JOYSTICK
A joystick or similar device, such as a steering wheel.
DIDEVTYPE_DEVICE
A device that does not fall into the previous categories.
flags
Flag value that specifies the scope of the enumeration. This parameter can be one of the following constants of the CONST_DIENUMDEVICESFLAGS enumeration. If this flag is 0 (DIEDFL_ALLDEVICES), then all installed devices are enumerated. If it is DIEDFL_ATTACHEDONLY, only devices actually attached to the system are enumerated.

Return Values

If the method succeeds, the method returns a DirectInputEnumDevices object.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

Remarks

All installed devices can be enumerated, even if they are not present. For example, a joystick may be installed on the system but not currently plugged into the computer.

If a single piece of hardware can function as more than one DirectInput device type, it will be returned for each device type it supports. For example, a keyboard with a built-in mouse will be enumerated as a keyboard and as a mouse. The product GUID would be the same for each device, however.


DirectInput.RunControlPanel

The DirectInput.RunControlPanel method runs the Windows Control Panel to allow the user to install a new input device or modify configurations.

object.RunControlPanel(hwndOwner As Long)

Parameters

object
Object expression that resolves to a DirectInput object.
hwndOwner
Handle to the window to be used as the parent window for the subsequent user interface. If this parameter is 0, no parent window is used.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

See Also

DirectInputDevice.RunControlPanel


DirectInputDevice

Applications use the methods of the DirectInputDevice class to gain and release access to DirectInput devices, manage device properties and information, set behavior, perform initialization, and invoke a device's property sheet.

The DirectInputDevice object is obtained by using the DirectInput.CreateDevice method.

The methods of the DirectInputDevice class can be organized into the following groups.

Access | Acquire
 | SetCooperativeLevel
 | Unacquire
Objects | GetDeviceObjectsEnum
 | GetObjectInfo
Properties | GetCapabilities
 | GetDeviceInfo
 | GetProperty
 | SetCommonDataFormat
 | SetDataFormat
 | SetProperty
Retrieving Data | GetDeviceData
 | GetDeviceState
 | GetDeviceStateJoystick
 | GetDeviceStateJoystick2
 | GetDeviceStateKeyboard
 | GetDeviceStateMouse
 | Poll
 | SetEventNotification
Force Feedback | CreateCustomEffect
 | CreateEffect
 | GetEffectsEnum
 | GetForceFeedbackState
 | SendForceFeedbackCommand
Miscellaneous | RunControlPanel
 | SendDeviceData


DirectInputDevice.Acquire

The DirectInputDevice.Acquire method obtains access to the input device.

object.Acquire()

Parameters

object
Object expression that resolves to a DirectInputDevice object.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes::

DIERR_INVALIDPARAM
DIERR_OTHERAPPHASPRIO

Remarks

Before a device can be acquired, a data format must be set by using the DirectInputDevice.SetDataFormat or DirectInputDevice.SetCommonDataFormat method.

A device must be acquired before input data can be retrieved from it.

See Also

DirectInputDevice.Unacquire


DirectInputDevice.CreateCustomEffect

The DirectInputDevice.CreateCustomEffect method creates a force-feedback effect consisting of a series of constant forces of fixed duration.

object.CreateCustomEffect(effectinfo As DIEFFECT, _
    channels As Long, samplePeriod As Long, _
    nSamples As Long, sampledata() As Long) _
    As DirectInputEffect

Parameters

object
Object expression that resolves to a DirectInputDevice object.
effectinfo
DIEFFECT type containing general parameters of the effect.
channels
The number of channels (axes) affected by this force. Must be 1 or 2.

If there is only a single channel, then the effect will be rotated in the direction specified by the x member of the DIEFFECT type. Not all devices support rotation of custom effects.

If there is more than one channel, the first channel is applied to the x-axis and the second to the y-axis. Rotation is not allowed.

samplePeriod
The sample period in microseconds. See Remarks.
nSamples
Number of elements in the sampledata array.
sampledata
Array of magnitudes. If channels is greater than 1, then the values are interleaved. For example, if channels is 2, then the first element of the array is assigned to the x-axis, the second to the y-axis, the third to the x-axis, and so on.

Remarks

In theory, samplePeriod is the length of time for which each magnitude in sampledata is valid, whereas DIEFFECT.lSamplePeriod is the length of time between samplings of the data (and the minimum time between changes in magnitude). Since each element in the array needs to be sampled exactly once on each iteration through the array, and some drivers ignore samplePeriod in any case, it is best to make the values of lSamplePeriod and samplePeriod identical.

See Also

Custom Forces


DirectInputDevice.CreateEffect

The DirectInputDevice.CreateEffect method creates a force-feedback effect. If the device is currently acquired at the exclusive cooperative level, the effect is also downloaded.

object.CreateEffect(effectGuid As String, _
  effectinfo As DIEFFECT) As DirectInputEffect

Parameters

object
Object expression that resolves to a DirectInputDevice object.
effectGuid
String representation of a GUID for an effect recognized by the hardware driver, or one of the following aliases for standard effects:

GUID_ConstantForce
GUID_RampForce
GUID_Square
GUID_Sine
GUID_Triangle
GUID_SawtoothUp
GUID_SawtoothDown
GUID_Spring
GUID_Damper
GUID_Inertia
GUID_Friction

effectinfo
DIEFFECT structure containing the parameters for the effect.

Return Values

If the method succeeds, the method returns a DirectInputEffect object.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes:

DIERR_DEVICENOTREG
DIERR_DEVICEFULL
DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED

Remarks

If no error is raised, the effect was created and the parameters of the effect were updated, but the effect was not necessarily downloaded. In order for it to be downloaded, the device must be acquired in exclusive mode.

See Also

DirectInputEffect.Download, DirectInputEffect.Start


DirectInputDevice.GetCapabilities

The DirectInputDevice.GetCapabilities method obtains the capabilities of the DirectInputDevice object.

object.GetCapabilities(caps As DIDEVCAPS)

Parameters

object
Object expression that resolves to a DirectInputDevice object.
caps
A DIDEVCAPS type to be filled with the device capabilities.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectInputDevice.GetDeviceData

The DirectInputDevice.GetDeviceData method retrieves buffered data from the device.

object.GetDeviceData( _
  deviceObjectDataArray() As DIDEVICEOBJECTDATA, _
  flags As CONST_DIDGDDFLAGS) As Long

Parameters

object
Object expression that resolves to a DirectInputDevice object.
deviceObjectDataArray()
Array of DIDEVICEOBJECTDATA types to receive the buffered data.
flags
Flags that control the manner in which data is obtained. This value can be 0 or one of the constants of the CONST_DIDGDDFLAGS enumeration.

Return Values

If it succeeds, the method returns the number of buffered data elements actually returned in deviceObjectDataArray.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes:

DI_BUFFEROVERFLOW
DIERR_INPUTLOST
DIERR_INVALIDPARAM
DIERR_NOTACQUIRED
DIERR_NOTBUFFERED

Remarks

Before device data can be obtained, you must set the data format by using the DirectInputDevice.SetDataFormat method, set the buffer size by using DirectInputDevice.SetProperty method, and acquire the device by using the DirectInputDevice.Acquire method.

You can use this method to retrieve one or more input events from the buffer you created by using SetProperty. You do not have to retrieve all pending events with a single call. You can, for example, pass in a deviceObjectDataArray() consisting of a single element and loop on GetDeviceData till no more data is returned.

If the buffer overflows, all pending data is lost and the DI_BUFFEROVERFLOW error is raised.

See Also

DirectInputDevice.Poll, Polling and Events


DirectInputDevice.GetDeviceInfo

The DirectInputDevice.GetDeviceInfo method obtains information about the device's identity.

object.GetDeviceInfo() As DirectInputDeviceInstance

Parameters

object
Object expression that resolves to a DirectInputDevice object.

Return Values

If it succeeds, the method returns a DirectInputDeviceInstance object

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectInputDevice.GetDeviceObjectsEnum

The DirectInputDevice.GetDeviceObjectsEnum method returns a DirectInputEnumDeviceObjects object which is used to enumerate the objects available on a device. A device object is typically an axis or a button.

object.GetDeviceObjectsEnum( _
  flags As CONST_DIDFTFLAGS) _
  As DirectInputEnumDeviceObjects

Parameters

object
Object expression that resolves to a DirectInputDevice object.
flags
Flags specifying the type of object to be enumerated. Can be one or more of the members of the CONST_DIDFTFLAGS enumeration.

Return Values

If the method succeeds, the return value is a DirectInputEnumDeviceObjects object.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

Remarks

The DIDFT_FFACTUATOR and DIDFT_FFEFFECTTRIGGER flags restrict enumeration to objects that meet all the criteria defined by the included flags. For all the other flags, an object is enumerated if it meets the criterion defined by any included flag in this category. For example, (DIDFT_FFACTUATOR Or DIDFT_FFEFFECTTRIGGER) restricts enumeration to force-feedback trigger objects, and (DIDFT_FFEFFECTTRIGGER Or DIDFT_TGLBUTTON Or DIDFT_PSHBUTTON) restricts enumeration to buttons of any kind that can be used as effect triggers.


DirectInputDevice.GetDeviceState

The DirectInputDevice.GetDeviceState method retrieves immediate data for a device other than a standard keyboard, mouse, or joystick.

object.GetDeviceState(cb As Long, state As Any)

Parameters

object
Object expression that resolves to a DirectInputDevice object.
cb
Size of the array whose first element is passed as state.
state
First element of an array to receive device state information.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes:

DIERR_INPUTLOST
DIERR_INVALIDPARAM
DIERR_NOTACQUIRED
E_PENDING

Remarks

Before device data can be obtained, you must set the cooperative level by using the DirectInputDevice.SetCooperativeLevel method, then set the data format by using DirectInputDevice.SetDataFormat, and acquire the device by using the DirectInputDevice.Acquire method.

See Also

DirectInputDevice.GetDeviceStateJoystick, DirectInputDevice.GetDeviceStateJoystick2, DirectInputDevice.GetDeviceStateKeyboard , DirectInputDevice.GetDeviceStateMouse, DirectInputDevice.SetDataFormat, Buffered and Immediate Data


DirectInputDevice.GetDeviceStateJoystick

The DirectInputDevice.GetDeviceStateJoystick method retrieves instantaneous data from a joystick device.

object.GetDeviceStateJoystick(state As DIJOYSTATE)

Parameters

object
Object expression that resolves to a DirectInputDevice object.
state
A DIJOYSTATE type that receives the current state of the device.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes:

DIERR_INPUTLOST
DIERR_INVALIDPARAM
DIERR_NOTACQUIRED
E_PENDING

Remarks

Before device data can be obtained, you must set the cooperative level by using the DirectInputDevice.SetCooperativeLevel method, then set the data format by using DirectInputDevice.SetCommonDataFormat, and acquire the device by using the DirectInputDevice.Acquire method.

See Also

DirectInputDevice.Poll


DirectInputDevice.GetDeviceStateJoystick2

The DirectInputDevice.GetDeviceStateJoystick2 method retrieves instantaneous data from a joystick device with extended capabilities.

object.GetDeviceStateJoystick2(state As DIJOYSTATE2)

Parameters

object
Object expression that resolves to a DirectInputDevice object.
state
A DIJOYSTATE2 type that receives the current state of the device. The format of the data is established by a prior call to the DirectInputDevice.SetDataFormat method.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes:

DIERR_INPUTLOST
DIERR_INVALIDPARAM
DIERR_NOTACQUIRED
E_PENDING

Remarks

Before device data can be obtained, you must set the cooperative level by using the DirectInputDevice.SetCooperativeLevel method, then set the data format by using DirectInputDevice.SetCommonDataFormat, and acquire the device by using the DirectInputDevice.Acquire method.

See Also

DirectInputDevice.Poll, Polling and Events


DirectInputDevice.GetDeviceStateKeyboard

The DirectInputDevice.GetDeviceStateKeyboard method retrieves instantaneous data from a keyboard device.

object.GetDeviceStateKeyboard(state As DIKEYBOARDSTATE)

Parameters

object
Object expression that resolves to a DirectInputDevice object.
state
A DIKEYBOARDSTATE type that receives the current state of the device.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes:

DIERR_INPUTLOST
DIERR_INVALIDPARAM
DIERR_NOTACQUIRED
E_PENDING

Remarks

Before device data can be obtained, you must set the cooperative level by using the DirectInputDevice.SetCooperativeLevel method, then set the data format by using DirectInputDevice.SetCommonDataFormat, and acquire the device by using the DirectInputDevice.Acquire method.

See Also

DirectInputDevice.Poll


DirectInputDevice.GetDeviceStateMouse

The DirectInputDevice.GetDeviceStateMouse method retrieves instantaneous data from a mouse device.

object.GetDeviceStateMouse(state As DIMOUSESTATE)

Parameters

object
Object expression that resolves to a DirectInputDevice object.
state
A DIMOUSESTATE type that receives the current state of the device.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes:

DIERR_INPUTLOST
DIERR_INVALIDPARAM
DIERR_NOTACQUIRED
E_PENDING

Remarks

Before device data can be obtained, you must set the cooperative level by using the DirectInputDevice.SetCooperativeLevel method, then set the data format by using DirectInputDevice.SetCommonDataFormat, and acquire the device by using the DirectInputDevice.Acquire method.

See Also

DirectInputDevice.Poll


DirectInputDevice.GetEffectsEnum

The DirectInputDevice.GetEffectsEnum method enumerates force-feedback effects supported by the device, including standard effects as well as effects designed by the device manufacturer.

object.GetEffectsEnum( _
  effType As CONST_DIEFTFLAGS) As DirectInputEnumEffects

Parameters

object
Object expression that resolves to a DirectInputDevice object.
effType
One of the following flags from the CONST_DIEFTFLAGS enumeration specifying the type of effect to be enumerated:

DIEFT_ALL
DIEFT_CONDITION
DIEFT_CONSTANTFORCE
DIEFT_CUSTOMFORCE
DIEFT_HARDWARE
DIEFT_PERIODIC
DIEFT_RAMPFORCE

Return Values

The method returns a DirectInputEnumEffects object whose methods can be used to retrieve information about the effects.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectInputDevice.GetForceFeedbackState

The DirectInputDevice.GetForceFeedbackState method retrieves the state of the device's force-feedback system.

object.GetForceFeedbackState() As CONST_DIGFFSFLAGS

Parameters

object
Object expression that resolves to a DirectInputDevice object.

Return Values

If it succeeds, the method returns flags from the CONST_DIGFFSFLAGS enumeration that describe the current state of the device's force-feedback system.

Future versions of DirectInput may define additional flags. Applications should ignore any flags that are not currently defined.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes:

DIERR_INPUTLOST
DIERR_INVALIDPARAM
DIERR_NOTEXCLUSIVEACQUIRED
DIERR_NOTINITIALIZED
DIERR_UNSUPPORTED

Remarks

The device must be acquired at the exclusive cooperative level for this method to succeed.


DirectInputDevice.GetObjectInfo

The DirectInputDevice.GetObjectInfo method retrieves information about a device object such as a button or axis.

object.GetObjectInfo( _
  Obj As Long, _
  how As CONST_DIPHFLAGS) _
  As DirectInputDeviceObjectInstance

Parameters

object
Object expression that resolves to a DirectInputDevice object.
Obj
Value that identifies the object whose information will be retrieved. The interpretation of this parameter depends on the value specified in the how parameter.
how
Value specifying how the Obj parameter should be interpreted. This value can be one of the constants of the CONST_DIPHFLAGS enumeration.

Return Values

The method returns a DirectInputDeviceObjectInstance object whose methods can be used to retrieve information about the object.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes:

DIERR_INVALIDPARAM
DIERR_OBJECTNOTFOUND


DirectInputDevice.GetProperty

The DirectInputDevice.GetProperty method retrieves information about the input device.

object.GetProperty( _
  guid As String, _
  propertyInfo As Any)

Parameters

object
Object expression that resolves to a DirectInputDevice object.
guid
Identifier of the property to be retrieved. The following properties are defined for an input device and can be passed as strings:
DIPROP_AUTOCENTER
Specifies whether device objects are self-centering. See DirectInputDevice.SetProperty for more information.
DIPROP_AXISMODE
Retrieves the axis mode. The retrieved value can be DIPROPAXISMODE_ABS or DIPROPAXISMODE_REL. (See the CONST_DINPUT enumeration.)
DIPROP_BUFFERSIZE
Retrieves the input-buffer size. The buffer size determines the amount of data that the buffer can hold between calls to the DirectInputDevice.GetDeviceData method before data is lost. This value may be set to 0 to indicate that the application will not be reading buffered data from the device.
DIPROP_DEADZONE
Retrieves a value for the dead zone of a joystick, in the range 0 to 10,000, where 0 indicates there is no dead zone, 5,000 indicates that the dead zone extends over 50 percent of the physical range of the axis on both sides of center, and 10,000 indicates that the entire physical range of the axis is dead. When the axis is within the dead zone, it is reported as being at the center of its range.
DIPROP_FFGAIN
Retrieves the gain of the device. See DirectInputDevice.SetProperty for more information.
DIPROP_FFLOAD
Retrieves the memory load for the device. This setting applies to the entire device, rather than to any particular object, so the lHow member of the associated DIPROPLONG type must be DIPH_DEVICE.

The lData member contains a value in the range 0 to 100, indicating the percentage of device memory in use.

DIPROP_GRANULARITY
Retrieves the input granularity. Granularity represents the smallest distance the object will report movement. Most axis objects have a granularity of 1, meaning that all values are possible. Some axes may have a larger granularity. For example, the wheel axis on a mouse may have a granularity of 20, meaning that all reported changes in position will be multiples of 20. In other words, when the user turns the wheel slowly, the device reports a position of 0, then 20, then 40, and so on.

This is a read-only property; you cannot set its value by calling the DirectInputDevice.SetProperty method.

DIPROP_RANGE
Retrieves the range of values an object can possibly report. The retrieved minimum and maximum values are set in the lMin and lMax members of the associated DIPROPRANGE type.

For some devices, this is a read-only property; you cannot set its value by calling the DirectInputDevice.SetProperty method.

DIPROP_SATURATION
Retrieves a value for the saturation zones of a joystick, in the range 0 to 10,000. The saturation level is the point at which the axis is considered to be at its most extreme position. For example, if the saturation level is set to 9,500, then the axis reaches the extreme of its range when it has moved 95 percent of the physical distance from its center position (or from the dead zone).
propertyInfo
A DIPROPLONG type to receive a single value, or a DIPROPRANGE type to receive a pair of values for the property. The lObj, lHow, and lSize members of this type must be initialized before the method is called.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes:

DIERR_INVALIDPARAM
DIERR_OBJECTNOTFOUND
DIERR_UNSUPPORTED

See Also

DirectInputDevice.SetProperty


DirectInputDevice.Poll

The DirectInputDevice.Poll method makes data available from polled objects on a DirectInput device. If the device does not require polling, then calling this method has no effect. If a device that requires polling is not polled periodically, no new data will be received from the device. Calling this method causes DirectInput to update the device state, generate input events (if buffered data is enabled), and set notification events (if notification is enabled).

object.Poll()

Parameters

object
Object expression that resolves to a DirectInputDevice object.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes:

DIERR_INPUTLOST
DIERR_NOTACQUIRED

Remarks

Before a device data can be polled, the data format must be set by using the DirectInputDevice.SetDataFormat or DirectInputDevice.SetCommonDataFormat method, and the device must be acquired by using the DirectInputDevice.Acquire method.


DirectInputDevice.RunControlPanel

The DirectInputDevice.RunControlPanel method opens the Control Panel property sheet associated with this device. If the device does not have a property sheet associated with it, the default device property sheet is displayed.

object.RunControlPanel(hwnd As Long)

Parameters

object
Object expression that resolves to a DirectInputDevice object.
hwnd
Handle to the parent window. If this parameter is 0, no parent window is used.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes:

DIERR_INVALIDPARAM


DirectInputDevice.SendDeviceData

The DirectInputDevice.SendDeviceData method sends data to a device that accepts output. The device must be in an acquired state.

object.SendDeviceData(count As Long, _
  data() As DIDEVICEOBJECTDATA, _
  flags As CONST_DESDDFLAGS) As Long

Parameters

object
Object expression that resolves to a DirectInputDevice object.
count
Number of elements in data.
data
Array of DIDEVICEOBJECTDATA types containing the data to send to the device.

The lOfs field of each DIDEVICEOBJECTDATA type must contain the instance identifier (not the data offset) for the device object to which the data is directed. (See DirectInputDeviceObjectInstance.GetType.) The lTimeStamp and lSequence members must be 0.

flags
Flags controlling the manner in which data is sent. This may be 0 or the following value:
DISDD_CONTINUE
The device data sent will be overlaid on the previously sent device data. See Remarks.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes:

DIERR_INPUTLOST
DIERR_NOTACQUIRED
DIERR_REPORTFULL
DIERR_UNPLUGGED

Remarks

There is no guarantee that the individual data elements will be sent in a particular order. However, data sent by successive calls to SendDeviceData will not be interleaved. Furthermore, if multiple pieces of data are sent to the same object with a single call, it is unspecified which piece of data is sent.

Consider, for example, a device that can be sent data in packets, each packet describing two pieces of information, call them A and B. Suppose the application attempts to send three data elements: B = 2, A = 1, and B = 0.

The actual device will be sent a single packet. The A field of the packet will contain the value 1, and the B field of the packet will be either 2 or 0.

If the data must to be sent to the device exactly as specified, then three calls to SendDeviceData should be performed, each call sending one data element.

In response to the first call, the device will be sent a packet where the A field is blank and the B field contains the value 2.

In response to the second call, the device will be sent a packet where the A field contains the value 1, and the B field is blank.

Finally, in response to the third call, the device will be sent a packet where the A field is blank and the B field contains the value 0.

If the DISDD_CONTINUE flag is set, then the device data sent will be overlaid on the previously sent device data. Otherwise, the device data sent will start from scratch.

For example, suppose a device supports two button outputs, Button0 and Button1. If an application first calls SendDeviceData passing "Button0 pressed", then a packet of the form "Button0 pressed, Button1 not pressed" is sent to the device. If the application then makes another call, passing "Button1 pressed" and the DISDD_CONTINUE flag, then a packet of the form "Button0 pressed, Button1 pressed" is sent to the device. However, if the application had not passed the DISDD_CONTINUE flag, the packet sent to the device would have been "Button0 not pressed, Button1 pressed".


DirectInputDevice.SendForceFeedbackCommand

The DirectInputDevice.SendForceFeedbackCommand method sends a command to the device's force-feedback system.

object.SendForceFeedbackCommand(flags As Long)

Parameters

object
Object expression that resolves to a DirectInputDevice object.
flags
A single value indicating the desired change in state. The value may be one of the members of the CONST_DISFFCFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes:

DIERR_INPUTLOST
DIERR_NOTACQUIRED
DIERR_REPORTFULL
DIERR_UNPLUGGED


DirectInputDevice.SetCommonDataFormat

The DirectInputDevice.SetCommonDataFormat method sets the input data format for standard devices.

object.SetCommonDataFormat( _
  format As CONST_DICOMMONDATAFORMATS)

Parameters

object
Object expression that resolves to a DirectInputDevice object.
format
One of the CONST_DICOMMONDATAFORMATS enumeration, identifying the data format to use for the device.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes:

DIERR_ACQUIRED
DIERR_INVALIDPARAM

Remarks

The data format must be set before the device can be acquired by using the DirectInputDevice.Acquire method. It is necessary to set the data format only once. The data format cannot be changed while the device is acquired.

See Also

DirectInputDevice.SetDataFormat


DirectInputDevice.SetCooperativeLevel

The DirectInputDevice.SetCooperativeLevel method establishes the cooperative level for this instance of the device. The cooperative level determines how this instance of the device interacts with other instances of the device and the rest of the system.

object.SetCooperativeLevel(hwnd As Long, _
  flags As CONST_DISCLFLAGS)

Parameters

object
Object expression that resolves to a DirectInputDevice object.
hwnd
Window handle to be associated with the device. This parameter must be a valid top-level window handle that belongs to the process. The window associated with the device must not be destroyed while it is still active in a DirectInput device.
flags
Flags that describe the cooperative level associated with the device. The flags are constants of the CONST_DISCLFLAGS enumeration.

The following combinations of flags are valid:
Flags | Meaning | Valid for
DISCL_NONEXCLUSIVE Or DISCL_BACKGROUND | Others can acquire device in exclusive or nonexclusive mode; your application has access to data at all times. | All.
DISCL_NONEXCLUSIVE Or DISCL_FOREGROUND | Others can acquire device in exclusive or nonexclusive mode; your application has access to data only when in the foreground. | All.
DISCL_EXCLUSIVE Or DISCL_BACKGROUND | Others can acquire device in nonexclusive mode; your application has access to data at all times. | Joystick.
DISCL_EXCLUSIVE Or DISC_FOREGROUND | Others can acquire device in nonexclusive mode; your application has access to data only when in the foreground. | All. Valid for mouse but prevents Windows from displaying the cursor.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes:

DIERR_INVALIDPARAM
DIERR_INVALIDHANDLE

Remarks

No two applications (or instances of the same application) can have a device acquired in exclusive mode at the same time. This is primarily a security feature; it prevents input intended for one application from going to another that may be running concurrently.

If the system mouse is acquired in exclusive mode, then the pointer will be removed from the screen until the device is unacquired.

Applications must call this method before acquiring the device by using the DirectInputDevice.Acquire method.

See Also

Cooperative Levels


DirectInputDevice.SetDataFormat

The DirectInputDevice.SetDataFormat method sets the data format for a DirectInput device that is not a standard keyboard, mouse, or keyboard.

object.SetDataFormat(format As DIDATAFORMAT, _
  formatArray() As DIOBJECTDATAFORMAT))

Parameters

object
Object expression that resolves to a DirectInputDevice object.
format
A DIDATAFORMAT type that describes the format of the data the device should return.
formatArray
Array of DIOBJECTDATAFORMAT types describing data formats for objects on the device.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes:

DIERR_ACQUIRED
DIERR_INVALIDPARAM

Remarks

The data format must be set before the device can be acquired by using the DirectInputDevice.Acquire method. It is necessary to set the data format only once. The data format cannot be changed while the device is acquired.

See Also

DirectInputDevice.SetCommonDataFormat


DirectInputDevice.SetEventNotification

The DirectInputDevice.SetEventNotification method sets the event notification status. This method specifies an event that is to be set when the device state changes. It is also used to turn off event notification.

object.SetEventNotification(hEvent As Long)

Parameters

object
Object expression that resolves to a DirectInputDevice object.
hEvent
Handle to the event that is to be set when the device state changes, or 0 to disable notification.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes:

DIERR_ACQUIRED
DIERR_HANDLEEXISTS
DIERR_INVALIDPARAM

Remarks

A device state change is defined as any of the following:

  • A change in the position of an axis
  • A change in the state (pressed or released) of a button
  • A change in the direction of a POV control
  • Loss of acquisition

You must call this method with the hEvent parameter set to 0 before destroying the event.

The event notification handle cannot be changed while the device is acquired.

See Also

Polling and Events, DirectXEvent


DirectInputDevice.SetProperty

The DirectInputDevice.SetProperty method sets properties that define the device behavior.

object.SetProperty( _
  guid As String, _
  propertyInfo As Any)

Parameters

object
Object expression that resolves to a DirectInputDevice object.
guid
Identifier of the property to be set. The following property values are predefined for an input device and can be passed as strings:
DIPROP_AXISMODE
Sets the axis mode. The value being set (either DIPROPAXISMODE_ABS or DIPROPAXISMODE_REL from the CONST_DINPUT enumeration) must be specified in the lData member of the associated DIPROPLONG type.

This setting applies to the entire device, so the lHow member of the DIPROPLONG type must be set to DIPH_DEVICE.

DIPROP_BUFFERSIZE
Sets the input-buffer size. See Remarks.

This setting applies to the entire device, so the lHow member of the associated DIPROPLONG type must be set to DIPH_DEVICE.

DIPROP_CALIBRATIONMODE
Allows the application to specify whether DirectInput should retrieve calibrated or uncalibrated data from an axis. By default, DirectInput retrieves calibrated data.

Setting the calibration mode for the entire device is equivalent to setting it for each axis individually.

The lData member of the DIPROPLONG type may be one of the following values:

DIPROPCALIBRATIONMODE_COOKED: DirectInput should return data after applying calibration information. This is the default mode.

DIPROPCALIBRATIONMODE_RAW: DirectInput should return raw, uncalibrated data. This mode is typically used only by Control Panel–type applications.

Note that setting a device into raw mode causes the dead zone, saturation, and range settings to be ignored.

DIPROP_DEADZONE
Sets the value for the dead zone of a joystick, in the range 0 to 10,000, where 0 indicates there is no dead zone, 5,000 indicates that the dead zone extends over 50 percent of the physical range of the axis on both sides of center, and 10,000 indicates that the entire physical range of the axis is dead. When the axis is within the dead zone, it is reported as being at the center of its range.

This setting can be applied to either the entire device or to a specific axis.

DIPROP_RANGE
Sets the range of values an object can possibly report. The minimum and maximum values are taken from the lMin and lMax members of the associated DIPROPRANGE type.

For some devices, this is a read-only property.

You cannot set a reverse range; lMax must be greater than lMin.

DIPROP_SATURATION
Sets the value for the saturation zones of a joystick, in the range 0 to 10,000. The saturation level is the point at which the axis is considered to be at its most extreme position. For example, if the saturation level is set to 9,500, then the axis reaches the extreme of its range when it has moved 95 percent of the physical distance from its center position (or from the dead zone).

This setting can be applied to either the entire device or to a specific axis.

propertyInfo
A DIPROPLONG type containing data for properties that take a single value, or a DIPROPRANGE type containing data for properties that take a pair of values.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error codes:

DIERR_INVALIDPARAM
DIERR_OBJECTNOTFOUND
DIERR_UNSUPPORTED

Remarks

The buffer size determines the amount of data that the buffer can hold between calls to the DirectInputDevice.GetDeviceData method before data is lost. This value may be set to 0 to indicate that the application will not be reading buffered data from the device. If the buffer size in the lData member of the DIPROPLONG type is too large to be supported by the device, the largest possible buffer size is set. To determine whether the requested buffer size was set, retrieve the buffer-size property and compare the result with the value you previously attempted to set.

See Also

DirectInputDevice.GetProperty


DirectInputDevice.Unacquire

The DirectInputDevice.Unacquire method releases access to the device.

object.Unacquire()

Parameters

object
Object expression that resolves to a DirectInputDevice object.

Error Codes

None.

See Also

DirectInputDevice.Acquire


DirectInputDeviceInstance

The DirectInputDeviceInstance class is used to obtain information about an instance of a DirectInput device.

An object of this class is returned by the DirectInputDevice.GetDeviceInfo and DirectInputEnumDevices.GetItem method.

The DirectInputDeviceInstance class has the following methods:

Information | GetDevType
 | GetGuidFFDriver
 | GetGuidInstance
 | GetGuidProduct
 | GetInstanceName
 | GetProductName
 | GetUsage
 | GetUsagePage


DirectInputDeviceInstance.GetDevType

The DirectInputDeviceInstance.GetDevType method retrieves the device type and subtype.

object.GetDevType() As Long

Parameters

object
Object expression that resolves to a DirectInputDeviceInstance object.

Return Values

The method returns a device type specifier. This value is a combination of a type (in the least significant byte) and subtype (in the next most significant byte), optionally combined using Or with DIDEVTYPE_HID, which specifies a Human Interface Device. The following constants are from the CONST_DIDEVICETYPE enumeration.

Device Types
DIDEVTYPE_MOUSE
A mouse or mouse-like device (such as a trackball).
DIDEVTYPE_KEYBOARD
A keyboard or keyboard-like device.
DIDEVTYPE_JOYSTICK
A joystick or similar device, such as a steering wheel.
DIDEVTYPE_DEVICE
A device that does not fall into the previous categories.
Mouse subtypes
DIDEVTYPEMOUSE_UNKNOWN
The subtype could not be determined.
DIDEVTYPEMOUSE_TRADITIONAL
The device is a traditional mouse.
DIDEVTYPEMOUSE_FINGERSTICK
The device is a fingerstick.
DIDEVTYPEMOUSE_TOUCHPAD
The device is a touchpad.
DIDEVTYPEMOUSE_TRACKBALL
The device is a trackball.
Keyboard subtypes
DIDEVTYPEKEYBOARD_UNKNOWN
The subtype could not be determined.
DIDEVTYPEKEYBOARD_PCXT
IBM PC/XT 83-key keyboard.
DIDEVTYPEKEYBOARD_OLIVETTI
Olivetti 102-key keyboard.
DIDEVTYPEKEYBOARD_PCAT
IBM PC/AT 84-key keyboard.
DIDEVTYPEKEYBOARD_PCENH
IBM PC Enhanced 101/102-key or Microsoft Natural® keyboard.
DIDEVTYPEKEYBOARD_NOKIA1050
Nokia 1050 keyboard.
DIDEVTYPEKEYBOARD_NOKIA9140
Nokia 9140 keyboard.
DIDEVTYPEKEYBOARD_NEC98
Japanese NEC PC98 keyboard.
DIDEVTYPEKEYBOARD_NEC98LAPTOP
Japanese NEC PC98 laptop keyboard.
DIDEVTYPEKEYBOARD_NEC98106
Japanese NEC PC98 106-key keyboard.
DIDEVTYPEKEYBOARD_JAPAN106
Japanese 106-key keyboard.
DIDEVTYPEKEYBOARD_JAPANAX
Japanese AX keyboard.
DIDEVTYPEKEYBOARD_J3100
Japanese J3100 keyboard.
Joystick Subtypes
DIDEVTYPEJOYSTICK_UNKNOWN
The subtype could not be determined.
DIDEVTYPEJOYSTICK_TRADITIONAL
A traditional joystick.
DIDEVTYPEJOYSTICK_FLIGHTSTICK
A joystick optimized for flight simulation.
DIDEVTYPEJOYSTICK_GAMEPAD
A device whose primary purpose is to provide button input.
DIDEVTYPEJOYSTICK_RUDDER
A device for yaw control.
DIDEVTYPEJOYSTICK_WHEEL
A steering wheel.
DIDEVTYPEJOYSTICK_HEADTRACKER
A device that tracks the movement of the user's head.
Human Interface Device
DIDEVTYPE_HID
The device uses the Human Interface Device (HID) protocol.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

Remarks

To look for a particular subtype of device such as a wheel, you should check both the type and the subtype.


DirectInputDeviceInstance.GetGuidFFDriver

The DirectInputDeviceInstance.GetGuidFFDriver method returns the unique identifier for the force-feedback driver.

object.GetGuidFFDriver() As String

Parameters

object
Object expression that resolves to a DirectInputDeviceInstance object.

Return Values

The method returns the GUID for the force feedback driver, in string form. This identifier is established by the manufacturer of the driver.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

See Also

Using GUIDs


DirectInputDeviceInstance.GetGuidInstance

The DirectInputDeviceInstance.GetGuidInstance method returns the unique identifier for the instance of the device.

object.GetGuidInstance() As String

Parameters

object
Object expression that resolves to a DirectInputDeviceInstance object.

Return Values

The method returns the GUID for the device instance, in string form.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

Remarks

An application can save the instance GUID into a configuration file and use it at a later time. Instance GUIDs are specific to a particular computer. An instance GUID obtained from one computer is unrelated to instance GUIDs on another.

See Also

DirectInputDeviceInstance.GetGuidProduct, Using GUIDs


DirectInputDeviceInstance.GetGuidProduct

The DirectInputDeviceInstance.GetGuidProduct method retrieves the manufacturer's unique identifier for the device.

object.GetGuidProduct() As String

Parameters

object
Object expression that resolves to a DirectInputDeviceInstance object.

Return Values

The method returns the GUID for the product, in string form. This identifier is established by the manufacturer of the device.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

See Also

DirectInputDeviceInstance.GetGuidInstance, Using GUIDs


DirectInputDeviceInstance.GetInstanceName

The DirectInputDeviceInstance.GetInstanceName method retrieves the name of the device instance.

object.GetInstanceName() As String

Parameters

object
Object expression that resolves to a DirectInputDeviceInstance object.

Return Values

The method returns the friendly name for the instance—for example, "Joystick 1."

Error Codes

If the method fails, an error is raised and Err.Number will be set.

See Also

DirectInputDeviceInstance.GetProductName


DirectInputDeviceInstance.GetProductName

The DirectInputDeviceInstance.GetProductName method retrieves the product name of the device.

object.GetProductName() As String

Parameters

object
Object expression that resolves to a DirectInputDeviceInstance object.

Return Values

The method returns the friendly name for the product—for example, "Microsoft SideWinder".

Error Codes

If the method fails, an error is raised and Err.Number will be set.

See Also

DirectInputDeviceInstance.GetInstanceName


DirectInputDeviceInstance.GetUsage

The DirectInputDeviceInstance.GetUsage method retrieves the usage code for Human Interface Devices.

object.GetUsage() As Integer

Parameters

object
Object expression that resolves to a DirectInputDeviceInstance object.

Return Values

If the device is a HID, the method returns the usage code.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

See Also

DirectInputDeviceInstance.GetUsagePage


DirectInputDeviceInstance.GetUsagePage

The DirectInputDeviceInstance.GetUsagePage method retrieves the usage page for Human Interface Devices.

object.GetUsagePage() As Integer

Parameters

object
Object expression that resolves to a DirectInputDeviceInstance object.

Return Values

If the device is a HID, the method returns the HID usage page.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

See Also

DirectInputDeviceInstance.GetUsage


DirectInputDeviceObjectInstance

The DirectInputDeviceObjectInstance class represents an object on a DirectInput device, such as a button or axis.

A DirectInputDeviceObjectInstance object is returned by the DirectInputDevice.GetObjectInfo and DirectInputEnumDeviceObjects.GetItem methods.

This class has the following methods:

Information | GetCollectionNumber
 | GetDesignatorIndex
 | GetDimension
 | GetExponent
 | GetFlags
 | GetGuidType
 | GetName
 | GetOfs
 | GetType
 | GetUsage
 | GetUsagePage


DirectInputDeviceObjectInstance.GetCollectionNumber

The DirectInputDeviceObjectInstance.GetCollectionNumber method retrieves the number of the HID link collection to which the device object belongs.

object.GetCollectionNumber() As Integer

Parameters

object
Object expression that resolves to a DirectInputDeviceObjectInstance object.

Return Values

If the device is a Human Interface Device and the object belongs to a collection, the method returns the number of the collection.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectInputDeviceObjectInstance.GetDesignatorIndex

The DirectInputDeviceObjectInstance.GetDesignatorIndex method retrieves the designator index for an object on a Human Interface Device.

object.GetDesignatorIndex() As Integer

Parameters

object
Object expression that resolves to a DirectInputDeviceObjectInstance object.

Return Values

The method returns an index that refers to a designator in the HID physical descriptor. This number can be passed to functions in the HID parsing library to obtain additional information about the device object.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectInputDeviceObjectInstance.GetDimension

The DirectInputDeviceObjectInstance.GetDimension method retrieves a HID code for the dimensional units in which the object's value is reported.

object.GetDimension() As Long

Parameters

object
Object expression that resolves to a DirectInputDeviceObjectInstance object.

Return Values

The method returns a code for the dimensional units in which the object's value is reported, if known, or 0 if not known.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

See Also

DirectInputDeviceObjectInstance.GetExponent


DirectInputDeviceObjectInstance.GetExponent

The DirectInputDeviceObjectInstance.GetExponent method retrieves the exponent to associate with the dimensional units of the device object.

object.GetExponent() As Integer

Parameters

object
Object expression that resolves to a DirectInputDeviceObjectInstance object.

Return Values

The method returns the exponent to associate with the dimension, if known. Dimensional units are always integral, so an exponent may be needed in order to convert them to non-integral types.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

See Also

DirectInputDeviceObjectInstance.GetDimension


DirectInputDeviceObjectInstance.GetFlags

The DirectInputDeviceObjectInstance.GetFlags method retrieves the flags associated with the device object.

object.GetFlags() As CONST_DIDEVICEOBJINSTANCEFLAGS

Parameters

object
Object expression that resolves to a DirectInputDeviceObjectInstance object.

Return Values

The method retrieves flags describing miscellaneous attributes of the object. The return value may consist of one or more members of the CONST_DIDEVICEOBJINSTANCEFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectInputDeviceObjectInstance.GetGuidType

The DirectInputDeviceObjectInstance.GetGuidType method retrieves the unique identifier of the object type.

object.GetGuidType() As String

Parameters

object
Object expression that resolves to a DirectInputDeviceObjectInstance object.

Return Values

The method may return one of the following string identifiers, representing the unique identifier for the object type. If the object type has a GUID not represented in the following list, a string representing the actual GUID will be returned. If the object type does not have a GUID, an empty string will be returned.

GUID_XAxis
The horizontal axis. For example, it may represent the left-right motion of a mouse.
GUID_YAxis
The vertical axis. For example, it may represent the forward-backward motion of a mouse.
GUID_ZAxis
The z-axis. For example, it may represent rotation of the wheel on a mouse, or movement of a throttle control on a joystick.
GUID_RxAxis
Rotation around the x-axis.
GUID_RyAxis
Rotation around the y-axis.
GUID_RzAxis
Rotation around the z-axis (often a rudder control).
GUID_Slider
A slider axis.
GUID_Button
A button on a mouse.
GUID_Key
A key on a keyboard.
GUID_POV
A point-of-view indicator or "hat".
GUID_Unknown
Unknown.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectInputDeviceObjectInstance.GetName

The DirectInputDeviceObjectInstance.GetName method retrieves the friendly name of the device object.

object.GetName() As String

Parameters

object
Object expression that resolves to a DirectInputDeviceObjectInstance object.

Return Values

The method retrieves the name of the object—for example, "X-Axis" or "Right Shift."

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectInputDeviceObjectInstance.GetOfs

The DirectInputDeviceObjectInstance.GetOfs method retrieves the offset of the device object's data within the data format for the device.

object.GetOfs() As Long

Parameters

object
Object expression that resolves to a DirectInputDeviceObjectInstance object.

Return Values

The method returns the offset within the data format at which data is reported for this object. This value can be used to identify the object in method calls and types that accept the DIPH_BYOFFSET flag.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

See Also

DirectInputDevice.GetObjectInfo, DIPROPLONG, DIPROPRANGE


DirectInputDeviceObjectInstance.GetType

The DirectInputDeviceObjectInstance.GetType method retrieves the type and instance identifier of the object.

object.GetType() As Long

Parameters

object
Object expression that resolves to a DirectInputDeviceObjectInstance object.

Return Values

Device type that describes the object. It is a combination of CONST_DIDFTFLAGS flags that describe the object type (axis, button, and so forth) and contains the object instance number in the middle 16 bits.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

Remarks

To extract the object instance ID, use the following operation:

Dim ObjID as Long
ObjID = (diObj.GetType And &HFFFF00) \ 256


DirectInputDeviceObjectInstance.GetUsage

The DirectInputDeviceObjectInstance.GetUsage method retrieves the Human Interface Device usage code for the device object.

object.GetUsage() As Integer

Parameters

object
Object expression that resolves to a DirectInputDeviceObjectInstance object.

Return Values

The method returns the HID usage associated with the object, if known. Human Interface Devices will always report a usage. Non-HID devices may optionally report a usage; if they do not, then the value of this member will be zero.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

See Also

DirectInputDeviceObjectInstance.GetUsagePage


DirectInputDeviceObjectInstance.GetUsagePage

The DirectInputDeviceObjectInstance.GetUsagePage method retrieves the Human Interface Device usage page for the device object.

object.GetUsagePage() As Integer

Parameters

object
Object expression that resolves to a DirectInputDeviceObjectInstance object.

Return Values

The method returns the HID usage page associated with the object, if known. Human Interface Devices will always report a usage page. Non-HID devices may optionally report a usage page; if they do not, then the value of this member will be zero.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

See Also

DirectInputDeviceObjectInstance.GetUsage


DirectInputEffect

An object of the DirectInputEffect class represents a force-feedback effect created by an application. The object is created by using the DirectInputDevice.CreateEffect method.

This class has the following methods:

Information | GetEffectGuid
 | GetEffectStatus
 | GetParameters
Manipulation | Download
 | SetParameters
 | Start
 | Stop
 | Unload


DirectInputEffect.Download

The DirectInputEffect.Download method places the effect on the device. If the effect is already on the device, then the existing effect is updated to match the values set by the DirectInputEffect.SetParameters method.

object.Download()

Parameters

object
Object expression that resolves to a DirectInputEffect object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following:

DIERR_NOTINITIALIZED
DIERR_DEVICEFULL
DIERR_INCOMPLETEEFFECT
DIERR_INPUTLOST
DIERR_NOTEXCLUSIVEACQUIRED
DIERR_INVALIDPARAM
DIERR_EFFECTPLAYING

Remarks

The device must be acquired at the exclusive cooperative level for this method to succeed.

It is valid to update an effect while it is playing. The semantics of such an operation are explained in the reference for DirectInputEffect.SetParameters.


DirectInputEffect.GetEffectGuid

The DirectInputEffect.GetEffectGuid method retrieves the GUID or GUID alias for the effect represented by the DirectInputEffect object.

object.GetEffectGuid() As String

Parameters

object
Object expression that resolves to a DirectInputEffect object.

Return Values

The method returns the GUID or alias that was passed to DirectInputDevice.CreateEffect—for example, "GUID_ConstantForce".

Error Codes

If the method fails, an error is raised and Err.Number will be set.

See Also

Using GUIDs


DirectInputEffect.GetEffectStatus

The DirectInputEffect.GetEffectStatus method retrieves the status of an effect.

object.GetEffectStatus() As Long

Parameters

object
Object expression that resolves to a DirectInputEffect object.

Return Values

The method returns status flags for the effect. The value may be zero, or one or more of the following constants of the CONST_DIEGESFLAGS enumeration:

DIEGES_PLAYING
The effect is playing.
DIEGES_EMULATED
The effect is emulated.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectInputEffect.GetParameters

The DirectInputEffect.GetParameters method retrieves information about an effect.

object.GetParameters(effectinfo As DIEFFECT)

Parameters

object
Object expression that resolves to a DirectInputEffect object.
effectinfo
DIEFFECT type to receive the effect parameters.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following:

DIERR_INVALIDPARAM
DIERR_MOREDATA
DIERR_NOTINITIALIZED


DirectInputEffect.SetParameters

The DirectInputEffect.SetParameters method sets the characteristics of an effect.

object.SetParameters(effectinfo As DIEFFECT, flags As CONST_DIEPFLAGS)

Parameters

object
Object expression that resolves to a DirectInputEffect object.
effectinfo
DIEFFECT type containing effect parameters.
flags
Flags from the CONST_DIEPFLAGS enumeration specifying which portions of the effect information are to be set and how the downloading of the parameters should be handled.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following:

DIERR_NOTINITIALIZED
DIERR_INCOMPLETEEFFECT
DIERR_INPUTLOST
DIERR_INVALIDPARAM
DIERR_EFFECTPLAYING

Remarks

To determine which parameters can be dynamically updated while the effect is playing, use the DirectInputEnumEffects.GetDynamicParams method.

The DirectInputEffect.SetParameters method automatically downloads the effect, but this behavior can be suppressed by setting the DIEP_NODOWNLOAD flag. If automatic download has been suppressed, then you can manually download the effect by calling DirectInputEffect.Download.

If the effect is playing while the parameters are changed, then the new parameters take effect as if they were the parameters when the effect started.

For example, suppose a periodic effect with a duration of three seconds is started. After two seconds, the direction of the effect is changed. The effect will then continue for one additional second in the new direction. The envelope, phase, amplitude, and other parameters of the effect continue smoothly as if the direction had not changed.

In the same scenario, if after two seconds the duration of the effect were changed to 1.5 seconds, then the effect would stop.

Normally, if the driver cannot update the parameters of a playing effect, the driver is permitted to stop the effect, update the parameters, and then restart the effect. Passing the DIEP_NORESTART flag suppresses this behavior. If the driver cannot update the parameters of an effect while it is playing, the error code DIERR_EFFECTPLAYING is returned and the parameters are not updated.

No more than one of the DIEP_NODOWNLOAD, DIEP_START, and DIEP_NORESTART flags should be set. (It is also valid to pass none of them.)

These three flags control download and playback behavior as follows:

If DIEP_NODOWNLOAD is set, the effect parameters are updated but not downloaded to the device.

If the DIEP_START flag is set, the effect parameters are updated and downloaded to the device, and the effect is started just as if the DirectInputEffect.Start method had been called with the iterations parameter set to 1 and with no flags. (Combining the update with DIEP_START is slightly faster than calling Start separately, because it requires less information to be transmitted to the device.)

If neither DIEP_NODOWNLOAD nor DIEP_START is set and the effect is not playing, then the parameters are updated and downloaded to the device.

If neither DIEP_NODOWNLOAD nor DIEP_START is set and the effect is playing, then the parameters are updated if the device supports on-the-fly updating. Otherwise the behavior depends on the state of the DIEP_NORESTART flag. If it is set, the error code DIERR_EFFECTPLAYING is returned. If it is clear, the effect is stopped, the parameters are updated, and the effect is restarted.


DirectInputEffect.Start

The DirectInputEffect.Start method begins playing an effect. If the effect is already playing, it is restarted from the beginning. If the effect has not been downloaded or has been modified since its last download, then it will be downloaded before being started. This default behavior can be suppressed by passing the DIES_NODOWNLOAD flag.

object.Start(iterations As Long, flags As Long)

Parameters

object
Object expression that resolves to a DirectInputEffect object.
iterations
Number of times to play the effect in sequence. The envelope is re-articulated with each iteration.

To play the effect exactly once, pass 1. To play the effect repeatedly until explicitly stopped, pass -1. To play the effect until explicitly stopped without re-articulating the envelope, modify the effect parameters with the DirectInputEffect.SetParameters method and change the lDuration member of DIEFFECT to -1.

flags
Flags from the CONST_DIESFLAGS enumeration that describe how the effect should be played by the device. The value may be zero or one or more of the following values:
DIES_SOLO
All other effects on the device should be stopped before the specified effect is played. If this flag is omitted, then the effect is mixed with existing effects already started on the device.
DIES_NODOWNLOAD
Do not automatically download the effect.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following:

DIERR_INVALIDPARAM
DIERR_INCOMPLETEEFFECT
DIERR_NOTEXCLUSIVEACQUIRED
DIERR_NOTINITIALIZED
DIERR_UNSUPPORTED

Remarks

The device must be acquired at the exclusive cooperative level for this method to succeed.

Not all devices support multiple iterations.


DirectInputEffect.Stop

The DirectInputEffect.Stop method stops an effect that is playing.

object.Stop()

Parameters

object
Object expression that resolves to a DirectInputEffect object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following:

DIERR_NOTEXCLUSIVEACQUIRED
DIERR_NOTINITIALIZED

Remarks

The device must be acquired at the exclusive cooperative level for this method to succeed.


DirectInputEffect.Unload

The DirectInputEffect.Unload method removes the effect from the device. If the effect is playing, it is automatically stopped before it is unloaded.

object.Unload()

Parameters

object
Object expression that resolves to a DirectInputEffect object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following:

DIERR_INPUTLOST
DIERR_INVALIDPARAM
DIERR_NOTEXCLUSIVEACQUIRED
DIERR_NOTINITIALIZED

Remarks

The device must be acquired at the exclusive cooperative level for this method to succeed.


DirectInputEnumDeviceObjects

The DirectInputEnumDeviceObjects class enumerates the DirectInputDevice objects installed on a system. This object is created and filled with data as a result of a call to DirectInputDevice.GetDeviceObjectsEnum method.

This class has the following methods:

Information | GetCount
 | GetItem


DirectInputEnumDeviceObjects.GetCount

The DirectInputEnumDeviceObjects.GetCount method returns the number of items in the DirectInputEnumDeviceObjects collection.

object.GetCount() As Long

Parameters

object
Object expression that resolves to a DirectInputEnumDeviceObjects object.

Return Values

The method returns the number of device objects enumerated for the device.

Error Codes

None.


DirectInputEnumDeviceObjects.GetItem

The DirectInputEnumDeviceObjects.GetItem method retrieves an object describing the specified device object.

object.GetItem(index As Long) _
  As DirectInputDeviceObjectInstance

Parameters

object
Object expression that resolves to a DirectInputEnumDeviceObjects object.
index
Index of the enumerated item to retrieve.

Return Values

The method returns a DirectInputDeviceObjectInstance object whose methods can be used to retrieve information about the device object.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

Remarks

To get the number of entries in the DirectInputEnumDeviceObjects first call the DirectInputEnumDeviceObjects.GetCount method.


DirectInputEnumDevices

The DirectInputEnumDevices enumerates the DirectInput devices installed on a system. This object is created and filled with data as a result of a call to DirectInput.GetDIEnumDevices method.

This class has the following methods:

Information | GetCount
 | GetItem


DirectInputEnumDevices.GetCount

The DirectInputEnumDevices.GetCount method returns the number of DirectInput devices in the DirectInputEnumDevices collection.

object.GetCount() As Long

Parameters

object
Object expression that resolves to a DirectInputEnumDevices object.

Return Values

If the method succeeds, the number of DirectInput devices in the DirectInputEnumDevices collection is returned.

Error Codes

None.


DirectInputEnumDevices.GetItem

The DirectInputEnumDevices.GetItem method returns information about an enumerated device.

object.GetItem(index As Long) As DirectInputDeviceInstance

Parameters

object
Object expression that resolves to a DirectInputEnumDevices object.
index
The specific DirectInput device data entry in DirectInputEnumDevices.

Return Values

The method returns a DirectInputDeviceInstance object whose methods can be used to retrieve information about the device.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

Remarks

To get the number of entries in DirectInputEnumDevices first call the DirectInputEnumDevices.GetCount method.


DirectInputEnumEffects

An object of the DirectInputEnumEffects class represents a collection of supported force-feedback effects on a device, and is used for retrieving information about the effects. The object is created by using the DirectInputDevice.GetEffectsEnum method.

The class has the following methods:

Information | GetCount
 | GetDynamicParams
 | GetEffectGuid
 | GetName
 | GetStaticParams
 | GetType


DirectInputEnumEffects.GetCount

The DirectInputEnumEffects.GetCount method returns the number of enumerated effects in the collection.

object.GetCount() As Long

Parameters

object
Object expression that resolves to a DirectInputEnumEffects object.

Return Values

The method returns the number of items in the collection.

Error Codes

If the method fails, it raises an error and Err.Number will be set.


DirectInputEnumEffects.GetDynamicParams

The DirectInputEnumEffects.GetDynamicParams method retrieves information about which effect parameters can be changed without stopping the effect, using the DirectInputEffect.SetParameters method.

object.GetDynamicParams(i As Long) As CONST_DIEPFLAGS

Parameters

object
Object expression that resolves to a DirectInputEnumEffects object.
i
Index (1-based) of the effect in the collection.

Return Values

The method returns flags from the CONST_DIEPFLAGS enumeration specifying which parameters can be dynamically updated while the effect is playing.

Error Codes

If the method fails, it raises an error and Err.Number will be set.

See Also

DirectInputEffect.SetParameters


DirectInputEnumEffects.GetEffectGuid

The DirectInputEnumEffects.GetEffectGuid method retrieves the GUID for the supported effect. This GUID can be passed to the DirectInputDevice.CreateEffect method.

object.GetEffectGuid(i As Long) As String

Parameters

object
Object expression that resolves to a DirectInputEnumEffects object.
i
Index (1-based) of the effect in the collection.

Return Values

The method returns the GUID in string form. For standard effects, the return value is an alias such as "GUID_ConstantForce".

Error Codes

If the method fails, it raises an error and Err.Number will be set.

See Also

Using GUIDs


DirectInputEnumEffects.GetName

The DirectInputEnumEffects.GetName method retrieves the name of the effect.

object.GetName(i As Long) As String

Parameters

object
Object expression that resolves to a DirectInputEnumEffects object.
i
Index (1-based) of the effect in the collection.

Return Values

The method returns the name of the effect, such as "Constant Force".

Error Codes

If the method fails, it raises an error and Err.Number will be set.


DirectInputEnumEffects.GetStaticParams

The DirectInputEnumEffects.GetStaticParams method retrieves information about effect parameters supported on the device.

object.GetStaticParams(i As Long) As CONST_DIEPFLAGS

Parameters

object
Object expression that resolves to a DirectInputEnumEffects object.
i
Index (1-based) of the effect in the collection.

Return Values

The method returns flags from the CONST_DIEPFLAGS enumeration specifying which parameters are supported by the effect.

Error Codes

If the method fails, it raises an error and Err.Number will be set.


DirectInputEnumEffects.GetType

The DirectInputEnumEffects.GetType method retrieves information about the type and capabilities of the effect.

object.GetType(i As Long) As CONST_DIEFTFLAGS

Parameters

object
Object expression that resolves to a DirectInputEnumEffects object.
i
Index (1-based) of the effect in the collection.

Return Values

The method returns flags from the CONST_DIEFTFLAGS enumeration giving information about the effect.

Error Codes

If the method fails, it raises an error and Err.Number will be set.

Remarks

The effect type is stored in the low byte and can be retrieved by a bitwise And with &HFF.


Types

This section contains information on the following types used with DirectInput:

  • DICONDITION
  • DICONSTANTFORCE
  • DIDATAFORMAT
  • DIDEVCAPS
  • DIDEVICEOBJECTDATA
  • DIEFFECT
  • DIENVELOPE
  • DIJOYSTATE
  • DIJOYSTATE2
  • DIKEYBOARDSTATE
  • DIMOUSESTATE
  • DIOBJECTDATAFORMAT
  • DIPERIODICFORCE
  • DIPROPLONG
  • DIPROPRANGE
  • DIRAMPFORCE


DICONDITION

The DICONDITION type describes parameters for a force-feedback condition in the DIEFFECT type.

Type DICONDITION
  lDeadBand As Long
  lNegativeCoefficient As Long
  lNegativeSaturation As Long
  lOffset As Long
  lPositiveCoefficient As Long
  lPositiveSaturation As Long
End Type

Members

lDeadBand
The region around lOffset where the condition is not active, in the range 0 to 10,000. In other words, the condition is not active between lOffset - lDeadBand and lOffset + lDeadBand.
lNegativeCoefficient
The coefficient constant on the negative side of the offset, in the range -10,000 to +10,000.

If the device does not support separate positive and negative coefficients, then the value of lNegativeCoefficient is ignored and the value of lPositiveCoefficient is used as both the positive and negative coefficients.

lNegativeSaturation
The maximum force output on the negative side of the offset, in the range 0 to 10,000.

If the device does not support force saturations, then the value of this member is ignored.

If the device does not support separate positive and negative saturations, then the value of lNegativeSaturation is ignored and the value of lPositiveSaturation is used as both the positive and negative saturations.

lOffset
The offset for the condition, in the range -10,000 to +10,000.
lPositiveCoefficient
The coefficient constant on the positive side of the offset, in the range -10,000 to +10,000.
lPositiveSaturation
The maximum force output on the positive side of the offset, in the range 0 to 10,000.

If the device does not support force saturation, then the value of this member is ignored.

Remarks

Different types of conditions will interpret the parameters differently, but the basic idea is that force resulting from a condition is equal to A(q - q0) where A is a scaling coefficient, q is some metric, and q0 is the neutral value for that metric.

The preceding simplified formula must be adjusted if a nonzero dead band is provided. If the metric is less than lOffset - lDeadBand, then the resulting force is given by the following formula:

force = lNegativeCoefficient * (q - (lOffset - lDeadBand))

Similarly, if the metric is greater than lOffset + lDeadBand, then the resulting force is given by the following formula:

force = lPositiveCoefficient * (q - (lOffset + lDeadBand))

A spring condition uses axis position as the metric.

A damper condition uses axis velocity as the metric.

An inertia condition uses axis acceleration as the metric.


DICONSTANTFORCE

The DICONSTANTFORCE type describes parameters for a constant force in the DIEFFECT type.

Type DICONSTANTFORCE
  lMagnitude As Long
End Type

Members

lMagnitude
Magnitude of the effect, in the range -10,000 to +10,000. If an envelope is applied to this effect, then the value represents the magnitude of the sustain. If no envelope is applied, then the value represents the amplitude of the entire effect.


DIDATAFORMAT

The DIDATAFORMAT type carries information describing a device's data format. This type is used with the DirectInputDevice.SetDataFormat method.

Type DIDATAFORMAT
    dataSize As Long
    lFlags As Long
    lObjSize As Long
    numObjs As Long
End Type

Members

dataSize
Size of a data packet returned by the device, in bytes. This value must be a multiple of 4 and must exceed the largest offset value for an object's data within the data packet.
lFlags
Flags describing other attributes of the data format. This value can be one of the CONST_DIDATAFORMATFLAGS enumeration.
lObjSize
Size of the DIOBJECTDATAFORMAT type, in bytes.
numObjs
Number of objects for which data is to be returned.

Remarks

Applications need to create a DIDATAFORMAT type only for nonstandard devices. For the mouse, keyboard, and joystick, you set the data format by using DirectInputDevice.SetCommonDataFormat.


DIDEVCAPS

The DIDEVCAPS type contains information about a DirectInput device's capabilities. This type is used with the DirectInputDevice.GetCapabilities method.

Type DIDEVCAPS
    lAxes As Long
    lButtons As Long
    lDevType As CONST_DIDEVICETYPE
    lDriverVersion As Long
    lFFMinTimeResolution As Long
    lFFSamplePeriod As Long
    lFirmwareRevision As Long
    lFlags As CONST_DIDEVCAPSFLAGS
    lHardwareRevision As Long
    lPOVs As Long
End Type

Members

lAxes
Number of axes available on the device.
lButtons
Number of buttons available on the device.
lDevType
A packed value containing information about the type and subtype of the device. The value is identical to that returned by the DirectInputDeviceInstance.GetDevType method.
lDriverVersion
The version number of the device driver.
lFFMinTimeResolution
The minimum amount of time, in microseconds, that the device can resolve when playing force-feedback effects. The device rounds any times to the nearest supported increment. For example, if the value of lFFMinTimeResolution is 1000, then the device would round any times to the nearest millisecond.
lFFSamplePeriod
The minimum time between playback of consecutive raw force commands.
lFirmwareRevision
Specifies the firmware revision of the device.
lFlags
Flags associated with the device. This value can be a combination of the constants of the CONST_DIDEVCAPSFLAGS enumeration.
lHardwareRevision
The hardware revision of the device.
lPOVs
Number of point-of-view controllers available on the device.

Remarks

The semantics of version numbers are left to the manufacturer of the device. The only guarantee is that newer versions will have larger numbers.


DIDEVICEOBJECTDATA

The DIDEVICEOBJECTDATA type contains raw buffered device information. This type is used with the DirectInputDevice.GetDeviceData method.

Type DIDEVICEOBJECTDATA
    lData As Long
    lOfs As Long
    lSequence As Long
    lTimeStamp As Long
End Type

Members

lData
Data obtained from the device.

For axis input, if the device is in relative axis mode, then the relative axis motion is reported. If the device is in absolute axis mode, then the absolute axis coordinate is reported.

For button input, only the low byte of lData is significant. The high bit of the low byte is set if the button went down; it is clear if the button went up.

lOfs
Offset into the current data format of the object whose data is being reported—that is, the location where the data would have been stored if it had been obtained by a call to the DirectInputDevice.GetDeviceStateX method where X refers to the specific device, for instance GetDeviceStateMouse. If the device is accessed as a keyboard, you can determine which key generated the event by comparing this value with the members of the CONST_DIKEYFLAGS enumeration. For the mouse and joystick, the value in lOfs is equivalent to the byte offset of the button or axis within the DIMOUSESTATE, DIJOYSTATE, or DIJOYSTATE2 type (depending on the data format that was established by using DirectInputDevice.SetCommonDataFormat.) Constants for these offsets are contained in the CONST_DIMOUSEOFS and CONST_DIJOYSTICKOFS enumerations. If a custom data format has been set by using DirectInputDevice.SetDataFormat, then lOfs is the offset of the device object's place in the custom data format.
lSequence
DirectInput sequence number for this event. All input events are assigned an increasing sequence number. This allows events from different devices to be sorted chronologically. Since this value can wrap around, care must be taken when comparing two sequence numbers.
lTimeStamp
System time at which the input event was generated, in milliseconds. This value wraps around approximately every 50 days.


DIEFFECT

The DIEFFECT type describes a force-feedback effect. It is passed to the DirectInputDevice.CreateEffect and DirectInputEffect.SetParameters methods in order to set parameters for an effect. Existing parameters are retrieved in this type through the DirectInputEffect.GetParameters method.

Type DIEFFECT
  bUseEnvelope As Long
  conditionFlags As CONST_DICONDITIONFLAGS
  conditionX As DICONDITION
  conditionY As DICONDITION
  constantForce As DICONSTANTFORCE
  envelope As DIENVELOPE
  lDuration As Long
  lFlags As Long
  lGain As Long
  lSamplePeriod As Long
  lStartDelay As Long
  lTriggerButton As Long
  lTriggerRepeatInterval As Long
  periodicForce As DIPERIODICFORCE
  rampForce As DIRAMPFORCE
  x As Long
  y As Long
End Type

Members

bUseEnvelope
True if the envelope described in the envelope member is to be applied to the effect.
conditionFlags
Flags from the CONST_DICONDITIONFLAGS enumeration. In the current version of DirectX for Visual Basic, this value should be 0.
conditionX
DICONDITION type describing parameters of the condition on the x-axis. Ignored for other types of effects.
conditionY
DICONDITION type describing parameters of the condition on the y-axis. Ignored for other types of effects.
constantForce
DICONSTANTFORCE type describing parameters of a constant force. Ignored for other types of effects.
envelope
DIENVELOPE type describing parameters of an envelope to be applied to the effect. Valid only if the bUseEnvelope member is True.
lDuration
Duration of the effect, in microseconds. A value of -1 indicates infinite duration. If an envelope is applied to an effect of infinite duration, then the attack will be applied, followed by an infinite sustain.
lFlags
Zero or more members of the CONST_DIEFFFLAGS enumeration specifying how other members are to be interpreted.
lGain
The gain to be applied to the effect, in the range 0 to 10,000. The gain is a scaling factor applied to all magnitudes of the effect and its envelope.
lSamplePeriod
The period, in microseconds, at which the device samples the effect—in other words, the granularity of changes in force. A value of 0 indicates that the default playback sample rate should be used.

If the device is not capable of sampling the effect at the specified rate, it will choose the supported rate that is closest to the requested value.

Setting a custom sample period can be used for special effects. For example, playing a sine wave with an artificially large sample period results in a rougher texture.

lStartDelay
Time, in microseconds, the device should wait after a DirectInputEffect.Start call before playing the effect. If this value is 0, then effect playback begins immediately.
lTriggerButton
Offset value of the button that will trigger the effect. This should be one of the members of the CONST_DIJOYSTICKOFS enumeration, or -1 to indicate that the effect does not have a trigger button.
lTriggerRepeatInterval
The interval, in microseconds, between the end of one playback and the start of the next when the effect is triggered by a button press and the button is held down. Setting this value to -1 suppresses repetition.

Not all devices support trigger repeat.

periodicForce
DIPERIODICFORCE type describing parameters of a periodic effect. Ignored for other types of effects.
rampForce
DIRAMPFORCE type describing parameters of a ramp force. Ignored for other types of effects.
x
Direction of the effect. Normally, this is the amount by which the direction is rotated from north (usually the negative y-axis), in hundredths of degrees. Thus a value of 0 indicates a force pushing toward the user, a value of 9000 indicates a force pushing from the user's right, and so on. In this case, y should be 0.

If lFlags contains DIEFF_CARTESIAN, this is a Cartesian value describing the relative amount of force on the x-axis. For example, if x = -1 and y = 1, the direction of the force is from the southwest. For more information, see Effect Direction.

y
If lFlags contains DIEFF_CARTESIAN, this is a Cartesian value describing the relative amount of force on the y-axis. Otherwise it should be 0.


DIENVELOPE

The DIENVELOPE type describes parameters for an envelope in the DIEFFECT type.

Type DIENVELOPE
  lAttackLevel As Long
  lAttackTime As Long
  lFadeLevel As Long
  lFadeTime As Long
End Type

Members

lAttackLevel
Amplitude for the start of the envelope, relative to the baseline (offset), in the range 0 to 10,000. If the effect's type-specific data does not specify a baseline, then the amplitude is relative to zero.
lAttackTime
The time, in microseconds, to reach the sustain level.
lFadeLevel
Amplitude for the end of the envelope, relative to the baseline, in the range 0 to 10,000. If the effect's type-specific data does not specify a baseline, then the amplitude is relative to zero.
lFadeTime
The time, in microseconds, to reach the fade level.


DIJOYSTATE

The DIJOYSTATE type contains information about the state of a joystick device. (This term includes other controllers such as game pads and steering wheels). This type is used with the DirectInputDevice.GetDeviceStateJoystick method.

Type DIJOYSTATE
    buttons(0 To 31) As Byte
    POV(0 To 3) As Long
    rx As Long
    ry As Long
    rz As Long
    slider(0 To 1) As Long
    x As Long
    y As Long
    z As Long
End Type

Members

buttons
Array of button states. The high-order bit of the byte is set if the corresponding button is down and clear if the button is up or does not exist.
POV
The current position of up to four direction controllers (such as point-of-view hats). The position is indicated in hundredths of degrees clockwise from north (away from the user). The center position is normally reported as -1; but see Remarks. For indicators that have only five positions, the value for a controller will be -1, 0, 9,000, 18,000, or 27,000.
rx
Information about the joystick x-axis rotation. If the joystick does not have this, the value is 0.
ry
Information about the joystick y-axis rotation. If the joystick does not have this axis, the value is 0.
rz
Information about the joystick z-axis rotation (often called the rudder). If the joystick does not have this axis, the value is 0.
slider
Two additional axis values whose semantics depend on the joystick. Use the DirectInputDevice.GetObjectInfo method to obtain semantic information about these values.
x
Information about the joystick x-axis (usually the left-right movement of a stick).
y
Information about the joystick y-axis (usually the forward-backward movement of a stick).
z
Information about the joystick z-axis (often the throttle control). If the joystick does not have this axis, the value is zero.

Remarks

You must prepare the device for joystick-style access by calling the DirectInputDevice.SetCommonDataFormat method, passing the DIFORMAT_JOYSTICK format constant.

If an axis is in relative mode, then the appropriate member contains the change in position. If it is in absolute mode, then the member contains the absolute axis position.

Some drivers report the centered position of the POV indicator as 65,535. You can determine whether an indicator is centered as follows:

Dim POVCentered as Boolean
POVCentered = MyDijoystate.POV(0) And &HFFFF;

See Also

DIJOYSTATE2


DIJOYSTATE2

The DIJOYSTATE2 type contains information about the state of a joystick device with extended capabilities. This type is used with the DirectInputDevice.GetDeviceStateJoystick2 method.

Most applications do not need to use this type, which is for highly specialized controllers including force-feedback devices. For standard game controllers, use the DIJOYSTATE type and obtain data by calling DirectInputDevice.GetDeviceStateJoystick.

Type DIJOYSTATE2
    buttons(0 To 31) As Byte
    frx As Long
    fry As Long
    frz As Long
    fslider(0 To 1) As Long
    fx As Long
    fy As Long
    fz As Long
    POV(0 To 3) As Long
    rx As Long
    ry As Long
    rz As Long
    slider(0 To 1) As Long
    vrx As Long
    vry As Long
    vrz As Long
    vslider(0 To 1) As Long
    vx As Long
    vy As Long
    vz As Long
    x As Long
    y As Long
    z As Long
End Type

Members

buttons
Array of button states. The high-order bit of the byte is set if the corresponding button is down and clear if the button is up or does not exist.
frx
Information about the x-axis torque.
fry
Information about the y-axis torque.
frz
Information about the z-axis torque.
fslider
Information about extra axis forces.
fx
Information about the x-axis force.
fy
Information about the y-axis force.
fz
Information about the z-axis force.
POV
The current position of up to four direction controllers (such as point-of-view hats). The position is indicated in hundredths of degrees clockwise from north (away from the user). The center position is normally reported as -1; but see Remarks. For indicators that have only five positions, the value for a controller will be -1, 0, 9,000, 18,000, or 27,000.
rx
Information about the joystick x-axis rotation. If the joystick does not have this, the value is 0.
ry
Information about the joystick y-axis rotation. If the joystick does not have this axis, the value is 0.
rz
Information about the joystick z-axis rotation (often called the rudder). If the joystick does not have this axis, the value is zero.
slider
Two additional axis values whose semantics depend on the joystick. Use the DirectInputDevice.GetObjectInfo method to obtain semantic information about these values.
vrx
Information about the x-axis angular velocity.
vry
Information about the y-axis angular velocity.
vrz
Information about the z-axis angular velocity.
vslider[0 To 1]
Information about extra axis velocities.
vx
Information about the x-axis velocity.
vy
Information about the y-axis velocity.
vz
Information about the z-axis velocity.
x
Information about the joystick x-axis (usually the left-right movement of a stick).
y
Information about the joystick y-axis (usually the forward-backward movement of a stick).
z
Information about the joystick z-axis (often the throttle control). If the joystick does not have this axis, the value is zero.

Remarks

You must prepare the device for access to a joystick with extended capabilities by calling the DirectInputDevice.SetCommonDataFormat method, passing the DIFORMAT_JOYSTICK2 data format variable.

If an axis is in relative mode, then the appropriate member contains the change in position. If it is in absolute mode, then the member contains the absolute axis position.

Some drivers report the centered position of the POV indicator as 65,535. You can determine whether an indicator is centered as follows:

Dim POVCentered as Boolean
POVCentered = MyDijoystate2.POV(0) And &HFFFF;


DIKEYBOARDSTATE

The DIKEYBOARDSTATE type contains information about the state of keyboard keys. This type is used with the DirectInputDevice.GetDeviceStateKeyboard method.

Type DIKEYBOARDSTATE
    key(0 To 255) As Byte
End Type

Members

key
Array of key states. The array can be indexed by using members of the CONST_DIKEYFLAGS enumeration. For each key, the high bit is set if the key is down, and clear if the key is up or does not exist.

Remarks

The following example checks to see if the Esc key is being pressed:

Dim keyState as DIKEYBOARDSTATE
' diDevice is a valid DirectInputDevice object.

Call diDevice.GetDeviceStateKeyboard(keyState)
If (keyState.key(DIK_ESCAPE) And &H80) Then
    ' Key is down
End If


DIMOUSESTATE

The DIMOUSESTATE type contains information about the state of a mouse device or another device that is being accessed as if it were a mouse device. This type is used with the DirectInputDevice.GetDeviceStateMouse method.

Type DIMOUSESTATE
    buttons(0 To 3) As Byte
    x As Long
    y As Long
    z As Long
End Type

Members

buttons
Array of button states. The high-order bit of the byte is set if the corresponding button is down.
x
Information about the mouse x-axis.
y
Information about the mouse y-axis.
z
Information about the mouse z-axis (typically a wheel). If the mouse does not have a z-axis, then the value is 0.

Remarks

Immediate data is returned in this type from a device that has been prepared by passing the DIFORMAT_MOUSE constant to the DirectInputDevice.SetCommonDataFormat method.

If an axis is in relative mode, then the appropriate member contains the change in position since the last call to this method. If the axis is in absolute mode, then the member contains the accumulated relative motion in relation to an arbitrary start point. The absolute axis position is not meaningful except in comparison with other absolute axis positions.


DIOBJECTDATAFORMAT

The DIOBJECTDATAFORMAT type contains information about a device object's data format for use with the DirectInputDevice.SetDataFormat method.

Type DIOBJECTDATAFORMAT {
    lFlags As CONST_DIDEVICEOBJINSTANCEFLAGS
    lOfs As Long
    lType As CONST_DIDFTFLAGS
    strGuid As String
End Type

Members

lFlags
Zero or more of the following values from the CONST_DIDEVICEOBJINSTANCEFLAGS enumeration.
DIDOI_ASPECTACCEL
The object selected by DirectInput.SetDataFormat must report acceleration information.
DIDOI_ASPECTFORCE
The object selected by DirectInput.SetDataFormat must report force information.
DIDOI_ASPECTPOSITION
The object selected by DirectInput.SetDataFormat must report position information.
DIDOI_ASPECTVELOCITY
The object selected by DirectInput.SetDataFormat must report velocity information.
lOfs
Byte offset within the data packet where the data for the input source will be stored. This value must be a multiple of four for Long size data, such as axes. It can be byte-aligned for buttons.
lType
Device type that describes the object. It is a combination of values from the CONST_DIDFTFLAGS enumeration describing the object type (axis, button, and so forth) and containing the object-instance number in the middle 16 bits.
strGuid
Unique identifier for the type of input source. An empty string indicates that any type of object is permissible.

The following strings can be used in place of actual GUID strings to identify the type of device object:

GUID_XAxis
GUID_YAxis
GUID_ZAxis
GUID_RxAxis
GUID_RyAxis
GUID_RzAxis
GUID_Slider
GUID_Button
GUID_Key
GUID_POV


DIPERIODICFORCE

The DIPERIODICFORCE type describes parameters for a periodic force in the DIEFFECT type.

Type DIPERIODICFORCE
  lMagnitude As Long
  lOffset As Long
  lPhase As Long
  lPeriod As Long
End Type

Members

lMagnitude
The magnitude of the effect, in the range 0 to 10,000. If an envelope is applied to this effect, then the value represents the magnitude of the sustain. If no envelope is applied, then the value represents the amplitude of the entire effect.
lOffset
The offset of the effect. The range of forces generated by the effect will be lOffset - lMagnitude to lOffset + lMagnitude. The value of the lOffset member is also the baseline for any envelope that is applied to the effect.
lPhase
The position in the cycle of the periodic effect at which playback begins, in the range 0 to 35,999. See Remarks.
lPeriod
The period of the effect, in microseconds.

Remarks

A device driver might not provide support for all values in the lPhase member. In this case the value will be rounded off to the nearest supported value.


DIPROPLONG

The DIPROPLONG type is used to store property information to be set on or retrieved from the input device by using the DirectInputDevice.SetProperty and DirectInputDevice.GetProperty methods, where the property is a single value.

Type DIPROPLONG
    lData As Long
    lHow As Long
    lObj As Long
    lSize As Long
End Type

Members

lData
The property-specific value being set or retrieved.
lHow
Value specifying how the lObj parameter should be interpreted. This value may be one of the members of the CONST_DIPHFLAGS enumeration.

If lObj is DIPROP_AXISMODE or DIPROP_BUFFERSIZE, lHow should be DIPH_DEVICE, because these properties cannot be set for an individual object.

lObj
Object for which the property is to be accessed.

If the lHow member is DIPH_BYID, this member must be the identifier for the object whose property setting is to be set or retrieved. This value can be retrieved for the object by using the DirectInputDeviceObjectInstance.GetType method.

If the lHow member is DIPH_BYOFFSET, this member must be a data format offset for the object whose property setting is to be set or retrieved. This value can be obtained by using the DirectInputDeviceObjectInstance.GetOfs method.

If lHow is DIPH_DEVICE, this value should be 0.

lSize
Size of this type.

Remarks

All members must be initialized with the proper values before the type is passed to the SetProperty method. All members except lData must be initialized with the proper values before the type is passed to GetProperty.

See Also

DIPROPRANGE


DIPROPRANGE

The DIPROPRANGE type is used to store property information to be set on or retrieved from the input device by using the DirectInputDevice.SetProperty and DirectInputDevice.GetProperty methods, where the property is a range of values.

Type DIPROPRANGE
    lHow As Long
    lMax As Long
    lMin As Long
    lObj As Long
    lSize As Long
End Type

Members

lHow
Value specifying how the lObj member should be interpreted. This value may be one of the members of the CONST_DIPHFLAGS enumeration.
lMax
Upper limit of the range. If the range of the device is unrestricted, this value will be DIPROPRANGE_NOMAX (from the CONST_DINPUT enumeration) when the DirectInputDevice.GetProperty method returns.
lMin
Lower limit of the range. If the range of the device is unrestricted, this value will be DIPROPRANGE_NOMIN (from the CONST_DINPUT enumeration)when the DirectInputDevice.GetProperty method returns.
lObj
Object for which the property is to be accessed.

If the lHow member is DIPH_BYID, this member must be the identifier for the object whose property setting is to be set or retrieved. This value can be retrieved for the object by using the DirectInputDeviceObjectInstance.GetType method.

If the lHow member is DIPH_BYOFFSET, this member must be a data format offset for the object whose property setting is to be set or retrieved. This value can be obtained by using the DirectInputDeviceObjectInstance.GetOfs method.

If lHow is DIPH_DEVICE, this value should be 0.

lSize
Size of this type.

See Also

DIPROPLONG


DIRAMPFORCE

The DIRAMPFORCE type describes parameters for a ramp force in the DIEFFECT type.

Type DIRAMPFORCE
  lRangeEnd As Long
  lRangeStart As Long
End Type

Members

lRangeEnd
The magnitude at the end of the effect, in the range -10,000 to +10,000.
lRangeStart
The magnitude at the start of the effect, in the range -10,000 to +10,000.

Remarks

The duration of a ramp force effect must be finite.


Enumerations

DirectInput uses enumerations to group constants in order to take advantage of the statement completion feature of Visual Basic. The enumerations used in DirectInput are:

  • CONST_DICOMMONDATAFORMATS
  • CONST_DICONDITIONFLAGS
  • CONST_DIDATAFORMATFLAGS
  • CONST_DIDEVCAPSFLAGS
  • CONST_DIDEVICEOBJINSTANCEFLAGS
  • CONST_DIDEVICETYPE
  • CONST_DIDFTFLAGS
  • CONST_DIDGDDFLAGS
  • CONST_DIEFFFLAGS
  • CONST_DIEFTFLAGS
  • CONST_DIEGESFLAGS
  • CONST_DIENUMDEVICESFLAGS
  • CONST_DIEPFLAGS
  • CONST_DIESFLAGS
  • CONST_DIGFFSFLAGS
  • CONST_DIJOYSTICKOFS
  • CONST_DIKEYFLAGS
  • CONST_DIMOUSEOFS
  • CONST_DINPUT
  • CONST_DINPUTERR
  • CONST_DIPHFLAGS
  • CONST_DISCLFLAGS
  • CONST_DISDDFLAGS
  • CONST_DISFFCFLAGS


CONST_DICOMMONDATAFORMATS

Members of the CONST_DICOMMONDATAFORMATS enumeration are used to specify the data format in the format parameter of the DirectInputDevice.SetCommonDataFormat method.

Enum CONST_DICOMMONDATAFORMATS
    DIFORMAT_JOYSTICK =  3
    DIFORMAT_JOYSTICK2 = 4
    DIFORMAT_KEYBOARD =  1
    DIFORMAT_MOUSE =     2
End Enum
DIFORMAT_JOYSTICK
Joystick whose state data can be received in a DIJOYSTATE type.
DIFORMAT_JOYSTICK2
Joystick with extended capabilities whose state data can be received in a DIJOYSTATE2 type.
DIFORMAT_KEYBOARD
Keyboard whose state data can be received in a DIKEYBOARDSTATE type.
DIFORMAT_MOUSE
Mouse whose state data can be received in a DIMOUSESTATE type.


CONST_DICONDITIONFLAGS

The CONST_DICONDITIONFLAGS enumeration is used in the conditionFlags member of the DIEFFECT type to set the axes and direction of a force-feedback effect.

Enum CONST_DICONDITIONFLAGS
    DICONDITION_USE_BOTH_AXES = 1
    DICONDITION_USE_DIRECTION = 2
End Enum
DICONDITION_USE_BOTH_AXES
Not currently supported.
DICONDITION_USE_DIRECTION
Not currently supported.


CONST_DIDATAFORMATFLAGS

The CONST_DIDATAFORMATFLAGS enumeration is used in the lFlags member of the DIDATAFORMAT type to describe additional attributes of the data format.

Enum CONST_DIDATAFORMATFLAGS
    DIDF_ABSAXIS = 1
    DIDF_RELAXIS = 2
End Enum
DIDF_ABSAXIS
The axes are in absolute mode. Setting this flag in the data format is equivalent to manually setting the axis mode property using the DirectInputDevice.SetProperty method. This may not be combined with DIDF_RELAXIS flag.
DIDF_RELAXIS
The axes are in relative mode. Setting this flag in the data format is equivalent to manually setting the axis mode property using the DirectInputDevice.SetProperty method. This may not be combined with the DIDF_ABSAXIS flag.


CONST_DIDEVCAPSFLAGS

The CONST_DIDEVCAPSFLAGS enumeration is used in the lFlags member of the DIDEVCAPS type to describe the DirectInput device.

Enum CONST_DIDEVCAPSFLAGS
    DIDC_ATTACHED =              1
    DIDC_DEADBAND =          16384 (&H4000)
    DIDC_EMULATED =              4
    DIDC_FFATTACK =            512 (&H200)
    DIDC_FFFADE =             1024 (&H400)
    DIDC_FORCEFEEDBACK =       256 (&H100)
    DIDC_POLLEDDATAFORMAT =      8
    DIDC_POLLEDDEVICE =          2
    DIDC_POSNEGCOEFFICIENTS = 4096 (&H1000)
    DIDC_POSNEGSATURATION =   8192 (&H2000)
    DIDC_SATURATION =         2048 (&H800)
End Enum
DIDC_ATTACHED
The device is physically attached.
DIDC_DEADBAND
The device supports deadband for at least one force-feedback condition.
DIDC_EMULATED
If this flag is set, the data is coming from a user mode device interface (such as HID) or by some other ring 3 means. If it is not set, the data is coming directly from a kernel mode driver.
DIDC_FFATTACK
The force-feedback system supports the attack parameter for at least one effect. If the device does not support attack then the lAttackLevel and lAttackTime members of the DIENVELOPE type will be ignored by the device.
DIDC_FFFADE
The force-feedback system supports the fade parameter for at least one effect. If the device does not support fade then the lFadeLevel and lFadeTime members of the DIENVELOPE type will be ignored by the device.
DIDC_FORCEFEEDBACK
The device supports force feedback.
DIDC_POLLEDDATAFORMAT
At least one object in the current data format is polled rather than interrupt-driven. For these objects, the application must explicitly call the DirectInputDevice.Poll method in order to obtain data.
DIDC_POLLEDDEVICE
At least one object on the device is polled rather than interrupt-driven. For these objects, the application must explicitly call the DirectInputDevice.Poll method in order to obtain data. HID devices may contain a mixture of polled and non-polled objects.
DIDC_POSNEGCOEFFICIENTS
The force-feedback system supports two coefficient values for conditions (one for the positive displacement of the axis and one for the negative displacement of the axis) for at least one condition. If the device does not support both coefficients, then the negative coefficient in the DICONDITION type will be ignored.
DIDC_POSNEGSATURATION
The force-feedback system supports a maximum saturation for both positive and negative force output for at least one condition. If the device does not support both saturation values, then the negative saturation in the DICONDITION structure will be ignored.
DIDC_SATURATION
The force-feedback system supports the saturation of condition effects for at least one condition. If the device does not support saturation, then the force generated by a condition is limited only by the maximum force which the device can generate.

See Also

CONST_DIEFTFLAGS


CONST_DIDEVICEOBJINSTANCEFLAGS

Members of the CONST_DIDEVICEOBJINSTANCEFLAGS enumeration describe device object capabilities and are returned by the DirectInputDeviceObjectInstance.GetFlags method. They are also present in the DIOBJECTDATAFORMAT type passed to the DirectInputDevice.SetDataFormat method

Enum CONST_DIDEVICEINSTANCEFLAGS
    DIDOI_ASPECTACCEL =     768 (&H300)
    DIDOI_ASPECTFORCE =    1024 (&H400)
    DIDOI_ASPECTMASK =     3840 (&HF00)
    DIDOI_ASPECTPOSITION =  256 (&H100)
    DIDOI_ASPECTVELOCITY =  512 (&H200)
    DIDOI_FFACTUATOR =        1
    DIDOI_FFEFFECTTRIGGER =   2
    DIDOI_POLLED =        32768 (&H8000)
End Enum
DIDOI_ASPECTACCEL
The object reports acceleration information.
DIDOI_ASPECTFORCE
The object reports force information.
DIDOI_ASPECTMASK
The bits that are used to report aspect information. An object can represent at most one aspect.
DIDOI_ASPECTPOSITION
The object reports position information.
DIDOI_ASPECTVELOCITY
The object reports velocity information.
DIDOI_FFACTUATOR
The object can have force-feedback effects applied to it.
DIDOI_FFEFFECTTRIGGER
The object can trigger playback of force-feedback effects.
DIDOI_POLLED
The object does not return data until the DirectInputDevice.Poll method is called.

Remarks

The only one of these flags that is of interest for applications developed with DirectX for Visual Basic is DIDIO_POLLED.


CONST_DIDEVICETYPE

Members of the CONST_DIDEVICETYPE enumeration are used to identify the input device type and subtype. A packed value representing the type and subtype is returned by the DirectInputDeviceInstance.GetDevType method and in the lDevType member of the DIDEVCAPS type returned by DirectInputDevice.GetCapabilities. A value representing a primary type is passed as the deviceType parameter to the DirectInput.GetDIEnumDevices method.

For a table of members listed by type and subtype, see DirectInputDeviceInstance.GetDevType.

Enum CONST_DIDEVICETYPE
    DIDEVTYPE_DEVICE              = 1
    DIDEVTYPE_HID             = 65536 (&H10000)
    DIDEVTYPE_JOYSTICK            = 4
    DIDEVTYPE_KEYBOARD            = 3
    DIDEVTYPE_MOUSE               = 2
    DIDEVTYPEJOYSTICK_FLIGHTSTICK = 3
    DIDEVTYPEJOYSTICK_GAMEPAD     = 4
    DIDEVTYPEJOYSTICK_HEADTRACKER = 7
    DIDEVTYPEJOYSTICK_RUDDER      = 5
    DIDEVTYPEJOYSTICK_TRADITIONAL = 2
    DIDEVTYPEJOYSTICK_UNKNOWN     = 1
    DIDEVTYPEJOYSTICK_WHEEL       = 6
    DIDEVTYPEKEYBOARD_J3100      = 12
    DIDEVTYPEKEYBOARD_JAPAN106   = 10
    DIDEVTYPEKEYBOARD_JAPANAX    = 11
    DIDEVTYPEKEYBOARD_NEC98       = 7
    DIDEVTYPEKEYBOARD_NEC98106    = 9
    DIDEVTYPEKEYBOARD_NEC98LAPTOP = 8
    DIDEVTYPEKEYBOARD_NOKIA1050   = 5
    DIDEVTYPEKEYBOARD_NOKIA9140   = 6
    DIDEVTYPEKEYBOARD_OLIVETTI    = 2
    DIDEVTYPEKEYBOARD_PCAT        = 3
    DIDEVTYPEKEYBOARD_PCENH       = 4
    DIDEVTYPEKEYBOARD_PCXT        = 1
    DIDEVTYPEKEYBOARD_UNKNOWN     = 0
    DIDEVTYPEMOUSE_FINGERSTICK    = 3
    DIDEVTYPEMOUSE_TOUCHPAD       = 4
    DIDEVTYPEMOUSE_TRACKBALL      = 5
    DIDEVTYPEMOUSE_TRADITIONAL    = 2
    DIDEVTYPEMOUSE_UNKNOWN        = 1
End Enum
DIDEVTYPE_DEVICE
A device that does not fall into the other categories.
DIDEVTYPE_HID
The device uses the Human Interface Device (HID) protocol.
DIDEVTYPE_JOYSTICK
A joystick or similar device, such as a steering wheel.
DIDEVTYPE_KEYBOARD
A keyboard or keyboard-like device.
DIDEVTYPE_MOUSE
A mouse or mouse-like device (such as a trackball).
DIDEVTYPEJOYSTICK_FLIGHTSTICK
A joystick optimized for flight simulation.
DIDEVTYPEJOYSTICK_GAMEPAD
A device whose primary purpose is to provide button input.
DIDEVTYPEJOYSTICK_HEADTRACKER
A device that tracks the movement of the user's head.
DIDEVTYPEJOYSTICK_RUDDER
A device for yaw control.
DIDEVTYPEJOYSTICK_TRADITIONAL
A traditional joystick.
DIDEVTYPEJOYSTICK_UNKNOWN
The subtype could not be determined.
DIDEVTYPEJOYSTICK_WHEEL
A steering wheel.
DIDEVTYPEKEYBOARD_J3100
Japanese J3100 keyboard.
DIDEVTYPEKEYBOARD_JAPAN106
Japanese 106-key keyboard.
DIDEVTYPEKEYBOARD_JAPANAX
Japanese AX keyboard.
DIDEVTYPEKEYBOARD_NEC98
Japanese NEC PC98 keyboard.
DIDEVTYPEKEYBOARD_NEC98106
Japanese NEC PC98 106-key keyboard.
DIDEVTYPEKEYBOARD_NEC98LAPTOP
Japanese NEC PC98 laptop keyboard.
DIDEVTYPEKEYBOARD_NOKIA1050
Nokia 1050 keyboard.
DIDEVTYPEKEYBOARD_NOKIA9140
Nokia 9140 keyboard.
DIDEVTYPEKEYBOARD_OLIVETTI
Olivetti 102-key keyboard.
DIDEVTYPEKEYBOARD_PCAT
IBM PC/AT 84-key keyboard.
DIDEVTYPEKEYBOARD_PCENH
IBM PC Enhanced 101/102-key or Microsoft Natural® keyboard.
DIDEVTYPEKEYBOARD_PCXT
IBM PC/XT 83-key keyboard.
DIDEVTYPEKEYBOARD_UNKNOWN
The subtype could not be determined.
DIDEVTYPEMOUSE_FINGERSTICK
The device is a fingerstick.
DIDEVTYPEMOUSE_TOUCHPAD
The device is a touchpad.
DIDEVTYPEMOUSE_TRACKBALL
The device is a trackball.
DIDEVTYPEMOUSE_TRADITIONAL
The device is a traditional mouse.
DIDEVTYPEMOUSE_UNKNOWN
The subtype could not be determined.


CONST_DIDFTFLAGS

Members of the CONST_DIDFTFLAGS enumeration are used in the flags parameter of the DirectInputDevice.GetDeviceObjectsEnum method to specify the type of device object to enumerate. These values are also returned by the DirectInputDeviceObjectInstance.GetFlags method to describe capabilities of the device object.

Enum CONST_DIDFTFLAGS
    DIDFT_ABSAXIS         =        2
    DIDFT_ALL             =        0
    DIDFT_ANYINSTANCE     = 16776960 (&HFFFF00)
    DIDFT_AXIS            =        3
    DIDFT_BUTTON          =       12
    DIDFT_COLLECTION      =       64 (&H40)
    DIDFT_FFACTUATOR      = 16777216 (&H1000000)
    DIDFT_FFEFFECTTRIGGER = 33554432 (&H2000000)
    DIDFT_INSTANCEMASK    = 16776960(&HFFFF00)
    DIDFT_NOCOLLECTION    = 16776960 (&HFFFF00)
    DIDFT_NODATA          =      128 (&H80)
    DIDFT_POV             =       16 (&H10)
    DIDFT_PSHBUTTON       =        4
    DIDFT_RELAXIS         =        1
    DIDFT_TGLBUTTON       =        8
End Enum
DIDFT_ABSAXIS
An absolute axis.
DIDFT_ALL
All objects.
DIDFT_ANYINSTANCE
Any instance of an object.
DIDFT_AXIS
An axis, either absolute or relative.
DIDFT_BUTTON
A push button or a toggle button.
DIDFT_COLLECTION
A HID link collection. HID link collections do not generate data of their own.
DIDFT_FFACTUATOR
An object that contains a force-feedback actuator. In other words, forces can be applied to this object.
DIDFT_FFEFFECTTRIGGER
An object that can be used to trigger force-feedback effects.
DIDFT_INSTANCEMASK
Same as DIDFT_ANYINSTANCE.
DIDFT_NOCOLLECTION
An object that does not belong to any HID link collection; in other words, an object for which DirectInputDeviceObjectInstance.GetCollectionNumber returns 0.
DIDFT_NODATA
An object that does not generate data.
DIDFT_POV
A point-of-view controller.
DIDFT_PSHBUTTON
A push button. A push button is reported as down when the user presses it and as up when the user releases it.
DIDFT_RELAXIS
A relative axis.
DIDFT_TGLBUTTON
A toggle button. A toggle button is reported as down when the user presses it and remains so until the user presses the button a second time.


CONST_DIDGDDFLAGS

Members of the CONST_DIDGDDFLAGS enumeration are used in the flags parameter of the DirectInputDevice.GetDeviceData method to control the manner in which data is obtained.

Enum CONST_DIDGDDFLAGS
    DIGDD_DEFAULT = 0
    DIGDD_PEEK    = 1
End Enum
DIGDD_DEFAULT
Remove retrieved items from the buffer.
DIGDD_PEEK
Do not remove retrieved items from the buffer. A subsequent GetDeviceData call will read the same data.


CONST_DIEFFFLAGS

Members of the CONST_DIEFFFLAGS enumeration are used in the lFlags member of the DIEFFECT type.

Enum CONST_DIEFFFLAGS
    DIEFF_CARTESIAN =    16 (&H10)
    DIEFF_OBJECTOFFSETS = 2
    DIEFF_POLAR =        32 (&H20)
End Enum
DIEFF_CARTESIAN
The direction of the effect is given in Cartesian coordinates. DIEFFECT.x and DIEFFECT.y contain valid values.
DIEFF_OBJECTOFFSETS
The value of the lTriggerButton member of DIEFFECT is the offset of the button in the data structure for the device.
DIEFF_POLAR
The direction of the effect is given in polar coordinates. DIEFFECT.x contains a valid value.

Remarks

The default behavior of DirectInputDevice.CreateEffect and DirectInputDevice.CreateCustomEffect is to create the effect as if DIEFFECT.lFlags contained (DIEFF_OBJECTOFFSETS Or DIEFF_POLAR). In other words, it is not necessary to specify these flags.


CONST_DIEFTFLAGS

Members of the CONST_DIEFTFLAGS enumeration describe types and capabilities of force-feedback effects. They are used to restrict effect enumeration in the DirectInputDevice.GetEffectsEnum method to one or more of the primary types. They are also returned by the DirectInputEnumEffects.GetType method.

Enum CONST_DIEFTFLAGS
    DIEFT_ALL =                   0
    DIEFT_CONDITION =             4
    DIEFT_CONSTANTFORCE =         1
    DIEFT_CUSTOMFORCE =           5
    DIEFT_DEADBAND =          16384 (&H4000)
    DIEFT_FFATTACK =            512 (&H200)
    DIEFT_FFFADE =             1024 (&H400)
    DIEFT_HARDWARE =            255 (&HFF)
    DIEFT_PERIODIC =              3
    DIEFT_POSNEGCOEFFICIENTS = 4096 (&H1000)
    DIEFT_POSNEGSATURATION =   8192 (&H2000)
    DIEFT_RAMPFORCE =             2
    DIEFT_SATURATION =         2048 (&H800)
End Enum
DIEFT_ALL
All effects are to be enumerated.
DIEFT_CONDITION
The effect is a condition, or conditions are to be enumerated.
DIEFT_CONSTANTFORCE
The effect is a constant force, or constant forces are to be enumerated.
DIEFT_CUSTOMFORCE
The effect is a custom force, or custom forces are to be enumerated.
DIEFT_DEADBAND
The effect supports deadband.
DIEFT_FFATTACK
The effect supports attack.
DIEFT_FFFADE
The effect supports fade.
DIEFT_HARDWARE
The effect is specific to the hardware, or hardware effects are to be enumerated.
DIEFT_PERIODIC
The effect is periodic, or periodic effects are to be enumerated.
DIEFT_POSNEGCOEFFICIENTS
The condition supports different positive and negative coefficients.
DIEFT_POSNEGSATURATION
The effect supports different positive and negative saturation_dx_saturation_glos.
DIEFT_RAMPFORCE
The effect is a ramp force, or ramp forces are to be enumerated.
DIEFT_SATURATION
The effect supports saturation.

See Also

CONST_DIDEVCAPSFLAGS


CONST_DIEGESFLAGS

Members of the CONST_DIEGESFLAGS enumeration are returned by the DirectInputEffect.GetEffectStatus method.

Enum CONST_DIEGESFLAGS
    DIEGES_EMULATED = 2
    DIEGES_PLAYING = 1
End Enum
DIEGES_EMULATED
The effect is emulated.
DIEGES_PLAYING
The effect is playing.


CONST_DIENUMDEVICESFLAGS

Members of the CONST_DIENUMDEVICESFLAGS enumeration are used in the flags parameter of the DirectInput.GetDIEnumDevices method to indicate whether all device, or only attached devices, are to be enumerated.

Enum CONST_DIENUMDEVICESFLAGS
    DIEDFL_ALLDEVICES  = 0
    DIEDFL_ATTACHEDONLY = 1
End Enum
DIEDFL_ALLDEVICES
All installed devices will be enumerated. This is the default behavior.
DIEDFL_ATTACHEDONLY
Only attached and installed devices.


CONST_DIEPFLAGS

Members of the CONST_DIEPFLAGS enumeration are passed to the DirectInputEffect.SetParameters method in order to specify which parameters are being set, and the subsequent behavior of the effect. Some members are also returned by the DirectInputEnumEffects.GetStaticParams and DirectInputEnumEffects.GetDynamicParams methods, giving information about support for the parameter.

Enum CONST_DIEPFLAGS
    DIEP_ALLPARAMS =            511 (&H1FF)
    DIEP_AXES =                  32 (&H20)
    DIEP_DIRECTION =             64 (&H40)
    DIEP_DURATION =               1
    DIEP_ENVELOPE =             128 (&H80)
    DIEP_GAIN =                   4
    DIEP_NODOWNLOAD =   -2147483648 (&H80000000)
    DIEP_NORESTART =     1073741824 (&H40000000)
    DIEP_SAMPLEPERIOD =           2
    DIEP_START =          536870912 (&H20000000)
    DIEP_TRIGGERBUTTON =          8
    DIEP_TRIGGERREPEATINTERVAL = 16 (&H10)
    DIEP_TYPESPECIFICPARAMS =   256 (&H100)
End Enum
DIEP_ALLPARAMS
Not used.
DIEP_AXES
Not used.
DIEP_DIRECTION
The x and y members of DIEFFECT are valid, or the direction parameter is supported. If you are setting or requesting effect parameters, you can specify that the direction is supplied or is to be returned in either Cartesian or polar coordinates by specifying DIEFF_CARTESIAN or DIEFF_POLAR in DIEFFECT.lFlags.
DIEP_DURATION
The lDuration member of DIEFFECT is valid, or the effect supports changing of the duration.
DIEP_ENVELOPE
The envelope member of DIEFFECT is valid, or the effect supports the application of an envelope.
DIEP_GAIN
The lGain member is valid, or the effect supports the application of gain.
DIEP_NODOWNLOAD
After setting parameters, the effect is not to be downloaded.
DIEP_NORESTART
Suppress the stopping and restarting of the effect in order to change parameters.
DIEP_SAMPLEPERIOD
The lSamplePeriod member is valid.
DIEP_START
After setting parameters, start the effect immediately.
DIEP_TRIGGERBUTTON
The lTriggerButton member is valid, or the effect supports a trigger button.
DIEP_TRIGGERREPEATINTERVAL
The lTriggerRepeatInterval member is valid, or the effect supports trigger repeat.
DIEP_TYPESPECIFICPARAMS
The effect has type-specific parameters that can be changed by the application. This value is returned by GetStaticParams for all standard effects and for hardware-specific effects with application-modifiable parameters. DirectX for Visual Basic supports hardware effects only if they do not have this flag set.


CONST_DIESFLAGS

The CONST_DIESFLAGS are used to control behavior of force-feedback effect playback.

Enum CONST_DIESFLAGS
    DIES_NODOWNLOAD  = -2147483648 (&H80000000)
    DIES_SOLO =                  1
End Enum
For an explanation of the members, see DirectInputEffect.Start.


CONST_DIGFFSFLAGS

Members of the CONST_DIGFFSFLAGS enumeration describe the state of a force-feedback device. They are returned by the DirectInputDevice.GetForceFeedbackState method.

Enum CONST_DIGFFSFLAGS
    DIGFFS_ACTUATORSOFF =        32 (&H20)
    DIGFFS_ACTUATORSON =         16 (&H10)
    DIGFFS_DEVICELOST = -2147483648 (&H80000000)
    DIGFFS_EMPTY =                1
    DIGFFS_PAUSED =               4
    DIGFFS_POWEROFF =           128 (&H80)
    DIGFFS_POWERON =             64 (&H40)
    DIGFFS_SAFETYSWITCHOFF =    512 (&H200)
    DIGFFS_SAFETYSWITCHON =     256 (&H100)
    DIGFFS_STOPPED =              2
    DIGFFS_USERFFSWITCHOFF =   2048 (&H800)
    DIGFFS_USERFFSWITCHON =    1024 (&H400)
End Enum
DIGFFS_ACTUATORSOFF
The device's force-feedback actuators are disabled.
DIGFFS_ACTUATORSON
The device's force-feedback actuators are enabled.
DIGFFS_DEVICELOST
The device suffered an unexpected failure and is in an indeterminate state. It must be reset either by unacquiring and reacquiring the device, or by sending a DISFFC_RESET command.
DIGFFS_EMPTY
The device has no downloaded effects.
DIGFFS_PAUSED
Playback of all active effects has been paused.
DIGFFS_POWEROFF
The force-feedback system is not currently available. If the device cannot report the power state, then neither DIGFFS_POWERON nor DIGFFS_POWEROFF will be returned.
DIGFFS_POWERON
Power to the force-feedback system is currently available. If the device cannot report the power state, then neither DIGFFS_POWERON nor DIGFFS_POWEROFF will be returned.
DIGFFS_SAFETYSWITCHOFF
The safety switch is currently off, meaning that the device cannot operate. If the device cannot report the state of the safety switch, then neither DIGFFS_SAFETYSWITCHON nor DIGFFS_SAFETYSWITCHOFF will be returned.
DIGFFS_SAFETYSWITCHON
The safety switch is currently on, meaning that the device can operate. If the device cannot report the state of the safety switch, then neither DIGFFS_SAFETYSWITCHON nor DIGFFS_SAFETYSWITCHOFF will be returned.
DIGFFS_STOPPED
No effects are playing and the device is not paused.
DIGFFS_USERFFSWITCHOFF
The user force-feedback switch is currently off, meaning that the device cannot operate. If the device cannot report the state of the user force-feedback switch, then neither DIGFFS_USERFFSWITCHON nor DIGFFS_USERFFSWITCHOFF will be returned.
DIGFFS_USERFFSWITCHON
The user force-feedback switch is currently on, meaning that the device can operate. If the device cannot report the state of the user force-feedback switch, then neither DIGFFS_USERFFSWITCHON nor DIGFFS_USERFFSWITCHOFF will be returned.


CONST_DIJOYSTICKOFS

The members of the CONST_DIJOYSTICKOFS enumeration represent the offset of the data for the various joystick device objects within the data format.

Enum CONST_DIJOYSTICKOFS
    DIJOFS_BUTTON0 =  48 (&H30)
    DIJOFS_BUTTON1 =  49 (&H31)
    DIJOFS_BUTTON10 = 58 (&H3A)
    DIJOFS_BUTTON11 = 59 (&H3B)
    DIJOFS_BUTTON12 = 60 (&H3C)
    DIJOFS_BUTTON13 = 61 (&H3D)
    DIJOFS_BUTTON14 = 62 (&H3E)
    DIJOFS_BUTTON15 = 63 (&H3F)
    DIJOFS_BUTTON16 = 64 (&H40)
    DIJOFS_BUTTON17 = 65 (&H41)
    DIJOFS_BUTTON18 = 66 (&H42)
    DIJOFS_BUTTON19 = 67 (&H43)
    DIJOFS_BUTTON2 =  50 (&H32)
    DIJOFS_BUTTON20 = 68 (&H44)
    DIJOFS_BUTTON21 = 69 (&H45)
    DIJOFS_BUTTON22 = 70 (&H46)
    DIJOFS_BUTTON23 = 71 (&H47)
    DIJOFS_BUTTON24 = 72 (&H48)
    DIJOFS_BUTTON25 = 73 (&H49)
    DIJOFS_BUTTON26 = 74 (&H4A)
    DIJOFS_BUTTON27 = 75 (&H4B)
    DIJOFS_BUTTON28 = 76 (&H4C)
    DIJOFS_BUTTON29 = 77 (&H4D)
    DIJOFS_BUTTON3 =  51 (&H33)
    DIJOFS_BUTTON30 = 78 (&H4E)
    DIJOFS_BUTTON31 = 79 (&H4F)
    DIJOFS_BUTTON4 =  52 (&H34)
    DIJOFS_BUTTON5 =  53 (&H35)
    DIJOFS_BUTTON6 =  54 (&H36)
    DIJOFS_BUTTON7 =  55 (&H37)
    DIJOFS_BUTTON8 =  56 (&H38)
    DIJOFS_BUTTON9 =  57 (&H39)
    DIJOFS_POV0 =     32 (&H20)
    DIJOFS_POV1 =     36 (&H24)
    DIJOFS_POV2 =     40 (&H28)
    DIJOFS_POV3 =     44 (&H2C)
    DIJOFS_RX =       12
    DIJOFS_RY =       16 (&H10)
    DIJOFS_RZ =       20 (&H14)
    DIJOFS_SLIDER0 =  24 (&H18)
    DIJOFS_SLIDER1 =  28 (&H1C)
    DIJOFS_X =         0
    DIJOFS_Y =         4
    DIJOFS_Z =         8
End Enum
DIJOFS_BUTTON(n)
Offset of the data for button n.
DIJOFS_POV(n)
Offset of the data for point-of-view controller n.
DIJOFS_RX, DIJOFS_RY, DIJOFS_RZ
Offset of the data for the axis rotation.
DIJOFS_SLIDER0, DIJOFS_SLIDER1
Offset of the data for the slider.
DIJOFS_X, DIJOFS_Y, DIJOFS_Z
Offset of the data for the axis.


CONST_DIKEYFLAGS

The CONST_DIKEYFLAGS enumeration groups the Keyboard Device Constants.


CONST_DIMOUSEOFS

The members of the CONST_DIMOUSEOFS enumeration represent the offset of the data for the various mouse device objects within the data format.

Enum CONST_DIMOUSEOFS
    DIMOFS_BUTTON0 = 12
    DIMOFS_BUTTON1 = 13
    DIMOFS_BUTTON2 = 14
    DIMOFS_BUTTON3 = 15
    DIMOFS_X =        0
    DIMOFS_Y =        4
    DIMOFS_Z =        8
End Enum
DIMOFS_BUTTON(n)
Offset of the data for button n.
DIMOFS_X, DIMOFS_Y, DIMOFS_Z
Offset of the data for the axis.


CONST_DINPUT

The CONST_DINPUT enumeration contains various constants that are used throughout DirectInput.

Enum CONST_DINPUT
    DIPROPAXISMODE_ABS =           0
    DIPROPAXISMODE_REL =           1
    DIPROPCALIBRATIONMODE_COOKED = 0
    DIPROPCALIBRATIONMODE_RAW =    1
    DIPROPRANGE_NOMAX =   2147483647 (&H7FFFFFFF)
    DIPROPRANGE_NOMIN =  -2147483648 (&H80000000)
End Enum
DIPROPAXISMODE_ABS
Used in DirectInputDevice.GetProperty and DirectInputDevice.SetProperty to represent absolute axis mode.
DIPROPAXISMODE_REL
Used in DirectInputDevice.GetProperty and DirectInputDevice.SetProperty to represent relative axis mode.
DIPROPCALIBRATIONMODE_COOKED
Used in setting the DIPROP_CALIBRATIONMODE property to indicate that DirectInput should return axis data after applying calibration information.
DIPROPCALIBRATIONMODE_RAW
Used in setting the DIPROP_CALIBRATIONMODE property to indicate that DirectInput should return raw, uncalibrated data. This mode is typically used only by Control Panel–type applications.
DIPROPRANGE_NOMAX
Returned from DirectInputDevice.GetProperty if the axis has no upper limit on its range.
DIPROPRANGE_NOMIN
Returned from DirectInputDevice.GetProperty if the axis has no lower limit on its range.


CONST_DINPUTERR

The CONST_DINPUTERR enumeration contains the error codes for DirectInput. All the error codes and definitions can be found in the Error Codes topic.


CONST_DIPHFLAGS

Members of the CONST_DIPHFLAGS enumeration are used to specify how a device object is identified. They are used in the DirectInputDevice.GetObjectInfo method as well as in the DIPROPLONG and DIPROPRANGE types.

Enum CONST_DIPHFLAGS
    DIPH_DEVICE  =  0
    DIPH_BYID  =    2
    DIPH_BYOFFSET = 1
End Enum
DIPH_DEVICE
The property applies to the entire device, not to a particular object.
DIPH_BYOFFSET
The device object is identified by the offset into the current data format of the object whose information is being accessed.
DIPH_BYID
The device object is identified by the instance identifier obtained from the return value of the DirectInputDeviceObjectInstance.GetType method.


CONST_DISCLFLAGS

The CONST_DISCLFLAGS enumeration is used in the flags parameter of the DirectInputDevice.SetCooperativeLevel method to determine how the device interacts with other instances of the device and the rest of the system.

Enum CONST_DISCLFLAGS
    DISCL_BACKGROUND   = 8
    DISCL_EXCLUSIVE    = 1
    DISCL_FOREGROUND   = 4
    DISCL_NONEXCLUSIVE = 2
End Enum
DISCL_BACKGROUND
The application requires background access. If background access is granted, the device may be acquired at any time, even when the associated window is not the active window.
DISCL_EXCLUSIVE
The application requires exclusive access. If exclusive access is granted, no other instance of the device may obtain exclusive access to the device while it is acquired. Note, however, non-exclusive access to the device is always permitted, even if another application has obtained exclusive access.

If an application acquires the mouse or keyboard device in exclusive mode, the user will not be able to use the window menu or move and resize the window.

DISCL_FOREGROUND
The application requires foreground access. If foreground access is granted, the device is automatically unacquired when the associated window moves to the background.
DISCL_NONEXCLUSIVE
The application requires non-exclusive access. Access to the device will not interfere with other applications that are accessing the same device.

Applications must specify either DISCL_FOREGROUND or DISCL_BACKGROUND; it is an error to specify both or neither. Similarly, applications must specify either DISCL_EXCLUSIVE or DISCL_NONEXCLUSIVE.


CONST_DISDDFLAGS

Members of the CONST_DISDDFLAGS enumeration are passed to the DirectInputDevice.SendDeviceData method.

Enum CONST_DISDDCFLAGS
    DISDD_CONTINUE = 1
    DISDD_DEFAULT =  0
End Enum
DISDD_CONTINUE
Data will overlaid on existing data. For more information, see the Remarks for DirectInputDevice.SendDeviceData.
DISDD_DEFAULT
Data will not be overlaid on existing data.


CONST_DISFFCFLAGS

Members of the CONST_DISFFCFLAGS enumeration are used to specify the command sent by using the DirectInputDevice.SendForceFeedbackCommand method.

Enum CONST_DISFFCFLAGS
    DISFFC_CONTINUE =         8
    DISFFC_PAUSE =            4
    DISFFC_RESET =            1
    DISFFC_SETACTUATORSOFF = 32 (&H20)
    DISFFC_SETACTUATORSON =  16 (&H10)
    DISFFC_STOPALL =          2
End Enum
DISFFC_CONTINUE
Paused playback of all active effects is to be continued. It is an error to send this command when the device is not in a paused state.
DISFFC_PAUSE
Playback of all active effects is to be paused. This command also stops the clock on effects, so that they continue playing to their full duration when restarted.

While the device is paused, new effects may not be started and existing ones may not be modified. Doing so may result in the subsequent DISFFC_CONTINUE command failing to perform properly.

To abandon a pause and stop all effects, use the DISFFC_STOPALL or DISFCC_RESET commands.

DISFFC_RESET
The device's force-feedback system is to be put in its startup state. All effects are removed from the device, are no longer valid, and must be recreated if they are to be used again. The device's actuators are disabled.
DISFFC_SETACTUATORSOFF
The device's force-feedback actuators are to be disabled. While the actuators are off, effects continue to play but are ignored by the device. Using the analogy of a sound playback device, they are muted rather than paused.
DISFFC_SETACTUATORSON
The device's force-feedback actuators are to be enabled.
DISFFC_STOPALL
Playback of any active effects is to be stopped. All active effects will be reset, but are still being maintained by the device and are still valid. If the device is in a paused state, that state is lost.

This command is equivalent to calling the DirectInputEffect.Stop method for each effect playing.


Keyboard Keys

This section contains information on the following topics:

  • Keyboard Device Constants
  • DirectInput and Japanese Keyboards


Keyboard Device Constants

Keyboard device constants, which are members of the CONST_DIKEYFLAGS enumeration, represent offsets within a keyboard device's data packet, a 256-byte array. The data at a given offset is associated with a keyboard key.

The standard keyboard device constants are the following (in ascending order):

Constant | Note
DIK_ESCAPE |
DIK_1 | On main keyboard
DIK_2 | On main keyboard
DIK_3 | On main keyboard
DIK_4 | On main keyboard
DIK_5 | On main keyboard
DIK_6 | On main keyboard
DIK_7 | On main keyboard
DIK_8 | On main keyboard
DIK_9 | On main keyboard
DIK_0 | On main keyboard
DIK_MINUS | On main keyboard
DIK_EQUALS | On main keyboard
DIK_BACK | BACKSPACE
DIK_TAB |
DIK_Q |
DIK_W |
DIK_E |
DIK_R |
DIK_T |
DIK_Y |
DIK_U |
DIK_I |
DIK_O |
DIK_P |
DIK_LBRACKET | [
DIK_RBRACKET | ]
DIK_RETURN | ENTER on main keyboard
DIK_LCONTROL | Left CTRL
DIK_A |
DIK_S |
DIK_D |
DIK_F |
DIK_G |
DIK_H |
DIK_J |
DIK_K |
DIK_L |
DIK_SEMICOLON |
DIK_APOSTROPHE |
DIK_GRAVE | Grave accent (`)
DIK_LSHIFT | Left SHIFT
DIK_BACKSLASH |
DIK_Z |
DIK_X |
DIK_C |
DIK_V |
DIK_B |
DIK_N |
DIK_M |
DIK_COMMA |
DIK_PERIOD | On main keyboard
DIK_SLASH | Forward slash (/)on main keyboard
DIK_RSHIFT | Right SHIFT
DIK_MULTIPLY | Asterisk on numeric keypad
DIK_LMENU | Left ALT
DIK_SPACE | Spacebar
DIK_CAPITAL | CAPS LOCK
DIK_F1 |
DIK_F2 |
DIK_F3 |
DIK_F4 |
DIK_F5 |
DIK_F6 |
DIK_F7 |
DIK_F8 |
DIK_F9 |
DIK_F10 |
DIK_NUMLOCK |
DIK_SCROLL | SCROLL LOCK
DIK_NUMPAD7 |
DIK_NUMPAD8 |
DIK_NUMPAD9 |
DIK_SUBTRACT | Hyphen (minus sign) on numeric keypad
DIK_NUMPAD4 |
DIK_NUMPAD5 |
DIK_NUMPAD6 |
DIK_ADD | Plus sign on numeric keypad
DIK_NUMPAD1 |
DIK_NUMPAD2 |
DIK_NUMPAD3 |
DIK_NUMPAD0 |
DIK_DECIMAL | Period (decimal point) on numeric keypad
DIK_F11 |
DIK_F12 |
DIK_F13 |
DIK_F14 |
DIK_F15 |
DIK_KANA | On Japanese keyboard
DIK_CONVERT | On Japanese keyboard
DIK_NOCONVERT | On Japanese keyboard
DIK_YEN | On Japanese keyboard
DIK_NUMPADEQUALS | On numeric keypad (NEC PC98)
DIK_CIRCUMFLEX | On Japanese keyboard
DIK_AT | On Japanese keyboard
DIK_COLON | On Japanese keyboard
DIK_UNDERLINE | On Japanese keyboard
DIK_KANJI | On Japanese keyboard
DIK_STOP | On Japanese keyboard
DIK_AX | On Japanese keyboard
DIK_UNLABELED | On Japanese keyboard
DIK_NUMPADENTER |
DIK_RCONTROL | Right CTRL key
DIK_NUMPADCOMMA | Comma on NEC PC98 numeric keypad
DIK_DIVIDE | Forward slash (/)on numeric keypad
DIK_SYSRQ |
DIK_RMENU | Right ALT
DIK_HOME |
DIK_UP | Up arrow
DIK_PRIOR | PAGE UP
DIK_LEFT | Left arrow
DIK_RIGHT | Right arrow
DIK_END |
DIK_DOWN | Down arrow
DIK_NEXT | PAGE DOWN
DIK_INSERT |
DIK_DELETE |
DIK_LWIN | Left Windows key
DIK_RWIN | Right Windows key
DIK_APPS | Application key
DIK_PAUSE |

For information on Japanese keyboards, see DirectInput and Japanese Keyboards.


DirectInput and Japanese Keyboards

There are substantial differences between Japanese and U.S. keyboards. The following chart lists the additional keys that are available on each type of Japanese keyboard. It also lists the keys that are available on U.S. keyboards but are missing on the various Japanese keyboards.

Also note that on some NEC PC-98 keyboards, the DIK_CAPSLOCK and DIK_KANA keys are toggle buttons and not push buttons. These generate a down event when first pressed, then generate an up event when pressed a second time.

Keyboard | Additional Keys | Missing Keys
DOS/V 106 Keyboard, NEC PC-98 106 Keyboard | DIK_AT, DIK_CIRCUMFLEX, DIK_COLON, DIK_CONVERT, DIK_KANA, DIK_KANJI, DIK_NOCONVERT, DIK_YEN | DIK_APOSTROPHE, DIK_EQUALS, DIK_GRAVE
NEC PC-98 Standard Keyboard, NEC PC-98 Laptop Keyboard | DIK_AT, DIK_CIRCUMFLEX, DIK_COLON, DIK_F13, DIK_F14, DIK_F15, DIK_KANA, DIK_KANJI, DIK_NOCONVERT, DIK_NUMPADCOMMA, DIK_NUMPADEQUALS, DIK_STOP, DIK_UNDERLINE, DIK_YEN | DIK_APOSTROPHE, DIK_BACKSLASH, DIK_EQUALS, DIK_GRAVE, DIK_NUMLOCK, DIK_NUMPADENTER, DIK_RCONTROL, DIK_RMENU, DIK_RSHIFT, DIK_SCROLL
AX Keyboard | DIK_AX, DIK_CONVERT, DIK_KANJI, DIK_NOCONVERT, DIK_YEN | DIK_RCONTROL, DIK_RMENU
J-3100 Keyboard | DIK_KANA, DIK_KANJI, DIK_NOLABEL, DIK_YEN | DIK_RCONTROL, DIK_RMENU


Error Codes

This table lists the error codes that can be returned by DirectInput methods and functions. Errors are represented by negative values and cannot be combined.

For a list of the errors each method or function can raise, see the individual descriptions. Lists of error codes in the documentation are necessarily incomplete. For example, any DirectInput method can return DIERR_OUTOFMEMORY even though the error code is not explicitly listed as a possible return value in the documentation for that method.

DI_BUFFEROVERFLOW
The input buffer overflowed and data was lost.
DIERR_ACQUIRED
The operation cannot be performed while the device is acquired.
DIERR_ALREADYINITIALIZED
This object is already initialized
DIERR_BADDRIVERVER
The object could not be created due to an incompatible driver version or mismatched or incomplete driver components.
DIERR_BETADIRECTINPUTVERSION
The application was written for an unsupported prerelease version of DirectInput.
DIERR_DEVICEFULL
The device is full.
DIERR_DEVICENOTREG
The device or device instance is not registered with DirectInput. This value is equal to the REGDB_E_CLASSNOTREG standard COM return value.
DIERR_EFFECTPLAYING
The parameters were updated in memory but were not downloaded to the device because the device does not support updating an effect while it is still playing.
DIERR_HASEFFECTS
The device cannot be reinitialized because there are still effects attached to it.
DIERR_GENERIC
An undetermined error occurred inside the DirectInput subsystem. This value is equal to the E_FAIL standard COM return value.
DIERR_HANDLEEXISTS
The device already has an event notification associated with it. This value is equal to the E_ACCESSDENIED standard COM return value.
DIERR_INCOMPLETEEFFECT
The effect could not be downloaded because essential information is missing. For example, no axes have been associated with the effect, or no type-specific information has been supplied.
DIERR_INPUTLOST
Access to the input device has been lost. It must be reacquired.
DIERR_INVALIDHANDLE
An invalid window handle was passed to the method.
DIERR_INVALIDPARAM
An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard COM return value.
DIERR_MOREDATA
Not all the requested information fitted into the buffer.
DIERR_NOAGGREGATION
This object does not support aggregation.
DIERR_NOINTERFACE
The specified interface is not supported by the object. This value is equal to the E_NOINTERFACE standard COM return value.
DIERR_NOTACQUIRED
The operation cannot be performed unless the device is acquired.
DIERR_NOTBUFFERED
The device is not buffered. Set the DIPROP_BUFFERSIZE property to enable buffering.
DIERR_NOTDOWNLOADED
The effect is not downloaded.
DIERR_NOTEXCLUSIVEACQUIRED
The operation cannot be performed unless the device is acquired in DISCL_EXCLUSIVE mode.
DIERR_NOTINITIALIZED
The object has not been initialized.
DIERR_NOTFOUND
The requested object does not exist.
DIERR_OBJECTNOTFOUND
The requested object does not exist.
DIERR_OLDDIRECTINPUTVERSION
The application requires a newer version of DirectInput.
DIERR_OTHERAPPHASPRIO
Another application has a higher priority level, preventing this call from succeeding. This value is equal to the E_ACCESSDENIED standard COM return value. This error can be returned when an application has only foreground access to a device but is attempting to acquire the device while in the background.
DIERR_OUTOFMEMORY
The DirectInput subsystem couldn't allocate sufficient memory to complete the call. This value is equal to the E_OUTOFMEMORY standard COM return value.
DIERR_READONLY
The specified property cannot be changed. This value is equal to the E_ACCESSDENIED standard COM return value.
DIERR_REPORTFULL
More information was requested to be sent than can be sent to the device.
DIERR_UNPLUGGED
The operation could not be completed because the device is not plugged in.
DIERR_UNSUPPORTED
The function called is not supported at this time. This value is equal to the E_NOTIMPL standard COM return value.
E_PENDING
Data is not yet available.


DirectInput Tools and Samples

This section describes tools and sample applications included with the DirectX SDK that pertain to DirectInput. Descriptions are organized as follows:

  • DirectInput Tools
  • DirectInput C/C++ Samples
  • DirectInput Visual Basic Samples


DirectInput Tools

The following tools are provided for use with DirectInput:

  • DirectInput QuickTest
  • Force Editor


DirectInput QuickTest

Description

The DirectInput QuickTest application allows you to see the properties of devices and device objects, and to see the input data from a device.

Path

Executable: (SDK root)\Samples\Multimedia\DInput\Bin\Diquick.exe

User's Guide

On the opening screen, select a device and click the Create button. If the device is successfully created, you see a property sheet with four different tabbed pages.

On the Mode tabbed page, choose a cooperative level, a data mode, and an axis mode. For a joystick, you will have to choose the polled data mode. You also need to confirm the device type in the "Form of" box. If you want to see buffered data, you must set the buffer size to greater than zero on this tabbed page.

The Caps tabbed page gives you miscellaneous information about the device.

On the Objects tabbed page you can enumerate selected buttons and axes on the device. The Properties button brings up a summary of the data represented by the DIDEVICEOBJECTINSTANCE structure (C++) or DirectInputDeviceObjectInstance object (Visual Basic) for the selected object. You can also set the range, deadzone, and saturation for an axis on this property sheet.

Finally, on the Data tabbed page you see input data from the device: immediate data on the left, and buffered data (if you've set a buffer size) on the right.


Force Editor

Description

The Force Editor application lets you design force-feedback effects and test them singly or in combination. Effects can be saved to file and then loaded into DirectInput applications.

Path

Executable: (SDK root)\Bin\Dxutils\Fedit.exe

User's Guide

Press F1 for online help.


DirectInput C/C++ Samples

[Visual Basic]

This section pertains only to application development in C and C++. See DirectInput Visual Basic Samples.

[C++]

The following sample programs demonstrate the use and capabilities of DirectInput:

  • DIGame Sample
  • FFDonuts Sample
  • FFFileRead Sample
  • JoyFFeed Sample
  • JoystImm Sample
  • KeybdBuf Sample
  • KeybdExc Sample
  • KeybdImm Sample
  • MouseExc Sample
  • MouseNon Sample
  • Scrawl Sample

In addition, amply commented source code illustrating basic DirectInput functionality is available at the following location:

(SDK root)\Samples\Multimedia\DInput\Src\Tutorials

Although DirectX samples include Microsoft® Visual C++® project workspace files, you might need to verify other settings in your development environment to ensure that the samples compile properly. For more information, see Compiling DirectX Samples and Other DirectX Applications.


DIGame Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectInput Visual Basic Samples.

[C++]

Description

The DIGame sample application is a simple shooting game that can be played with keyboard, mouse, or joystick.

Path

Source: (SDK root)\Samples\Multimedia\DInput\Src\DIGame

Executable: (SDK root)\Samples\Multimedia\DInput\Bin

User's Guide

The default input device is the keyboard. Change the device by choosing Select Input Device from the File menu.

Move the ship up and down with the arrow keys, the mouse, or the joystick. Change directions by moving left or right. Fire by pressing the spacebar, the left mouse button, or the primary button on the joystick.

To start again, select New Game from the File menu.

Programming Notes

The input code is all in Digame.cpp.


FFDonuts Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectInput Visual Basic Samples.

[C++]

Description

This is a variation on the Space Donuts sample program that adds force-feedback output if a force-feedback joystick is installed in your computer.

Path

Source: (SDK root)\Samples\Multimedia\DInput\Src\FFdonuts

Executable: (SDK root)\Samples\Multimedia\DInput\Bin

User's Guide

When the program is started, you see a dialog box that lets you set the magnitude of the force-feedback effects.

When your ship appears, move the joystick forward to accelerate forward and pull it back to decelerate or move backward. Moving the joystick left or right rotates the ship. Press the trigger button to fire. Press the second button to activate the shields. Observe the force-feedback effects as you fire, collide with objects, and bounce off the edge of the screen.

Programming Notes

The force-feedback routines are in the Input.c file. The program illustrates the use of constant and periodic effects, envelopes, and gain. Note that the fire-button effect is played in response to an ordinary input event rather than being associated with a trigger button in the DIEFFECT structure.

See Also

Space Donuts (DirectDraw sample)


FFFileRead Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectInput Visual Basic Samples.

[C++]

Description

This sample shows how to read and create effects from a file created by Force Editor.

Path

Source: (SDK root)\Samples\Multimedia\DInput\Src\FFFileRead

Executable: (SDK root)\Samples\Multimedia\DInput\Bin\FFeedFileRead.exe

Media: (SDK root)\Samples\Multimedia\DInput\Media

User's Guide

Click Read File and load a supplied .ffe file from the Media folder or one of your own files. Then click Play Effects.

Programming Notes

For each file effect enumerated, the EnumAndCreateEffectsCallback function initializes an IDirectInputEffect pointer and adds it to a linked list. The OnPlayEffects function traverses this list and plays all effects.


JoyFFeed Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectInput Visual Basic Samples.

[C++]

Description

This application applies raw forces to a force-feedback joystick, illustrating how a simulator-type application can use force feedback to generate forces computed by a physics engine.

You must have a force-feedback device connected to your system in order to run the application.

Path

Source: (SDK root)\Samples\Multimedia\DInput\Src\JoyFFeed

Executable: (SDK root)\Samples\Multimedia\DInput\Bin

User's Guide

When you run the application, it displays a window with a crosshair and a black spot in it. Click the mouse anywhere within the window's client area to move the black spot. (Note that moving the joystick handle does not do anything.) JoyFFeed exerts a constant force on the joystick handle from the direction of the spot, in proportion to the distance from the crosshair. You can also hold down the mouse button and move the spot continuously.

Programming Notes

This sample program enumerates the input devices and acquires the first force-feedback joystick that it finds. If none are detected, it displays a message and terminates.

When the user moves the black spot, the joySetForcesXY function converts the cursor coordinates to a force direction and magnitude. This data is used to modify the parameters of the constant force effect.


JoystImm Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectInput Visual Basic Samples.

[C++]

Description

The JoystImm sample obtains and displays joystick data.

Path

Source: (SDK root)\Samples\Multimedia\DInput\Src\JoystImm

Executable: (SDK root)\Samples\Multimedia\DInput\Bin

User's Guide

Observe how the displayed data changes when you move and twist the stick, rotate the throttle wheel, and press buttons in various combinations.

Programming Notes

The application polls the joystick for immediate data in response to a timer set inside the dialog procedure.


KeybdBuf Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectInput Visual Basic Samples.

[C++]

Description

The KeybdBuf program obtains and displays keyboard data.

Path

Source: (SDK root)\Samples\Multimedia\DInput\src\KeybdBuf

Executable: (SDK root)\Samples\Multimedia\DInput\bin

User's Guide

Each time you press or release a key, the event is recorded on the screen. Keys are identified by their index values (see Keyboard Device Constants).

Programming Notes

This sample illustrates how an application can use DirectInput to obtain buffered keyboard data.


KeybdExc Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectInput Visual Basic Samples.

[C++]

Description

The KeybdExc sample shows how to use the keyboard at the exclusive cooperative level.

Path

Source: (SDK root)\Samples\Multimedia\DInput\Src\KeybdExc

Executable: (SDK root)\Samples\Multimedia\DInput\Bin\KeybdExc.exe

User's Guide

Hold down one or more keys and the index value of each key (see Keyboard Device Constants) is shown. Note that the Windows key does not activate the system Start menu, as it does in the KeybdImm Sample.

Programming Notes

This sample illustrates how an application can use DirectInput to obtain immediate keyboard data at the exclusive foreground cooperative level. The application repeatedly calls IDirectInputDevice7::GetDeviceState and displays a string containing the values of all the keys that are down.


KeybdImm Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectInput Visual Basic Samples.

[C++]

Description

The KeybdImm program obtains and displays keyboard data.

Path

Source: (SDK root)\Samples\Multimedia\DInput\Src\KeybdImm

Executable: (SDK root)\Samples\Multimedia\DInput\Bin

User's Guide

Hold down one or more keys and the index value of each key (see Keyboard Device Constants) is shown.

Programming Notes

This sample illustrates how an application can use DirectInput to obtain immediate keyboard data at the nonexclusive foreground cooperative level. The application repeatedly calls IDirectInputDevice7::GetDeviceState and displays a string containing the values of all the keys that are down.


MouseExc Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectInput Visual Basic Samples.

[C++]

Description

The MouseExc program demonstrates how to initialize and get immediate data from a DirectInput device.

Path

Source: (SDK root)\Samples\Multimedia\DInput\Src\MouseExc

Executable: (SDK root)\Samples\Multimedia\DInput\Bin

User's Guide

Move the mouse around and observe how the change in coordinates is displayed. Hold down a mouse button and its number is shown. Note that the system cursor is not present.

Programming Notes

This sample illustrates how an application can use DirectInput to obtain relative mouse data in exclusive foreground mode. Approximately 30 times per second the program displays the change in mouse coordinates since the last call to IDirectInputDevice7::GetDeviceState.


MouseNon Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectInput Visual Basic Samples.

[C++]

Description

The MouseNon program demonstrates how to initialize and get immediate data from a DirectInput device.

Path

Source: (SDK root)\Samples\Multimedia\DInput\Src\MouseNon

Executable: (SDK root)\Samples\Multimedia\DInput\Bin

User's Guide

Move the mouse around and observe how the change in coordinates is displayed. Hold down a mouse button and its number is shown. Note that the cursor doesn't have to be in the application window, but the application does have to be in the foreground.

Programming Notes

This sample illustrates how an application can use DirectInput to obtain relative mouse data in non-exclusive foreground mode. Approximately 30 times per second the program displays the change in mouse coordinates since the last call to IDirectInputDevice7::GetDeviceState.


Scrawl Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectInput Visual Basic Samples.

[C++]

Description

The Scrawl application demonstrates use of the mouse in exclusive mode in a windowed application.

Path

Source: (SDK root)\Samples\Multimedia\DInput\Src\Scrawl

Executable: (SDK root)\Samples\Multimedia\DInput\Bin

User's Guide

The main mouse button is always the left button, and the secondary button is always the right button, regardless of any settings the user may have made in Control Panel.

To scrawl, hold down the left button and move the mouse. Click the right mouse button to invoke a pop-up menu. From the pop-up menu you can clear the client window, set the mouse sensitivity, or close the application.

Programming Notes

The Scrawl application demonstrates many aspects of DirectInput programming, including the following:

  • Using the mouse in exclusive mode in a windowed application.
  • Releasing the mouse when Windows needs to use it for menu access.
  • Reacquiring the mouse when Windows no longer needs it.
  • Reading buffered device data.
  • Deferring screen updates till movement on both axes has been fully processed.
  • Event notifications of device activity.
  • Restricting the cursor to an arbitrary region.
  • Scaling raw mouse coordinates before using them.
  • Using relative axis mode.


DirectInput Visual Basic Samples

[C++]

This section pertains only to application development in Visual Basic. See DirectInput C/C++ Samples.

[Visual Basic]

The following sample programs demonstrate the use and capabilities of DirectInput:

  • ForceFeedback Sample
  • Joystick Sample
  • Keyboard Sample
  • ScrawlB Sample


ForceFeedback Sample

[C++]

This topic pertains only to application development in Visual Basic. See DirectInput C/C++ Samples.

[Visual Basic]

Description

This sample is a simple force-feedback editor that allows you to create an effect, set parameters, and play the effect.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\Dinput\Src\FFeedback

Executable: (SDK root)\Samples\Multimedia\VBSamples\Dinput\Bin\ForceFeedback.exe

User's Guide

Select an effect type from the list, and modify the parameters. Play the effect by pressing the primary button on the joystick.

Programming Notes

The sample shows how to turn off the autocenter property and how to create and modify effects. Changes in effect parameters are applied immediately.


Joystick Sample

[C++]

This topic pertains only to application development in Visual Basic. See DirectInput C/C++ Samples.

[Visual Basic]

Description

The Joystick sample shows how to enumerate joysticks, set joystick properties, and get immediate data.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\Dinput\Src\Joystick

Executable: (SDK root)\Samples\Multimedia\VBSamples\Dinput\Bin\Joystick.exe

User's Guide

Select a joystick from the list. The data from the axes and buttons is displayed.

Programming Notes

The list box is unsorted so that the selection can easily be retrieved from the DirectInputEnumDevices collection.


Keyboard Sample

[C++]

This topic pertains only to application development in Visual Basic. See DirectInput C/C++ Samples.

[Visual Basic]

Description

The Keyboard sample shows how to create a keyboard device and retrieve immediate data from it.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\Dinput\Src\Keyboard

Executable: (SDK root)\Samples\Multimedia\VBSamples\Dinput\Bin\Keyboard.exe

User's Guide

As you hold down one or more keys, the names of the keys (from CONST_DIKEYFLAGS) are shown in the list box.

Programming Notes

The background cooperative level is used, so keys are read even when the application does not have the input focus.


ScrawlB Sample

[C++]

This topic pertains only to application development in Visual Basic. See DirectInput C/C++ Samples.

[Visual Basic]

Description

The ScrawlB sample shows how to use the mouse in exclusive mode, how to use event notification for mouse events, and how to retrieve and interpret buffered data.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\Dinput\Src\Scrawlb

Executable: (SDK root)\Samples\Multimedia\VBSamples\Dinput\Bin\Scrawlb.exe

User's Guide

Hold down the left button to draw. Click the right button to see a context menu. Choosing Suspend (or pressing and releasing ALT) releases the system cursor so you can move or resize the window or click on another application. Click on the client window again to resume drawing.

Note that if you use ALT+TAB to switch to another application, ScrawlB reclaims the mouse as soon as it passes over the client window.

Programming Notes

The application subclasses the main window in order to intercept WM_ENTERMENULOOP messages. This is the best way to find out if the user has opened the system menu by pressing ALT+SPACEBAR, so that ScrawlB can release the mouse. However, subclassing can lead to difficulties when debugging. See the comments in modMain.bas.

The frmCanvas module implements DirectXEvent in order to be able to process input events. The Visual Basic MouseMove event is also used by this form for getting Windows mouse events when DirectInput does not have access to the mouse. When this event is triggered, the application knows that the cursor is back in the client window, so the mouse can be reacquired.


DirectMusic

This documentation covers the following Microsoft® DirectMusic® application programming interface (API) topics:

  • About DirectMusic
  • Why Use DirectMusic?
  • DirectMusic Architecture
  • DirectMusic Essentials
  • DirectMusic Tutorials
  • DirectMusic Reference
  • DirectMusic Samples


About DirectMusic

DirectMusic is the musical component of the Microsoft® DirectX® API. Unlike the Microsoft® DirectSound® API, which is for the capture and playback of digital sound samples, DirectMusic works with message-based musical data, which is converted into wave samples, either in hardware or in a software synthesizer. The default software implementation uses the Microsoft® Software Synthesizer to create wave samples that are then streamed to DirectSound. Instrument voices are synthesized from samples according to the downloadable sounds (DLS) standard.

As well as supporting input in Musical Instrument Digital Interface (MIDI) format, DirectMusic can compose music at run time. This music is not algorithmically generated, but is based on elements authored by a human composer. (The authoring tool, Microsoft® DirectMusic® Producer, is documented separately.) The music is performed with variations and can respond dynamically to program events.

Like other components of DirectX, DirectMusic is based on the Component Object Model (COM).

DirectMusic delivers full functionality on Microsoft® Windows® 95, Microsoft® Windows® 98, and Microsoft® Windows® 2000. However, hardware acceleration is available only on Windows 2000 and Windows 98 Second Edition.


Why Use DirectMusic?

The DirectMusic API addresses fundamental requirements for delivering music on the Windows platform:

  • Consistent playback experience. By using downloadable sounds, an application can be sure that musical instruments will sound the same on all computers and can perform with instruments of its own design.
  • Jitter-free timing. Playback of MIDI-generated music has timing accuracy within two milliseconds.
  • Extensibility. DirectMusic does not restrict vendors to a base-level feature set.
  • Hardware acceleration. On Windows 98 Second Edition and Windows 2000, DirectMusic can stream its output to DLS-capable hardware synthesizers.
  • Software emulation. Computers without hardware acceleration are fully DirectMusic-capable with minimum impact on performance.

In addition, DirectMusic provides important features for easing application development and for enriching the user's experience:

  • Generic mechanism for loading and performing musical segments, regardless of the performance technology. DirectMusic supports standard MIDI files, authored music segments, and third-party technology equally.
  • Multiple performances. More than one piece of music can be played at once, with completely separate timing, instrument sets, and so on.
  • More than 16 MIDI channels. By mapping performance channels to channel groups, DirectMusic breaks through the 16-channel limitation and makes it possible for any number of voices to be played simultaneously, up to the limits of the synthesizer.
  • Automated management of DLS instruments.
  • Dynamic and interactive playback. In combination with DirectMusic Producer, the DirectMusic performance engine can be used to create dynamic musical soundtracks based on stored compositional material. The music does not assume its final form until it is about to be played and can respond to program events.
  • Synchronization of all music playback through the use of a master clock.


DirectMusic Architecture

This section introduces the components of DirectMusic. The following topics are discussed:

  • Core and Performance Layers
  • Overview of DirectMusic Objects and Interfaces (C/C++)
  • Overview of DirectMusic Classes (Visual Basic)
  • Overview of DirectMusic Data Flow
  • DirectMusic Messages
  • Downloadable Sounds
  • Microsoft Software Synthesizer

For information about how to implement these components in your application, see DirectMusic Essentials.


Core and Performance Layers

The DirectMusic core layer manages timing and ports and provides services for managing DLS collections. It supports buffered, time-stamped MIDI input and output. By default, DirectMusic itself sequences the MIDI data.

The core layer also includes the Microsoft Software Synthesizer, which functions as the hardware emulation layer for DLS support. If the user's computer does not have DLS hardware acceleration, the software synthesizer uses DLS to synthesize wave output from the sequenced MIDI data. Vendors can also create their own software synthesizers.

The DirectMusic performance layer is responsible for the higher-level aspects of music playback, including the loading and playback of MIDI files and the composition of music, based on elements authored in DirectMusic Producer or a similar application.

[C++]

The interfaces and related API elements for the core layer are declared in the Dmusicc.h header file, and those for the performance layer are in the Dmusici.h header file.

[Visual Basic]

DirectX for Visual Basic exposes primarily the performance layer. For specialized applications that need to work with multiple ports, manipulate DLS data at a low level, or create their own data tracks, use C++.


Overview of DirectMusic Objects and Interfaces

[Visual Basic]

The information in this section pertains only to applications written in C++. See Overview of DirectMusic Classes.

[C++]

In DirectMusic, it is helpful to make a distinction between objects and their COM interfaces because many objects have multiple interfaces. The object that supports the IDirectMusicCollection interface, for example, also supports the standard COM IPersistStream interface, as well as the IDirectMusicObject interface.

In this documentation, DirectMusic objects are referred to by the name of their principal or unique interface, but without the initial I; thus the object represented by IDirectMusicCollection is called the DirectMusicCollection object. Objects are also referred to by short names, such as collection, performance, segment, and track.

Interface pointers are often used as pointers to their objects so that these objects can be accessed through the methods of other interfaces. In fact, one interface, IDirectMusicDownloadedInstrument, has no unique methods of its own and is used only as a parameter to the methods of other interfaces.

DirectMusic consists of many COM objects and interfaces that are related to one another in rather complex ways. However, they can be divided into categories, according to their broad functionality, as follows:

  • Core Objects and Interfaces
  • Loader Objects and Interfaces
  • Instrument Objects and Interfaces
  • Tool Objects and Interfaces
  • Performance Objects and Interfaces
  • Composition Objects and Interfaces
  • Synthesizer Objects and Interfaces


Core Objects and Interfaces

[Visual Basic]

The information in this topic pertains only to applications written in C++. See Overview of DirectMusic Classes.

[C++]

The core objects handle the basic needs of DirectMusic: input, output, and timing. These objects are usually managed by other objects, such as DirectMusicPerformance, and you might never need to use their interfaces directly.

DirectMusic Object

The DirectMusic object, represented by the IDirectMusic interface, is used for creating ports and buffers, for connecting with DirectSound, and for setting up a master clock. There should not be more than one instance of this object per application.

Many applications never need to use the IDirectMusic interface directly. In this respect, it differs from other DirectX base interfaces. For example, IDirectSound is the starting point for every DirectSound application, performing essential tasks such as setting the cooperative level and creating sound buffers. In DirectMusic, most initialization is handled by other objects, such as DirectMusicPerformance, and these objects are created independently by direct calls to CoCreateInstance.

Port

Each device that sends or receives music data is encapsulated in a DirectMusicPort object. The methods of the IDirectMusicPort interface allow direct manipulation of the port, but most applications do not need to use these methods because the port is managed by the performance. For example, you assign channels to a port through the DirectMusicPerformance object so that data in those channels is correctly routed.

Buffer

The IDirectMusicBuffer interface represents the data currently ready to be played by the port (or read from the port). Most applications do not deal directly with the buffer object, but methods are available to manipulate its contents directly, if necessary.

Thru

The IDirectMusicThru interface is used to set up direct transmission of data from a capture port to another port.

Reference Clock

Objects that implement the IReferenceClock interface represent the master clock that synchronizes all DirectMusic activity and the latency clock of a port.


Loader Objects and Interfaces

[Visual Basic]

The information in this topic pertains only to applications written in C++. See Overview of DirectMusic Classes.

[C++]

Certain types of objects, such as DirectMusicCollection and DirectMusicStyle, have to be loaded (typically from a file) before they can be incorporated into a music performance. Others, such as DirectMusicSegment, can be either loaded or constructed at run time. The interfaces introduced in this section are essential for loading.

Loader

The DirectMusicLoader object, through its IDirectMusicLoader interface, manages the enumeration, caching, and loading of objects.

Stream

Data being read from a file or resource is represented by a stream object. Most applications do not have to deal directly with streams, which are created and managed by the loader. The stream object implements the following two interfaces:

  • IStream streams the data from a file or resource and passes it to the object being loaded, which parses it by using its own implementation of IPersistStream.
  • IDirectMusicGetLoader has a single method that returns a pointer to the DirectMusicLoader object that created the stream. It is used when a reference to another object is found in a stream and the object being loaded needs to call the loader to load the referred to object.

For a closer look at the use of these interfaces in the loading process, see DirectMusic Loader.

Object

Every object in DirectMusic that represents a file or resource supports the IDirectMusicObject interface, which is used as a generic pointer by the loader. When an application has obtained a pointer to this interface, the IDirectMusicObject::QueryInterface method can be used to obtain a pointer to the object's own unique interface, such as IDirectMusicCollection or IDirectMusicStyle. However, you can usually obtain the interface that you need from the call to IDirectMusicLoader::GetObject.

The methods of IDirectMusicObject are used internally by the loader for identifying objects.


Instrument Objects and Interfaces

[Visual Basic]

The information in this topic pertains only to applications written in C++. See Overview of DirectMusic Classes.

[C++]

An instrument is an object that represents a basic musical timbre or other sound. For all ports except legacy hardware MIDI ports, each instrument is associated with its own set of downloadable sounds (DLS), which must be downloaded to the port before the instrument can be used.

Downloadable sounds can be handled at three levels of abstraction. At the highest level, you load a band from a file and let the band object handle the DLS downloading for the instruments. At the next level, you directly access individual instruments in a collection and download them to a port. At the lowest level, you work with the DLS data itself.

The following objects and interfaces are used for managing instruments.

Collection

Instruments are stored in a DirectMusicCollection object, which represents an instance of a DLS file. Once the DirectMusicCollection object has been loaded, the IDirectMusicCollection interface can be used to enumerate instruments in the collection and to obtain a pointer to an instrument that has a given MIDI patch number.

Instrument

An instrument from a collection is represented by a pointer to the IDirectMusicInstrument interface. This pointer can be passed to the IDirectMusicPerformance::DownloadInstrument or the IDirectMusicPort::DownloadInstrument method to download DLS data to a port.

Once an instrument has been downloaded, it is represented by an IDirectMusicDownloadedInstrument interface pointer. This pointer is used only to unload the instrument by calling IDirectMusicPort::UnloadInstrument.

Applications that need to download their own DLS data for an instrument (such as collection-editing tools) use the methods of the IDirectMusicPortDownload interface (implemented by the port object) to get that data to the synthesizer. When this interface is used to allocate a buffer for instrument data, an IDirectMusicDownload interface pointer is returned. The single method of this interface can be used to obtain a pointer to the buffer itself.

Band

The DirectMusicBand object represents a set of instruments and MIDI program changes for a musical segment. The band is created in an authoring tool and can be loaded separately from a file, or it can be part of an authored segment or style.

The IDirectMusicBand interface can be used to download and unload bands. It also has a method for creating a secondary segment from a band. This segment can be played by the performance to effect program changes.

The key differences between a collection and a band are as follows:

  • A collection is a group of instruments available for use in the playback of any segment. A band is a group of instruments that actually plays a particular segment.
  • Instruments in a collection contain DLS data defining their timbre. Instruments in a band contain no such data but are linked to instruments in one or more collections.
  • An instrument from a collection is not inherently associated with any particular performance channel (PChannel) of a segment. A band assigns the patch number of an instrument to each PChannel in a segment and assigns a voice priority to the channel.
  • A collection does not contain any information about how the instruments are to be played. A band contains settings for the volume, pan, and transposition of each instrument.


Tool Objects and Interfaces

[Visual Basic]

The information in this topic pertains only to applications written in C++. See Overview of DirectMusic Classes.

[C++]

Tools are objects that intercept musical messages and process them before they are passed on to the port. All tools (except the output tool implemented by DirectMusic) are application-defined.

Tool

The IDirectMusicTool interface represents a single tool. The methods of this interface are implemented by the application or DLL to define the tool's functionality.

Graph

Tools are collected in a graph, represented by the IDirectMusicGraph interface, which is implemented by both the segment and the performance object. The interface is used for directing messages from one tool to the next, as well as for adding tools to the graph, retrieving pointers to individual tools, and shutting down the graph.


Performance Objects and Interfaces

[Visual Basic]

The information in this topic pertains only to applications written in C++. See Overview of DirectMusic Classes.

[C++]

The following objects and interfaces are used in the playback of musical data. With a total of over 75 methods, the interfaces in this group play a major role in any DirectMusic application.

Performance

The DirectMusicPerformance object is the overall manager of music playback. Through the IDirectMusicPerformance interface, it adds and removes ports, downloads instruments, attaches graphs (collections of tools), manages event notification for multiple segments, and plays segments.

Segment

A DirectMusicSegment object represents a chunk of data, most often a piece of music, contained in one or more tracks. Typically, a segment is either loaded from a file or created at run time by a DirectMusicComposer object. To play the segment, the application passes the IDirectMusicSegment interface pointer to the IDirectMusicPerformance::PlaySegment method.

Methods of the IDirectMusicSegment interface are used to manage timing and looping, event notification, tracks, tool graphs, and various other parameters of the segment.

An instance of a segment that is playing is represented by another interface, IDirectMusicSegmentState. Methods of this interface return information about the state of playback, and a pointer to this interface is used by the performance to stop or remove the segment instance.

Track

A chunk of timed data of a particular kind is represented by a DirectMusicTrack object, more simply referred to as a track. Methods of the IDirectMusicTrack interface can be used to set and retrieve data, play the data, and set notifications. Most applications do not use this interface directly because tracks are normally handled through the methods of the DirectMusicSegment object that contains them.

Note A DirectMusicTrack is not the same thing as an instrument track. A DirectMusicTrack represents any kind of timed data, such as MIDI messages, a chord progression, or band changes.


Composition Objects and Interfaces

[Visual Basic]

The information in this topic pertains only to applications written in C++. See Overview of DirectMusic Classes.

[C++]

The objects and interfaces in this category are used in the real-time composition of music. Except for the composer itself, they represent data loaded from a file created in an application such as DirectMusic Producer. For a closer look at the role of each object, see Music Composition.

Composer

Methods of the IDirectMusicComposer interface allow an application to compose musical segments and transitions, using chord maps, styles, and templates created by a human author.

Style

Styles contain basic information about a piece of music, including note patterns. Styles often form part of authored segments, in which they do most of their work behind the scenes. They can also be used to compose entirely new segments at run time. Styles are represented by the IDirectMusicStyle interface.

Chord map

A DirectMusicChordMap object represents a collection of chords and pathways used by DirectMusicComposer in determining the chord progression in a piece of music.

The IDirectMusicChordMap interface is obtained for a DirectMusicChordMap object loaded from a file. A pointer to this interface is passed to the methods of IDirectMusicComposer so that a segment or transition can be composed at run time, using the authored chord map. You can also change the chord pattern of an existing segment by applying a new chord map.

Template

Templates are a special type of DirectMusicSegment object. They are never played directly, but are used by the DirectMusicComposer in the real-time construction of segments based on styles and chord maps.


Synthesizer Objects and Interfaces

[Visual Basic]

The information in this topic pertains only to applications written in C++. See Overview of DirectMusic Classes.

[C++]

The synthesizer is responsible for converting MIDI messages into waveform data and streaming this to the wave output device. Although DirectMusic comes with its own software synthesizer, it allows the implementation of custom synthesizers. It also allows output to be directed to different devices. Information on these topics is contained in the DirectX Driver Development Kit (DDK).

Synthesizer

A synthesizer implemented by an application is represented by the IDirectMusicSynth interface. Most applications do not use this interface, and it is not documented in the DirectX SDK.

Synth Sink

The wave stream to which the synthesizer is sending data—for example, DirectSound or Microsoft® Win32® waveform audio—is represented by an IDirectMusicSynthSink interface. Most applications do not use this interface, and it is not documented in the DirectX SDK.


Overview of DirectMusic Classes

[C++]

The information in this section pertains only to applications written in Visual Basic. For C++ applications, see Overview of DirectMusic Objects and Interfaces.

[Visual Basic]

The DirectMusic classes can be grouped according to their broad functionality, as follows:

  • Loader Class
  • Performance Classes
  • Composition Classes
  • Instrument Classes


Loader Class

[C++]

The information in this topic pertains only to applications written in Visual Basic. For C++ applications, see Overview of DirectMusic Objects and Interfaces.

[Visual Basic]

The first step in playing music is to load data from a file or resource. An object of the DirectMusicLoader class is used for loading bands, collections, segments, and styles. All file input and output and parsing of the data is handled by DirectMusic.

Each of the DirectMusicLoader methods (other than SetSearchDirectory) returns an object representing the data. Other objects referred to by the primary object being loaded are also made available. For example, if you load a style by using DirectMusicLoader.LoadStyle and that style contains a reference to a band, the band object can be retrieved at any time by calling a method of the style object.


Performance Classes

[C++]

The information in this topic pertains only to applications written in Visual Basic. For C++ applications, see Overview of DirectMusic Objects and Interfaces.

[Visual Basic]

The DirectMusicPerformance class is at the heart of any DirectMusic application. Most applications have a single object of this class, which is responsible for managing timing and ports, changing global musical parameters such as the master tempo, and playing musical segments.

Each individual piece of music, such as a MIDI file or a segment authored in an application such as DirectMusic Producer, is represented by an object of the DirectMusicSegment class. Methods of this class can be used to set or retrieve musical parameters for the segment and to manage the DLS instruments associated with it. A special kind of DirectMusicSegment, the template, is used in run-time composition of playable segments.

When a DirectMusicSegment object is passed to DirectMusicPerformance.PlaySegment, the method returns an object of the DirectMusicSegmentState class that represents the playing instance of the segment. Methods of this object can be used to obtain information such as the time at which it started playing. The DirectMusicSegmentState is also passed to DirectMusicPerformance to determine whether the segment is currently playing or to stop playback.


Composition Classes

[C++]

The information in this topic pertains only to applications written in Visual Basic. For C++ applications, see Overview of DirectMusic Objects and Interfaces.

[Visual Basic]

Much of the music played in DirectMusic applications is fully authored either as a MIDI file or as a segment. However, DirectMusic also allows applications to compose music at run time, based on elements such as styles and templates.

The DirectMusicComposer class has methods that create DirectMusicSegment objects representing either templates, playable segments based on a chord map or template, or transitions based on other segments. The composer object can also be used to change the chord map of an existing segment.

The DirectMusicChordMap class represents a chord map loaded from a file or resource, which provides DirectMusicComposer with the information that it needs to compose chord progressions.

An object of the DirectMusicStyle class is also based on data from a file or resource, either as a separate entity or as part of an authored segment. It represents a set of musical patterns used in composition and can be passed to methods of DirectMusicComposer. Its own methods can be used to retrieve other elements that might have been determined in the style, such as motifs and bands.


Instrument Classes

[C++]

The information in this topic pertains only to applications written in Visual Basic. For C++ applications, see Overview of DirectMusic Objects and Interfaces.

[Visual Basic]

The DirectMusicBand class represents a set of instruments (with their volume, pan, and transposition) mapped to the parts in a piece of music. Band changes determined in a style take place automatically when a segment based on that style is played, but you can also obtain a DirectMusicBand object from a style or from a separate file or resource and create a DirectMusicSegment from it. This segment can then be played to effect program changes.

The DirectMusicCollection class represents a DLS collection. Most applications do not need to work directly with collections because the instrument data is downloaded to the port when a segment is played or when a band is downloaded.

The key differences between a collection and a band are as follows:

  • A collection is a group of instruments available for use in the playback of any segment. A band is a group of instruments that actually plays a particular segment.
  • Instruments in a collection contain DLS data defining their timbre. Instruments in a band contain no such data, but are linked to instruments in one or more collections.
  • An instrument from a collection is not inherently associated with any particular performance channel (PChannel) of a segment. A band assigns the patch number of an instrument to each PChannel in a segment and assigns a voice priority to the channel.
  • A collection does not contain any information about how the instruments are to be played. A band contains settings for the volume, pan, and transposition of each instrument.


Overview of DirectMusic Data Flow

Typically, a DirectMusic application obtains musical data from one or more of the following sources:

  • MIDI files.
  • Segment files authored in an application such as DirectMusic Producer.
  • Component files authored in an application such as DirectMusic Producer and turned into a complete composition by the DirectMusicComposer object.

Note Any of these data sources can be stored in the application as a resource.

Data from these sources is encapsulated in DirectMusicSegment objects. Each segment object represents data from a single source. At any given moment in a performance, one or more segments can be playing: a primary segment and, possibly, one or more secondary segments. Source files can be mixed—for example, a secondary segment based on a MIDI file can be played along with a primary segment based on an authored segment file.

A segment comprises several tracks, each containing timed data of a particular kind—for example, notes or tempo changes.

Most tracks generate messages when the segment is played by the performance, and the performance dispatches the messages to any application-defined tools, which can modify messages and pass them on, delete messages, and send new messages. Tools are grouped in segment graphs that process only messages from their own segments, and a performance graph that accepts messages from all segments.

[Visual Basic]

Application-defined tools are not supported by DirectX for Visual Basic.

Finally, the messages are delivered to the output tool, which converts the data to MIDI format before passing it to a port. Channel-specific MIDI messages are directed to the appropriate channel group on the port. The port synthesizes a sound wave that is streamed to a wave output device (normally a DirectSound buffer).

The following illustration shows how musical data gets from files to the wave output device. For the sake of simplicity, only a single segment is shown. This segment gets its data from only one of the three possible sources shown: a MIDI file, an authored segment file, or component files combined by the DirectMusicComposer object.

For a closer look at the flow of messages through the performance, see DirectMusic Messages.

For information on how to implement the process illustrated in the illustration, see the DirectMusic Essentials section, in particular the topics DirectMusic Loader and Playing Music.

For more about segment and component files, see Music Composition.[C++.Visual Basic]


DirectMusic Messages

Musical data passes through the DirectMusic performance engine in the form of messages. Most DirectMusic applications do not work directly with messages, but a basic knowledge of their structure can help you understand how DirectMusic works.

DirectMusic works with two different kinds of messages:

  • Performance messages. All sequenced data passes through the performance engine in this form. These messages contain detailed information about timing and routing of the data.
  • Standard MIDI messages. These can be read from a MIDI file or device and either passed directly (thrued) to another device or converted to performance message format before being passed to the performance. Final output to the synthesizer is also in the form of MIDI messages.

The following topics give more information about messages and how they are routed:

  • Channels
  • Message Creation and Delivery
  • Performance Message Types
  • MIDI Messages


Channels

A channel is a destination for a message that is specific to one part in the performance. For example, a channel might receive a note-on message that causes the instrument on that channel to make a sound, or a program-change message that assigns a different instrument to that part. (See MIDI Channel Messages.)

Under the MIDI 1.0 standard, there are 16 MIDI channels, meaning that no more than 16 instruments can be playing at one time. To support this standard but at the same time make more channels available to applications, DirectMusic creates channel groups. Up to 65,536 channel groups can exist at one time, each containing 16 channels, for a total of over one million channels. A particular port can be assigned any number of channel groups, up to its capability to support them. Legacy MIDI hardware ports have only a single channel group.

System-exclusive messages address all 16 channels within a channel group, but not other channel groups.

Every instrument in a DirectMusic performance has a unique performance channel, or PChannel. The PChannel represents a particular MIDI channel in a particular group on a particular port. When a band is selected by a performance, each instrument in that band is mapped to a PChannel.

[C++]

The number of notes that can be played simultaneously is limited by the number of voices available on the port. (This number can be determined from the dwMaxVoices member of the DMUS_PORTCAPS structure.)

[Visual Basic]

The number of notes that can be played simultaneously is limited by the number of voices available on the port. (This number can be determined from the lMaxVoices member of the DMUS_PORTCAPS type.)

A voice is a set of resources dedicated to the synthesis of a single note being played on a channel. If there are more notes playing than there are available voices, one or more notes must be suppressed by the synthesizer. The choice is determined by the priority of the voice currently playing the note, which is based in turn on the priority of the channel. By default, channels are ranked according to their index value, except that channel 10, the MIDI percussion channel, is ranked highest.

[C++]

Applications and synthesizers can set their own channel priorities. For more information, see the Remarks for IDirectMusicPort::GetChannelPriority. See also DMUS_CHANNEL_PRIORITY_PMSG.


Message Creation and Delivery

When a segment is played, most of its tracks generate messages containing information about events that are to take place during playback. (For more information, see Tracks.)

A few tracks send more than one kind of message. For example, a style track sends note messages and time signature messages. In such cases, an application can disable certain kinds of messages in the track. For more information, see Setting and Retrieving Track Parameters.

Applications can also place messages in the queue directly. You might do this, for example, to change the tempo.

[C++]

For sample code, see IDirectMusicPerformance::SendPMsg.

[Visual Basic]

For sample code, see the DLSEffects sample.

The performance engine determines when each message is to be processed in real time (reference time). In the case of channel messages, the performance also determines to what PChannel the message is directed. This information, along with other data—including the message type, its source track, and pointers to the first graph and tool that are to receive the message—are stored in the message.

Certain messages, such as tempo and time-signature changes, are immediately processed and freed by the performance. Other messages, such as notes and patch changes, are placed in a queue, in which they are processed in order of time stamp.

Notes There is no guarantee that messages with the same time stamp will be processed in any particular order.

Tempo messages tell the performance how to convert music time to reference time. Time-signature messages are purely informational, because the time signature is built into the segment and cannot be changed.

[C++]

Messages are first sent to any tools in the segment's graph, and then to tools in the performance's graph. (The application is responsible for creating either or both of these graphs and defining the tools. There is no default graph.)

The first tool in a graph processes the message, and then, if it wants to pass it on, has the graph stamp the message with a pointer to the next tool. For more information, see Tutorial 2: Using Tools.

At this point, the graph also flags the message with a delivery type that determines when the message is delivered to the next tool. This flag is based on what delivery type the tool is expecting, as follows:

  • If the message is flagged as DMUS_PMSGF_TOOL_IMMEDIATE, it is delivered to the next tool immediately.
  • If it is flagged as DMUS_PMSGF_TOOL_QUEUE, the message is delivered just before the time at which it is supposed to play, taking latency into account (see Latency and Bumper Time).
  • If it is flagged as DMUS_PMSGF_TOOL_ATTIME, it is delivered at exactly the time at which it is to be processed. Notification messages are given this flag because there is little or no latency involved in processing a notification.

The current tool can change the delivery type after the graph has finished stamping and flagging the message.

Ultimately, unless a message has been discarded, it arrives at the DirectMusic output tool, which converts all the data that it receives into standard MIDI messages and delivers these to the synthesizer through the port buffer.


Performance Message Types

[C++]

Messages are stored in various structures derived from DMUS_PMSG. Because C does not support inheritance, the members of DMUS_PMSG are included in the declaration for each message type as the DMUS_PMSG_PART macro. These members contain data common to all messages, including the type of the message, time stamps, the performance channel to which the message is directed, and what graph and tool are next in line to process the message. The other members contain data that is unique to the message type.

The following message structures are defined:

DMUS_PMSG | Simple message with no additional parameters.
DMUS_CHANNEL_PRIORITY_PMSG | Channel-priority change. See Channels.
DMUS_CURVE_PMSG | Curve.
DMUS_MIDI_PMSG | Any MIDI message that does not have a unique message type—for example, a control change.
DMUS_NOTE_PMSG | Music note. (Includes duration, so MIDI note-on and note-off messages are combined in this type.)
DMUS_NOTIFICATION_PMSG | Notification. See Notification and Event Handling.
DMUS_PATCH_PMSG | MIDI patch change.
DMUS_SYSEX_PMSG | MIDI system-exclusive message.
DMUS_TEMPO_PMSG | Tempo change.
DMUS_TIMESIG_PMSG | Time-signature change.
DMUS_TRANSPOSE_PMSG | Transposition.

[Visual Basic]

DirectX for Visual Basic does not give applications direct access to message structures. Instead, it provides the following methods for sending particular kinds of messages:

DirectMusicPerformance.SendCurvePMSG | MIDI curve.
DirectMusicPerformance.SendNotePMSG | Musical note.
DirectMusicPerformance.SendPatchPMSG | Patch change.
DirectMusicPerformance.SendMIDIPMSG | Miscellaneous MIDI events.
DirectMusicPerformance.SendTempoPMSG | Tempo change.
DirectMusicPerformance.SendTimeSigPMSG | Time-signature change.
DirectMusicPerformance.SendTransposePMSG | Transposition change.


MIDI Messages

This section gives an overview of standard MIDI messages and how such messages, typically streamed from a MIDI file, are handled by DirectMusic. Most applications do not deal directly with MIDI messages because the loader and the performance manage all the details of playback.

MIDI input is converted into performance message format before being routed through tools by the performance. The output tool converts the data back into the standard MIDI message format before passing it to the synthesizer.

Note There is no guarantee that MIDI messages will be processed in the same order in which they occur in the file. DirectMusic messages are delivered in order of time stamp, and two MIDI messages with identical time stamps might not be delivered in the expected order. Be sure, in authoring MIDI content, not to give events simultaneous time stamps if they must take place sequentially. For example, do not place a program change at the same time as a note that depends on the program change.

MIDI messages consist of a status byte, usually followed by 1 or 2 data bytes. System-exclusive MIDI messages are of variable length. The status byte indicates the type of message and, in some cases, the channel that is to receive the message. When several events of the same kind are in sequence in the file, the status byte can be omitted. This is called the running status. Data bytes are recognizable because the high bit is always clear, whereas in status bytes, it is always set.

The time at which MIDI events are streamed from a file is controlled by a number before each message, indicating how many ticks separate this event from the last. The actual duration of a tick depends on the time format in the file header.

MIDI messages are divided into two main categories:

  • MIDI Channel Messages
  • MIDI System Messages


MIDI Channel Messages

A channel message is addressed to a particular MIDI channel, which corresponds to a single part in the music.

A channel message can be either a mode message or a voice message.

A mode message determines how a channel deals with subsequent voice messages. For example, a mode message might instruct the channel to remain silent, ignoring all note-on messages until further notice.

Most channel messages are voice messages: they instruct the channel to begin or stop playing a note or to modify the note in some way, or they change the instrument by assigning a different MIDI patch number to the channel.

Voice messages are of the following types:

Voice message | Purpose
Note-on | Play a note.
Note-off | Stop playing the note.
Control change | Modify the tone with data from a pedal, lever, or other device; also used for miscellaneous controls such as volume and bank select.
Program (patch) change | Select an instrument for the channel by assigning a patch number.
Aftertouch | Modify an individual note, or all notes on the channel, according to the aftertouch of a key.
Pitch bend change | Modify the pitch of all notes played on the channel.

These descriptions apply to standard MIDI messages, not MIDI data that has been converted to performance message format. For example, a pair of MIDI messages to start and stop a note are combined by DirectMusic into a single message giving the duration of the note. DirectMusic messages also contain much additional information about the timing and routing of the message.

MIDI notes

The data bytes of a note-on message represent the pitch and velocity. In most cases, a pitch value of 0 represents C below subcontra C (called C0 in MIDI notation), 12 represents subcontra C (or C1), 60 is middle C (or C5), and so on. For drum kits, the data byte represents a particular drum sound instead. For example, as long as the General MIDI (GM) percussion key map is being adhered to, a value of 60 represents a high bongo sound. Channel 10 is reserved for drum kits, so the synthesizer knows that note-on messages on that channel are to be treated differently than on other channels.

For information on how DirectMusic converts to and from MIDI notes, see Music Values and MIDI Notes.

Program changes

Program changes and patch numbers are very important in MIDI playback and in DirectMusic. A program change assigns a particular instrument (also called a program or timbre) to a channel so that the notes sent to that channel are played with the appropriate sound. Instruments are identified by patch numbers. If the GM instrument set is loaded, a program change specifying patch number 1 always causes the channel to play its notes as an acoustic grand piano. (Of course, the actual sound produced at the speakers depends on how the instrument is synthesized.)

Bank selection

Because a single data byte is used to select the patch number in a program change and only 7 bits in each data byte of a MIDI message are significant, a program change can select from a maximum of 128 instruments. To provide a greater choice, the MIDI specification allows for the use of up to 16,384 instrument banks, each containing up to 128 instruments.

To select an instrument from a different bank, the MIDI sequencer must first send a control change message called bank select. The 2 data bytes of this message are referred to as the most significant byte (MSB) and least significant byte (LSB), and they are combined to identify a bank. Once the bank has been selected, each subsequent program change selects an instrument from that bank.

DirectMusic patch numbers

[Visual Basic]

This topic pertains only to applications written in C++. DirectX for Visual Basic does not allow applications to change patch numbers except by using the DirectMusicPerformance.SendPatchPMSG method.

[C++]

In DirectMusic, the instrument patch number is not the 7-bit MIDI patch number, but a 32-bit value that packs the MIDI patch number together with the MSB and LSB of the bank select and a 1-bit flag for a drum kit. This extended patch number is returned by the IDirectMusicCollection::EnumInstrument, IDirectMusicCollection::GetInstrument, and IDirectMusicInstrument::GetPatch methods. It can be changed for an instrument by using the IDirectMusicInstrument::SetPatch method.

The organization of DirectMusic patch values is as follows:

Bits | Purpose
0-7 | MIDI patch number (bit 7 is always 0)
8-15 | LSB bank select (bit 15 is always 0)
16-23 | MSB bank select (bit 23 is always 0)
24-30 | Unused
31 | Flag for drum kit


MIDI System Messages

System messages are not exclusive to any channel. They are of three kinds, as shown in the following table.

Message type | Purpose
System common | Miscellaneous commands and data.
System exclusive | Equipment-specific commands and data.
System real-time | Synchronization of clock-based MIDI equipment.

Unlike other MIDI messages, system-exclusive messages can contain any number of data bytes. After transmitting the data, the sequencer sends a system-common message called an EOX, which signals the end of the system-exclusive message.

[C++]

In DirectMusic, the DMUS_SYSEX_PMSG structure contains the length of the data and a pointer to an array of data bytes.

[Visual Basic]

DirectX for Visual Basic does not give applications direct access to system-exclusive messages.


Downloadable Sounds

In the past, most computer music has been produced in one of two fundamentally different ways, each with its advantages and disadvantages:

  • Waveforms are reproduced from digital samples, typically stored in a .wav file or, in the case of Red Book audio, on a standard CD track. Digital samples can reproduce any sound, and the output is very similar on all sound cards. However, they require large amounts of storage and resources for streaming.
  • Instrument sounds are synthesized, usually in hardware, in response to messages, typically from a MIDI file. MIDI files are compact and require few streaming resources, but the output is limited to the number of instruments available in the General MIDI set and in the synthesizer, and can sound very different on different systems.

One way to combine the advantages of digital sampling with the compactness and flexibility of MIDI is wave-table synthesis—the synthesis of instrument sounds from digital samples. These samples are obtained from recordings of real instruments, and then stored on the hardware. The samples are looped and adjusted in such a way as to produce sounds of any length at various pitches and volumes.

Wave-table synthesis produces more realistic timbres than algorithmic FM synthesis, but is still limited to a fixed set of instruments. Moreover, a particular instrument can sound different on different pieces of hardware, depending on the manufacturer's implementation of that instrument.

To overcome these limitations, the downloadable sounds (DLS) standard has been published by the MIDI Manufacturers Association. DLS is a way of allowing wave-table synthesis to be based on samples provided at run time, rather than hard-wired into the system. The data describing an instrument is downloaded to the synthesizer, and then the instrument can be played like any other MIDI instrument. Because DLS data can be distributed as part of an application, developers can be sure that their soundtracks are delivered uniformly on all systems. Moreover, they are not limited in their choice of instruments.

A DLS instrument is created from one or more digital samples, typically representing single pitches, which are then modified by the synthesizer to create other pitches. Multiple samples are used to make the instrument sound realistic over a wide range of pitches. When a DLS instrument is downloaded, each sample is assigned to a certain range of pitches, called a region. Usually, there are no more than 16 regions.

In addition, samples can be given an articulation, which defines things like attack (how quickly a note reaches full volume), decay (how quickly it falls away from full volume), and other characteristics that make the sound more like that produced by a real instrument.

Downloadable sounds are stored in instrument collections, from which they are downloaded to the synthesizer.

DLS instruments are assigned patch numbers and respond to MIDI messages as do other MIDI instruments. However, a DLS instrument does not have to belong to the General MIDI set. In fact, it does not have to represent a musical instrument at all. Any sound, even a fragment of speech or a fully composed measure of music, can be turned into a DLS instrument.

For more information on DLS collections and how instruments are created, see the documentation for DirectMusic Producer. For a guide to incorporating DLS in your applications, see Using Downloadable Sounds.


Microsoft Software Synthesizer

The Microsoft Software Synthesizer is supplied with DirectMusic and is the default port when hardware DLS is not available or is not supported by the operating system. The synthesizer creates a waveform based on a stream of MIDI messages, using instrument timbres synthesized from DLS samples. By default, the samples are from the Roland GS collection, which is also part of the DirectMusic installation. The synthesizer sends its output to the DirectSound mixer.

Note The Roland GM/GS Sound Set cannot be modified. See the Copyright Warning for the legal restrictions.

The Microsoft Software Synthesizer includes reverberation capabilities, which are on by default. The Waves TrueVerb reverberation technology is licensed to Microsoft as the SimpleVerb implementation.


DirectMusic Essentials

This section gives practical information on how to implement DirectMusic in applications. For a more general overview, see DirectMusic Architecture.

The following topics are discussed:

  • Building DirectMusic Projects
  • Debugging DirectMusic Projects
  • Integrating DirectMusic and DirectSound
  • Using Ports
  • DirectMusic Loader
  • DirectMusic File Format
  • Using Downloadable Sounds
  • Playing Music
  • Music Parameters
  • Capturing Music
  • DirectMusic Tools
  • Music Composition


Building DirectMusic Projects

[Visual Basic]

This topic pertains only to application development in C++.

[C++]

Unlike other components of DirectX, the DirectMusic API is completely COM-based and does not contain any library functions, such as helper functions to create COM objects. Therefore, there is no Dmusic.lib file to link to during the build.

Most projects must include the Dmusicc.h and Dmusici.h header files, which contain declarations for the core and performance layers, respectively, and Dmerror.h, which contains return values. Dmusicf.h contains file formats and is needed only for applications such as music authoring tools that work directly with files and do not rely solely on the loaders built into DirectMusic.

Dmksctrl.h contains declarations for the IKsControl interface used for property sets. You do not need this file if you have the Ksproxy.h and Ks.h files.

DirectMusic uses the multithreading capabilities of the Windows 32-bit operating system. Multithreading allows DirectMusic to generate, process, and synthesize music in the background while your application is accomplishing other tasks. Develop your project with multithreading in mind. At least be sure to link with the multithreaded libraries.

Also be sure that your application has access to the GUIDs used by DirectMusic. For more information, see Compiling DirectX Samples and Other DirectX Applications.


Debugging DirectMusic Projects

[Visual Basic]

This topic pertains only to application development in C++.

[C++]

The DirectMusic dynamic-link libraries (DLLs) installed with the debug version of the DirectX software development kit generate information in the debug output window as the application is running. By default, all available information is shown.

You can control the volume of information that goes to your debug output window by changing values in Win.ini. The output for each DirectMusic DLL can be set separately, as in the following example:

[Debug]
DMBAND=1
DMCOMPOS=1
DMIME=1
DMLOADER=0
DMUSIC=1
DMSTYLE=3
DMSYNTH=5

Each value can be in the range from 0 through 5, where 0 produces the least detailed debugging information and 5 the most. If there is no entry in Win.ini, the debug output is at level 0. You can focus on problems in a particular component by setting higher values for the other components. You can also change the debug level by using the DirectX property sheet in Control Panel. However, this method sets the same value for all DirectMusic components.

See also Debugging DirectX Applications.


Integrating DirectMusic and DirectSound

The Microsoft Software Synthesizer and other synthesizers normally stream their output wave data to a DirectSound buffer. DirectMusic is capable of handling all the details of linking to DirectSound without any action on your part. When it creates or links to a DirectSound object, DirectMusic ensures that the primary buffer format matches that of the highest format among all DirectMusic ports.

[C++]

In an application that uses only music files for its soundtrack and does not require DirectSound for playing wave files or resources, the DirectSound object is typically created when the DirectMusic performance is initialized. This is shown in the following example, in which pPerf is a pointer to the IDirectMusicPerformance interface:

pPerf->Init(NULL, NULL, hwnd);

In this example, the first NULL specifies that the DirectMusic object is to be created and managed internally, the second NULL specifies the same for the DirectSound object, and hwnd is the handle of the controlling window for DirectSound.

Note It is a good idea to supply the top-level application window handle when requesting that DirectMusic create the DirectSound object. See the Remarks for IDirectMusicPerformance::Init and IDirectSound::SetCooperativeLevel.

[Visual Basic]

In an application that uses only music files for its soundtrack and does not require DirectSound for playing wave files or resources, the DirectSound object is typically created when the DirectMusic performance is initialized. This is shown in the following example, where Perf is a DirectMusicPerformance object:

Perf.Init(Nothing, hwnd);

In this example, Nothing specifies that the DirectSound object is to be created and managed internally, and hwnd is the handle of the controlling window for DirectSound.

Note It is a good idea to supply the top-level application window handle when requesting that DirectMusic create the DirectSound object. See the Remarks for DirectMusicPerformance.Init and DirectSound.SetCooperativeLevel.

More information is contained in the following topics:

  • Setting the DirectSound Object
  • Setting the DirectSound Buffer Object


Setting the DirectSound Object

[C++]

Allowing DirectMusic to create and manage the DirectSound object works for applications that are not using DirectSound independently. However, if your application is using DirectSound to play wave data from a source other than the DirectMusic synthesizer, you must ensure that the same IDirectSound interface is used by DirectMusic. Create the DirectSound object first; then pass the interface pointer to DirectMusic. This can be done in the call to IDirectMusicPerformance::Init, as in the following example, in which pPerf is the IDirectMusicPerformance and pDS is a pointer to IDirectSound:

pPerf->Init(NULL, pDS, NULL);

Note When an IDirectSound pointer is passed to IDirectMusicPerformance::Init, the third parameter, the window handle, is ignored. The application is responsible for setting the controlling window by calling IDirectSound::SetCooperativeLevel.

Set the DSSCL_PRIORITY cooperative level for any DirectSound object to be used with DirectMusic. If you set the DSSCL_NORMAL cooperative level, DirectMusic cannot upgrade the primary buffer format.

If you create the DirectMusic object by using CoCreateInstance, rather than letting the performance do it for you, you must also explicitly link it to an existing IDirectSound interface. This is done by using the IDirectMusic::SetDirectSound method.

You can also use the IDirectMusicPort::SetDirectSound method to assign a different DirectSound object to a port. Do this when different ports are on different audio devices, each represented by its own IDirectSound interface. The DirectSound object for a port cannot be changed once the port has been activated.

When a port that requires DirectSound is activated, it takes the first available IDirectSound interface pointer from the following list:

  1. The IDirectSound interface passed to IDirectMusicPort::SetDirectSound.
  2. The IDirectSound interface passed to IDirectMusic::SetDirectSound.
  3. The IDirectSound interface created by DirectMusic if NULL was passed to IDirectMusic::SetDirectSound.

When DirectSound is in emulation mode, it has exclusive use of the audio device. An application should release DirectSound whenever it loses the focus to allow other applications to use the device. Typically, this is done in response to a WM_ACTIVATE message.

If DirectMusic created the DirectSound object, it automatically releases the object when all ports are deactivated (and creates a new one when the first port using DirectMusic is reactivated). However, if you created the DirectSound object yourself, you are responsible for releasing it. This is done by using the IDirectMusic::SetDirectSound or the IDirectMusicPort::SetDirectSound method, passing NULL as the pDirectSound parameter.

[Visual Basic]

Allowing DirectMusic to create and manage the DirectSound object works for applications that are not using DirectSound independently. However, if your application is using DirectSound to play wave data from a source other than the DirectMusic synthesizer, you must ensure that the same DirectSound object is used by DirectMusic. Create the DirectSound object first; then pass it to DirectMusic. This is done in the call to DirectMusicPerformance.Init, as in the following example, in which Perf is the DirectMusicPerformance object and DS is the DirectSound object:

Perf.Init(DS, 0);

Note When a DirectSound object is passed to DirectMusicPerformance.Init, the second parameter, the window handle, is ignored. The application is responsible for setting the controlling window by calling DirectSound.SetCooperativeLevel.

Set the DSSCL_PRIORITY cooperative level for any DirectSound object to be used with DirectMusic. If you set the DSSCL_NORMAL cooperative level, DirectMusic cannot upgrade the primary buffer format.


Setting the DirectSound Buffer Object

[Visual Basic]

This topic pertains only to applications written in C++. DirectX for Visual Basic does not support custom DirectSound buffers for DirectMusic output.

[C++]

When DirectMusic is linked to DirectSound, it creates and manages a secondary DirectSound buffer for the wave output from each port, in a format matching that of the port. You can override the default behavior and ensure that the data is streamed to a different buffer by using the IDirectMusicPort::SetDirectSound method. You might do this, for example, to have 3-D effects on the sound buffer. (See the 3DMusic Sample.) You might even create multiple instances of the synthesizer port, each with its own DirectSound 3-D buffer, to place different instruments at different points in space.

The buffer that you pass to IDirectMusicPort::SetDirectSound must be a secondary streaming buffer with a matching format. Get information about the wave format and recommended buffer size by calling the IDirectMusicPort::GetFormat method.

DirectMusic does not attempt to upgrade the primary buffer when you pass your own IDirectSoundBuffer to IDirectMusicPort::SetDirectSound.


Using Ports

A port is a device that sends or receives musical data. It can correspond to a hardware device, a software synthesizer, or a software filter.

[C++]

Each port in a DirectMusic application is represented by an IDirectMusicPort interface. Methods of this interface are used to retrieve information about the device, manage the memory on the device, download and unload DLS instruments, read incoming data, and cue playback buffers.

Every performance must have at least one port. If you want to use a port other than the default port to set up special parameters for the default port, first set up a DMUS_PORTPARAMS structure. You do not have to fill in all members, but you must let DirectMusic know which members have valid information by putting the appropriate flags in the dwValidParams member. Then, pass the structure to the IDirectMusic::CreatePort method.

The following C++ code example demonstrates how an object might be created for the default port, setting five channel groups on the port, assuming that pDirectMusic is a valid IDirectMusic pointer.

IDirectMusicPort*  pPort;
DMUS_PORTPARAMS    dmos;

ZeroMemory( &dmos, sizeof(DMUS_PORTPARAMS) );
dmos.dwSize = sizeof(DMUS_PORTPARAMS);
dmos.dwValidParams = DMUS_PORTPARAMS_CHANNELGROUPS;
dmos.dwChannelGroups = 5;
HRESULT hr = pDirectMusic->CreatePort( GUID_NULL, &dmos,
        &pPort, NULL )

Once you have a port, activate it by calling IDirectMusic::Activate or IDirectMusicPort::Activate and attach it to the performance by using the IDirectMusicPerformance::AddPort method.

When you add a port to a performance, assign a block of PChannels to it by calling the IDirectMusicPerformance::AssignPChannelBlock method. The only time this is not necessary is when you add the default port by passing NULL to IDirectMusicPerformance::AddPort. In that case, PChannels 0 through 15 are assigned to the MIDI channels in the first group on the port.

You can map PChannels differently, add more PChannels, or assign PChannels to a different port by using the IDirectMusicPerformance::AssignPChannelBlock and IDirectMusicPerformance::AssignPChannel methods.

[Visual Basic]

DirectX for Visual Basic supports only a single port for each performance, and all PChannels are mapped to this port. Choose the port after initializing the performance by using DirectMusicPerformance.SetPort. To use the default port, pass –1 as the index parameter.

Available ports are automatically enumerated when you initialize the performance. You can look for a particular port or capabilities by using the DirectMusicPerformance.GetPortCount, DirectMusicPerformance.GetPortCaps, and DirectMusicPerformance.GetPortName methods. The following code example looks for the first software synthesizer and sets this as the port for the performance, with support for up to 16 channel groups:

' perf is a DirectMusicPerformance object.
Dim X As Integer
Dim portcaps As DMUS_PORTCAPS

perf.Init(Nothing, Me.hWnd)
For X = 1 to perf.GetPortCount
    Call perf.GetPortCaps(X, portcaps)
    If portcaps.lFlags And DMUS_PC_SOFTWARESYNTH Then
        perf.SetPort(X, 16)
        Exit For
    End If
Next X
' If no port was set, set the default port, or take other action.

More information about ports is contained in the following topics:

  • Default Port
  • Legacy Ports
  • Port Property Sets


Default Port

Under Windows 95 and versions of Windows 98 prior to Windows 98 Second Edition, and always when hardware that supports DLS is not available, the Microsoft Software Synthesizer is the default port. Under later versions of Windows 98 and under Windows 2000, a hardware synthesizer might be the default port.

[C++]

If you want your application to use the default port, you do not have to call the IDirectMusic::CreatePort method before adding the port to the performance. Instead, you can pass NULL to IDirectMusicPerformance::AddPort.

Obtain the default port by a call to IDirectMusic::GetDefaultPort, and then check its capabilities by using the IDirectMusicPort::GetCaps method. If the port does not meet the needs of your application, use the IDirectMusic::EnumPort method to find the Microsoft Software Synthesizer or another port.

[Visual Basic]

A performance uses the default port if –1 is passed as the index parameter to DirectMusicPerformance.SetPort. If you do this, however, you have no way of checking the port's capabilities. If your application needs a port with particular capabilities, examine the ports in the collection created by DirectMusic when the performance is intialized. For more information, see Using Ports.


Legacy Ports

Under Windows 95 and Windows 98, DirectMusic supports legacy ports—that is, it sequences output data to a MIDI device that uses FM or hardware wave-table synthesis.

Legacy ports have the following restrictions in DirectMusic:

  • Not supported on Windows 2000.
  • No support for downloadable sounds.
  • Master volume cannot be changed. (This can be done for other ports by setting a global parameter. See Setting and Retrieving Global Parameters.)
  • There is only one channel group. (See Channels.)

Most applications do not need to consider the presence of legacy ports because the Microsoft Software Synthesizer produces consistent results on all output devices capable of playing waveform audio.

[C++]

You can recognize a legacy port by the DMUS_PORT_WINMM_DRIVER flag in the dwType member of the DMUS_PORTCAPS structure returned by the IDirectMusic::EnumPort or the IDirectMusicPort::GetCaps method.

Legacy ports also differ from others in that the application determines whether channels on the legacy port are shared between logical ports by setting the fShare member of the DMUS_PORTPARAMS structure. This member is relevant only for ports that have the DMUS_PC_SHAREABLE flag in the dwFlags member of DMUS_PORTCAPS, as is always the case for legacy ports.

[Visual Basic]

You can recognize a legacy port by the DMUS_PORT_WINMM_DRIVER flag in the lType member of the DMUS_PORTCAPS type returned by DirectMusicPerformance.GetPortCaps.


Port Property Sets

[Visual Basic]

This topic pertains only to applications written in C++. DirectX for Visual Basic does not support port property sets.

[C++]

Through property sets, DirectMusic provides unlimited support for new features in hardware and drivers. A property set is associated with a particular port.

Hardware vendors define new capabilities as properties and publish the specification for these properties, including GUIDs. You can use the IKsControl::KsProperty method to find out whether a property is available, and then to set and retrieve values for that property. Obtain the IKsControl interface for a port by calling the IDirectMusicPort::QueryInterface method, passing IID_IKsControl as the interface identifier.

A property set is represented by a GUID, and each item within the set is represented by a zero-based index. The meaning of the indexed items for a GUID never changes. For a list of the property sets supported by DirectMusic, see KSPROPERTY.

All property sets predefined by DirectMusic have only one item, usually at index 0. However, the full definition of kernel-streaming (KS) properties is supported, and vendors are free to create property sets with any number of items and instances, and data of any size.

Routing of the property item request to the port varies, depending on the port implementation. No properties are supported by ports that represent DirectMusic emulation over the Win32 handle-based multimedia calls (the midiOut and midiIn functions).

The following code example uses the IKsControl::KsProperty method to determine if the port supports General MIDI in hardware:

BOOL IsGMSupported(IDirectMusicPort *pPort)
{
    HRESULT     hr;
    IKsControl  *pControl;
    KSPROPERTY  ksp;
    DWORD       dwFlags;
    ULONG       cb;
    BOOL        fIsSupported;

    // Query for an IKsControl interface.
    hr = pPort->QueryInterface(IID_IKsControl, (void**)&pControl);
    if (FAILED(hr))
    {
        // Port does not support properties; assume no GM support.
        return FALSE;
    }
    // Ask about GM.
    ksp.Set   = GUID_DMUS_PROP_GM_Hardware;
    ksp.Id    = 0;
    ksp.Flags = KSPROPERTY_TYPE_BASICSUPPORT;
    hr = pControl->KsProperty(&ksp, sizeof(ksp),
            &dwFlags, sizeof(dwFlags), &cb);
    fIsSupported = FALSE;
    if (SUCCEEDED(hr) || (cb >= sizeof(dwFlags))
    {
        // Set is supported.
        fIsSupported = (BOOL)(dwFlags & KSPROPERTY_TYPE_GET);
    }
    pControl->Release();
    return fIsSupported;
}

The following code example shows how a property can be changed. In this case, the reverberation properties of the software synthesizer are set to those contained in a DMUS_WAVES_REVERB_PARAMS structure.

/* Assume that m_* variables have been initialized to valid values.
   m_pPort is a pointer to IDirectMusicPort. */

DMUS_WAVES_REVERB_PARAMS Params;

Params.fInGain = m_fReverbIn;
Params.fHighFreqRTRatio = m_fReverbHigh;
Params.fReverbMix = m_fReverbMix;
Params.fReverbTime = m_fReverbTime;

IKsControl *pControl;
if (m_pPort)
{
    // Query for IKsControl interface.
    HRESULT hr = m_pPort->QueryInterface(IID_IKsControl,
            (void**)&pControl);
    if (SUCCEEDED(hr))
    {
        KSPROPERTY ksp;
        ULONG cb;

        ZeroMemory(&ksp, sizeof(ksp));
        ksp.Set   = GUID_DMUS_PROP_WavesReverb;
        ksp.Id    = 0;
        ksp.Flags = KSPROPERTY_TYPE_SET;

        pControl->KsProperty(&ksp,
                             sizeof(ksp),
                             (LPVOID)&Params,
                             sizeof(Params),
                             &cb);
        pControl->Release();
    }
}

The following code example turns on the reverb effect for the port represented by m_pPort:

DWORD dwEffects = 0;
IKsControl *pControl;
HRESULT hr = m_pPort->QueryInterface(IID_IKsControl,
        (void**)&pControl);
if (SUCCEEDED(hr))
{
  KSPROPERTY ksp;
  ULONG cb;

  ZeroMemory(&ksp, sizeof(ksp));
  dwEffects = DMUS_EFFECT_REVERB;
  ksp.Set   = GUID_DMUS_PROP_Effects;
  ksp.Id    = 0;
  ksp.Flags = KSPROPERTY_TYPE_SET;

  pControl->KsProperty(&ksp,
             sizeof(ksp),
             (LPVOID)&dwEffects,
             sizeof(dwEffects),
             &cb);
  pControl->Release();
}

The final example shows how you might turn off reverb, leaving any other effects intact:

DWORD dwEffects = 0;
IKsControl *pControl;
HRESULT hr = m_pPort->QueryInterface(IID_IKsControl,
        (void**)&pControl);
if (SUCCEEDED(hr))
{
  KSPROPERTY ksp;
  ULONG cb;

  ZeroMemory(&ksp, sizeof(ksp));
  ksp.Set   = GUID_DMUS_PROP_Effects;
  ksp.Id    = 0;
  ksp.Flags = KSPROPERTY_TYPE_GET;

  pControl->KsProperty(&ksp,
             sizeof(ksp),
             (LPVOID)&dwEffects,
             sizeof(dwEffects),
             &cb);

  ZeroMemory(&ksp, sizeof(ksp));
  dwEffects = dwEffects & ~DMUS_EFFECT_REVERB;
  ksp.Set   = GUID_DMUS_PROP_Effects;
  ksp.Id    = 0;
  ksp.Flags = KSPROPERTY_TYPE_SET;

  pControl->KsProperty(&ksp,
             sizeof(ksp),
             (LPVOID)&dwEffects,
             sizeof(dwEffects),
             &cb);

  pControl->Release();
}


DirectMusic Loader

[C++]

Many DirectMusic objects have to be loaded from a file or resource before they can be incorporated into a music performance. The IDirectMusicLoader interface is used to manage the loading of such objects, as well as to find and enumerate objects and cache them so that they are not loaded more than once.

An application should have only one instance of the loader in existence at a time. You should create a single global loader object and not free it until there is no more loading to be done. This strategy ensures that objects are found and cached efficiently.

The DirectMusic implementation of IStream streams the data from the source. The parsing of the data is handled by the various objects themselves through their implementations of IPersistStream. When you are dealing only with standard DirectMusic data, you do not need to use these interfaces directly.

Objects that are referred to by other objects are loaded transparently. For example, suppose a style being loaded from a DirectMusic Producer file contains a reference to a band whose data is in another file. When the style's IPersistStream finds the reference, it obtains the IDirectMusicGetLoader interface from the IStream that passed it the data stream. Using this interface, it obtains a pointer to the DirectMusicLoader. Then it calls IDirectMusicLoader::GetObject to load the band.

[Visual Basic]

Many DirectMusic objects have to be loaded from a file or resource before they can be incorporated into a music performance. The DirectMusicLoader class is used to manage the loading of such objects.

An application should have only one DirectMusicLoader object in existence at a time. You should create a single global loader object and not free it until there is no more loading to be done. This strategy ensures that objects are found and loaded efficiently.

However, if your application has occasion to load a segment more than once, you should be aware that because of the caching system used internally by DirectMusic, you might get back the same segment object, with the same settings such as start and loop points and any connection to a DLS collection. To ensure that this does not happen, you should release the DirectMusicLoader object by setting it to Nothing, and then create a new one, before reloading the segment.

Objects that are referred to by other objects are loaded transparently. For example, suppose a style being loaded from a DirectMusic Producer file contains a reference to a band whose data is in another file. DirectMusic loads the band automatically, and the application retrieves it by using the DirectMusicStyle.GetBand method.

More information on using the loader is contained in the following topics:

  • Setting the Loader's Search Directory
  • Scanning a Directory for Objects
  • Enumerating Objects
  • Loading an Object from a File
  • Loading an Object from a Resource
  • Getting Object Descriptors
  • Caching Objects
  • Setting Objects
  • Custom Loading


Setting the Loader's Search Directory

[C++]

By default, the loader looks for objects in the current directory unless a full path is specified in the wszFileName member of the DMUS_OBJECTDESC structure describing the object being sought. Using the IDirectMusicLoader::SetSearchDirectory method, you can set a different default path for the IDirectMusicLoader::GetObject and IDirectMusicLoader::EnumObject methods. This default path can apply to all objects, or only to objects of a certain class.

The following code example sets the search path for style files:

HRESULT mySetLoaderPath (
    IDirectMusicLoader *pILoader)    // Previously created
{
    return pILoader->SetSearchDirectory(
            CLSID_DirectMusicStyle,
            L"c:\\mymusic\\funky",
            FALSE);
}

Having called this function, the application can now load a style by file name, without including the full path, as in the following code example:

HRESULT myLoadStyleFromPath (
    IDirectMusicStyle **ppIStyle,    // Receives a pointer to a style
    IDirectMusicLoader *pILoader)    // Loader already created
{
    HRESULT hr;
    DMUS_OBJECTDESC Desc;

    ZeroMemory(&Desc, sizeof(DMUS_OBJECTDESC);
    Desc.dwSize = sizeof(DMUS_OBJECTDESC);
    wcscpy(Desc.wszFileName, L"polka.sty");   // Short file name
    Desc.guidClass = CLSID_DirectMusicStyle;  // Object class
    Desc.dwValidData = DMUS_OBJ_CLASS | DMUS_OBJ_FILENAME;

    hr = pILoader->GetObject(&Desc,
            IID_IDirectMusicStyle, (void **) ppIStyle);
    return hr;
}
[Visual Basic]

By default, the loader looks for file objects in the current directory unless a full path has been passed to the load method. Using the DirectMusicLoader.SetSearchDirectory method, you can set a different default path for the DirectMusicLoader.LoadBand, DirectMusicLoader.LoadCollection, DirectMusicLoader.LoadSegment, and DirectMusicLoader.LoadStyle methods.


Scanning a Directory for Objects

[Visual Basic]

This topic pertains only to applications written in C++.

[C++]

The IDirectMusicLoader::ScanDirectory method scans the current search directory for objects of a given class. You can further narrow the search by providing a subclass and a file extension other than "*".

The method compiles a list of all matching files and uses the IDirectMusicObject::ParseDescriptor method to extract the GUID and the name of the object. These identifiers are retained in an internal database so that the application can subsequently load objects by GUID or name, rather than by file name. (See Loading an Object from a File.)

Note It is always a good idea to call IDirectMusicLoader::ScanDirectory before loading any objects. Even though you might be loading objects explicitly by file name, those objects could contain references to other objects not identified by file name, and the loader would not be able to find these referenced objects if ScanDirectory was not called on every directory in which the objects might be.

If you include a pointer to a string in the pwszScanFileName parameter of the ScanDirectory method, the results of the scan are cached in a file by that name to speed up subsequent scans. When a cache file is available, the method updates object information only for files whose time stamps or sizes have changed.

Note In the current version of DirectMusic, ScanDirectory does not use the cache file. Nevertheless, you can implement a cache file now, and it will speed up performance under future versions.

For an example, see Enumerating Objects.


Enumerating Objects

[Visual Basic]

This topic pertains only to applications written in C++.

[C++]

Use the IDirectMusicLoader::EnumObject method to iterate through all objects of a given class, or of all classes, that have previously been listed in the internal database through a call to IDirectMusicLoader::ScanDirectory or calls to IDirectMusicLoader::GetObject. A description of each object found is returned in a DMUS_OBJECTDESC structure.

Note To be sure of finding all objects, call ScanDirectory first. EnumObject works by checking the internal database of objects, not by parsing disk files.

The following example enumerates all listed style objects in the current search directory and displays information about each one by using the TRACE debugging macro. The loop continues until there are no more objects of that class to enumerate.

void myListStyles(
        IDirectMusicLoader *pILoader)

{
    HRESULT hr = pILoader->SetSearchDirectory(
            CLSID_DirectMusicStyle,
            L"c:\\mymusic\\wassup",
            TRUE);
    if (SUCCEEDED(hr))
    {
        hr = pILoader->ScanDirectory(
                CLSID_DirectMusicStyle,
                L"sty",
                L"stylecache");
        if (hr == S_OK)    // Only if files were found...
        {
            DWORD dwIndex;
            DMUS_OBJECTDESC Desc;
            Desc.dwSize = sizeof(DMUS_OBJECTDESC);
            for (dwIndex = 0; ;dwIndex++)
            {
                if (S_OK ==(pILoader->EnumObject(
                        CLSID_DirectMusicStyle,
                        dwIndex, &Desc)))
                {
                    TRACE("Name: %S, Category: %S, Path: %S\n",
                            Desc.wszName,
                            Desc.wszCategory,
                            Desc.wszFileName);
                }
                else break;
            }
        }
    }
}

This code example does not use the SUCCEEDED macro to test the result of the method call because EnumObject returns a success code, S_FALSE, for an invalid index number.


Loading an Object from a File

[C++]

To load an object, first obtain the IDirectMusicLoader interface, as in the following code example:

IDirectMusicLoader* m_pLoader;

CoInitialize(NULL);
HRESULT hr = CoCreateInstance(
    CLSID_DMLoader,
    NULL,
    CLSCTX_INPROC,
    IID_IDirectMusicLoader,
    (void**)&m_pLoader);

Then, describe the object, and call the IDirectMusicLoader::GetObject method to load it and obtain the desired interface.

The following code example loads a style from disk and returns a pointer to it in the variable addressed by the parameter.

void myLoadStyle(
    IDirectMusicStyle **ppIStyle)
{
    IDirectMusicLoader *pILoader;        // Loader interface

/* Normally you would create the loader once and use it for the
   duration of the application. This reduces overhead and takes
   advantage of the loader's ability to cache objects. However,
   this example creates it dynamically and throws it
   away once the style is loaded. */

    CoCreateInstance(
            CLSID_DirectMusicLoader,NULL,
            CLSCTX_INPROC,
            IID_IDirectMusicLoader,
            (void **) &pILoader);

    if (pILoader)
    {
        DMUS_OBJECTDESC Desc;

        // Start by initializing Desc with the file name and
        // class GUID for the style object.

        wcscpy(Desc.wszFileName,L"c:\\mymusic\\funky\\polka.sty");
        Desc.guidClass = CLSID_DirectMusicStyle;
        Desc.dwSize = sizeof (DMUS_OBJECTDESC);
        Desc.dwValidData = DMUS_OBJ_CLASS |
                           DMUS_OBJ_FILENAME |
                           DMUS_OBJ_FULLPATH;

        pILoader->GetObject(&Desc, IID_IDirectMusicStyle,
                (void **) ppIStyle);
        pILoader->Release();
    }
}

This code example identifies the file by a full path name and indicates this by setting the DMUS_OBJ_FULLPATH flag. If you have previously set the search directory, you can use the short name of the file without full path information. For an example, see Setting the Loader's Search Directory.

To identify the particular file object being sought, fill in at least one of the wszName, guidObject, and wszFileName members of the DMUS_OBJECTDESC structure, and set the corresponding flag or flags in the dwValidData member. If you identify the file by wszName or guidObject, but not by wszFileName, you must first call the IDirectMusicLoader::ScanDirectory method to make the GUIDs and names in the current directory available. For more information, see Scanning a Directory for Objects.

[Visual Basic]

To load an object, first create a DirectMusicLoader object. Then, call one of the following methods:

  • DirectMusicLoader.LoadBand
  • DirectMusicLoader.LoadCollection
  • DirectMusicLoader.LoadSegment
  • DirectMusicLoader.LoadStyle

Pass in either a simple file name or a full path for the file that contains the desired object. Each of these methods returns an instance of the appropriate class.

The following code example, in which objDX is a DirectX7 object, loads a segment from a file in the current search directory:

Dim objDMLoader As DirectMusicLoader
Dim objSeg As DirectMusicSegment

Set objDMLoader = objDX.DirectMusicLoaderCreate
Set objSeg = objDMLoader.LoadSegment("Myseg.sgt")

See also Loading an Object from a Resource.


Loading an Object from a Resource

[C++]

Loading an object from a resource, or from some other location in memory, is done like loading an object from a file. (See Loading an Object from a File.) In this case, however, the wszName, guidObject, and wszFileName members of the DMUS_OBJECTDESC structure are irrelevant. Instead, you must obtain a pointer to the block of memory occupied by the object, and its size, and put these in the pbMemData and llMemLength members respectively, of the DMUS_OBJECTDESC structure. You must also set the DMUS_OBJ_MEMORY flag in the dwFlags member.

The memory cannot be released once IDirectMusicLoader::GetObject has been called because the loader keeps the pointer to the memory internally to facilitate caching data. If you want to clear it out, call IDirectMusicLoader::SetObject with the same DMUS_OBJECTDESC descriptor, but with NULL in pbMemData. This is not an issue when loading from a resource because resource memory is not freed.

The following code example loads a MIDI file from a resource into a segment:

HRESULT LoadMidi(HMODULE hMod, WORD ResourceID)
{
    HRESULT              hr;
    DMUS_OBJECTDESC      ObjDesc;
    IDirectMusicSegment* pSegment = NULL;

    HRSRC hFound = FindResource(hMod,
            MAKEINTRESOURCE(ResourceID), RT_RCDATA);
    HGLOBAL hRes = LoadResource(hMod, hFound);

    ObjDesc.dwSize = sizeof(DMUS_OBJECTDESC);
    ObjDesc.guidClass = CLSID_DirectMusicSegment;
    ObjDesc.dwValidData = DMUS_OBJ_CLASS | DMUS_OBJ_MEMORY;
    ObjDesc.pbMemData = (BYTE *) LockResource(hRes);
    ObjDesc.llMemLength = SizeofResource(hMod, hFound);

    hr = m_pDXPerformance->m_pLoader->GetObject(
            &ObjDesc, IID_IDirectMusicSegment2,
            (void**) &m_pSegment );

    return hr;
}

Objects referred to by other objects must be loaded first. For example, if you load a segment that contains a reference to a style, the style must already be loaded for the segment to play correctly. You can also call DirectMusicLoader::SetObject on the style so that the segment can find it.

[Visual Basic]

Loading an object from a resource, or from some other location in memory, is done like loading an object from a file. (See Loading an Object from a File.) The DirectMusicLoader.LoadBandFromResource, DirectMusicLoader.LoadChordMapFromResource, DirectMusicLoader.LoadCollectionFromResource, DirectMusicLoader.LoadSegmentFromResource, and DirectMusicLoader.LoadStyleFromResource methods each take a module name and resource identifier as parameters and return an instance of the appropriate class.

The following resource types are recognized by the loader:

"DMBAND" | LoadBandFromResource
"DMCHORD" | LoadChordmapFromResource
"DMCOLL" | LoadCollectionFromResource
"DMSEG" | LoadSegmentFromResource
"DMSTYLE" | LoadStyleFromResource

Objects referred to by other objects must be loaded first. For example, if you load a segment that contains a reference to a style, the style must be loaded first for the segment to play correctly.

The following code example, in which loader is the DirectMusicLoader object and perf is the DirectMusicPerformance, loads and plays a MIDI file stored as a "DMSEG" resource in the executable:

Dim seg As DirectMusicSegment
Set seg = loader.LoadSegmentFromResource("listen.exe", "CANYON.MID")
Call seg.Download(perf)
Call perf.PlaySegment(SEG, 0, 0)


Getting Object Descriptors

[Visual Basic]

This topic pertains only to applications written in C++.

[C++]

Once you have loaded an object. you can use its IDirectMusicObject interface to retrieve information about it in a DMUS_OBJECTDESC structure. You must first obtain the IDirectMusicObject interface for the object.

The following code example uses the IDirectMusicObject::GetDescriptor method to obtain the name of a style:

/* It is assumed that pStyle is a valid pointer to an
   IDirectMusicStyle interface. */

if (pStyle)
{
    IDirectMusicObject *pIObject;
    DMUS_OBJECTDESC Desc;

    if (SUCCEEDED(pStyle->QueryInterface(IID_IDirectMusicObject,
            (void **) &pIObject)
    {
        if (SUCCEEDED(pIObject->GetDescriptor(&Desc))
        {
            if (Desc.dwValidData & DMUS_OBJ_NAME)
            {
                TRACE("Style name is %S\n",Desc.wszName);
            }
        }
        pIObject->Release();
    }
}


Caching Objects

[Visual Basic]

This topic pertains only to applications written in C++.

[C++]

When an object is cached, the same interface pointer is always returned by the IDirectMusicLoader::GetObject method.

Caching is used extensively in the file-loading process to resolve links to objects. If an object is not found in the cache, it has to be reloaded, even if it already exists. For example, two segments could refer to the same style. When the first segment loads, it calls the loader to get the style. The style in turn creates a style object, loads it from disk, stores a pointer to the style in the cache, and returns it to the segment. If caching is enabled, when the second segment loads, it asks for the style, and the loader immediately returns it. Then, both segments point to the same style. If caching is disabled, the second segment's request for the style causes a duplicate style to be loaded from the file. This is very inefficient.

Another example: IDirectMusicBand counts on the loader to keep the General MIDI DLS collection cached. Every time it comes across a GM instrument, it gets the collection from the loader by requesting it with GUID_DefaultGMCollection. If caching for CLSID_DirectMusicCollection is disabled, every patch change in a MIDI file causes a separate copy of the entire GM collection to be created.

By default, caching is enabled for all object classes. You can disable caching for an object class, or for all objects, by using the IDirectMusicLoader::EnableCache method. This method can also be used to re-enable caching for any or all object classes.

If you want to clear the cache without disabling future caching, use the IDirectMusicLoader::ClearCache method.

To cache a single object, pass it to the IDirectMusicLoader::CacheObject method. You can remove it from the cache, ensuring that it will be loaded again on the next call to GetObject, by using the IDirectMusicLoader::ReleaseObject method.

Call ReleaseObject on a cached object, particularly a segment, before destroying the object by calling its own Release method. If you do not, a copy of the object remains in the cache, along with certain state information. In the case of a segment, any instance that you later create will be loaded from the cache, and its start point and loop points will be the same as they were when the previous instance was destroyed.

With judicious use of CacheObject, ReleaseObject, and EnableCache, you can have the objects that you do not need released, while the others remain in the cache.


Setting Objects

[Visual Basic]

This topic pertains only to applications written in C++.

[C++]

Sometimes it is desirable to tell the loader where to get an object, without actually loading that object, so that the loader can retrieve it if the object is later referred to by other objects as they are being loaded. You might also want to give an object a new attribute so that the loader can find it by that attribute.

The SetObject method takes as a parameter a DMUS_OBJECTDESC structure that contains two key pieces of information:

  • A pointer to the data. This can be either a file path or a pointer to a block of memory. (See Loading an Object from a File and Loading an Object from a Resource.)
  • An identifier for the object when it is referred to later. This could be a GUID or a name. Later, the call to GetObject will find the stored object by using the same name or GUID. You cannot change a GUID or name that already exists in the object.
  • The following code example assigns a name to an unnamed object (such as a MIDI file) in a resource:
HRESULT SetObjectFromResource(const GUID* guid, int ID,
        char* type, WCHAR* name)
{
  HRSRC hResource = NULL;
  HGLOBAL hData = NULL;
  hResource = FindResource(g_hInstance, MAKEINTRESOURCE(ID), type);
  if (hResource != NULL)
  {
    hData = LoadResource(g_hInstance, hResource);
    if (hData != NULL)
    {
      DMUS_OBJECTDESC desc;
      if(m_pLoader && (hResource != NULL) && (hData != NULL))
      {
        ZeroMemory(&desc,sizeof(desc));
        desc.pbMemData = (BYTE*) LockResource(*hData);
        desc.llMemLength = SizeofResource(g_hInstance, (*hResource));
        desc.guidClass = (*guid);
        desc.dwSize = sizeof(desc);
        desc.dwValidData = DMUS_OBJ_CLASS | DMUS_OBJ_MEMORY;
        if (name)
        {
            wcscpy(desc.wszName, name);
            desc.dwValidData |= DMUS_OBJ_NAME;
        }
        return m_pLoader->SetObject(&desc);
      }
    }
  }
  return E_FAIL;
}

The following code could be used to assign a name to a MIDI file stored as a resource of type MIDI:

SetObjectFromResource(CLSID_DirectMusicSegment, 101,
        "MIDI", "canyon");

The object can now be loaded at any time by name.


Custom Loading

[Visual Basic]

This topic pertains only to applications written in C++. DirectX for Visual Basic supports only loading of standard DirectMusic objects.

[C++]

Specialized applications might create their own object types that encapsulate data from a file or resource. It can be convenient to have the DirectMusic loader handle the loading of such objects. This is especially true if the custom object is referred to by other objects or contains references to other objects.

To implement a loading mechanism that takes advantage of the DirectMusic loader, take the following steps:

  • Register the object class so that it can be found by IDirectMusicLoader::GetObject.
  • Implement the IDirectMusicObject interface on the object so that the loader can get the information that it needs to find and cache it.
  • Implement the IPersistStream interface on the object, with full functionality in the IPersistStream::Load method. This allows you to parse the data that you obtain through calls on the IStream interface passed by the DirectMusicLoader.
  • In the implementation of Load, ensure that references to other objects are dealt with by querying the IStream for the IDirectMusicGetLoader interface, then calling IDirectMusicGetLoader::GetLoader to obtain a pointer to the DirectMusicLoader that created the stream. Once you have this pointer, call IDirectMusicLoader::GetObject to load the new object.

An application might need to manage file input itself—for example, if all objects are stored in a special compressed resource file. The application can create its own loader by creating an object that supports the IDirectMusicLoader interface, with the IDirectMusicLoader::GetObject method implemented. All other methods are optional. This implementation of the loader must also create its own stream object that has both the IStream and the IDirectMusicGetLoader interfaces.


DirectMusic File Format

[Visual Basic]

This section pertains only to applications written in C++. DirectX for Visual Basic does not support file parsing, which is always handled transparently by the DirectMusicLoader object.

[C++]

This section describes the format of music files created in an application such as DirectMusic Producer and read by DirectMusic when IDirectMusicLoader::GetObject is called. Most applications do not parse these files directly. This format information is included for developers of music-authoring applications or DirectMusic plug-ins who want to be able to save data in a compatible format or load data into their own objects.

DirectMusic data is stored in the resource interchange file format (RIFF). The following topics contain information about RIFF files and how DirectMusic data is stored:

  • About RIFF
  • RIFF Notation
  • DirectMusic File Chunks

For a reference to data structures used in DirectMusic files, see File Structures.


About RIFF

The basic building block of a RIFF file is a chunk. A chunk is a logical unit of data. Each chunk contains the following fields:

  • A four-character code (FOURCC) specifying the chunk identifier. Conventionally, this is uppercase for registered chunk types, and lowercase otherwise.
  • A DWORD value specifying the size of the data member in the chunk.
  • The data.

A chunk contained in another chunk is a subchunk. The only chunks allowed to contain subchunks are those with a chunk identifier of RIFF or LIST.

The first chunk in a file must be identified as RIFF. All other chunks in the file are subchunks of the RIFF chunk.

RIFF chunks include an additional field in the first 4 bytes of the data field. This additional field provides the form type of the chunk. The form type is a four-character code identifying the format of the data stored in the file. For example, DirectMusic styles have the form type DMST.

LIST chunks also include an additional field in the first 4 bytes of the data field. This additional field contains the list type of the field. The list type is a four-character code identifying the contents of the list. For example, DirectMusic styles have a LIST chunk with a list type of "part" that contains data pertaining to a particular part (instrument track) in the performance.

A LIST chunk is a grouping of subchunks. Some of these subchunks might appear multiple times, but a LIST is not an array. The terminology can be a little confusing. You might expect the chunk labeled <part-list>, for example, to be a list of parts. In fact, it is a list of the elements of a "part" chunk, which describes a single part.

Note Every four-character code used in DirectMusic files has a corresponding macro in Dmusicf.h. For example, the FOURCC for DMST is returned by the DMUS_FOURCC_STYLE_FORM macro .

For more information on RIFF files in general, see Resource Interchange File Format Services in the Platform SDK documentation.


RIFF Notation

The descriptions of DirectMusic files in the following sections use a subset of the conventional notation for RIFF files. The principal parts of this notation are shown in the following table:

Notation | Description
<element> | File element labeled "element", or of type element.
[ <element> ] | Optional file element.
<element>... | One or more copies of the specified element.
[<element>]... | Zero or more copies of the specified element.
name, 'name', NAME, or 'NAME' | FOURCC identifier of a form type, list type, or chunk.
// Comment | Comment.

Labels are used only in the notation, not in the files themselves. The label <cheh-ck> refers to a chunk with a unique FOURCC identifier and format. Wherever a chunk of this kind occurs in the notation, the same label is used.

The data or subelements associated with a label are described as follows:

<cheh-ck> -> cheh( <DMUS_IO_CHORDENTRY> )

This notation shows that the chunk labeled <cheh-ck> consists of the FOURCC identifier "cheh" followed by a DMUS_IO_CHORDENTRY structure. Of course, a DWORD showing the size of the data must precede the data, as it does in any RIFF chunk. The presence of this data-size element is assumed and is not shown in the notation.

The next example shows a list element, consisting of the FOURCC LIST followed by the list identifier "cmap" and one or more elements labeled <choe-list>. The <choe-list> element would be expanded elsewhere.

<cmap-list> -> LIST( 'cmap'
    <choe-list>... )


DirectMusic File Chunks

The following sections describe the format of chunks used in DirectMusic RIFF files:

  • Common Chunks
  • Band Form
  • Chord-map Form
  • Segment Form
  • Style Form
  • Tool Form
  • Tool Graph Form
  • Track Form


Common Chunks

The following chunks occur within various list chunks and forms.

GUID Chunk

<guid-ck> -> guid( <GUID> )

This is the GUID identifier of the element.

Version Chunk

<vers-ck> -> vers( <DMUS_IO_VERSION> )

This chunk contains version information for the element.

UNFO Chunk

<UNFO-list> -> LIST( 'UNFO'
    <unfo-text-ck>...
    )

The UNFO chunk is like a standard RIFF INFO list, except that it uses Unicode characters. INFO and UNFO lists consist of various chunks that contain null-terminated strings.

Reference List Chunk

The reference list chunk contains information about a reference to an object in another file. For example, a band object might contain a reference to a DLS collection in a separate file.

The notation for a reference list is as follows:

<DMRF-list> ->LIST( 'DMRF'
    <refh-ck>       // Reference header
    [<guid-ck>]     // Object GUID
    [<date-ck>]     // File date
    [<name-ck>]     // Name
    [<file-ck>]     // File name
    [<catg-ck>]     // Category name
    [<vers-ck>]     // Version information
)

The data begins with a header that includes information about the object being referred to:

<refh-ck> -> refh( <DMUS_IO_REFERENCE> )

All other chunks are optional. The GUID and version chunks were described previously. The notation for the others is as follows:

<date-ck> -> date( <FILETIME> )
<name-ck> -> name( <WCHAR>... )  // Null-terminated string
<file-ck> -> file( <WCHAR>... )  // Null-terminated string
<catg-ck> -> catg( <WCHAR>... )  // Null-terminated string


Band Form

The following notation shows the format of the top-level chunk, or form, of a band file. Band forms can also be contained in other chunks.

RIFF( 'DMBD'
    [<guid-ck>]     // GUID for band
    [<vers-ck>]     // Optional version information
    [<UNFO-list>]   // Name, author, copyright information, comments
    <lbil-list>     // List of instruments
)

For the first three chunks, which are optional, see Common Chunks.

The data is contained in a list of lists:

<lbil-list> -> LIST( 'lbil'
    <lbin-list>...
    )

Each instrument is described in a list that has the following format:

<lbin-list> -> LIST( 'lbin'
    <bins-ck>
    [<DMRF-list>]
    )

Within the instrument list, the following chunk contains a header describing the instrument:

<bins-ck> -> bins( <DMUS_IO_INSTRUMENT> )

The instrument list can also contain <DMRF-list>, which is a reference to a DLS file. See Common Chunks.


Chord-map Form

The following notation shows the organization of the top-level chunk, or form, of a chord-map file:

RIFF( 'DMPR'
    <perh-ck>       // Chord-map header chunk
    [ <guid-ck> ]   // GUID chunk
    [ <vers-ck> ]   // Version chunk
    [ <UNFO-list> ] // UNFO list
    <chdt-ck>       // Chord data chunk
    <chpl-list>     // Chord palette
    <cmap-list>     // Chord graph
    <spsq-list>     // Signpost list
)

Each of the items—with the exception of the GUID chunk, version chunk, and UNFO list—is required. See Common Chunks

The required chunks and their subchunks are as follows:

<perh-ck> -> perh( <DMUS_IO_CHORDMAP> )

This is the basic header information for a chord map.

<chdt-ck> -> chdt(
    <WORD>    // Size of DMUS_IO_CHORDMAP_SUBCHORD
    <DMUS_IO_CHORDMAP_SUBCHORD>...
    )

The <chdt-ck> chunk contains a WORD, indicating the number of bytes per subchord followed by an array of unique subchords. The subchord identifiers referred to in other parts of this file all correspond directly to an index into this array.

<chpl-list> -> LIST( 'chpl'
    <chrd-list>...
    )

This list contains the chord palette. Currently there must be exactly 24 items in this list.

<chrd-list> -> LIST( 'chrd'
    <UNAM-ck>    // Chord name
    <sbcn-ck>    // Subchord indexes
    )

This list contains the basic chord information. This information is the chord's name and a list of identifiers for its subchords.

<UNAM-ck> -> UNAM ( <WCHAR>... )

The UNAM chunk stores the name of the chord.

<sbcn-ck> -> sbcn( <WORD>... )

The "sbcn" chunk contains one or more subchord identifiers. These correspond directly to an index into the array found in <chdt-ck>. Currently a maximum of four chords is supported.

<cmap-list>  ->  LIST( 'cmap'
    <choe-list>...
    )

The "cmap" list contains the entire chord connection graph for the chord map. The bulk of the data for the chord map resides in this chunk.

<choe-list> -> LIST( 'choe'
    <cheh-ck>      // Chord entry data
    <chrd-list>    // Chord data; see above.
    <ncsq-ck>      // Next chord list
    )

The "choe" list contains data for a single entry in the chord graph, along with pointers to all the chords that can occur next in the chord graph.

<cheh-ck> -> cheh( <DMUS_IO_CHORDENTRY> )

This is the chord entry header. The identifier in the structure is the identifier for the chord connection graph, not a subchord identifier.

<ncsq-ck> -> ncsq (
    <WORD>         // Size of DMUS_IO_NEXTCHORD
    <DMUS_IO_NEXTCHORD>...
    )

The "ncsq" chunk contains data that connects one chord in the connection graph to another. Each chord in the connection graph is represented by a 16-bit identifier.

<spsq-list> -> LIST( 'spsq'
    <spst-list>...
    )

The "spsq" list contains data for each of the signposts.

<spst-list>  ->  LIST( 'spst'
    <spsh-ck>
    <chrd-list>  // Chord data; see above.
    [ <cade-list> ]
    )

The "spst" list contains data for a single signpost, consisting of a header, chord information, and optional cadence chords.

<cade-list> -> LIST( 'cade'
    <chrd-list>...
    )

The "cade" list contains the chord information for cadence chords. Currently, there is support for up to two cadence chords in this list. Any additional chords or other information is ignored.

<spsh-ck> -> spsh(
    <DMUS_IO_CHORDMAP_SIGNPOST>
)

Finally, the "spsh" chunk contains the signpost data.


Segment Form

The following notation shows the organization of the top-level chunk of a segment file:

RIFF( 'DMSG'
    <segh-ck>       // Segment header chunk
    [<guid-ck>]     // GUID for the segment
    [<vers-ck>]     // Optional version information
    [<UNFO-list>]   // Name, author, copyright information, comments
    <trkl-list>     // List of tracks
    [<DMTG-form>]   // Optional tool graph
    )

The individual chunks and their subchunks are as follows:

<segh-ck> -> segh( <DMUS_IO_SEGMENT_HEADER> )

This chunk contains the basic header information for a segment. For the next three chunks, see Common Chunks.

Next, comes the track list. Each track is encapsulated in a Track Form.

<trkl-list> -> LIST( 'trkl'
    <DMTK-form>...
    )

Finally, the segment form can contain a Tool Graph Form.


Style Form

The following notation shows the organization of the top-level chunk of a style file:

RIFF( 'DMST'
    <styh-ck>       // Style header chunk
    <guid-ck>       // Unique identifier
    [<UNFO-list>]   // Name, author, copyright information, comments
    [<vers-ck>]     // Version chunk
    <part-list>...  // List of parts in the style, used by patterns
    <pttn-list>...  // List of patterns in the style
    <DMBD-form>...  // List of bands in the style
    [<motf-list>]   // List of motifs in the style
    [<prrf-list>]   // List of chord-map references in the style
)

The individual chunks and their subchunks are as follows:

<styh-ck> -> styh( <DMUS_IO_STYLE> )

This chunk contains the basic header information for a style. For the next three chunks, see Common Chunks.

Next, comes a chunk for each musical part in the style:

<part-list> -> LIST('part'
    <prth-ck>       // Part header chunk
    [<UNFO-list>]
    [<note-ck>]     // List of notes in the part
    [<crve-ck>]     // List of curves in the part
    )

The part list includes a header, an optional UNFO chunk, and a list of notes and curves, as shown in the following example. (For the UNFO list, see Common Chunks.)

<prth-ck> -> prth( <DMUS_IO_STYLEPART> )

<note-ck> -> note(
    < DWORD >  // Size of DMUS_IO_STYLENOTE
    < DMUS_IO_STYLENOTE >...
    )

<crve-ck> -> crve(
    < DWORD >  // Size of DMUS_IO_STYLECURVE
    < DMUS_IO_STYLECURVE >...
    )

After the part-list chunk comes the pattern-list chunk:

<pttn-list> -> LIST( 'pttn'
    <ptnh-ck>       // Pattern-header chunk
    <rhtm-ck>       // List of rhythms for chord matching
    [<UNFO-list>]
    [<mtfs-ck>]     // Motif settings chunk
    <pref-list>...  // List of part reference IDs
    )

The pattern list consists of the following subchunks. (For the optional UNFO list, see Common Chunks.)

<ptnh-ck> -> ptnh(
    < DMUS_IO_PATTERN >
    )

<rhtm-ck> -> rhtm(
    < DWORD >...
    )

This chunk consists of an array of DWORDs, one for each measure, giving the rhythm pattern. For information on the arrangement of the bits, see the dwRhythmPattern member of DMUS_RHYTHM_PARAM.

<mtfs-ck> -> mtfs(
    < DMUS_IO_MOTIFSETTINGS >
    )

<pref-list> -> LIST( 'pref'
    <prfc-ck>   // Part reference chunk
    )

The "pref" chunk in turn consists of an array of part references:

<prfc-ck> -> prfc(
    < DMUS_IO_PARTREF >
    )

The last chunk in the style form is the list of chord-map references:

<prrf-list> -> LIST( 'prrf'
    <DMRF-list>...
    )

For more information on <DMRF-list>, see Common Chunks.


Tool Form

The tool form contains information about tools. Tools can be embedded in a Tool Graph Form or stored as separate files.

<DMTL-form> -> RIFF( 'DMTL'
    <tolh-ck>
    [<guid-ck>]     // GUID for tool object instance
    [<vers-ck>]     // Version information
    [<UNFO-list>]   // Name, author, copyright information, comments
    [<data>]        // Tool data
)

The tool header chunk is as follows:

<tolh-ck> -> tolh( <DMUS_IO_TOOL_HEADER> )

For the next three elements, which are optional, see Common Chunks.

The <data> element consists of a chunk of the type identified in the DMUS_IO_TOOL_HEADER. The format of this chunk depends on the definition of the tool. It can be a list or a chunk.


Tool Graph Form

A tool-graph chunk can occur either as a top-level form or as a subchunk of a segment form.

RIFF( 'DMTG'
    [<guid-ck>]     // GUID for tool graph
    [<vers-ck>]     // Optional version information
    [<UNFO-list>]   // Name, author, copyright information, comments
    <toll-list>     // List of tools
)

For the first three elements, which are optional, see Common Chunks.

The main and only required part of the tool-graph chunk is the tool list:

<toll-list> -> LIST( 'toll'
    <DMTL-form>...
    )

For more information on the <DMTL-form> chunk, see Tool Form.


Track Form

The track form contains information about a single track. It can be embedded in a Segment Form or stored in its own file.

<DMTK-form> -> RIFF( 'DMTK'
    <trkh-ck>
    [<guid-ck>]     // GUID for track object instance
    [<vers-ck>]     // Version information
    [<UNFO-list>]   // Name, author, copyright information, comments
    [<data>]        // Track data
)

The subchunks of the form are as follows:

<trkh-ck> -> trkh(
    <DMUS_IO_TRACK_HEADER>
    )

This chunk contains the basic header information for a track.

For the next three elements, which are optional, see Common Chunks.

The last element in the track form is the data for the track. The chunk type used for the data is identified in the DMUS_IO_TRACK_HEADER structure. The following standard track chunks are defined:

  • Band Track Form
  • Chord Track List
  • Chord-map Track List
  • Command Track Chunk
  • Mute Track Chunk
  • Sequence Track List
  • Signpost Track Chunk
  • Style Track List
  • Sysex Track Chunk
  • Tempo Track Chunk
  • Time Signature Track Chunk


Band Track Form

The band track form can be a top-level form but is also found as the data part of a Track Form. It is organized as follows:

RIFF( 'DMBT'
    [<bdth-ck>]     // Band track header
    [<guid-ck>]     // GUID for band track
    [<vers-ck>]     // Optional version information
    [<UNFO-list>]   // Name, author, copyright information, comments
    <lbdl-list>     // List of band lists
    )

The subchunks of the form are as follows:

<bnth-ck> -> bdth( <DMUS_IO_BAND_TRACK_HEADER> )

This optional chunk contains header information for a band track. The only data in the structure is a flag for automatic downloading.

For the next three elements, which are optional, see Common Chunks.

The last chunk contains one or more bands:

<lbdl-list> -> LIST( 'lbdl'
    <lbnd-list>...
    )

Each band is encapsulated in a list of the following type:

<lbnd-list> -> LIST( 'lbnd'
    <bdih-ck>
    <DMBD-form>
    )

The band list begins with a header:

<bdih-ck> -> ( <DMUS_IO_BAND_ITEM_HEADER> )

The header is followed by a Band Form containing information about the instruments in the band.


Chord Track List

The chord track list contains chord data for a Track Form. It is organized as follows:

<cord-list> -> LIST( 'cord'
    <crdh-ck>       // Header
    <crdb-ck>       // Chord body chunk
    )

The subchunks are as follows:

<crdh-ck> -> crdh ( <DWORD> )

The header is a DWORD containing the chord root in the upper 8 bits and the scale in the lower 24 bits. For an explanation of what these bits represent, see DMUS_IO_SUBCHORD.

The body of data for the chord track list consists of information about a chord change and the component subchords:

<crdb-ck> -> crdb(
    <DWORD>           // Size of DMUS_IO_CHORD
    <DMUS_IO_CHORD>
    <DWORD>           // Number of subchords
    <DWORD>           // Size of DMUS_IO_SUBCHORD
    <DMUS_IO_SUBCHORD>...
    )


Chord-map Track List

The chord-map track list contains data for a Track Form. It is organized as follows:

<pftr-list> -> LIST('pftr'
    <pfrf-list>...
    )

The data consists of one or more lists containing time stamps and references to chord maps:

<pfrf-list> -> LIST('pfrf'
    <stmp-ck>
    <DMRF-list>
    )

The notation for the time stamp chunk is as follows:

<stmp-ck> -> stmp( <DWORD> )

For information on <DMRF-list>, see Common Chunks.


Command Track Chunk

The command track chunk contains data for a Track Form. It is organized as follows:

<cmnd-ck> -> cmnd(
    <DWORD>    //Size of DMUS_IO_COMMAND
    <DMUS_IO_COMMAND>...
    )


Mute Track Chunk

The mute track chunk contains data for a Track Form. It is organized as follows:

<mute-ck> -> mute(
    <DWORD>     //Size of DMUS_IO_MUTE
    <DMUS_IO_MUTE>...
    )


Sequence Track List

The sequence track list contains data for a Track Form. It is organized as follows:

<seqt-list> -> LIST('seqt'
    <evtl-ck>
    <curl-ckt>
    )

The list contains two chunks, one for sequence items and one for curve items:

<evtl-ck> -> evtl(
    <DWORD>     // Size of DMUS_IO_SEQ_ITEM
    <DMUS_IO_SEQ_ITEM>...
    )

<curl-ck> -> curl(
    <DWORD>     // Size of DMUS_IO_CURVE_ITEM
    <DMUS_IO_CURVE_ITEM>...
    )


Signpost Track Chunk

The signpost track chunk contains data for a Track Form. It is organized as follows:

<sgnp-list> -> sgnp(
    <DWORD>    // Size of DMUS_IO_SIGNPOST
    <DMUS_IO_SIGNPOST>...
    )


Style Track List

The style track list contains data for a Track Form. It is organized as follows:

<sttr-list> -> LIST('sttr'(
    <strf-list>...
    )

The data consists of one or more lists containing time stamps and references to styles:

<strf-list> -> LIST('strf'(
    <stmp-ck>
    <DMRF-list>
    )

For information on <DMRF-list>, see Common Chunks.


Sysex Track Chunk

The sysex track chunk contains data for a Track Form. It is an array of sysex items, as shown in the following notation:

<syex-ck> -> syex(
    <DMUS_IO_SYSEX_ITEM>
    <BYTE>...  // Data
    )...


Tempo Track Chunk

The tempo track chunk contains data for a Track Form. It is organized as follows:

<tetr-ck> -> tetr(
    <DWORD>    // Size of DMUS_IO_TEMPO_ITEM
    <DMUS_IO_TEMPO_ITEM>...
    )


Time Signature Track Chunk

The time signature track chunk contains data for a Track Form. It is organized as follows:

<tims-ck> -> tims(
    <DWORD>    // Size of DMUS_IO_TIMESIGNATURE_ITEM
    <DMUS_IO_TIMESIGNATURE_ITEM>...
    )


Using Downloadable Sounds

This section covers the use of downloadable sounds (DLS) in DirectMusic. For an architectural overview of DLS, see Downloadable Sounds.

Most applications do not have to deal directly with instruments or downloadable sounds. The opening of collections and downloading of instrument data is handled by the band object. When you download a band, all the instrument data associated with that band is downloaded as well. For more information, see Using Bands.

[C++]

For specialized DirectMusic applications that do their own DLS management, two steps must be taken: loading the instrument collection and downloading instrument data to a port.

These steps are covered in the following sections:

  • Loading a Collection
  • Working with Instruments
  • Playing a MIDI File with Custom Instruments

Applications that allow the editing of instruments and collections must work with DLS data at an even lower level. This topic is covered in the following section:

  • Low-Level DLS
[Visual Basic]

More information about working with collections is presented in the following topics:

  • Loading a Collection
  • Playing a MIDI File with Custom Instruments


Loading a Collection

[C++]

The simplest way to load a collection from a file is to use the IDirectMusicLoader interface. (For more information, see Loading an Object from a File.) Once you have obtained a pointer to the IDirectMusicCollection interface, you have access to all the instruments in the collection. At this point, though, none of them have actually been downloaded to a port. In fact, no instrument data is loaded into memory until it is needed.

The collection is a COM object that supports the IDirectMusicCollection, IDirectMusicObject, and IPersistStream interfaces. IPersistStream is a standard COM interface providing methods for saving and loading objects that use a simple serial stream for their storage needs.

IDirectMusicCollection does not load the entire collection when IPersistStream::Load is called. Typically, objects supporting IPersistStream load all the persistent data in the stream and do not use the IStream pointer outside the Load method. However, supporting IPersistStream::Load in this manner in IDirectMusicCollection would mean that the entire DLS collection would have to be loaded into memory even if only a single instrument in the collection was to be used. Instead, IDirectMusicCollection saves the IStream pointer, and later uses it to load only the data for instruments that are downloaded to a DirectMusic port. IDirectMusicCollection assumes that the data stream provided through the IPersistStream interface is in the DLS file format.

The following code example does manually what the IDirectMusicLoader::GetObject method does automatically: it creates a collection object and loads a stream into it:

HRESULT myLoadCollectionFromStream(
        IStream *pIStream,    // Stream created from a file
        IDirectMusicCollection **ppICollection )

{
    HRESULT hr;

    hr = CoCreateInstance(CLSID_DirectMusicCollection,
                          NULL,
                          CLSCTX_INPROC,
                          IID_IDirectMusicCollection,
                          (void **)ppICollection);
    if (SUCCEEDED(hr))
    {
        IPersistStream* pIPersistStream;
        hr = *ppICollection->QueryInterface(
                IID_IPersistStream, (void**)&pIPersistStream);
        if (SUCCEEDED(hr))
        {
            hr = pIPersistStream->Load(pIStream);
            pIPersistStream->Release();
        }
    }
    return hr;
}

The following code example uses the DirectMusicLoader to load the collection by file name:

HRESULT myLoadCollectionByName(
        IDirectMusicLoader *pILoader,
        char *pszFileName,
        IDirectMusicCollection **ppICollection)
{
    HRESULT hr;
    DMUS_OBJECTDESC Desc;             // Descriptor

    // Start by initializing Desc with the file name and GUID
    // for the collection object.
    // The file name starts as a char string, so convert
    // to Unicode.

    mbstowcs(Desc.wszFileName,pszFileName,DMUS_MAX_FILENAME);
    Desc.dwSize = sizeof(DMUS_OBJECTDESC);
    Desc.guidClass = CLSID_DirectMusicCollection;
    Desc.dwValidData = DMUS_OBJ_CLASS
            | DMUS_OBJ_FILENAME
            | DMUS_OBJ_FULLPATH;

    hr = pILoader->GetObject(&Desc,
            IID_IDirectMusicCollection,
            (void **) ppICollection);
    return hr;
}

To load the standard GM/GS set, pass GUID_DefaultGMCollection to the loader in the guidObject member of the DMUS_OBJECTDESC structure. If you intend to use the loader to access this object more than once, make sure that caching is enabled (as it is by default) so that you do not create another copy of the GM collection each time that you request it.

Note The GM/GS Sound Set cannot be altered. For more information, see the Copyright Warning.

The following code example illustrates how to load a collection identified by its GUID:

HRESULT myGetGMCollection(
        IDirectMusicLoader *pILoader,
        IDirectMusicCollection **ppICollection)
{
    HRESULT hr;
    DMUS_OBJECTDESC desc;

    desc.dwSize = sizeof(DMUS_OBJECTDESC);
    desc.guidClass = CLSID_DirectMusicCollection;
    desc.guidObject = GUID_DefaultGMCollection;
    desc.dwValidData = (DMUS_OBJ_CLASS | DMUS_OBJ_OBJECT);
    hr = pILoader->GetObject(&desc, IID_IDirectMusicCollection,
            (void **) ppICollection);
    return hr;
}
[Visual Basic]

To load an instrument collection, call the DirectMusicLoader.LoadCollection or the DirectMusicLoader.LoadCollectionFromResource method. Each of these methods returns a DirectMusicCollection object. This object has no methods, and its sole function is as a parameter to DirectMusicSegment.ConnectToCollection. Call that method to associate the collection with a segment, and then download the instruments by calling DirectMusicSegment.Download.

These steps are necessary only when you want to use a collection other than the default one. Normally, when you call DirectMusicSegment.Download, the instruments downloaded to the port are from the default collection authored into the segment or from the General MIDI set, if the segment does not contain a custom collection or is a MIDI file. When you download a band, all DLS data needed by the instruments in that band is downloaded. See Using Bands.


Working with Instruments

[Visual Basic]

This topic pertains only to applications written in C++. DirectX for Visual Basic does not allow applications to work with individual instruments from a collection.

[C++]

Once a DirectMusicCollection is created and loaded from a collection file, you can retrieve the patch number and name of all the available instruments by using the IDirectMusicCollection::EnumInstrument method.

The following code example enumerates all instruments in a collection and displays their names and patch numbers.

void myListInstruments(
        IDirectMusicCollection *pCollection)

{
    HRESULT hr = S_OK;
    DWORD dwPatch;
    WCHAR wszName[MAX_PATH];
    DWORD dwIndex;
    for (dwIndex = 0; hr == S_OK; dwIndex++)
    {
        hr = pCollection->EnumInstrument(
                dwIndex, &dwPatch, wszName, MAX_PATH);
        if (hr == S_OK)
        {
           printf("Patch %lx is %S\n",dwPatch,wszName);
        }
    }
}

You can obtain a pointer to a specific instrument by passing its patch number to the IDirectMusicCollection::GetInstrument method.

After obtaining an instrument, you can change its patch number by using the IDirectMusicInstrument::SetPatch method.

Loading a collection and retrieving the instruments is only the first step in making the instruments available. You must next download them to the port.

To download an instrument to a port, pass an IDirectMusicInstrument interface pointer to the IDirectMusicPort::DownloadInstrument method. This method makes the DLS data available on the port; it does not actually associate the instrument with any particular performance.

You can also download an instrument by using the IDirectMusicPerformance::DownloadInstrument method. In addition to downloading the DLS data, this method assigns the instrument to a particular performance channel.

To save memory, only waves and articulation required for given ranges of notes are downloaded. For example, for a bassoon you might specify that only data for the note range from low C through middle B is to be downloaded. Only the data for the regions falling within that range would be downloaded.

The following code example, given a collection, a patch number, a port, and a range of notes, retrieves the instrument from the collection and downloads it. It sets up an array of one DMUS_NOTERANGE structure and passes this to the IDirectMusicPort::DownloadInstrument method. Typically, only a single range of notes is specified, but you can specify multiple ranges. If you pass NULL instead of a pointer to an array, the data for all regions is downloaded.

HRESULT myDownload(
    IDirectMusicCollection *pCollection,    // DLS collection
    IDirectMusicPort *pPort,                // Destination port
    IDirectMusicDownloadedInstrument **ppDLInstrument,
    DWORD dwPatch,                          // Requested instrument
    DWORD dwLowNote,                        // Low note of range
    DWORD dwHighNote)                       // High note of range

{
    HRESULT hr;
    IDirectMusicInstrument* pInstrument;
    hr = pCollection->GetInstrument(dwPatch, &pInstrument);
    if (SUCCEEDED(hr))
    {
        DMUS_NOTERANGE NoteRange[1];         // Optional note range
        NoteRange[0].dwLowNote = dwLowNote;
        NoteRange[0].dwHighNote = dwHighNote;
        hr = pPort->DownloadInstrument(pInstrument,
                ppDLInstrument,
                NoteRange,   // Array of ranges
                1);          // Number of elements in the array
        pInstrument->Release();
    }
    return hr;
}

The DownloadInstrument method returns a pointer to the IDirectMusicDownloadedInstrument interface. This pointer has just one purpose: to identify the instrument in a subsequent call to the IDirectMusicPort::UnloadInstrument method, which unloads the instance of the instrument on a particular port. (The DirectMusicCollection is not bound to any specific port. You can download different instruments to different ports or download a single instrument to multiple ports.)

The following code example downloads an instrument, and then unloads it, which illustrates how the IDirectMusicDownloadedInstrument pointer can be used:

HRESULT myFickleDownload(
        IDirectMusicInstrument* pInstrument,
        IDirectMusicPort *pPort,
        DWORD dwPatch)

{
    HRESULT hr;
    IDirectMusicDownloadedInstrument * pDLInstrument;
    hr = pPort->DownloadInstrument(
            pInstrument, &pDLInstrument,
            NULL, 0);
    if (SUCCEEDED(hr))
    {
        pPort->UnloadInstrument(pDLInstrument);
        pDLInstrument->Release();
    }
    return hr;
}

The IDirectMusicBand::Download method automates the downloading of all instruments in a band. You supply a pointer to a performance, and the method downloads each instrument to the appropriate port attached to that performance.


Playing a MIDI File with Custom Instruments

By default, when you play a MIDI file, the instruments used are those in the Roland GM/GS Sound Set, contained in the Gm.dls file. However, you can play a MIDI file, using instruments from any collection.

[C++]

To do so, first load the collection, as described in Loading a Collection, obtaining a pointer to the IDirectMusicCollection interface. Then call IDirectMusicSegment::SetParam on the MIDI segment to establish a connection between the segment and the collection.

The following code example shows how the connection is made:

/* Assume that pSegment was created from a MIDI file
   and that pLoadedCollection is a valid IDirectMusicCollection
   pointer. */

HRESULT hr = pSegment->SetParam(GUID_ConnectToDLSCollection,
        0xFFFFFFFF, 0, 0,
        (void*)pLoadedCollection);

As with any other collection, instruments to be used in playing a MIDI file must be downloaded before the segment is played, unless automatic downloading has been enabled. (For more information on automatic downloading, see Setting and Retrieving Global Parameters and Downloading and Unloading Bands.) If instruments are not being downloaded automatically, you must download them by calling IDirectMusicSegment::SetParam, as in the following code example:

/* pSegment is an IDirectMusicSegment pointer, and pPerformance
   is a valid pointer to IDirectMusicPerformance. */

pSegment->SetParam(GUID_Download, 0xFFFFFFFF, 0, 0, (void *) pPerformance);

For more information on downloading by using SetParam, see Setting and Retrieving Track Parameters.

[Visual Basic]

To do so, load the collection, associate it with the segment, based on the MIDI file, and download the collection as you would with any other segment. For more information, see Loading a Collection.

Note When a custom collection is attached to a MIDI segment, the connection to the GM collection is not broken. For example, suppose you load a collection containing a single instrument that has a patch number of 12 and connect this to the segment. MIDI channels with any patch number other than 12 continue to be played by the appropriate instruments in the GM collection.


Low-Level DLS

[Visual Basic]

This topic pertains only to applications written in C++. DirectX for Visual Basic does not support low-level manipulation of DLS data.

[C++]

If you are writing a DirectMusic application that edits DLS collections, you must be able to download instrument data to the synthesizer without encapsulating it in a DirectMusicInstrument object.

Working with DLS data requires knowledge of the DLS specification and file structure. For detailed information on these topics, contact the MIDI Manufacturers Association.

To download raw instrument data, you must first get a pointer to the IDirectMusicPortDownload interface, as shown in the following code example, in which it is assumed that pIPort is a valid pointer to an IDirectMusicPort interface:

IDirectMusicPortDownload **ppIDownloadPort;

HRESULT hr = pIPort->QueryInterface(IID_IDirectMusicPortDownload,
        (void **) ppIDownloadPort);

If the HRESULT is not S_OK, the port does not support DLS downloading.

Next, identify the buffers that must be prepared and downloaded. To send an instrument to the synthesizer, create one instrument buffer that represents the entire instrument definition with all the regions and articulations, and a series of wave buffers, one for each wave that the instrument refers to for its regions.

Each buffer must be tagged with a unique identifier. Identifiers are used to resolve linkages between buffers, in particular the links between regions and waves. Tally the number of buffers that you need to download, and call IDirectMusicPortDownload::GetDLId to allocate a range of identifiers. For example, if you are downloading an instrument with three waves, you must download four buffers in all. Therefore, request a set of four identifiers.

For each buffer, calculate the size needed; then call IDirectMusicPortDownload::AllocateBuffer to allocate it. This method returns an IDirectMusicDownload interface representing the buffer. Call IDirectMusicDownload::GetBuffer to access the memory.

Note There are two methods called GetBuffer:

IDirectMusicPortDownload::GetBuffer returns an IDirectMusicDownload interface pointer for a buffer object whose download identifier is known.

IDirectMusicDownload::GetBuffer returns a pointer to the memory in the buffer.

Now write the data into each buffer. Each buffer starts with a DMUS_DOWNLOADINFO structure, which defines the size and functionality of the download. This structure must be prepared as follows:

  • Set the dwDLType member to either DMUS_DOWNLOADINFO_INSTRUMENT for an instrument or DMUS_DOWNLOADINFO_WAVE for a wave.
  • Set the dwDLId member to one of the unique identifiers that you obtained by using IDirectMusicPortDownload::GetDLId.
  • Set the dwNumOffsetTableEntries member to the number of entries in the DMUS_OFFSETTABLE structure.
  • Set the cbSize member to the size of the download chunk, including DMUS_DOWNLOADINFO and DMUS_OFFSETTABLE.

The DMUS_DOWNLOADINFO structure is always followed by a DMUS_OFFSETTABLE structure. This offset table is used to manage all links within the data. Whenever a structure in the data refers to another structure, it addresses it with an integer index, instead of a pointer. For every structure within the data that can be referred to, there is a unique index. The DMUS_OFFSETTABLE translates this integer index into a byte offset into the data.

The instrument or wave data follows the DMUS_OFFSETTABLE. If the download is an instrument, the data starts with the DMUS_INSTRUMENT structure. Otherwise, it starts with the DMUS_WAVE structure.

The instrument data that follows the DMUS_INSTRUMENT structure is organized in the following structures:

  • DMUS_ARTICPARAMS
  • DMUS_ARTICULATION
  • DMUS_COPYRIGHT
  • DMUS_EXTENSIONCHUNK
  • DMUS_INSTRUMENT
  • DMUS_NOTERANGE
  • DMUS_REGION

The wave data pointed to by the DMUS_WAVE structure is organized in a DMUS_WAVEDATA structure.

When the buffers are all ready, download them by using IDirectMusicPortDownload::Download. Download the wave buffers first so that they are in place and can be referred to when the instrument is downloaded.

Once the buffers have been downloaded, the synthesizer is ready to play the instrument. The memory in the buffer is no longer accessible.

Later, when done playing the instrument, unload the buffers, and release them. First, unload the instrument buffer, then all the wave buffers. To unload, call IDirectMusicPortDownload::Unload and pass it the IDirectMusicDownload objects. Then, release each buffer with a call to IDirectMusicDownload::Release.

To update an instrument that has already been downloaded, you cannot write over the previously downloaded buffer. Instead, replace the instrument, but not the waves. To do this, call IDirectMusicPortDownload::AllocateBuffer to allocate a new IDirectMusicDownload interface with a buffer of the correct size. Be sure to generate a new identifier for the buffer with a call to IDirectMusicPortDownload::GetDLId. Write the new articulation information into the buffer; then download it. Then unload the previously downloaded buffer with a call to IDirectMusicPortDownload::Unload.

To update a wave buffer, take one extra step. Create both a new wave buffer and an updated instrument buffer that refers to it. Download the new wave, then the new instrument. Then unload the old instrument, followed by the old wave.


Playing Music

This section introduces the basic elements of a DirectMusic performance and the key methods that you need to get music data from source to output.

The following topics are discussed:

  • Creating the Performance
  • Segments
  • Tracks
  • Using Bands
  • Timing
  • Notification and Event Handling


Creating the Performance

[C++]

The manager of music playback is the performance object, which does most of the work of getting music from the source to the output buffer. It performs the following tasks:

  • Adding ports
  • Assigning instruments to channels
  • Downloading instrument data to the synthesizer
  • Playing and stopping segments
  • Dispatching messages
  • Managing tools and timing

Most applications have a single DirectMusicPerformance object, but it is possible to have more than one performance with different parameters, such as master tempo or volume.

The following code example creates a performance and obtains a pointer to the IDirectMusicPerformance interface:

IDirectMusicPerformance* pPerf;

if (FAILED(CoCreateInstance(
        CLSID_DirectMusicPerformance,
        NULL,
        CLSCTX_INPROC,
        IID_IDirectMusicPerformance,
        (void**)&pPerf
    )))
{
    pPerf = NULL;
}

Once the performance is created, it must be initialized. An important part of initialization is the creation of a DirectMusic object. You can create a DirectMusic object by passing CLSID_DirectMusic to CoCreateInstance, and then passing the IDirectMusic interface pointer to IDirectMusicPerformance::Init. However, in most cases, it is more convenient to have Init create the DirectMusic object. You can also choose whether or not to retrieve a pointer to the IDirectMusic interface, depending on how much control you need over ports and the master clock. If you intend to use only the default synthesizer and the default master clock, you probably do not need access to the methods of IDirectMusic; in this case, you would pass NULL to Init.

The following code example initializes the performance, retrieves a pointer to IDirectMusic, and creates an IDirectSound interface initialized with the application window handle:

IDirectMusic* pDirectMusic;

if (SUCCEEDED(pPerf->Init(&pDirectMusic,
        NULL,     // Create a DirectSound object.
        hWnd      // Application window handle
        )))
{
    // Performance initialized
}
[Visual Basic]

The manager of music playback is the performance object, which does most of the work of getting music from the source to the output buffer. It performs the following tasks:

  • Enumerating ports and setting the active port
  • Playing and stopping segments
  • Dispatching messages
  • Managing the timing

Most applications have a single DirectMusicPerformance object, but it is possible to have more than one performance with different parameters, such as master tempo or volume, or even playing on different ports.

The follow code example, in which objDX is a DirectX7 object, creates a performance with its own DirectSound object, initializes it, and sets it to use the default port with one channel group:

Dim objDMPerformance as DirectMusicPerformance

Set objDMPerformance = objDX.DirectMusicPerformanceCreate
Call objDMPerformance.Init(Nothing, 0)
Call objDMPerformance.SetPort(-1, 1)

For more information on setting up the performance, see Integrating DirectMusic and DirectSound and Using Ports.


Segments

[C++]

The basic chunk of data in DirectMusic is called a segment. A segment is represented by an IDirectMusicSegment interface. You can create a segment in any of the following ways:

  • Load a file or resource object that supports the IDirectMusicSegment interface. For more information, see DirectMusic Loader.
  • Get a motif from a style by using the IDirectMusicStyle::GetMotif method.
  • Use methods of the IDirectMusicComposer interface to create a composition or transition at run time. See Overview of Programming for Composition and Using Transitions.
  • Make a copy of an existing segment by using the IDirectMusicSegment::Clone method.
  • Construct a segment from existing tracks. Create a segment object by calling CoCreateInstance, and then add tracks by calling IDirectMusicSegment::InsertTrack.
  • Use the IDirectMusicBand::CreateSegment method. This creates a special type of secondary segment that is used only for making band changes. See Making Band Changes Programmatically.

Each segment consists of one or more tracks, each represented by an IDirectMusicTrack interface. Tracks contain most of the data for the segment, whether that data consists of note events, band changes, tempo changes, or other timed events. Applications generally do not need to use this interface because the tracks are managed through the segment object. For more information, see Tracks.

[Visual Basic]

The basic chunk of data in DirectMusic is called a segment. A segment is represented by a DirectMusicSegment object. You can create a segment in any of the following ways:

  • Load a file or resource object that supports the DirectMusicSegment class by using the DirectMusicLoader.LoadSegment or the DirectMusicLoader.LoadSegmentFromResource method. For more information, see DirectMusic Loader.
  • Get a motif from a style by using the DirectMusicStyle.GetMotif method.
  • Use methods of the DirectMusicComposer class to create a composition or transition at run time. See Overview of Programming for Composition and Using Transitions.
  • Make a copy of an existing segment by using the DirectMusicSegment.Clone method.
  • Use the DirectMusicBand.CreateSegment method. This creates a special type of secondary segment that is used only for making band changes. See Making Band Changes Programmatically.

Segments can serve different purposes. The following are the kinds of segments that you are most likely to use:

  • Primary segment. A piece of music such as a MIDI file, a segment authored in DirectMusic Producer, or a segment formed at run time by the composer object.
  • Motif segment. A short piece of music to be played over the primary segment. Motifs are part of a style object, but you can also create short secondary segments from other sources and play them over the primary segment like motifs.
  • Band segment. A set of instruments and instrument settings for the various channels in the performance. The application can play a band segment to execute changes in the band performing the music.
  • Template segment. A guide to chord progressions, groove levels, and embellishments, used in conjunction with a style and chord map to compose music at run time. Unlike other segments, a template segment is never played directly by an application; instead, it is passed to the composer object to be used in creating a musical segment.
[C++]

The playback of segments is controlled by the IDirectMusicPerformance interface and begins with a call to IDirectMusicPerformance::PlaySegment. An instance of a playing segment is represented by an IDirectMusicSegmentState interface, which can be used to retrieve information about the current state of the segment.

[Visual Basic]

The playback of segments is controlled by the DirectMusicPerformance object and begins with a call to DirectMusicPerformance.PlaySegment. An instance of a playing segment is represented by a DirectMusicSegmentState object, which can be used to retrieve information about the current state of the segment.

Only one primary segment can play inside a performance. When you cue a primary segment for playback, you can specify that it is to be played after the currently playing segment is finished, or you can use it to replace the current primary segment.

Secondary segments, on the other hand, play over the current primary segment, and any number of secondary segments can be playing simultaneously.

Secondary segments do not normally alter the performance of the primary segment. For example, a secondary segment can be based on a different style without affecting the style of the primary segment.

[C++]

However, a secondary segment can be designated as a control segment, in which case it takes over the task of responding to IDirectMusicPerformance::SetParam and IDirectMusicPerformance::GetParam calls, which normally go to tracks in the primary segment. Thus a control segment might control the current chord or groove level. For more information, see Tracks.

For more information on playing secondary segments as control segments, see DMUS_SEGF_FLAGS.

[Visual Basic]

However, a secondary segment can be designated a control segment, in which case it takes over the task of responding to certain calls such as DirectMusicPerformance.GetCommand and would also control some aspects of the music, such as the current chord or groove level.

For more information on playing secondary segments as control segments, see CONST_DMUS_SEGF_FLAGS.

For more information on segment playback, see Segment Timing.


Tracks

Tracks are the components of a segment that contain its sequenced data, including information about notes, underlying chords, tempo, patch and band changes, and everything else that the performance needs to know to play a piece of music.

[Visual Basic]

DirectX for Visual Basic does not provide applications with access to individual tracks. All playback is handled at the segment level.

[C++]

Each track is represented by an IDirectMusicTrack interface. The methods of this interface are called by the performance, and most applications do not need to use them directly.

When an application calls IDirectMusicPerformance::PlaySegment, DirectMusic calls the IDirectMusicTrack::Play method on the segment's tracks. Most tracks respond by immediately generating time-stamped messages containing data that is valid for the part of the segment that is being played. These messages are placed in a queue. (See Message Creation and Delivery for more information about what happens after that.)

A few tracks do not actively generate messages in response to IDirectMusicTrack::Play, but instead do their work by responding to requests for information that come from the performance or other tracks in the form of a GetParam call. (See Setting and Retrieving Track Parameters.)

The following list shows the standard track types implemented by DirectMusic, with a brief description of each one. For a list of the methods supported by the standard tracks, see the reference for IDirectMusicTrack.

  • Band. Downloads DLS data to the performance. Sends messages of type DMUS_PATCH_PMSG, DMUS_TRANSPOSE_PMSG, DMUS_CHANNEL_PRIORITY_PMSG, and DMUS_MIDI_PMSG (for volume and pan). Used in segments based on MIDI files and styles.
  • Chord. Used to convert music values (as stored in patterns) to MIDI values. Sends messages of type DMUS_NOTIFICATION_PMSG (for GUID_NOTIFICATION_CHORD notifications).
  • Chord map. Used in template segments to compose chord tracks.
  • Command. Used in template segments to compose chord tracks, and in style segments to determine which patterns is played. Sends messages of type DMUS_NOTIFICATION_PMSG (for GUID_NOTIFICATION_COMMAND notifications).
  • Motif. Used to play motifs to accompany other segments. Sends messages of type DMUS_CURVE_PMSG, DMUS_NOTE_PMSG, and DMUS_NOTIFICATION_PMSG (for GUID_NOTIFICATION_MEASUREANDBEAT notifications).
  • Mute. Used with either style-based or MIDI-based segments. Allows PChannels to be remapped to other PChannels or to be muted.
  • Sequence. Sends sequence messages of type DMUS_NOTE_PMSG and DMUS_MIDI_PMSG. Used in segments based on MIDI files. Also sends messages of type DMUS_CURVE_PMSG for segments saved in the .sgt format.
  • Signpost. Used in template segments to compose chord tracks.
  • Style. Fundamental track for segments based on styles. Sends messages of type DMUS_TIMESIG_PMSG, DMUS_CURVE_PMSG, DMUS_NOTE_PMSG, and DMUS_NOTIFICATION_PMSG (for GUID_NOTIFICATION_MEASUREANDBEAT notifications).
  • SysEx. Sends system-exclusive messages of type DMUS_SYSEX_PMSG. Used in segments based on MIDI files.
  • Tempo. Sets the tempo of the performance by sending messages of type DMUS_TEMPO_PMSG.
  • Time Signature. Sends messages of type DMUS_TIMESIG_PMSG as well as GUID_NOTIFICATION_MEASUREANDBEAT notifications. Used in segments based on MIDI files.


Using Bands

A band is a choice of instruments assigned to particular parts in a style. At performance time, each instrument track is mapped to a PChannel, which stores the following information:

  • MIDI volume.
  • MIDI pan.
  • Transposition. If this value is nonzero, music notes on the channel are automatically transposed for the instrument.
  • The instrument's MIDI patch number, including MSB and LSB bank selects.
  • A reference to the DLS collection from which to load the instrument. By default, the DLS collection is the standard General MIDI collection.

Segments and styles always contain at least one band, called the default band. Styles can contain additional bands. When you load a segment or style, the default band and any other bands are automatically loaded, as well. However, you must still download the DLS data for the instruments in any band that you intend to use.

[C++]

You can retrieve a pointer to the default band by using the IDirectMusicStyle::GetDefaultBand method.

Other bands might be authored into the style and can be found and retrieved by using the IDirectMusicStyle::EnumBand and IDirectMusicStyle::GetBand methods. Bands can also be obtained from other style files or from band files. Once you have obtained an IDirectMusicBand interface, you have access to that band and can substitute it for the default band.

[Visual Basic]

You can retrieve an object representing the default band by using the DirectMusicStyle.GetDefaultBand method. Other bands might be authored into the style and can be retrieved by using the DirectMusicStyle.GetBand method. Bands can also be obtained from other style files or from band files. Once you have obtained a DirectMusicBand object, you have access to that band and can substitute it for the default band.

Loading a band from its own file is like loading any other object in DirectMusic. For more information, see DirectMusic Loader.

More information about bands is contained in the following topics:

  • Downloading and Unloading Bands
  • Making Band Changes Programmatically
  • Ensuring Timely Band Changes


Downloading and Unloading Bands

Before a band can be used, the instruments that it refers to must be downloaded to the performance. This step maps the instruments to PChannels and downloads the DLS data to the port.

By default, the application is responsible for downloading any band that it uses. However, you can turn on automatic downloading of bands. When automatic downloading is on, the instruments in the band are downloaded when the segment containing the band is cued. The instruments are automatically unloaded when the segment is stopped, unless another segment using the same instruments is cued to play immediately or is currently playing.

Note Automatic downloading should be used only when the timing of segment starts is not critical. Repeated loading and unloading of instruments takes time and can cause serious degradation of performance in complex musical environments.

Be aware also that automatic unloading, which is part of the automatic downloading mechanism, can lead to undesired results. For example, suppose you play a short secondary segment that changes the instrument on a channel. The instrument is automatically downloaded when the secondary segment starts, replacing the existing instrument. When the secondary segment ends, the instrument is automatically unloaded. Therefore, there is no instrument on that channel, and the channel plays silence.

Downloading a band makes the band available to the performance but does not perform any program changes. Program changes take place in response to messages generated by the segment's band track, which is typically authored into a segment file. For information on how to make program changes at run time, see Making Band Changes Programmatically.

Information about how to implement downloading and unloading of bands is contained in the following topics:

  • Automatically Downloading Bands
  • Manually Downloading Bands
  • Unloading Bands


Automatically Downloading Bands

[C++]

You can turn on automatic downloading of bands in one of the following ways:

  • Call the IDirectMusicPerformance::SetParam method for the GUID_PerfAutoDownload parameter. See Setting and Retrieving Global Parameters and the following example.
  • Call the IDirectMusicSegment::SetParam or the IDirectMusicTrack::SetParam method for the GUID_Enable_Auto_Download parameter. See Setting and Retrieving Track Parameters.

In the following code example, the global parameter for the performance pPerf is set to enable automatic downloading of bands:

BOOL fAuto = TRUE;
pPerf->SetGlobalParam(GUID_PerfAutoDownload, &fAuto, sizeof(BOOL));
[Visual Basic]

You can turn on automatic downloading of bands for the entire performance by using the DirectMusicPerformance.SetMasterAutoDownload method, or for an individual segment by using the DirectMusicSegment.SetAutoDownloadEnable method.


Manually Downloading Bands

[C++]

You can manually download a band in one of the following ways:

  • Obtain an IDirectMusicBand interface from a loaded object, and call the IDirectMusicBand::Download method. (See the following example.) This is the best way to download the band if you want to unload it after any segments using the band have been released.
  • Call the IDirectMusicSegment::SetParam method with the GUID_Download parameter to download the band in the segment's first band track. You can also use IDirectMusicPerformance::SetParam to set this parameter on the primary segment, or IDirectMusicTrack::SetParam to set it directly on a band track. See Setting and Retrieving Track Parameters.

There is no danger in downloading the same instrument multiple times. If an instrument appears in one band multiple times or if it appears in multiple bands that are all opened and downloaded at the same time, only one copy of the instrument is sent down to the synthesizer.

The following function loads a band from disk and downloads it:

HRESULT myDownloadBand(
    IDirectMusicLoader *pILoader,      // Loader interface
    IDirectMusicBand **ppBand,         // To retrieve pointer
    IDirectMusicPerformance *pPerf,    // Performance to use band
    WCHAR *pwszFile)                   // File to load

{
    HRESULT hr;
    DMUS_OBJECTDESC Desc;              // Descriptor

    // Start by initializing Desc with the file name and GUID
    // for the band object.

    wcscpy(Desc.wszFileName,pwszFile);
    Desc.dwSize = sizeof(Desc);
    Desc.guidClass = CLSID_DirectMusicBand;
    Desc.dwValidData = DMUS_OBJ_CLASS |
            DMUS_OBJ_FILENAME | DMUS_OBJ_FULLPATH;

    hr = pILoader->GetObject(&Desc, IID_IDirectMusicBand,
            (void **) ppBand);
    if (SUCCEEDED(hr))
    {

        // Download the band via the performance.
        hr = (*ppBand)->Download(pPerf);

    }
    return hr;
}
[Visual Basic]

You can manually download a band by obtaining a DirectMusicBand object from a file, a resource, or a DirectMusicStyle object, and then using its DirectMusicBand.Download method.


Unloading Bands

[C++]

Bands take up memory, so they should be unloaded when they are no longer in use. If you have enabled automatic downloading of bands, the bands associated with a segment are unloaded automatically when the segment ends. Otherwise, you can manually unload a band in one of the following ways:

  • Call the IDirectMusicBand::Unload method.
  • Call the IDirectMusicSegment::SetParam method for the GUID_Unload parameter to unload the band in the segment's band track. You can also use IDirectMusicPerformance::SetParam to set this parameter on the primary segment, or IDirectMusicTrack::SetParam to set it directly on the band track. See Setting and Retrieving Track Parameters. For an example, see Tutorial 1, Step 6: Shut Down DirectMusic.

The IDirectMusicPerformance::CloseDown method also unloads any remaining downloaded instruments.

[Visual Basic]

Bands take up memory, so they should be unloaded when they are no longer in use. If you have enabled automatic downloading of bands, the bands associated with a segment are unloaded automatically when the segment ends. Otherwise, you can manually unload a band by using the DirectMusicBand.Unload method.

The DirectMusicPerformance.CloseDown method also unloads any remaining downloaded instruments.


Making Band Changes Programmatically

Usually, the band track in a loaded segment performs program changes. However, you can also do so manually.

[C++]

First, create a secondary segment with a call to the IDirectMusicBand::CreateSegment method, and then play that segment by calling IDirectMusicPerformance::PlaySegment. Typically, you would use DMUS_SEGF_MEASURE or DMUS_SEGF_GRID (see DMUS_SEGF_FLAGS) in the dwFlags parameter to ensure that the band change takes effect on an appropriate boundary.

The following code example creates a segment from a band and plays it:

/ * It is presumed that automatic downloading is turned on or that the application has called pBand->Download. */

HRESULT myPlayBand(
    IDirectMusicBand *pBand,         // Pointer to a band object
    IDirectMusicPerformance *pPerf,  // Performance to use the band
    REFERENCE_TIME rfTime,           // Time to play at
    DWORD dwFlags)                   // Performance flags

{
    IDirectMusicSegment *pSegment;
    HRESULT hr = pBand->CreateSegment(&pSegment);
    if (SUCCEEDED(hr))
    {
        hr = pPerf->PlaySegment(pSegment,
                dwFlags | DMUS_SEGF_SECONDARY,
                rfTime,
                NULL);
        pSegment->Release();
    }
    return hr;
}
[Visual Basic]

First, create a segment by using DirectMusicBand.CreateSegment, and then play that segment by calling DirectMusicPerformance.PlaySegment. Typically, you would use DMUS_SEGF_MEASURE or DMUS_SEGF_GRID (see CONST_DMUS_SEGF_FLAGS) in the lFlags parameter to ensure that the band change takes effect on an appropriate boundary.

A performance can be playing instruments from more than one band at a time. For example, suppose your application is playing a primary segment using one band, and then plays a motif from a style that has a different band. As long as the instruments in the first band are mapped to different PChannels than the instruments in the second, no conflict arises. However, motif segments do not normally have their own band tracks, so you might get silence from the motif's PChannels unless you first create a band segment and play it. (It is possible to add a band track to a motif segment, but creating a separate band segment is easier.)


Ensuring Timely Band Changes

A consideration in playing band segments is the randomness in the timing of notes played by a style track. For instance, a note that is on measure 1, beat 1 might actually play somewhat earlier or later than the actual beat boundary. The band segment is not aware of this; therefore, some of the notes might play with the incorrect instrument.

[C++]

To prevent this problem, an application should cue the band segment early. Suppose, for example, that you have a style segment pStyleSeg and a band segment pBandSeg. You want to play both the style segment and the band segment on the next measure boundary of the performance (pPerf). You know that the style contains notes that could go out up to 30 ticks earlier (in music time) than the start time of the segment. The following code example ensures that the band segment is played 31 ticks before the style segment, so all instruments are in place before any note is played:

/* First, get the time of the next measure, and convert it to
   music time. */

REFERENCE_TIME rtResolved;
MUSIC_TIME mtResolved;

pPerf->GetResolvedTime( 0, &rtResolved, DMUS_TIME_RESOLVE_MEASURE );
pPerf->ReferenceToMusicTime( rtResolved, &mtResolved );

/* Now, play the band segment 31 ticks before the measure boundary. */

mtResolved -= 31;
pPerf->PlaySegment(pBandSeg, 0, mtResolved, NULL);

/* Play the style segment on the measure boundary. */

pPerf->PlaySegment(pStyleSeg, DMUS_TIME_RESOLVE_MEASURE, 0, NULL);
[Visual Basic]

To prevent this problem, an application should cue the band segment early. Suppose, for example, that you have a style segment styleSeg and a band segment bandSeg. You want to play both the style segment and the band segment on the next measure boundary of the performance (perf). You know that the style contains notes that could go out up to 30 ticks earlier (in music time) than the start time of the segment. The following code example ensures that the band segment is played 31 ticks before the style segment, so all instruments are in place before any note is played:

'First, get the time of the next measure,
' and convert it to music time.

Dim ctResolved As Long
Dim mtResolved As Long

ctResolved = perf.GetResolvedTime(ctResolved, DMUS_SEGF_MEASURE)
mtResolved = perf.ClockToMusicTime(ctResolved)

' Now, play the band segment 31 ticks before the measure boundary.

mtResolved = mtResolved - 31
Call perf.PlaySegment(bandSeg, 0, mtResolved)

' Play the style segment on the measure boundary.

Call perf.PlaySegment(styleSeg, DMUS_SEGF_MEASURE, 0 )

Note If there is no randomness in the notes played by a segment (for example, one based on a MIDI file), you do not need to worry about the timeliness of a band segment played at the same time. By default, all band segments start 1 tick early.


Timing

This section is an overview of various timing issues in DirectMusic. The following topics are discussed:

  • Master Clock
  • Clock Time vs. Music Time
  • Changing the Tempo
  • Prepare Time
  • Latency and Bumper Time
  • Segment Timing


Master Clock

[Visual Basic]

This topic pertains only to applications written in C++. DirectX for Visual Basic does not enable applications to select a different master clock.

[C++]

To guarantee accurate timing with an acceptably low latency, DirectMusic incorporates a master clock in kernel mode. This clock is based on a hardware timer. DirectMusic automatically selects the system clock as the master clock, but an application can select a different one, such as the wave-out crystal on a sound card.

The master clock is a high-resolution timer that is shared by all processes, devices, and applications that are using DirectMusic. The clock is used to synchronize all music playback in the system. It is a standard IReferenceClock interface. The IReferenceClock::GetTime method returns the current time as a 64-bit integer (defined as the REFERENCE_TIME type) in increments of 100 nanoseconds.

To obtain an interface to the master clock, call the IDirectMusic::GetMasterClock method.

You can choose a different master clock for your application, but only if there are no other DirectMusic applications running. First, you get descriptions of all devices that can serve as the master clock by using the IDirectMusic::EnumMasterClock method. Once you have obtained the GUID of the device that you want to use as the master clock, you pass this to the IDirectMusic::SetMasterClock method.


Clock Time vs. Music Time

[C++]

In DirectX for C++, the time returned by the master clock is a 64-bit value defined as type REFERENCE_TIME. Reference time is measured in units of approximately 100 nanoseconds, so the clock ticks about 10 million times each second. The value returned by the IReferenceClock::GetTime method is relative to an arbitrary start time.

Music time is a 32-bit value defined as type MUSIC_TIME. It is not an absolute measure of time, but is relative to the tempo. The clock is started when the performance is initialized and ticks DMUS_PPQ times for each quarter-note. (DMUS_PPQ is currently defined as 768.)

When a performance is initialized, it starts keeping an internal clock. You can retrieve the current performance time in both reference time and music time by using the IDirectMusicPerformance::GetTime method.

The IDirectMusicPerformance::AdjustTime method can be used to make small changes to the performance time. Most applications do not need to do this, but it can be useful when synchronizing to another source.

To convert between the two kinds of time in a performance, you can use the IDirectMusicPerformance::MusicToReferenceTime and IDirectMusicPerformance::ReferenceToMusicTime methods.

When a segment is cued to play by a call to IDirectMusicPerformance::PlaySegment and the start time is given in reference time, DirectMusic must convert the start time to music time. If no primary segment is currently playing, the conversion is made immediately, based on the current tempo. Otherwise, if another segment is playing, the start time of the cued segment is not converted to music time until the start time has been reached.

If the tempo is changed before the segment starts playing, the start time can be affected, or the segment might not start on the desired boundary. In the first case, in which the conversion to music time is done immediately, the start time (in reference time) is advanced if the tempo speeds up and delayed if the tempo slows down. In the second case, in which conversion is made at start time, a change in tempo can mean that the segment does not start at correct resolution boundaries. For example, if the segment is supposed to start on a measure boundary (as indicated in the dwFlags parameter of PlaySegment), the start time (in reference time) is calculated when the segment is cued. However, if the tempo then changes, a measure boundary might not fall at that time.

When a primary segment is passed to PlaySegment with the DMUS_SEGF_QUEUE flag (see DMUS_SEGF_FLAGS), the i64StartTime parameter is ignored, and the segment is cued to play after any primary segments whose start times have already been converted. If a previously cued segment is still stamped in reference time, that segment plays at its designated time, perhaps interrupting another segment.

An example should make this clearer. Say you have three segments, each 10 seconds in length. You cue segment A to play 5 seconds from now. Because no primary segment is currently playing, the start time is immediately converted to music time. At 6 seconds, you cue segment B to play at 20 seconds. In this case, because music is already playing and the tempo might change, the conversion to music time is not made immediately. Then you cue segment C with the DMUS_SEGF_QUEUE flag so that it starts immediately after segment A finishes, at 15 seconds. At 20 seconds segment B starts playing and interrupts segment C.

[Visual Basic]

In DirectX for Visual Basic, the time returned by the master clock is a Long, representing units of approximately one millisecond. The value returned by DirectMusicPerformance.GetClockTime is relative to an arbitrary start point.

Music time is also a Long. It is not an absolute measure of time, but is relative to the tempo. The clock is started when the performance is initialized and ticks 768 times for each quarter-note. You can retrieve the current music time by using DirectMusicPerformance.GetMusicTime.

To convert between the two kinds of time in a performance, you can use the DirectMusicPerformance.MusicToClockTime and DirectMusicPerformance.ClockToMusicTime methods.

When a segment is cued to play by a call to DirectMusicPerformance.PlaySegment and the start time is given in clock time, DirectMusic must convert the start time to music time. If no primary segment is currently playing, the conversion is made immediately, based on the current tempo. Otherwise, if another segment is playing, the start time of the cued segment is not converted to music time until the start time has been reached.

If the tempo is changed before the segment starts playing, the start time can be affected, or the segment might not start on the desired boundary. In the first case, in which the conversion to music time is made immediately, the start time (in reference time) is advanced if the tempo speeds up and delayed if the tempo slows down. In the second case, in which conversion is made at start time, a change in tempo can mean that the segment does not start at correct resolution boundaries. For example, if the segment is supposed to start on a measure boundary (as indicated in the lFlags parameter of PlaySegment), the start time (in clock time) is calculated when the segment is cued, However, if the tempo then changes, a measure boundary might not fall at that time.

When a primary segment is passed to PlaySegment with the DMUS_SEGF_QUEUE flag (see CONST_DMUS_SEGF_FLAGS), the startTime parameter is ignored, and the segment is cued to play after any primary segments whose start times have already been converted. If a previously cued segment is still stamped in reference time, that segment plays at its designated time, perhaps interrupting another segment.

An example should make this clearer. Say you have three segments, each 10 seconds in length. You cue segment A to play 5 seconds from now. Because no primary segment is currently playing, the start time is immediately converted to music time. At 6 seconds, you cue segment B to play at 20 seconds. In this case, because music is already playing and the tempo might change, the conversion to music time is not made immediately. Then you cue segment C with the DMUS_SEGF_QUEUE flag so that it starts immediately after segment A finishes, at 15 seconds. At 20 seconds segment B starts playing and interrupts segment C.


Changing the Tempo

The tempo of a performance dictates the conversion between the two types of time used in DirectMusic, which in turn controls the resolution of events to musical boundaries. (See Clock Time vs. Music Time.) The tempo track of the primary segment usually controls the tempo, but an application can also set the tempo dynamically.

[C++]

There are two ways to do so: by sending a message and by setting a track parameter.

The following code example sends a message to change the tempo:

/* Assume that pIDMSegment is a valid IDirectMusicSegment and
   IDMPerformance is a valid IDirectMusicPerformance. */

// Disable tempo track in segment so that it does not reset the tempo.
pIDMSegment->SetParam( GUID_DisableTempo, 0xFFFF,0,0, NULL );

DMUS_TEMPO_PMSG* pTempo;

if( SUCCEEDED(pIDMPerformance->AllocPMsg(
        sizeof(DMUS_TEMPO_PMSG), (DMUS_PMSG**)&pTempo)))
{
    // Queue the tempo event.
    ZeroMemory(pTempo, sizeof(DMUS_TEMPO_PMSG));
    pTempo->dwSize = sizeof(DMUS_TEMPO_PMSG);
    pTempo->dblTempo = 100;
    pTempo->dwFlags = DMUS_PMSGF_REFTIME;
    pTempo->dwType = DMUS_PMSGT_TEMPO;
    pIDMPerformance->SendPMsg((DMUS_PMSG*)pTempo);
}

The following code example shows how to change the tempo parameter. For more information, see Setting and Retrieving Track Parameters.

DMUS_TEMPO_PARAM Tempo;
Tempo.dblTempo = 100;
pIDMSegment->SetParam(GUID_TempoParam, 0xFFFF, 0, 0, &Tempo);
[Visual Basic]

There are two ways to do so: by setting the master tempo and by sending a tempo message.

The master tempo is a factor by which all tempos in the performance are multiplied. For example, if you set the master tempo by calling DirectMusicPerformance.SetMasterTempo with a parameter of 0.75, and then play a segment that has a tempo of 120 beats per minute, the segment plays with a tempo of 90.

Sending a tempo by using the DirectMusicPerformance.SendTempoPMSG method changes the tempo at the time for which the message is stamped. The new tempo is valid until another tempo message is sent, either directly by the application or by a segment that is being played. The tempo value can be modified by the master tempo.

The following call, where perf is a DirectMusicPerformance object, immediately sets the tempo to 100 beats per minute. If you pass 0 as the lTime parameter to signify that the message is to go out immediately, you must also set the DMUS_PMSGF_REFTIME flag.

Call perf.SendTempoPMSG(0, DMUS_PMSGF_REFTIME, 100)


Prepare Time

As a segment is played, the performance makes repeated calls to the segment's tracks, causing them to generate messages for the supplied time range, which is some fraction of a second. These messages are then placed in the queue behind those that were generated in previous calls. By default, about a second's worth of messages are in the queue at any given time.

For an illustration, see Latency and Bumper Time.

[C++]

The queue is like a gas tank that is constantly being topped off by calls to IDirectMusicTrack::Play. Each time the performance calls Play, it calculates the end time for that call by adding the prepare time to the current time. If the current time is 10,000 milliseconds (or the equivalent in REFERENCE_TIME units) and the prepare time is the default 1000 ms, the end time is 11,000—that is, all new messages that are to play up to time 11,000 must be prepared and placed in the queue.

The size of the queue can be changed by calling the IDirectMusicPerformance::SetPrepareTime method, and the current size can be retrieved by using IDirectMusicPerformance::GetPrepareTime.

Most applications do not need to change the default prepare time, and the process just described is not visible to the application. However, it is helpful to understand the concept of prepare time because of the DMUS_SEGF_AFTERPREPARETIME flag, which the application can pass to IDirectMusicPerformance::PlaySegment.

[Visual Basic]

The queue is like a gas tank that is constantly being topped off. Each time the performance calls on the segment to send messages, it calculates the end time for that call by adding the prepare time to the current time. If the current time is 10,000 milliseconds and the prepare time is the default 1000 ms, the end time is 11,000—that is, all new messages that are to play up to time 11,000 must be prepared and placed in the queue.

The size of the queue can be changed by calling the DirectMusicPerformance.SetPrepareTime method, and the current size can be retrieved by using DirectMusicPerformance.GetPrepareTime.

Most applications do not need to change the default prepare time, and the process just described is not visible to the application. However, it is helpful to understand the concept of prepare time because of the DMUS_SEGF_AFTERPREPARETIME flag, which the application can pass to DirectMusicPerformance.PlaySegment.

Normally, if you set a start time of "now" for the segment, the performance invalidates any messages currently in the queue. Any tracks that are still valid at this point (for example, tracks of secondary segments that continue to play despite the introduction of a new primary segment) then have to resend their messages, taking into account any changes made to the musical environment by the new segment. To avoid unnecessary processing and to ensure continuity (for example, to ensure that a long note or nonmusical DLS sound is not cut short), you can use the DMUS_SEGF_AFTERPREPARETIME flag to specify that the segment is not to start playing until all messages currently in the queue have been processed and passed to the port buffer. So, for example, if messages up to time 10,000 are in the queue and the current time is 9,000, a segment cued to play immediately starts playing just after the 10,000 ms mark.

For more information, see Segment Timing.


Latency and Bumper Time

[C++]

Latency is the delay between the time at which the port receives a musical message and the time at which it has synthesized enough of a wave to play. The IDirectMusicPerformance::GetLatencyTime method retrieves the current time plus the latency for the performance as a whole. This is the largest value returned by any of the ports' latency clocks.

The bumper is an extra amount of time allotted for code to run between the time that a musical event is put into the port buffer and the time that the port starts to process it. By default, the bumper length is 50 milliseconds. An application can change this value by using the IDirectMusicPerformance::SetBumperLength method, and retrieve the current value by calling IDirectMusicPerformance::GetBumperLength.

Latency time and bumper time can be combined. Suppose an event is supposed to play at 10,000 milliseconds. The latency of the port is known to be 100 ms, and the bumper length is at its default value of 50 ms. The performance therefore places the message into the port buffer at 9,850 ms.

Once a message has been placed in the port buffer, it no longer belongs to the performance and cannot be stopped from playing by using the IDirectMusicPerformance::Invalidate or the IDirectMusicPerformance::Stop method. The first message that can be invalidated has a time stamp equal to or greater than the current time plus the latency time and the bumper time. This value can be retrieved by using the IDirectMusicPerformance::GetQueueTime method.

[Visual Basic]

Latency is the delay between the time at which the port receives a musical message and the time at which it has synthesized enough of a wave to play. The DirectMusicPerformance.GetLatencyTime method retrieves the current time plus the latency for the performance as a whole. This is the largest value returned by any of the ports' latency clocks.

The bumper is an extra amount of time allotted for code to run between the time that a musical event is put into the port buffer and the time that the port starts to process it. By default, the bumper length is 50 milliseconds. An application can change this value by using the DirectMusicPerformance.SetBumperLength method, and retrieve the current value by calling DirectMusicPerformance.GetBumperLength.

Latency time and bumper time can be combined. Suppose an event is supposed to play at 10,000 milliseconds. The latency of the port is known to be 100 ms, and the bumper length is at its default value of 50 ms. The performance therefore places the message into the port buffer at 9,850 ms.

Once a message has been placed in the port buffer, it no longer belongs to the performance and cannot be stopped from playing by using the DirectMusicPerformance.Invalidate or the DirectMusicPerformance.Stop method. The first message that can be invalidated has a time stamp equal to or greater than the current time plus the latency and bumper time. This value can be retrieved by using the DirectMusicPerformance.GetQueueTime method.

The following illustration illustrates the relationship of the times and durations retrieved by various methods. The current time is at the left, and the last time for which messages have been prepared is at the right. Prepare time is only an approximation of the total timespan of messages in the queue at any given moment.

[Visual Basic]

The methods in the illustration are from the C++ API, but most have the same names in DirectX for Visual Basic. For example, IDirectMusicPerformance::GetPrepareTime is equivalent to DirectMusicPerformance.GetPrepareTime. The GetTime method in the illustration is equivalent to DirectMusicPerformance.GetClockTime.


Segment Timing

[C++]

Segments play from the beginning unless a start point is set by a call to the IDirectMusicSegment::SetStartPoint method. If a repeat count is set by using IDirectMusicSegment::SetRepeats, the entire segment repeats that number of times, unless a loop has been defined by a call to IDirectMusicSegment::SetLoopPoints. In this case, only the part of the segment between the loop points repeats.

The performance time at which the segment starts playing is determined by two parameters of IDirectMusicPerformance::PlaySegment:

  • The i64StartTime parameter sets the earliest time at which the segment can start playing. If i64StartTime is 0, this time is as soon as possible. The time at which the segment starts depends on the type of segment. If it is a primary segment or a control segment, the earliest start time is at queue (or flush) time. If it is a noncontrol secondary segment, the earliest start is at latency time. For more information on queue time and latency time, see Latency and Bumper Time.
  • The dwFlags parameter determines how soon after the scheduled time the segment starts playing, depending on the rhythm of the currently playing segment. Usually, you will want to wait for an appropriate moment before introducing a new segment, a transition, or a motif. You control the delay by setting one of the following DMUS_SEGF_FLAGS:
[Visual Basic]

Segments play from the beginning unless a start point is set by a call to the DirectMusicSegment.SetStartPoint method. If a repeat count is set by using DirectMusicSegment.SetRepeats, the entire segment repeats that number of times, unless a loop has been defined by a call to DirectMusicSegment.SetLoopPoints. In this case, only the part of the segment between the loop points repeats.

The performance time at which the segment starts playing is determined by two parameters of DirectMusicPerformance.PlaySegment:

  • The startTime parameter sets the earliest time at which the segment can start playing. If startTime is 0, this time is as soon as possible. The time at which the segment starts depends on the type of segment. If it is a primary segment or a control segment, the earliest start time is at queue (or flush) time. If it is a noncontrol secondary segment, the earliest start is at latency time. For more information on queue time and latency time, see Latency and Bumper Time.
  • The lFlags parameter determines how soon after the scheduled time the segment starts playing, depending on the rhythm of the currently playing segment. Usually, you will want to wait for an appropriate moment before introducing a new segment, a transition, or a motif. You control the delay by setting one of the following CONST_DMUS_SEGF_FLAGS:
DMUS_SEGF_AFTERPREPARETIME
Play at the earliest start time plus the prepare time. This ensures that any messages from the currently playing segment that have already been queued to the port are not invalidated. This saves processing time and also ensures that any motifs continue to play smoothly over a transition from one primary segment to another.
DMUS_SEGF_GRID
Play on a grid boundary. A grid is a subdivision of a beat. The time signature (authored into the style) determines how many grids each beat is divided into.
DMUS_SEGF_BEAT
Play on a beat.
DMUS_SEGF_MEASURE
Play at the beginning of a measure.
DMUS_SEGF_DEFAULT
Use the cued segment's default boundary.

If none of these flags is set, the segment starts playing at exactly the earliest start time.

For information on how tempo changes can affect start times, see Clock Time vs. Music Time.


Notification and Event Handling

From time to time, your application might need to respond to a music event; for example, you might need to know when the end of a segment has been reached, or you might want to synchronize graphics with the beat of the music. Get the desired information by asking DirectMusic to notify you when a certain type of event has taken place.

[C++]

Specify what types of music events you want to be notified of by calling the IDirectMusicPerformance::AddNotificationType method once for each desired type of event. The following code example tells DirectMusic to set segment-related events. The actual type of event (such as a segment start or a segment end) will be derived later from the notification message.

/* It is assumed that pPerformance is a valid
   IDirectMusicPerformance pointer. */

GUID guid = GUID_NOTIFICATION_SEGMENT;
// C syntax:
pPerformance->AddNotificationType(&guid);
// C++ syntax:
pPerformance->AddNotificationType(guid);

You can also add notification types for a particular segment by using the IDirectMusicSegment::AddNotificationType method. You could do this, for example, to receive notification of when a particular segment stops playing. You cannot use this method to request GUID_NOTIFICATION_PERFORMANCE types because these must come from the performance object.

Notifications are sent in the form of DMUS_NOTIFICATION_PMSG message structures. You can poll for any pending notification messages within the Windows message loop by calling the IDirectMusicPerformance::GetNotificationPMsg method, or you can have DirectMusic signal an event object in a separate thread when a message is pending.

If you want to be alerted of pending DirectMusic notification messages by a Windows event object, you must first obtain an event handle by calling the Win32 CreateEvent function. Typically, you would create an autoreset event with a call such as the following:

HANDLE g_hNotify = CreateEvent(NULL, FALSE, FALSE, NULL);

After creating the event, assign the handle to the performance by passing it to the IDirectMusicPerformance::SetNotificationHandle method. You can use the second parameter of this method to change the default time that DirectMusic holds onto the event if it is not retrieved; a value of 0 in this parameter indicates that the default time of 2 seconds is to be used.

In the following example, g_pPerf is a valid pointer to the IDirectMusicPerformance interface:

g_pPerf->SetNotificationHandle(g_hNotify, 0);

The following code example runs repeatedly in its own thread, checking for signaled events and retrieving notification messages.

void WaitForEvent( LPVOID lpv)
{
    DWORD dwResult;
    DMUS_NOTIFICATION_PMSG* pPmsg;
    char szCount[4];

    while (TRUE)
    {
        dwResult = WaitForSingleObject(g_hNotify, 100);
        while (S_OK == g_pPerf->GetNotificationPMsg(&pPmsg))
        {
            // Check notification type, and do something in response.
            .
            .
            .
            g_pPerf->FreePMsg((DMUS_PMSG*)pPmsg);
        }
    }
}

This thread is run as follows:

_beginthread(WaitForEvent, 0, NULL);

When notifications are no longer needed, the following code example shuts down the thread, removes the notification handle from the performance, and destroys the event object.

_endthread();
g_pPerf->SetNotificationHandle(0, 0);
CloseHandle(g_hNotify);

It is not necessary to create an event to retrieve notification messages in your application's message loop. As long as you have requested notifications by calling the IDirectMusicPerformance::AddNotificationType method, the performance sends messages that can be retrieved by calling IDirectMusicPerformance::GetNotificationPMsg.

More than one message can be waiting when an event is signaled or when you call GetNotificationPMsg in the message loop. To be sure of catching all notifications, call GetNotificationPMsg repeatedly until it returns S_FALSE.

Multiple messages with the same time stamp are not queued in any particular order.

You must free any message that you retrieve, by calling the IDirectMusicPerformance::FreePMsg method.

[Visual Basic]

Specify what types of music events you want to be notified of by calling the DirectMusicPerformance.AddNotificationType method once for each desired type of event. The following code example, in which perf is a DirectMusicPerformance object, requests notifications for segment events. The type of event (such as a segment start or a segment end) will be derived later from the notification message.

Call perf.AddNotificationType(DMUS_NOTIFY_ON_SEGMENT)

Notifications are sent in the form of a DMUS_NOTIFICATION_PMSG message type. You can poll for any pending notification messages by calling the DirectMusicPerformance.GetNotificationPMsg method in Sub Main or another loop, or you can have DirectMusic signal an event when a message is pending.

To have DirectMusic signal events, use DirectX7.CreateEvent to obtain an event handle, and then pass this handle to DirectMusicPerformance.SetNotificationHandle. The module that you pass to CreateEvent must implement the DirectXEvent class and must also provide an implementation of the DirectXEvent.DXCallback method, which is called by DirectMusic whenever an event is signaled.

The following code example sets up notification for a form module called frmMain:

' DX is a DirectX7 object; perf is a DirectMusicPerformance object.
Dim hEvent As Long
hEvent = DX.CreateEvent(frmMain)
Call perf.SetNotificationHandle(hEvent)

The form module contains code similar to the following, which looks for a message indicating that the segment has finished playing:

Implements DirectXEvent

Private Sub DirectXEvent_DXCallback(ByVal eventid As Long)

  Dim GotMSG As Boolean
  Dim PMsg As DMUS_NOTIFICATION_PMSG

  Do
    GotMSG = gobjDMPerformance.GetNotificationPMSG(PMsg)
    If GotMSG Then
      If PMsg.lNotificationOption = DMUS_NOTIFICATION_SEGEND Then
        ' Segment has finished playing.
      End If
    End If
  Loop Until Not GotMSG

End Sub

It is not necessary to create an event to retrieve notification messages in your application's main loop. As long as you have requested notifications by calling the DirectMusicPerformance.AddNotificationType method, the performance sends messages that can be retrieved by calling DirectMusicPerformance.GetNotificationPMsg.

More than one message can be waiting when an event is signaled or when you call GetNotificationPMsg in the loop. To be sure of catching all notifications, call GetNotificationPMsg repeatedly until it returns False.

Multiple messages with the same time stamp are not queued in any particular order.


Music Parameters

[Visual Basic]

In DirectX for Visual Basic, music parameters are set and retrieved by using various methods of DirectMusicPerformance and DirectMusicSegment.

To have the music respond immediately to a changed parameter, an application can flush messages from the queue by using the DirectMusicPerformance.Invalidate method. This method causes all tracks to resend messages from the specified point forward.

[C++]

DirectMusic lets you control many aspects of track behavior by changing parameters during execution, using one of the following SetParam methods:

  • IDirectMusicPerformance::SetParam sets data on a specific track within the current control segment of this performance. The control segment is normally the primary segment, but a secondary segment can be designated as the control segment when it is played. See DMUS_SEGF_FLAGS.
  • IDirectMusicSegment::SetParam sets data on a specific track within this segment.
  • IDirectMusicTrack::SetParam sets data on this track.

In addition, the IDirectMusicPerformance::SetGlobalParam method allows you to set values that apply across the entire performance.

The equivalent GetParam and GetGlobalParam methods retrieve current values for a track or the performance.

To have the music respond immediately to a changed parameter, an application can flush messages from the queue by using the IDirectMusicPerformance::Invalidate method. This method causes all tracks to resend messages from the specified point forward.

More information about parameters is contained in the following topics:

  • Setting and Retrieving Track Parameters
  • Setting and Retrieving Global Parameters


Setting and Retrieving Track Parameters

[Visual Basic]

Some methods of DirectMusicPerformance and DirectMusicSegment have the effect of setting or retrieving parameters on a particular track, usually in the control segment. However, applications using DirectX for Visual Basic do not need to be concerned about tracks as such, and these methods can be used without any knowledge of what is happening at a lower level.

[C++]

Set and retrieve track parameters by using the SetParam and GetParam methods of either the performance, the segment, or the track. When calling one of these methods on the performance or segment, you can identify the track by setting the dwGroupBits and dwIndex parameters. However, in most cases, you can let DirectMusic find the appropriate track for you. For more information, see Identifying the Track.

In some cases, you must specify the time within the track at which the change is to take effect or for which the parameter is to be retrieved. To see whether this value is used for a particular track parameter, see Track Parameter Types.

For a few parameters, a call to SetParam turns a feature on or off, and no data is needed. When setting other parameters, however, you must also supply a structure or variable containing the data. Only parameters with associated data can be retrieved, so when using GetParam, you must always supply a pointer to an appropriate variable or structure to receive the data.

To determine whether a particular parameter is supported by a track, use the IDirectMusicTrack::IsParamSupported method, and check for an S_OK result.

More information is given in the following topics:

  • Identifying the Track
  • Track Parameter Types
  • Disabling and Enabling Messages


Identifying the Track

[Visual Basic]

This topic pertains only to applications written in C++.

[C++]

When you set or retrieve a parameter by using IDirectMusicTrack::SetParam or IDirectMusicTrack::GetParam, the parameter is associated with the track on which the method is called. However, when you call IDirectMusicPerformance::SetParam, IDirectMusicPerformance::GetParam, IDirectMusicSegment::SetParam, or IDirectMusicSegment::GetParam, DirectMusic needs to find the appropriate track.

Normally, you can let DirectMusic determine which track contains the desired parameter. To do this, set dwGroupBits to 0xFFFFFFFF and dwIndex to 0. For example, the following call to IDirectMusicSegment::SetParam turns off the tempo track so that looping a segment does not reset the tempo:

pIDMSegment->SetParam(GUID_DisableTempo, 0xFFFFFFFF, 0, 0, NULL);

There are times, however, when you need to identify a track. Typically, this would be the case when a segment contains multiple tracks of the same type. To set or retrieve the parameter on the desired track, you must identify it by group and index value.

Every track belongs to one or more groups, each group being represented by a bit in the dwGroupBits parameter of one of the methods under discussion. (The track is assigned to a group or groups when it is inserted in the performance. See IDirectMusicSegment::InsertTrack. In the case of segments loaded from a file, track groups are assigned by the author of the segment.)

A track is identified by a zero-based index value within each of the groups that it belongs to. The index value is determined by the order in which the tracks were inserted.

Suppose a segment contains the following tracks:

Track | Group bits
A | 0x1
B | 0x2
C | 0x1
D | 0x3

Group 1 contains tracks A, C, and D, and group 2 contains tracks B and D. If you call GetParam or SetParam with a value of 1 in dwGroupBits and a value of 0 in dwIndex, the parameter is retrieved from track A, which is the first track in group 1. If dwIndex is 1, the parameter is retrieved from track C, the second track in the group. Track D belongs to two groups, 1 and 2, so it can be identified as either dwGroupBits = 1 and dwIndex =2, or dwGroupBits = 2 and dwIndex = 1.

If you set more than 1 bit in dwGroupBits, the parameter is retrieved from the nth track containing any of those bits, where n is the value in dwIndex.


Track Parameter Types

[Visual Basic]

This topic pertains only to applications written in C++.

[C++]

The track parameter that is being set or retrieved by one of the SetParam or GetParam methods is identified by a GUID in the rguidType parameter of the method. Each parameter that requires data is associated with a particular data type, and pParam must point to a variable or structure of this type. In some cases, part of the data structure must be initialized even when calling GetParam.

The predefined parameters are listed in the following table, which links you to tables with more detailed information about each parameter. In the detailed tables, pParam and mtTime refer to the parameters of the various GetParam and SetParam methods. Although parameters are always associated with particular track types, you will usually call the method on the segment or the performance and let DirectMusic find the appropriate track. (See Identifying the Track.)

GUID_ChordParam | GUID_EnableTimeSig
GUID_Clear_All_Bands | GUID_IDirectMusicBand
GUID_CommandParam | GUID_IDirectMusicChordMap
GUID_CommandParam2 | GUID_IDirectMusicStyle
GUID_ConnectToDLSCollection | GUID_MuteParam
GUID_Disable_Auto_Download | GUID_RhythmParam
GUID_DisableTempo | GUID_SeedVariations
GUID_DisableTimeSig | GUID_StandardMIDIFile
GUID_Download | GUID_TempoParam
GUID_Enable_Auto_Download | GUID_TimeSignature
GUID_EnableTempo | GUID_Unload


GUID_ChordParam

[C++]
Track type | Chord.
Purpose | Set or retrieve a chord change.
Data type (*pParam) | DMUS_CHORD_PARAM.
mtTime | The time, in track time, at which to add the chord to the track, or the time at or directly after the chord to be retrieved from the track.

[Visual Basic]

This topic pertains only to applications written in C++.


GUID_Clear_All_Bands

[C++]
Track type | Band.
Purpose | Clear all bands from the track.
Data type (*pParam) | None.
mtTime | Not used.

[Visual Basic]

This topic pertains only to applications written in C++.


GUID_CommandParam

[C++]
Track type | Command.
Purpose | Set or retrieve a groove or embellishment command.
Data type (*pParam) | DMUS_COMMAND_PARAM2.
mtTime | The time, in track time, at which to add the command to the track, or the time at or directly after the command to be retrieved from the track.

[Visual Basic]

This topic pertains only to applications written in C++.


GUID_CommandParam2

[C++]
Track type | Command.
Purpose | Set or retrieve a groove or embellishment command.
Data type (*pParam) | DMUS_COMMAND_PARAM2. The mtTime member of this structure gives the actual time of the command.
mtTime | The time, in track time, at which to add the command to the track, or the time at or directly after the command to be retrieved from the track.

[Visual Basic]

This topic pertains only to applications written in C++.


GUID_ConnectToDLSCollection

[C++]
Track type | Band.
Purpose | Connect a band to a DLS collection. See Playing a MIDI File with Custom Instruments.
Data type (*pParam) | IDirectMusicCollection pointer.
mtTime | Not used.

[Visual Basic]

This topic pertains only to applications written in C++.


GUID_Disable_Auto_Download

[C++]
Track type | Band.
Purpose | Disable automatic downloading of instruments. See Using Bands.
Data type (*pParam) | None.
mtTime | Not used.

[Visual Basic]

This topic pertains only to applications written in C++.


GUID_DisableTempo

[C++]
Track type | Tempo.
Purpose | Disable tempo messages. See Disabling and Enabling Messages.
Data type (*pParam) | None.
mtTime | Not used.

[Visual Basic]

This topic pertains only to applications written in C++.


GUID_DisableTimeSig

[C++]
Track type | Time signature, style, and motif.
Purpose | Disable time-signature messages. See Disabling and Enabling Messages.
Data type (*pParam) | None.
mtTime | Not used.

[Visual Basic]

This topic pertains only to applications written in C++.


GUID_Download

[C++]
Track type | Band.
Purpose | Download instrument data for the track's bands. See Playing a MIDI File with Custom Instruments. See also GUID_Unload.
Data type (*pParam) | IDirectMusicPerformance pointer.
mtTime | Not used.

Remarks

Setting this parameter by using IDirectMusicSegment::SetParam downloads only the instruments in the first band track. To download instruments in the other tracks, iterate through the band tracks by using IDirectMusicSegment::GetTrack, and call IDirectMusicTrack::SetParam on each track.

[Visual Basic]

This topic pertains only to applications written in C++.


GUID_Enable_Auto_Download

[C++]
Track type | Band.
Purpose | Enable automatic downloading of instruments. See Using Bands.
Data type (*pParam) | None.
mtTime | Not used.

[Visual Basic]

This topic pertains only to applications written in C++.


GUID_EnableTempo

[C++]
Track type | Tempo.
Purpose | Enable tempo messages. See Disabling and Enabling Messages.
Data type (*pParam) | None.
mtTime | Not used.

[Visual Basic]

This topic pertains only to applications written in C++.


GUID_EnableTimeSig

[C++]
Track type | Time signature, style, and motif.
Purpose | Disable time-signature messages. See Disabling and Enabling Messages.
Data type (*pParam) | None.
mtTime | Not used.

[Visual Basic]

This topic pertains only to applications written in C++.


GUID_IDirectMusicBand

[C++]
Track type | Band.
Purpose | Set a band.
Data type (*pParam) | IDirectMusicBand.
mtTime | The time, in track time, at which to add the band to the track.

[Visual Basic]

This topic pertains only to applications written in C++.


GUID_IDirectMusicChordMap

[C++]
Track type | Chord map.
Purpose | Set or retrieve the chord map.
Data type (*pParam) | IDirectMusicChordMap pointer (SetParam) or address of a variable to receive this pointer (GetParam).
mtTime | The time, in track time, at which to add the chord map to the track, or the time at or directly after the chord map to be retrieved from the track.

[Visual Basic]

This topic pertains only to applications written in C++.


GUID_IDirectMusicStyle

[C++]
Track type | Style.
Purpose | Set or retrieve the style.
Data type (*pParam) | IDirectMusicStyle pointer (SetParam) or address of a variable to receive this pointer (GetParam).
mtTime | The time, in track time, at which to add the style to the track, or the time at or directly after the style to be retrieved from the track.

[Visual Basic]

This topic pertains only to applications written in C++.


GUID_MuteParam

[C++]
Track type | Mute.
Purpose | Set or retrieve channel-mapping information.
Data type (*pParam) | DMUS_MUTE_PARAM. The dwPChannel member must be initialized before this structure is passed to GetParam.
mtTime | The time, in track time, at which to add the mute event to the track, or the time at or directly after the mute event to be retrieved from the track.

[Visual Basic]

This topic pertains only to applications written in C++.


GUID_RhythmParam

[C++]
Track type | Chord.
Purpose | Retrieve the rhythm pattern for a sequence of chords stored in a measure in the track.
Data type (*pParam) | DMUS_RHYTHM_PARAM. The TimeSig member must be initialized before this structure is passed to GetParam.
mtTime | The time, in track time, at or directly after the beginning of the measure containing the rhythm pattern to be retrieved from the track.

[Visual Basic]

This topic pertains only to applications written in C++.


GUID_SeedVariations

[C++]
Track type | Style and motif.
Purpose | A nonzero value seeds the random number generator for variation selection. A value of 0 reverts to the default behavior of getting the seed from the system clock.
Data type (*pParam) | Long.
mtTime | Not used.

Remarks

Setting this parameter to nonzero is useful for testing since it ensures that the same sequence of random numbers is generated each time. The parameter should be set only once, before the track is played. The style and command track must be designed so that each time that the segment is played, the same patterns are chosen at the same places in the segment. Each loop plays different variations than the one before it, but each time the entire segment is replayed from the beginning, each loop sounds the same as the first time the segment was played.

[Visual Basic]

This topic pertains only to applications written in C++.


GUID_StandardMIDIFile

[C++]
Track type | Band.
Purpose | Ensure that a standard MIDI file (one not authored specifically for DirectMusic) plays correctly.
Data type (*pParam) | None.
mtTime | Not used.

Note This parameter must be set for any segment based on a standard MIDI file before any instruments are downloaded.

[Visual Basic]

This topic pertains only to applications written in C++.


GUID_TempoParam

[C++]
Track type | Tempo.
Purpose | Set or retrieve the tempo.
Data type (*pParam) | DMUS_TEMPO_PARAM. For SetParam, the mtTime member of the structure is ignored. For GetParam, the mtTime member receives the offset of the tempo change from the requested time and is always 0 or less.
mtTime | The time, in track time, at which to set the tempo, or the time at or directly after the tempo change to retrieve.

[Visual Basic]

This topic pertains only to applications written in C++.


GUID_TimeSignature

[C++]
Track type | Time signature and style.
Purpose | Retrieve the time signature.
Data type (*pParam) | DMUS_TIMESIGNATURE. The mtTime member receives the offset of the time signature change from the requested time and is always 0 or less.
mtTime | The time, in track time, at which to set the time signature, or the time at or directly after the time-signature change to retrieve.

[Visual Basic]

This topic pertains only to applications written in C++.


GUID_Unload

[C++]
Track type | Band.
Purpose | Unload instrument data for the track's bands. See also GUID_Download.
Data type (*pParam) | IDirectMusicPerformance pointer.
mtTime | Not used.

[Visual Basic]

This topic pertains only to applications written in C++.


Setting and Retrieving Global Parameters

[C++]

By using the IDirectMusicPerformance::SetGlobalParam and IDirectMusicPerformance::GetGlobalParam methods, you can set and retrieve parameters that affect the entire performance, rather than a single track.

The parameter to be set or retrieved is identified by a GUID in the rguidType parameter of the method. Each parameter is associated with a particular data type, whose size is given in the dwSize parameter. The predefined GUIDs and their data types are shown in the following table.

Parameter type GUID (rguidType) and Data (*pParam) | Description
GUID_PerfAutoDownload BOOL | This parameter controls whether instruments are automatically downloaded when a segment is played. By default, it is off. See Downloading and Unloading Bands.
GUID_PerfMasterGrooveLevel char | The master groove level is a value that is always added to the groove level established by the command track. The resulting value is adjusted, if necessary, to fall within the range from 1 through 100.
GUID_PerfMasterTempo float | The master tempo is a scaling factor that is applied to the tempo by the final output tool. By default, it is 1. A value of 0.5 would halve the tempo, and a value of 2.0 would double it. This value can be set in the range from DMUS_MASTERTEMPO_MIN through DMUS_MASTERTEMPO_MAX.
GUID_PerfMasterVolume long | The master volume is an amplification or attenuation factor, in hundredths of a decibel, applied to the default volume of the entire performance. The range of permitted values is determined by the port. Legacy hardware MIDI ports do not support changing master volume.

Applications can also use custom types of global parameters. To create a new type, establish a GUID and a data type for it.

When a parameter is set, the performance allocates memory for the data in a linked list of items identified by GUID. The data can be retrieved by a call to IDirectMusicPerformance::GetGlobalParam. Even predefined parameters have to be set before they can be retrieved. GetGlobalParam fails if SetGlobalParam has never been called on the parameter.

[Visual Basic]

The DirectMusicPerformance class has the following methods for setting and retrieving global parameters, which affect the entire performance:

GetMasterAutoDownload SetMasterAutoDownload | This parameter controls whether instruments are automatically downloaded when a segment is played. By default, it is off. See Downloading and Unloading Bands.
GetMasterGrooveLevel SetMasterGrooveLevel | The master groove level is a value that is always added to the groove level established by the command track. The resulting value is adjusted, if necessary, to fall within the range from 1 through 100.
GetMasterTempo SetMasterTempo | The master tempo is a scaling factor that is applied to the tempo by the final output tool. By default, it is 1. A value of 0.5 would halve the tempo, and a value of 2.0 would double it. This value can be set in the range from 0.25 through 2.0.
GetMasterVolume SetMasterVolume | The master volume is an amplification or attenuation factor, in hundredths of a decibel, applied to the default volume of the entire performance. The range of permitted values is determined by the port. Legacy hardware MIDI ports do not support changing master volume.


Disabling and Enabling Messages

[C++]

By setting the GUID_DisableTempo and GUID_DisableTimeSig parameters on a track, you can disable the generation of DMUS_TEMPO_PMSG and DMUS_TIMESIG_PMSG messages, respectively. You might want to do this, for example, when you have set the tempo dynamically and do not want the primary segment to send tempo messages.

To re-enable messages, call one of the SetParam methods with GUID_EnableTempo and GUID_EnableTimeSig as the rguidType parameter. You can also set these parameters to force a segment to send tempo messages, even though it is not the control segment, or to cause a secondary segment to send time-signature messages. (For more information on control segments, see Segments and DMUS_SEGF_FLAGS.)

For more information on how to set a parameter, see Setting and Retrieving Track Parameters.

See also the Remarks for IDirectMusicTrack::IsParamSupported.

[Visual Basic]

By using the DirectMusicSegment.SetTempoEnable and DirectMusicSegment.SetTimeSigEnable methods, you can disable the generation of tempo and time-signature messages, respectively. You might want to do this, for example, when you have set the tempo dynamically and do not want the primary segment to send tempo messages.

You can also use SetTempoEnable to force a segment to send tempo messages, even though it is not the control segment, and SetTimeSigEnable to cause a secondary segment to send time signature messages. (For more information on control segments, see Segments and DMUS_SEGF_FLAGS.)


Capturing Music

[Visual Basic]

This topic pertains only to applications written in C++. DirectX for Visual Basic does not support music capture.

[C++]

Capturing MIDI messages from a device such as a keyboard is very easy in DirectMusic.

Typically, you would create a port for the capture device and use its IDirectMusicPort::SetReadNotificationHandle method to cause an event to be signaled whenever messages are available to be read. In response to the event, call the IDirectMusicPort::Read method repeatedly to place pending events into a buffer until S_FALSE is returned. Each time Read is called, as many events are put into the buffer as are available, or as fit into the buffer. If at least one event was put into the buffer, S_OK is returned.

To retrieve events from the buffer, call the IDirectMusicBuffer::GetNextEvent method. Each call retrieves a single event until no more are available, at which point S_FALSE is returned.

The following code example illustrates this process:

/* Assume that hEvent was created with CreateEvent and
   given to the capture port pPort by a call to
   SetReadNotificationHandle. Assume also that pBuffer was
   initialized by IDirectMusic::CreateMusicBuffer. */

REFERENCE_TIME rt;
DWORD          dwGroup;
DWORD          cb;
BYTE          *pb;

DWORD dw = WaitForMultipleObjects(1, hEvent, FALSE, INFINITE);
for (;;)
{
    hr = pPort->Read(pBuffer);
    if (hr == S_FALSE)
      {
          break;  // No more messages to read into the buffer
      }
    pBuffer->ResetReadPtr();
    for (;;)
    {
        hr = pBuffer->GetNextEvent(&rt, &dwGroup, &cb, &pb);
        if (hr == S_OK)
        {
            // pb points to the data structure for the message, and
            // you can do anything that you want with it.
        }
        else if (hr == S_FALSE)
        {
            break;  // No more messages in the buffer
        }
    }  // Done with the buffer
}  // Done reading pending events

If you do not want to intercept messages, but simply want to send them from one port to another, you can use the IDirectMusicThru interface.


DirectMusic Tools

In DirectMusic, a tool is an object that intercepts messages and handles them in some way. The tool might alter the message, and then pass it on to the next tool, free the message, or send a new message based on information in the old one.

DirectMusic has an output tool that is normally the last to receive messages. It is this tool that converts performance messages to standard MIDI messages and streams them to the synthesizer. Other tools are implemented by the application or obtained from libraries.

[Visual Basic]

DirectX for Visual Basic does not support the use of application-defined or third-party tools.

[C++]

To implement a tool, you must first create an object that supports the IDirectMusicTool interface. The object's implementation of the IDirectMusicTool methods determines what messages are processed by the tool and what work is performed on these messages.

All tools other than the output tool are normally collected in graphs; even if your application is using only one other tool, you should create a DirectMusicGraph to contain it. Then add this graph to a segment or the performance. Graphs provide a convenient mechanism for directing messages from one tool to another.

When the performance engine is playing a segment, it allows each tool in the segment graph, and then each tool in the performance graph to process each message. After a tool processes a message, it should call the IDirectMusicGraph::StampPMsg method (obtaining the IDirectMusicGraph pointer from the pGraph member of the DMUS_PMSG structure) to stamp the message with a pointer to the next tool, if any, that is to receive it. Then, the tool puts the message back in the pipeline.

Tools process messages in a high-priority thread. Do not call time-consuming functions, such as those involving graphics or file input/output, from within a tool's IDirectMusicTool::ProcessPMsg method. If a tool needs to trigger an action, it should do so by signaling a different thread, perhaps the application's main thread.

When implementing the methods of IDirectMusicTool, be sure not to create circular references to parent objects. Circular references come about when one object creates another and the child keeps an additional reference to the parent. For example, suppose a tool creates a new reference to the graph passed into its IDirectMusicTool::Init method. If the tool fails to release this reference, there is a problem when the segment attempts to release the graph. Because the tool still has a reference to the graph, the graph is not fully released; and because the graph has a reference to the tool, the tool cannot be released either.

For more information on how to set up a tool, see Tutorial 2: Using Tools.


Music Composition

This section is an introduction to the composition engine of DirectMusic. You can use the engine to implement a dynamic musical program, using previously authored elements, such as styles, templates, and bands.

The following topics are discussed in this section:

  • Overview of Music Authoring
  • Music Files for Composition
  • Overview of Programming for Composition
  • How Music Varies During Playback
  • Music Values and MIDI Notes
  • Using Compositional Elements


Overview of Music Authoring

The author of compositional music elements uses a tool such as DirectMusic Producer to create the basic elements of each musical theme required by the application. For more information on the following topics, see the documentation for DirectMusic Producer.

  • Authoring Styles
  • Authoring Chord Maps
  • Authoring Style-based Segments
  • Authoring MIDI-based Segments
  • Authoring Templates
  • Authoring Bands

Note In this section, the human composer is referred to as the author to avoid confusion with the composer object of DirectMusic.


Authoring Styles

A style is a basic definition of the music. It is a collection of patterns, along with a time signature (meter) and a tempo (beats per minute). A style can also contain one or more bands.

A pattern is a musical figure one or more measures long consisting of a basic sequence of notes for each instrument, or part. These notes are not fixed but are ultimately mapped to particular pitches, according to the current key, chord, and play mode. Patterns also include variations.

A motif is a special type of pattern designed to be played solo over the basic score. Typically, a motif would be used in an interactive application to mark an event: for example, the drumbeat that occurs in the DMDonuts sample whenever the ship hits the edge of the screen.

In DirectMusic Producer, patterns are created by the author on a grid analogous to a piano roll. Each part has its own row (corresponding to a PChannel), on which notes are represented by bars of varying length (duration), thickness (velocity), position on a vertical scale (pitch), and position on a horizontal scale (time).

The author can create many variations for each pattern. Typically, he or she would do this by copying the pattern, and then making small changes to one or more parts. At run time, variations are chosen by the style playback mechanism. However, the author can disable any variation for any chord—that is, specify that the variation must never be chosen when a certain chord is being played.

The author also assigns a groove range to the pattern, specifying the groove levels at which the pattern can be played.

The pattern can also be designated as an embellishment. Embellishments are of four types—intro, fill, break, and end—and a pattern can be assigned to one or more of these categories. When the music is played and a certain type of embellishment is called for, only patterns of that type are candidates for playback.


Authoring Chord Maps

Much modern music, especially music in the popular, rock, folk, and jazz idioms, is based on the concept of chord progression, meaning that all the notes played within a given span of time are associated with a certain chord, and the music moves harmoniously from one chord to another.

The notes within a pattern authored for DirectMusic are derived from or intended to harmonize with a single chord. At run time, however, the pattern is transposed according to the chord progression—that is, each time the underlying chord changes, DirectMusic modifies the pitch of the notes accordingly.

The chord map is a road map of chord progressions. Within the chord-map designer, the author chooses chords that can express the desired musical feeling or personality. He or she then arranges these chords in a flowchart along a time line. (The time line is conceptually circular, so it keeps looping back to the beginning as long as that segment of music is being played.)

Certain important chords are designated as signposts. These are chords that must be played at certain points. The music is always moving from one signpost to the next. Between the signposts, however, the chord progression can follow various routes from one chord to another, as mapped out by the author.

The route through the chord chart can be chosen at run time by the composition engine, providing variation in addition to that found in the patterns themselves. It can also be chosen by the authoring tool when the author is creating a segment.

A chord in the chord map can consist of several different chords, referred to as subchords. To achieve polytonality by playing different inversions of the same chord, the author can assign different parts to different subchords. Each subchord is valid for one or more levels, and these are matched up with levels assigned to parts in the style.

Note DirectMusic allows up to DMUS_MAXSUBCHORD subchords in a chord, and this value is defined as 8. However, DirectMusic Producer currently allows authors to create a maximum of four subchords per chord.


Authoring Style-based Segments

A style-based segment is a largely prebuilt piece of music that the author constructs from the following elements:

  • Style. A style consists of general information about the music (such as time signature and tempo), as well as patterns.
  • Chord progression. This might be derived automatically by the authoring tool from a chord map (by choosing a path through the chord chart), or entered manually by the author.
  • Series of commands for selecting appropriate patterns at set times. A characteristic of the patterns in styles is that they can be designated as embellishments (intro, fill, break, and end) and can also be assigned a certain groove range by the author. The command track of the segment might instruct the style playback engine to select an intro pattern and play it for the first measure, then play only patterns with a groove level of 25 for the next four measures, then play a break, and so on.
  • Band. The author can assign instruments and PChannels to all the parts in the various patterns.


Authoring MIDI-based Segments

A MIDI-based segment is created in DirectMusic Producer by importing a MIDI file. The author can then add tempo, key, and band changes, as well as loop points. Unlike a style-based segment, a MIDI segment has no patterns and no command track. Instead, it has a sequence track that contains MIDI notes and other commands.


Authoring Templates

A template is a segment, but unlike a style-based segment, it is not bound to a particular style and does not have a fixed chord progression.

Instead of a chord progression, the template has a series of signpost group markers along a time line. Signposts are chords that mark the beginning and end of regions in which variations in the chord progression are possible. When the author creates a signpost, he or she assigns it to a group.

The following happens later, either within the authoring tool or at run time, when the DirectMusicComposer generates a segment by combining the template with a particular style and chord map. Each time the engine encounters a pair of signpost group markers along the time line in the template, it looks in the chord map for a pair of signpost chords that belong to that group. If it finds a pair and the interval between them fits into the time available, it follows the chord progression between those two signpost chords, as defined in the chord map. If it is unable to find a path that works or there is no end signpost marker, the engine plays any chord from the group of the beginning signpost group marker.

The author might use templates to apply similar chord progressions, groove levels, and embellishments to different styles while composing segments. However, templates can also be combined with styles and chord maps by the DirectMusicComposer object at run time.


Authoring Bands

A band is a set of instruments, with their performance parameters, associated with particular parts in a piece of music. This is not the same as a DLS collection, which represents a set of instruments that can be downloaded to the synthesizer and thus made available to any application.

In a tool such as DirectMusic Producer, the author creates a band by assigning instruments to PChannels. These instruments can be from any DLS collection, and instruments from different sources can be mixed within a band. For example, a band might have a jazz guitar from the General MIDI set in part 1, a sixties organ from the Roland GS set in part 2, and an ethnic percussive instrument from a custom DLS collection in part 3. Each of these instruments is also given volume, pan, and transposition settings.

PChannels map instruments to parts. If a pattern calls for a particular note on PChannel 1, that note is played by the instrument in the current band that is assigned to PChannel 1. The sound is modified by the band's settings for the volume, pan, and transposition of that instrument.

Bands can be saved as separate files or included in styles or segments.


Music Files for Composition

When programming for DirectMusic composition, you will use a variety of files produced in a tool such as DirectMusic Producer. You load these elements into the application as COM objects and obtain interfaces to them. (See DirectMusic Loader.)

The following table summarizes the types of files that you will encounter.

[C++]

The Class GUID is the value that you put in the guidClass member of the DMUS_OBJECTDESC structure when loading the object.

Element | Class GUID | Interface | File type
Band | CLSID_DirectMusicBand | IDirectMusicBand | .bnd
DLS collection | CLSID_DirectMusicCollection | IDirectMusicCollection | .dls
Chord map | CLSID_DirectMusicChordMap | IDirectMusicChordMap | .cdm
Segment | CLSID_DirectMusicSegment | IDirectMusicSegment | .sgt
Style | CLSID_DirectMusicStyle | IDirectMusicStyle | .sty
Template | CLSID_DirectMusicSegment | IDirectMusicSegment | .tpl

[Visual Basic]
Element | DirectMusicLoader method | Class | File type
Band | LoadBand | DirectMusicBand | .bnd
DLS collection | LoadCollection | DirectMusicCollection | .dls
Chord map | LoadChordMap | DirectMusicChordMap | .cdm
Segment | LoadSegment | DirectMusicSegment | .sgt
Style | LoadStyle | DirectMusicStyle | .sty
Template | LoadSegment | DirectMusicSegment | .tpl

Note Bands can be authored as part of a style, in which case they are automatically loaded when the style is loaded. Similarly, styles and bands can be authored into a segment, in which case you do not need separate files for those elements.

Files can also contain references to other files. If a style contains a reference to a band, the band is automatically loaded when the style is, provided the loader can find the band file.


Overview of Programming for Composition

When you implement music composed at run time, you will use previously authored objects as building blocks. In consultation with the author or other content provider, you can choose to get the musical data in the form of small building blocks that offer you the greatest possible flexibility and variation at run time, or you can use larger prefabricated elements that define the form of the music more fully.

[C++]

Using the largest building blocks, you load highly structured segments (either style-based or MIDI-based) that contain everything that the performance needs to know about the music to play it. All you have to do is load the segment and query for the IDirectMusicSegment interface. You pass this interface pointer to the IDirectMusicPerformance::PlaySegment method. The style playback engine then selects pattern variations from the style and plays them according to a fixed chord progression—or, in the case of a MIDI-based segment, plays the MIDI sequence. Band changes are usually contained in the segment, as well.

[Visual Basic]

Using the largest building blocks, you load highly structured segments (either style-based or MIDI-based) that contain everything that the performance needs to know about the music to play it. All you have to do is load the segment by using the DirectMusicLoader.LoadSegment or the DirectMusicLoader.LoadSegmentFromResource method. You then pass the returned DirectMusicSegment object to the DirectMusicPerformance.PlaySegment method. The style playback engine then selects pattern variations from the style and plays them according to a fixed chord progression—or, in the case of a MIDI-based segment, plays the MIDI sequence. Band changes are usually contained in the segment, as well.

If you want to use smaller building blocks, obtain the following elements:

  • Chord maps, which are road maps of chord progressions.
  • Styles, which define a basic melody and rhythm with variations, motifs, and embellishments.
  • Template segments, which are structural plans that control various aspects of playback, including the length of the segment, whether it loops, where groove level changes and embellishment patterns are to be placed, and what types of chords in the chord map are to serve as signposts.
[C++]

You then construct a segment by combining any chord map, style, and template, using the IDirectMusicComposer::ComposeSegmentFromTemplate method.

To have even more flexibility in music composition at run time, create segments based on predefined shapes, rather than templates, using the IDirectMusicComposer::ComposeSegmentFromShape method. The shape is used in creating the command and signpost tracks, which control the choice of embellishment patterns, the chord progression, and the frequency of chord changes.

When playing segments, you can also control the band used to play the parts. Bands are typically authored right into styles and templates, but they might be supplied as separate files so that band changes can be made dynamically by the application. In this case, you must create a secondary segment containing only the band, using the IDirectMusicBand::CreateSegment method, and play this segment when it is time to assign instruments and instrument settings to the primary segment. For more information, see Using Bands.

[Visual Basic]

You then construct a segment by combining any chord map, style, and template, using the DirectMusicComposer.ComposeSegmentFromTemplate method.

To have even more flexibility in music composition at run time, create segments based on predefined shapes, rather than templates, using the DirectMusicComposer.ComposeSegmentFromShape method. The shape is used in creating the command and signpost tracks, which control the choice of embellishment patterns, the chord progression, and the frequency of chord changes.

When playing segments, you can also control the band used to play the parts. Bands are typically authored right into styles and templates, but they might be supplied as separate files so that band changes can be made dynamically by the application. In this case, you must create a secondary segment containing only the band, using the DirectMusicBand.CreateSegment method, and play this segment when it is time to assign instruments and instrument settings to the primary segment. For more information, see Using Bands.


How Music Varies During Playback

As DirectMusic plays a segment (other than a simple MIDI file or an authored segment based on a MIDI file), changes are made to the basic harmony and rhythm so that the performance does not sound static. Changes are partly scripted and partly random.

  • Choice of pattern. Typically a style contains multiple patterns, which are selected in response to commands from the command track. For example, if the command track calls for a break embellishment to be played, the style playback engine selects a break pattern that is compatible with the current groove level. (The author specifies which groove levels are appropriate for each pattern.) If there is more than one suitable pattern, a random choice is made.
  • Variations within a pattern. Any part within a pattern can have multiple variations. Variations can play in an order specified by the author; otherwise, the style playback engine makes a random choice of variations on each repetition of the pattern.
  • Groove level. The current groove level of the segment determines which of the patterns in the style can be selected for playback. The current level is set by the command track, which is normally authored into a segment or template. The current groove level of a segment can be changed programmatically, and a modifier can be applied to all segments by setting the master groove level for the performance.
  • Transposition. As the segment plays, the underlying chord changes according to the progression in the chord track. The notes in the current pattern are automatically transposed to harmonize with the new chord.
  • Variations in timing. The playback engine can introduce small random changes in the parameters of individual notes—when they begin and when they end.
  • Band. The choice of instruments and instrument settings (volume, pan, and transposition) can be changed as the segment is playing, either by the band track within an authored segment or dynamically by the application. The application can change the band by creating a secondary segment based on a band object, then playing that segment.

In many cases, applications exert control over the music by playing different segments, rather than by manipulating existing segments. For example, to have the music reflect a change in the intensity of a game, you can simply transition to a new segment authored for that intensity level. You can achieve a similar effect with a single style-based segment by having the author create patterns with different groove ranges, then changing the groove level in response to game events.

For more information on how to change the music at run time, see Music Parameters.


Music Values and MIDI Notes

Notes in a pattern within a DirectMusic style are not fixed notes. Rather, they are music values that become actual notes only when they are transposed to the current chord according to the current play mode and subchord level.

A music value is a representation of the note's intended role. For example, a music value can specify that a note is intended to be played as the second position in the chord, up one in the scale. When that music value is applied to a particular chord, it is converted to the appropriate MIDI note—the one in the second position in the chord, up one in the scale.

[C++]

For an explanation of the data format of music values, see DMUS_NOTE_PMSG.

[Visual Basic]

For an explanation of the data format of music values, see DMUS_NOTE_PMSG.

The play mode determines how to interpret the note against the chord. For example, if the mode is DMUS_PLAYMODE_NORMALCHORD, the note is interpreted against the intervals of the chord and scale, based on the root of the chord. If the mode is DMUS_PLAYMODE_FIXEDTOKEY, the note is interpreted as a linear value.

[Visual Basic]

For more information on the various play modes, see CONST_DMUS_PLAYMODE_FLAGS.

The subchord level is a value in the range from 0 trhough 31 that determines which subchords can be used in establishing the music value. A DirectMusic chord consists of one or more subchords, allowing for complex harmonies with multiple parallel chord progressions. Each subchord supports one or more levels. The author of the music defines the supported levels for each subchord.

When a segment is played, each note is encapsulated in a DMUS_NOTE_PMSG type. The midiValue member of this type holds the MIDI note value that would normally be sent to the synthesizer. The message also holds the original music value, as well as the play mode and subchord level that were used in transposition.

Music values and play modes are primarily of interest to tools, which are not supported by DirectX for Visual Basic. If you want to inject a note into the performance by using DirectMusicPerformance.SendNotePMSG, specify the desired midiValue in the DMUS_NOTE_PMSG type, and ignore the musicValue, playModeFlags, and subChordLevel members.

The following code example sends a message to play middle C immediately:

' perf is the DirectMusicPerformance.
Dim note As DMUS_NOTE_PMSG

note.midiValue = 60
note.mtDuration = 500
note.flags = DMUS_NOTEF_NOTEON
note.velocity = 127
Call perf.SendNotePMSG(0, DMUS_PMSGF_REFTIME, 1, note)
[C++]

For more information on the various play modes, see DMUS_PLAYMODE_FLAGS.

The subchord level is a value in the range from 0 through 31 that determines which subchords can be used in establishing the music value. A DirectMusic chord (as represented by a DMUS_CHORD_PARAM or DMUS_CHORD_KEY structure) consists of one or more subchords, allowing for complex harmonies with multiple parallel chord progressions. Each subchord supports one or more levels, as specified in the dwLevels member of the DMUS_SUBCHORD structure. The author of the music defines the supported levels for each subchord.

When a segment is played, each note is encapsulated in a DMUS_NOTE_PMSG structure. The bMidiValue member of this structure holds the MIDI note value that would normally be sent to the synthesizer. The message also holds the original music value, as well as the play mode and subchord level that were used in transposition. A tool can use this information to alter the note in any way it likes. For example, a tool could intercept a note that was transposed in a certain play mode, change the play mode, obtain a new MIDI note by using the IDirectMusicPerformance::MusicToMIDI method, and put the new value in the bMidiValue member of the message before passing it on.

The MusicToMIDI method is at the heart of the style playback mechanism of DirectMusic. It is called by the style track to convert its internal music values into notes, using the current chord in the chord track.

If a tool wants to reverse the process and obtain a new music value from a MIDI note using a different chord, play mode, or subchord level, it calls the IDirectMusicPerformance::MIDIToMusic method. The new music value can be placed in the wMusicValue member of the note message, in which it might be of use to other application-defined tools. However, the DirectMusic output tool ignores it and plays the note in bMidiValue as usual.


Using Compositional Elements

This section is a guide to incorporating music components into a DirectMusic application. It is presumed that you have a basic understanding of the purpose of each component and how it is represented by an object. If not, you might first want to read Composition Objects and Interfaces and Overview of Music Authoring.

You can incorporate DirectMusic into your applications without working with individual components, such as styles, chord maps, and templates. If you prefer, you can work with fully authored segments, or even with MIDI files. Using individual components simply gives you greater control over the performance at run time.

This section covers the following topics:

  • Using Authored Segments
  • Using Styles
  • Using Motifs
  • Using Chord Maps
  • Using Templates
  • Using Transitions


Using Authored Segments

An authored segment is a file or resource that contains all the data for a piece of music. It can be based on a MIDI file or on a style and a chord map. Unlike a simple MIDI file or resource, it can contain band changes and variations.

Note A template is an authored segment as well, but it does not represent a self-contained piece of music. For more information, see Using Templates.

[C++]

Create a segment in your application by loading the segment as an object and obtaining the IDirectMusicSegment interface, as in the following code example, in which the segment is loaded from a DirectMusic Producer file:

/* It is assumed that pLoader is a valid pointer to
   an IDirectMusicLoader interface and that the search
   directory has been properly set. */

DMUS_OBJECTDESC ObjectDescript;
IDirectMusicSegment* pSegment;

ObjectDescript.dwSize = sizeof(DMUS_OBJECTDESC);
ObjectDescript.idClass = CLSID_DirectMusicSegment;
strcpy(ObjectDescript.wszFileName, L"Dance.sgt");
ObjectDescript.dwValidData = DMOBJ_CLASS | DMOBJ_PATH ;
pLoader->GetObject(&ObjectDescript, IID_IDirectMusicSegment2,
    (void**) pSegment)))

You can now pass pSegment to the IDirectMusicPerformance::PlaySegment method.

[Visual Basic]

Create a segment in your application by using the DirectMusicLoader.LoadSegment or the DirectMusicLoader.LoadSegmentFromResource method, as in the following code example, in which the segment is loaded from a DirectMusic Producer file:

' loader is the DirectMusicLoader object.
Dim seg As DirectMusicSegment
Set seg = loader.LoadSegment("Sample.sgt")

You can now pass seg to the DirectMusicPerformance.PlaySegment method.


Using Styles

The DirectMusicStyle object represents a collection of musical patterns, usually including embellishments and motifs, with a time signature, tempo, and band. It defines the basic rhythm and the notes that are played in each instrument part.

You can obtain the DirectMusicStyle object from a style or segment file or from a resource. For more information, see DirectMusic Loader and Music Files for Composition.

A style by itself does not contain enough information to create a segment of music at run time. You need two other components: a chord map (map of chord progressions) and a command track to set the groove level and embellishments as the music plays. The command track can come from a template or be generated at run time from a shape. The chord map generally comes from a chord-map file or resource.

[C++]

To create a segment with a command track based on a template, call the IDirectMusicComposer::ComposeSegmentFromTemplate method. (See Using Templates.)

To create a segment based on a shape, call the IDirectMusicComposer::ComposeSegmentFromShape method. You supply pointers to the style and the chord map, and a variable to receive a pointer to the created segment. You also supply a rate of harmonic motion, which controls the frequency of chord changes, and a shape constant, which determines the progression of groove levels and embellishments.

[Visual Basic]

To create a segment with a command track based on a template, call the DirectMusicComposer.ComposeSegmentFromTemplate method. (See Using Templates.)

To create a segment based on a shape, call the DirectMusicComposer.ComposeSegmentFromShape method. You supply pointers to the style and the chord map, and a variable to receive a pointer to the created segment. You also supply a rate of harmonic motion, which controls the frequency of chord changes, and a shape constant, which determines the progression of groove levels and embellishments.


Using Motifs

A motif is a special kind of pattern in a style intended to be played over the basic style pattern, typically in response to an interactive event. Although a motif can be as complex as any other pattern, even containing variations and multiple instrument parts, usually it is a short, simple musical figure that sounds good against a variety of background patterns. It might also be a sound effect played by a custom DLS instrument or instruments.

[C++]

All the motifs authored into a style become available to you as soon as you have loaded that style. To get a particular motif ready for playback, call the IDirectMusicStyle::GetMotif method, passing in the following parameters:

  • The name of the motif. You might know this from the documentation for the style, or you can obtain it from an index value by using the IDirectMusicStyle::EnumMotif method.
  • A pointer to receive the IDirectMusicSegment interface to the segment object to be created by the method.

The following code example obtains and plays the motif whose name is passed in as pwszMotifName.

void PlayMotif(IDirectMusicPerformance* pPerf,
         IDirectMusicStyle* pStyle,
         WCHAR* pwszMotifName)
{
  IDirectMusicSegment* pSeg;

  // Get the motif segment from the style. Check for S_OK
  // specifically because GetMotif() returns S_FALSE if it
  // does not find the motif.

  if (S_OK == pStyle->GetMotif(pwszMotifName, &pSeg))
  {
    /* Play the segment. DMUS_SEGF_BEAT means play on the next beat if
       there is a segment currently playing. DMUS_SEGF_SECONDARY means
       play the segment as a secondary segment, which plays over
       the currently playing primary segment. The 0 indicates to
       play now. The final NULL means do not return an
       IDirectMusicSegmentState* in the last parameter
       because you don't need to track the state of playback. */

    pPerf->PlaySegment(pSeg,
                       DMUS_SEGF_BEAT | DMUS_SEGF_SECONDARY,
                       0,
                       NULL);
    pSeg->Release();
  }
}

Note that pSeg is played as a secondary segment because a motif is normally played over a primary segment. You cannot play a motif as a primary segment because it does not have a chord track or band track. If you do want to play a motif against silence, create a primary segment from a style that has only blank patterns, and keep that segment playing while you play the motif.

[Visual Basic]

All the motifs authored into a style become available to you as soon as you have loaded that style. To get a particular motif ready for playback, call the DirectMusicStyle.GetMotif method, passing in the name of the motif. You might know this from the documentation for the style, or you can obtain it from an index value by using the DirectMusicStyle.GetMotifName method.

The following code example obtains and plays the first motif in the style:

' style is a DirectMusicStyle.
' perf is the DirectMusicPerformance.
Dim MotifName As String
Dim segMotif As DirectMusicSegment

MotifName = style.GetMotifName(0)
Set segMotif = style.GetMotif(MotifName)
Call perf.PlaySegment(segMotif, DMUS_SEGF_SECONDARY, 0)

Note that segMotif is played as a secondary segment because a motif is normally played over a primary segment. You cannot play a motif as a primary segment because it does not have a chord track or band track. If you want to play a motif against silence, create a primary segment from a style that has only blank patterns, and keep that segment playing while you play the motif.


Using Chord Maps

A chord-map object represents a collection of chords that provides the foundation of the harmonic structure and the mood of the music. A chord map contains several pathways with many interconnected chords, providing many possibilities for the composition engine to choose from in determining the chord progression in a piece of music.

For authored segments, applications do not normally need to concern themselves with chord maps. The chord map is used at the authoring stage to create a fixed chord progression. However, chord maps can be used to compose segments at run time and to alter the chord progression of existing segments.

You obtain the DirectMusicChordMap object from a chord-map file or resource. For more information, see DirectMusic Loader and Music Files for Composition.

[C++]

If a chord map has been authored into a style, you can retrieve a pointer to its IDirectMusicChordMap interface by passing its name (assigned by the author) to the IDirectMusicStyle::GetChordMap method. You can also use the IDirectMusicStyle::EnumChordMap method to search for a particular chord map, or the IDirectMusicStyle::GetDefaultChordMap method to obtain a pointer to the default chord map for the style.

Note DirectMusic Producer does not support authoring chord maps into style files.

You set the chord map for a composition when you create a segment by using either IDirectMusicComposer::ComposeSegmentFromTemplate or IDirectMusicComposer::ComposeSegmentFromShape. For more information, see Using Styles.

Once a segment has been created, you can change its chord map by calling the IDirectMusicComposer::ChangeChordMap method. This changes the mood of the music without altering its basic rhythm and melody.

Every chord map has an underlying scale, consisting of 24 tones. You can determine the tones of the scale by using the IDirectMusicChordMap::GetScale method. The lower 24 bits of the variable pointed to by the pdwScale parameter of this method are set or clear, depending on whether the corresponding tone is part of the scale. The upper 8 bits give the root of the scale as an integer in the range from 0 through 23 (low C to middle B).

[Visual Basic]

You set the chord map for a composition when you create a segment by using either DirectMusicComposer.ComposeSegmentFromTemplate or DirectMusicComposer.ComposeSegmentFromShape. For more information, see Using Styles.

Once a segment has been created, you can change its chord map by calling the DirectMusicComposer.ChangeChordMap method. This changes the mood of the music without altering its basic rhythm and melody.


Using Templates

A template is a special kind of segment that can be used in composing a playable segment of music at run time. The template sets the length of the segment and any loop points. It provides the command track, which controls changes in the groove level and the choice of embellishment patterns. It also prescribes how the chord map is used in composing the segment, by specifying from which signpost group each new chord must come.

[C++]

A template is represented by a DirectMusicSegment object.

There are two ways to obtain a template:

  • Obtain one from a template file or resource. You load the file as a DirectMusicObject and query for the IDirectMusicSegment interface. For more information, see DirectMusic Loader.
  • Create one from a shape, using the IDirectMusicComposer::ComposeTemplateFromShape method. You choose the length, the overall shape, whether intro and end embellishment patterns are to be played, and how long the ending is to be. You get back a pointer to the IDirectMusicSegment interface.

Once you have obtained a template segment object, you can pass it to the IDirectMusicComposer::ComposeSegmentFromTemplate method, along with pointers to a style and a chord map. You also supply a rate of harmonic motion, which sets the frequency of chord changes. The ComposeSegmentFromTemplate method creates a segment and returns a pointer to its IDirectMusicSegment interface at the address given in the ppSectionSeg parameter. You pass this pointer to the IDirectMusicPerformance::PlaySegment method.

[Visual Basic]

A template is represented by a DirectMusicSegment object.

There are two ways to obtain a template object:

  • Obtain one from a template file or resource by using DirectMusicLoader.LoadSegment or DirectMusicLoader.LoadSegmentFromResource.
  • Create one from a shape, using the DirectMusicComposer.ComposeTemplateFromShape method. You choose the length, the overall shape, whether intro and end embellishment patterns are to be played, and how long the ending is to be.

Once you have obtained a template segment object, you can pass it to the DirectMusicComposer.ComposeSegmentFromTemplate method, along with pointers to a style and a chord map. You also supply a rate of harmonic motion, which sets the frequency of chord changes. The ComposeSegmentFromTemplate method creates a segment that can be passed to the DirectMusicPerformance.PlaySegment method.


Using Transitions

To avoid a sudden and perhaps discordant break when stopping one segment and beginning another, or when bringing the music to a close, you can have the composer create an intermediate or closing segment that provides an appropriate transition.

[C++]

There are two methods for composing transitional segments.

  • The IDirectMusicComposer::AutoTransition method, given a pointer to the performance, creates a transition from the currently playing segment to a second segment of your choice, and then automatically cues the transitional segment and the second segment for playback, returning an IDirectMusicSegmentState interface for both. The transition begins playing immediately or on the next boundary, as specified in the dwFlags parameter. Optionally, the second segment can be NULL so that the transition is to silence.
  • The IDirectMusicComposer::ComposeTransition method composes a transition from any point in one segment to the beginning of a second segment, or to silence, and returns an IDirectMusicSegment interface so that the application can play the transition.

Both these methods take a chord map, a command, and a set of flags as parameters.

  • The chord map, as usual, is used to create a chord track that defines the chord progression in the segment.
  • The command is one of the DMUS_COMMANDT_TYPES enumeration. It determines which type of pattern—either an ordinary groove pattern or one of the embellishments—is called for in the command track of the transitional segment. When the segment plays, an appropriate pattern is selected from the style.
  • The flags are from DMUS_COMPOSEF_FLAGS and further define the transition, principally its timing. The DMUS_COMPOSEF_MODULATE flag can be used to cause the transition to move smoothly from one tonality to another; it cannot be used when there is no second segment because there can be no modulation to silence.
[Visual Basic]

There are two methods for composing transitional segments.

  • The DirectMusicComposer.AutoTransition method, given a DirectMusicPerformance, creates a transition from the currently playing segment to a second segment of your choice, and then automatically cues the transitional segment and the second segment for playback. The transition begins playing immediately or on the next boundary, as specified in the lFlags parameter. Optionally, the second segment can be Nothing so that the transition is to silence.
  • The DirectMusicComposer.ComposeTransition method composes a transition from any point in one segment to the beginning of a second segment, or to silence, and returns a DirectMusicSegment object so that the application can play the transition.

Both these methods take a chord map, a command, and a set of flags as parameters.

  • The chord map, as usual, is used to create a chord track that defines the chord progression in the segment.
  • The command is one of the CONST_DMUS_COMMANDT_TYPES enumeration. It determines which type of pattern—either an ordinary groove pattern or one of the embellishments—is called for in the command track of the transitional segment. When the segment plays, an appropriate pattern is selected from the style.
  • The flags are from CONST_DMUS_COMPOSEF_FLAGS and further define the transition, principally its timing. The DMUS_COMPOSEF_MODULATE flag can be used to cause the transition to move smoothly from one tonality to another; it cannot be used when there is no second segment, because there can be no modulation to silence.

Transitions are normally a single measure in length. There are two exceptions: when the DMUS_COMPOSEF_LONG flag is included and when the command is DMUS_COMMANDT_END and the end embellishment in the style is more than one measure long.


DirectMusic Tutorials

This section contains tutorials providing step-by-step instructions for implementing basic Microsoft® DirectMusic® functionality.

  • DirectMusic C/C++ Tutorials
  • DirectMusic Visual Basic Tutorials


DirectMusic C/C++ Tutorials

[Visual Basic]

This section pertains only to applications written in C++. See DirectMusic Visual Basic Tutorials.

[C++]

This section contains the following tutorials showing how to implement DirectMusic in a C or C++ application:

  • Tutorial 1: Playing a MIDI File
  • Tutorial 2: Using Tools
  • Tutorial 3: Using Compositions


Tutorial 1: Playing a MIDI File

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectMusic Visual Basic Tutorials.

[C++]

This tutorial is a guide to setting up the simplest possible DirectMusic application, one that just plays a primary segment. In this example the segment represents a MIDI file, but the process of loading and playing the data would be exactly the same if the source were a segment authored in a tool such as DirectMusic Producer.

The tutorial is divided into the following steps:

  • Step 1: Initialize COM
  • Step 2: Create the Performance
  • Step 3: Create the Loader
  • Step 4: Load the MIDI File
  • Step 5: Play the MIDI File
  • Step 6: Shut Down DirectMusic


Step 1: Initialize COM

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectMusic Visual Basic Tutorials.

[C++]

Before making any calls to DirectMusic, you have to initialize COM as follows:

if (FAILED(CoInitialize(NULL)))
{
    // Terminate the application.
}   // Else full speed ahead!

Next: Step 2: Create the Performance


Step 2: Create the Performance

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectMusic Visual Basic Tutorials.

[C++]

The central object of any DirectMusic application is the performance, which manages the playback of segments. It is created by using the COM CoCreateInstance function, as in the following sample function:

IDirectMusicPerformance* CreatePerformance(void)
{
    IDirectMusicPerformance* pPerf;

    if (FAILED(CoCreateInstance(
            CLSID_DirectMusicPerformance,
            NULL,
            CLSCTX_INPROC,
            IID_IDirectMusicPerformance2,
            (void**)&pPerf
        )))
    {
        pPerf = NULL;
    }
    return pPerf;
}

You can use this function to initialize a global performance pointer that will be used in later steps:

IDirectMusicPerformance* g_pPerf = CreatePerformance();
if (g_pPerf == NULL)
{
    // Failure -- performance not created
}

Once the performance has been created, you need to initialize it by calling the IDirectMusicPerformance::Init method. The method creates a DirectMusic object to manage the default port. Because you don't need to access the IDirectMusic methods directly, you don't need to retrieve a pointer to it, so you pass NULL as the first parameter to Init. You also pass NULL as the IDirectSound pointer and as the window handle, so that DirectMusic will create a DirectSound object and pass the current focus window to it when setting the cooperative level.

if (FAILED(g_pPerf->Init(NULL, NULL, NULL)))
{
    // Failure -- performance not initialized
};

Now you need to add a port to the performance. Calling the IDirectMusicPerformance::AddPort method with a NULL parameter automatically adds the default port (normally the Microsoft Software Synthesizer) with one channel group, and assigns PChannels 0-15 to the group's MIDI channels.

if (FAILED(pPerf->AddPort(NULL)))
{
    // Failure -- port not initialized
}

Next: Step 3: Create the Loader


Step 3: Create the Loader

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectMusic Visual Basic Tutorials.

[C++]

In order to load any object from disk, you first need to create the DirectMusicLoader object. This is done just as for any other COM object, as shown in the following sample function:

IDirectMusicLoader* CreateLoader(void)
{
    IDirectMusicLoader* pLoader;

    if (FAILED(CoCreateInstance(
            CLSID_DirectMusicLoader,
            NULL,
            CLSCTX_INPROC,
            IID_IDirectMusicLoader,
            (void**)&pLoader
        )))
    {
        pLoader = NULL;
    }
    return pLoader;
}

You'll use this function to initialize a global variable:

IDirectMusicLoader* g_pLoader = CreateLoader();
if (g_pLoader == NULL)
{
    // Failure -- loader not created
}

Next: Step 4: Load the MIDI File


Step 4: Load the MIDI File

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectMusic Visual Basic Tutorials.

[C++]

In this step you will implement a function, LoadMIDISegment, that takes a pointer to the IDirectMusicLoader created in the last step and uses it to create a segment object encapsulating the data from a MIDI file.

IDirectMusicSegment* LoadMIDISegment(IDirectMusicLoader* pLoader,
        WCHAR wszMidiFileName )
{
    DMUS_OBJECTDESC ObjDesc;
    IDirectMusicSegment* pSegment = NULL;

Let's assume that all the MIDI files you want to play are in the current working directory. You need to let the loader know this, by setting the search directory. (If the search directory is not being changed elsewhere, in order to load objects from other directories, this actually has to be done only once, not each time you load a file.)

    char szDir[_MAX_PATH];
    WCHAR wszDir[_MAX_PATH];

    if(_getcwd( szDir, _MAX_PATH ) == NULL)
    {
        return NULL;
    }

/*
Convert from multibyte format to Unicode using the following macro:
#define MULTI_TO_WIDE( x,y )  MultiByteToWideChar( CP_ACP, \
        MB_PRECOMPOSED, y, -1, x, _MAX_PATH );
*/

    MULTI_TO_WIDE(wszDir, szDir);
    HRESULT hr = pLoader->SetSearchDirectory(GUID_DirectMusicAllTypes,
        wszDir, FALSE);
    if (FAILED(hr))
    {
        return NULL;
    }

You then describe the object to be loaded, in a DMUS_OBJECTDESC structure:

    ObjDesc.guidClass = CLSID_DirectMusicSegment;
    ObjDesc.dwSize = sizeof(DMUS_OBJECTDESC);
    wcscpy( ObjDesc.wszFileName, wszMidiFileName );
    ObjDesc.dwValidData = DMUS_OBJ_CLASS | DMUS_OBJ_FILENAME;

Now load the object and query it for the IDirectMusicSegment interface. This is done in a single call to IDirectMusicLoader::GetObject. Note that loading the object also initializes the tracks and does everything else necessary to get the MIDI data ready for playback.

    pLoader->GetObject(&ObjDesc,
            IID_IDirectMusicSegment2, (void**) &pSegment);

To ensure that the segment plays as a standard MIDI file, you now need to set a parameter on the band track. Use the IDirectMusicSegment::SetParam method and let DirectMusic find the track, by passing -1 (or 0xFFFFFFFF) in the dwGroupBits method parameter.

    g_pMIDISeg->SetParam(GUID_StandardMIDIFile,
            -1, 0, 0, (void*)g_pPerf);

This step is necessary because DirectMusic handles program changes and bank selects differently for standard MIDI files than it does for MIDI content authored specifically for DirectMusic. The GUID_StandardMIDIFile parameter must be set before the instruments are downloaded.

The next step is to download the instruments. This is necessary even for playing a simple MIDI file, because the default software synthesizer needs the DLS data for the General MIDI instrument set. If you skip this step, the MIDI file will play silently. Again, you call SetParam on the segment, this time specifying the GUID_Download parameter:

    g_pMIDISeg->SetParam(GUID_Download, -1, 0, 0, (void*)g_pPerf);

Note that there's no harm in requesting the download even though this might already have been done in a previous call to the LoadMIDISegment function. A redundant request is simply ignored. Eventually you have to unload the instruments, but that can wait until you're ready to shut down DirectMusic.

The function now returns a pointer to the segment, which is ready to be played.

    return pSegment;

} // End of LoadSegment()

Before loading a new segment, clean up any existing one. Then pass a file name to the LoadMIDISegment function.

if (g_pMIDIseg)
{
    g_pMIDIseg->Release();
    g_pMIDIseg = NULL;
}

if (g_pLoader)
{
    IDirectMusicSegment* g_pMIDIseg = LoadMIDISegment(g_pLoader,
            L"tune.mid");
}

Next: Step 5: Play the MIDI File


Step 5: Play the MIDI File

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectMusic Visual Basic Tutorials.

[C++]

Now that all of the preparatory work has been done, playing the music is simplicity itself.

IDirectMusicSegmentState* g_pSegState;
if (g_pMIdiSEG)
{
    g_pPerf->PlaySegment(g_pMIDISeg, 0, 0, &g_pSegState);
}

The call to IDirectMusicPerformance::PlaySegment takes the following parameters:

  • The segment you created in the previous step.
  • A set of timing flags and a start time (not needed here because you simply want the segment to play as soon as possible).
  • The address of a pointer to a segment state object. You can use the returned pointer in order to retrieve information about the segment. This parameter can be NULL if you won't be needing the segment state.

If you want the file to be played more than once, before calling PlaySegment you must call the IDirectMusicSegment::SetRepeats method.

If you want to stop the music before it has played to the end or finished its repeats, you do so by using the IDirectMusicPerformance::Stop method. The simplest way to use this method is simply to request that all music currently playing or cued to play be stopped immediately:

g_pPerf->Stop(NULL, NULL, 0, 0)

Alternatively, you can supply a pointer to the current segment or segment state in order to stop playback of just one segment, or one instance of that segment.

Next: Step 6: Shut Down DirectMusic


Step 6: Shut Down DirectMusic

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectMusic Visual Basic Tutorials.

[C++]

Before exiting, the program must unload the instruments, release all the objects that have been created, and dereference COM (remember, every call to CoInitialize must have a matching call to CoUninitialize).

The following function performs the necessary cleanup:

HRESULT FreeDirectMusic()
{
    // If there is any music playing, stop it. This is
    // not really necessary, because the music will stop when
    // the instruments are unloaded or the performance is
    // closed down.
    g_pPerf->Stop( NULL, NULL, 0, 0 );

    // Unload instruments – this will cause silence.
    // CloseDown unloads all instruments, so this call is also not
    // strictly necessary.
    g_pMIDISeg->SetParam(GUID_Unload, -1, 0, 0, (void*)g_pPerf);

    // Release the segment.
    g_pMIDISeg->Release();

    // CloseDown and Release the performance object.
    g_pPerf->CloseDown();
    g_pPerf->Release();

    // Release the loader object.
    g_pLoader->Release();

    // Release COM.
    CoUninitialize();

    return S_OK;
}


Tutorial 2: Using Tools

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectMusic Visual Basic Tutorials.

[C++]

This tutorial shows how a tool might be implemented as a C++ class and used in a DirectMusic application. The CEchoTool class enables an application to add one or more echoes to every music note in a performance.

The sample code is based on the EchoTool sample application included with the DirectX SDK.

The tutorial is broken down into the following steps:

  • Step 1: Declare the Tool Class
  • Step 2: Define the IUnknown Methods
  • Step 3: Specify Message Types
  • Step 4: Define the ProcessPMsg Method
  • Step 5: Define the Class Methods
  • Step 6: Add the Tool to the Performance


Step 1: Declare the Tool Class

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectMusic Visual Basic Tutorials.

[C++]

The first step in creating a tool for DirectMusic in C++ is to declare a class derived from IDirectMusicTool.

Here is the declaration for the sample CEchoTool class:

class CEchoTool : public IDirectMusicTool
{
public:
  CEchoTool();
  ~CEchoTool();

public:
// IUnknown
  virtual STDMETHODIMP QueryInterface(const IID &iid, void **ppv);
  virtual STDMETHODIMP_(ULONG) AddRef();
  virtual STDMETHODIMP_(ULONG) Release();

// IDirectMusicTool
  HRESULT STDMETHODCALLTYPE Init(
          IDirectMusicGraph* pGraph);
  HRESULT STDMETHODCALLTYPE GetMsgDeliveryType(
          DWORD* pdwDeliveryType);
  HRESULT STDMETHODCALLTYPE GetMediaTypeArraySize(
          DWORD* pdwNumElements);
  HRESULT STDMETHODCALLTYPE GetMediaTypes(
          DWORD** padwMediaTypes,
          DWORD dwNumElements);
  HRESULT STDMETHODCALLTYPE ProcessPMsg(
          IDirectMusicPerformance* pPerf,
          DMUS_PMSG* pDMUS_PMSG);
  HRESULT STDMETHODCALLTYPE Flush(
         IDirectMusicPerformance* pPerf,
         DMUS_PMSG* pDMUS_PMSG,
         REFERENCE_TIME rtTime);
private:
  long m_cRef;                // Reference counter
  DWORD m_dwEchoNum;          // Number of echoes to generate
  MUSIC_TIME m_mtDelay;       // Delay time between echoes
  CRITICAL_SECTION m_CrSec;   // To make SetEchoNum()
                              //   and SetDelay() thread-safe
public:
// Public class methods
  void SetEchoNum(DWORD);
  void SetDelay(MUSIC_TIME);
};

Next: Step 2: Define the IUnknown Methods


Step 2: Define the IUnknown Methods

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectMusic Visual Basic Tutorials.

[C++]

The inherited IUnknown methods of the sample CEchoTool class are implemented as follows:

STDMETHODIMP CEchoTool::QueryInterface(const IID &iid, void **ppv)
{
  if (iid == IID_IUnknown || iid == IID_IDirectMusicTool)
  {
    *ppv = static_cast<IDirectMusicTool*>(this);
  } else
  {
    *ppv = NULL;
    return E_NOINTERFACE;
  }

  reinterpret_cast<IUnknown*>(this)->AddRef();
  return S_OK;
}

STDMETHODIMP_(ULONG) CEchoTool::AddRef()
{
    return InterlockedIncrement(&m_cRef);
}

STDMETHODIMP_(ULONG) CEchoTool::Release()
{
    if( 0 == InterlockedDecrement(&m_cRef) )
    {
        delete this;
        return 0;
    }
    return m_cRef;
}

Next: Step 3: Specify Message Types


Step 3: Specify Message Types

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectMusic Visual Basic Tutorials.

[C++]

The CEchoTool class needs to define all the IDirectMusicTool methods. But because it does not need to perform any work in Init or Flush, it simply returns E_NOTIMPL from those methods.

The following methods are used to specify what messages will get passed to the tool for processing:

  • GetMsgDeliveryType specifies when messages should be passed to the tool—as soon as they are available, at the exact time they are stamped for, or just in time to be processed and put in the port buffer. These three "delivery types" are represented respectively by the DMUS_PMSGF_TOOL_IMMEDIATE, DMUS_PMSGF_TOOL_ATTIME, and DMUS_PMSGF_TOOL_QUEUE flags in the dwFlags member of the DMUS_PMSG structure.
  • GetMediaTypes establishes what type of messages should be passed to the tool, based on the content of the message. CEchoTool processes only music notes and patch changes, so it will accept MIDI short messages, music note messages, and DirectMusic patch messages. These messages are identified by flags of the DMUS_PMSGT_TYPES enumerated type in the DMUS_PMSG message structure.
  • GetMediaTypeArraySize returns the number of elements in the media type array.

CEchoTool implements these methods in the following sample code:

HRESULT STDMETHODCALLTYPE CEchoTool::GetMsgDeliveryType(
        DWORD* pdwDeliveryType )
{
    // This tool wants messages immediately.
    // This is the default, so returning E_NOTIMPL
    // would work. The other method is to specifically
    // set *pdwDeliveryType to the delivery type,
// DMUS_PMSGF_TOOL_IMMEDIATE, DMUS_PMSGF_TOOL_QUEUE,
// or DMUS_PMSGF_TOOL_ATTIME.

    *pdwDeliveryType = DMUS_PMSGF_TOOL_IMMEDIATE;
  return S_OK;
}

HRESULT STDMETHODCALLTYPE CEchoTool::GetMediaTypeArraySize(
        DWORD* pdwNumElements)
{
  *pdwNumElements = 3;
  return S_OK;
}

HRESULT STDMETHODCALLTYPE CEchoTool::GetMediaTypes(
        DWORD** padwMediaTypes,
        DWORD dwNumElements)
{
  if (dwNumElements == 3)
  {
    (*padwMediaTypes)[0] = DMUS_PMSGT_NOTE;
    (*padwMediaTypes)[1] = DMUS_PMSGT_MIDI;
    (*padwMediaTypes)[2] = DMUS_PMSGT_PATCH;
    return S_OK;
  }
  else
  {
    // This should never happen.
    return E_FAIL;
  }
}

Next: Step 4: Define the ProcessPMsg Method


Step 4: Define the ProcessPMsg Method

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectMusic Visual Basic Tutorials.

[C++]

The actual work of the tool is performed in the method derived from IDirectMusicTool::ProcessPMsg. This method will be called for every message of the type listed in the array returned by IDirectMusicTool::GetMediaTypes.

The CEchoTool::ProcessPMsg method first performs some initialization of local variables:

HRESULT STDMETHODCALLTYPE CEchoTool::ProcessPMsg(
  IDirectMusicPerformance* pPerf,
  DMUS_PMSG* pMsg)
{
  DMUS_NOTE_PMSG* pNote;
  DWORD dwCount;
  DWORD dwEchoNum;
  MUSIC_TIME mtDelay;

  // SetEchoNum() and SetDelay() use these member variables,
  // so use a critical section to make them thread-safe.
  EnterCriticalSection(&m_CrSec);
  dwEchoNum = m_dwEchoNum;
  mtDelay = m_mtDelay;
  LeaveCriticalSection(&m_CrSec);

Next the method calls the IDirectMusicGraph::StampPMsg method on the message. If there is another tool to which this message must be directed after we're finished with it here, StampPMsg succeeds. (Note that DirectMusic provides a final output tool, so StampPMsg should succeed even if there are no other application-specific tools to which the message must be routed.) If it fails, our method returns S_FREE so that the message will automatically be discarded.

  if ((NULL == pMsg->pGraph) ||
    FAILED(pMsg->pGraph->StampPMsg(pMsg)))
  {
    return DMUS_S_FREE;
  }

Now it's time for CEchoTool to perform its work on the message. Remember, it is set up to receive messages only of type DMUS_PMSGT_NOTE, DMUS_PMSGT_MIDI; or DMUS_PMSGT_PATCH. (These types are part of the DMUS_PMSGT_TYPES enumeration.)

For each successive echo to be created, the tool does the following:

  • Creates a new message by calling the IDirectMusicPerformance::AllocPMsg method.
  • Copies the DMUS_PMSG structure for the original message into the new one and updates some members for COM management.
  • Assigns the new message to a different performance channel.
  • In the case of a music note, progressively reduces the volume of each echo.
  • Adds the delay time to the time at which the message is to be played.
  • Puts the new message in the pipeline by calling the IDirectMusicPerformance::SendPMsg method. Note that because IDirectMusicGraph::StampPMsg is not called on the message, it will not be routed to any tools other than the default final output tool.

Here's the sample code that deals with MIDI notes:

  if( pPMsg->dwType == DMUS_PMSGT_MIDI )
  {
    // copy MIDI messages into the echo channels.
    for( dwCount = 1; dwCount <= dwEchoNum; dwCount++ )
    {
      DMUS_MIDI_PMSG* pMidi;
      if( SUCCEEDED( pPerf->AllocPMsg( sizeof(DMUS_MIDI_PMSG),
        (DMUS_PMSG**)&pMidi )))
      {
        // Copy the original message into this message.
        memcpy( pMidi, pPMsg, sizeof(DMUS_MIDI_PMSG) );

        // Addref or clear out any fields that contain
        // or may contain pointers to objects.
        if( pMidi->pTool ) pMidi->pTool->AddRef();
        if( pMidi->pGraph ) pMidi->pGraph->AddRef();
        pMidi->punkUser = NULL;

        // Set the PChannel so the message goes to the
        // next higher group.
        pMidi->dwPChannel = pMidi->dwPChannel +
                (16*dwCount);

        // Add to the time of the echoed message.
        pMidi->mtTime += (dwCount * mtDelay);

        // Set the message so only MUSIC_TIME is valid.
        // REFERENCE_TIME will be recomputed inside
        // SendPMsg().
        pMidi->dwFlags = DMUS_PMSGF_MUSICTIME;

        // Send the message
        pPerf->SendPMsg( (DMUS_PMSG*)pMidi );
      }
    }
  }

Patch changes are also copied and sent to all possible echo channels, even those not currently being used, so that if echoes are added later they will be played by the correct instruments. Note that in the sample EchoTool application, MAX_ECHOES is defined in Echotool.h.

  else if( pPMsg->dwType == DMUS_PMSGT_PATCH )
  {
    for( dwCount = 1; dwCount <= MAX_ECHOES; dwCount++ )
    {
      DMUS_PATCH_PMSG* pPatch;
      if( SUCCEEDED( pPerf->AllocPMsg( sizeof(DMUS_PATCH_PMSG),
        (DMUS_PMSG**)&pPatch )))
      {
        // Copy the original message into this message,
        memcpy( pPatch, pPMsg, sizeof(DMUS_PATCH_PMSG) );

        // Addref or clear out any fields that contain
        // or may contain pointers to objects
        if( pPatch->pTool ) pPatch->pTool->AddRef();
        if( pPatch->pGraph ) pPatch->pGraph->AddRef();
        pPatch->punkUser = NULL;

        // Set the PChannel so the message goes to the
        // next higher group.
        pPatch->dwPChannel = pPatch->dwPChannel +
          (16*dwCount);

        // Add to the time of the echoed message.
        pPatch->mtTime += (dwCount * mtDelay);

        // Set the message so only MUSIC_TIME is valid.
        // REFERENCE_TIME will be recomputed inside
        // SendPMsg()
        pPatch->dwFlags = DMUS_PMSGF_MUSICTIME;

        // Send the message.
        pPerf->SendPMsg( (DMUS_PMSG*)pPatch );
      }
    }
  }

The method deals with music notes much as it did with MIDI notes, but taking the additional step of reducing the volume:

  else if( pPMsg->dwType == DMUS_PMSGT_NOTE )
  {
    // Create a variable to track the next note's velocity
    BYTE bVelocity;
    pNote = (DMUS_NOTE_PMSG*)pPMsg;
    bVelocity = pNote->bVelocity;

    for( dwCount = 1; dwCount <= dwEchoNum; dwCount++ )
    {
      if( SUCCEEDED( pPerf->AllocPMsg( sizeof(DMUS_NOTE_PMSG),
              (DMUS_PMSG**)&pNote )))
      {
        // Copy the original note into this message.
        memcpy( pNote, pPMsg, sizeof(DMUS_NOTE_PMSG) );

        // Addref or clear out any fields that contain
        // or may contain pointers to objects.
        if( pNote->pTool ) pNote->pTool->AddRef();
        if( pNote->pGraph ) pNote->pGraph->AddRef();
        pNote->punkUser = NULL;

        // Add to the time of the echoed note.
        pNote->mtTime += (dwCount * mtDelay);

        // Reduce the volume of the echoed note.
        bVelocity = (BYTE) (bVelocity -
                ((bVelocity * (dwCount * 15))/100));
        pNote->bVelocity = bVelocity;

        // Set the note so only MUSIC_TIME is valid.
        // REFERENCE_TIME will be recomputed inside
        // SendPMsg().
        pNote->dwFlags = DMUS_PMSGF_MUSICTIME;
        pNote->dwPChannel = pNote->dwPChannel +
          (16*dwCount);

        // Send the message.
        pPerf->SendPMsg( (DMUS_PMSG*)pNote );
      }
    }
  }

Finally, the ProcessPMsg method returns DMUS_S_REQUEUE so the original message will be put back in the pipeline.

  return DMUS_S_REQUEUE;
} // End CEchoTool::ProcessPMsg()

Next: Step 5: Define the Class Methods


Step 5: Define the Class Methods

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectMusic Visual Basic Tutorials.

[C++]

Besides its inherited IUnknown and IDirectMusicTool methods, the sample CEchoTool class has a constructor and destructor as well as two public methods for setting the parameters of the echo. The definition of these methods is somewhat peripheral to this tutorial, but is included here for completeness.

CEchoTool::CEchoTool()
{
  m_cRef = 1;               // So one Release() will free this
  m_dwEchoNum = 3;          // Default to 3 echoes per note
  m_mtDelay = DMUSPPQ / 2;  // Default to 8th-note echoes
  InitializeCriticalSection(&m_CrSec);
}

CEchoTool::~CEchoTool()
{
  DeleteCriticalSection(&m_CrSec);
}

void CEchoTool::SetEchoNum(DWORD dwEchoNum)
{
  // ProcessPMsg() uses m_dwEchoNum, so use a critical
  // section to make it thread-safe.
  if( dwEchoNum <= MAX_ECHOES )
  {
    EnterCriticalSection(&m_CrSec);
    m_dwEchoNum = dwEchoNum;
    LeaveCriticalSection(&m_CrSec);
  }
}

void CEchoTool::SetDelay(MUSIC_TIME mtDelay)
{
  // ProcessPMsg() uses m_mtDelay, so use a critical
  // section to make it thread-safe.
  EnterCriticalSection(&m_CrSec);
  m_mtDelay = mtDelay;
  LeaveCriticalSection(&m_CrSec);
}

Next: Step 6: Add the Tool to the Performance


Step 6: Add the Tool to the Performance

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectMusic Visual Basic Tutorials.

[C++]

Once it has defined the CEchoTool class, the application can create a tool object, insert it into a graph, and add it to the performance so that it will intercept appropriate messages in the pipeline.

The following code creates an instance of the CEchoTool class, initializes the number of echoes to be produced by the tool, creates a graph to contain the tool, and adds the graph to the performance. (In the EchoTool sample application, some of this work is done in a helper function, AddTool. The code has been modified here to make it easier to follow.)

/* It is assumed that pPerf is a valid pointer to the
   IDirectMusicPerformance interface of a performance object. */

CEchoTool         *pEchoTool;
IDirectMusicGraph* pGraph;

pEchoTool = new CEchoTool;
if (pEchoTool)
{
    pEchoTool->SetEchoNum(0);

    // Create an IDirectMusicGraph object to hold the tool.
    if (SUCCEEDED(CoCreateInstance(
            CLSID_DirectMusicGraph,
            NULL,
            CLSCTX_INPROC,
            IID_IDirectMusicGraph,
            (void**)&pGraph)))
    {
        // Add the tool to the graph.
        if (SUCCEEDED(pGraph->InsertTool(
                (IDirectMusicTool*)pCEchoTool,
                NULL,   // Apply to all PChannels
                0,      // How many PChannels otherwise
                0)))    // Index of tool in graph
        {
        // Add the graph to the performance. This increments the
        // reference count, so the original graph can then be
        // released.
        pPerf->SetGraph(pGraph);
        }
        pGraph->Release();
    }
}

Note that setting the graph on the performance ensures that messages from all segments will have the opportunity to be processed by its tools. Alternatively, you could use the IDirectMusicSegment::SetGraph method to apply tools only to a particular segment.


Tutorial 3: Using Compositions

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectMusic Visual Basic Tutorials.

[C++]

This tutorial shows how to set up a music performance that is based on elements authored in DirectMusic Producer, and how to have the music performed interactively—that is, in such as way that it responds to program events.

The code samples are based on the DMDonuts sample in the DirectX SDK. Because DMDonuts is a large and complex application, only the main points will be covered here. For the complete DirectMusic implementation, see the Donuts.cpp source file and its included headers, where all the relevant code is delimited by DMUSIC BEGIN and DMUSIC END comments.

The tutorial is broken down into the following steps:

  • Step 1: Defines and Globals
  • Step 2: Initialize the Performance
  • Step 3: Load the Music Elements
  • Step 4: Set Up Notifications
  • Step 5: Create the Primary Segments
  • Step 6: Play a Primary Segment
  • Step 7: Transition to Another Primary Segment
  • Step 8: Play a Motif
  • Step 9: Handle Notifications
  • Step 10: Shut Down DirectMusic


Step 1: Defines and Globals

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectMusic Visual Basic Tutorials.

[C++]

The following defines and global variables are declared at the beginning of Donuts.cpp. They are given here for you to refer to as you work through the tutorial.

BOOL          bMusicEnabled = TRUE;

// Various constants
const  GUID guidZero =    {0};
#define MOTIF_BOUNCE       0
#define MOTIF_DEATH        1
#define MOTIF_SHIELD       2
#define MOTIF_BLOWUP       4
#define MOTIF_BLOWUPLITE   3
#define NUM_MOTIFS         5
#define NUM_STYLES         2
#define SEGMENT_1          0
#define SEGMENT_2          1
#define SEGMENT_TRANS_1    2
#define SEGMENT_TRANS_2    3
#define NUM_SEGMENTS       4
#define NUM_CHORDMAP       4
#define BLOWUPS_PER_BEAT   2
#define MEASURE_LENGTH     DMUS_PPQ * 4
// parts/quarter * quarters/measure (assumes 4/4)

// Global interfaces
IDirectMusicStyle*        gapStyle[NUM_STYLES];
IDirectMusicChordMap*     gapChordMap[NUM_STYLES] [NUM_CHORDMAP];
IDirectMusicSegment*      gapMotif[NUM_STYLES] [NUM_MOTIFS];
IDirectMusicSegment*      gapSegment[NUM_SEGMENTS] =
                          {NULL, NULL, NULL, NULL};
IDirectMusicComposer *    gpComposer = NULL;
IDirectMusicPerformance*  gpPerformance = NULL;
IDirectMusic*             gpDirectMusic = NULL;
IDirectMusicLoader*       gpLoader = NULL;
IDirectMusicSegment*      gpIntroTemplate = NULL;
IDirectMusicSegment*      gpGameTemplate = NULL;
IDirectMusicSegment*      gapShieldSegment[NUM_STYLES] = {NULL, NULL};
IDirectMusicSegment*      gapDefaultSegment[NUM_STYLES] =
                                  {NULL, NULL};
IDirectMusicBand*         gapShieldBand[NUM_STYLES] = {NULL, NULL};
IDirectMusicBand*         gapDefaultBand[NUM_STYLES] = {NULL, NULL};

// Global variables
BOOL        bAnyHits = FALSE;
int         gnCurrentStyle = 0;
int         gnCurrentChordMap = 0;
int         gnLastStyle = 0;
int         gnLastChordMap = 0;

BOOL        gbShieldsOn = FALSE;
static int  snLastTempo;
static int  snSubLevel;
static int  snMaxBlowUps = BLOWUPS_PER_BEAT;

Next: Step 2: Initialize the Performance


Step 2: Initialize the Performance

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectMusic Visual Basic Tutorials.

[C++]

The DirectMusic performance is set up in the InitializeGame function in Donuts.cpp.

First the application queries the registry to obtain the search path for the DirectX sample music files, by calling the GetSearchPath function. Then it creates COM objects for the composer and the performance, as follows:

CoInitialize(NULL);

if ( !SUCCEEDED(::CoCreateInstance(
        CLSID_DirectMusicComposer,
        NULL,
        CLSCTX_INPROC,
        IID_IDirectMusicComposer,
        (void**)&gpComposer
)))
{
    return CleanupAndExit("Couldn't create a composer object");
}

if ( !SUCCEEDED( CoCreateInstance( CLSID_DirectMusicPerformance,
        NULL,
        CLSCTX_INPROC,
        IID_IDirectMusicPerformance,
        (void**)&gpPerformance )))
{
    return CleanupAndExit("Couldn't create a performance object");
}

The application then initializes the performance by calling IDirectMusicPerformance::Init, which creates a DirectMusic object that can be used to create and activate its ports. Depending on whether or not DirectSound is being used for other sound effects, the call either attaches the existing DirectSound object to the performance by passing in lpDS or creates one by passing in NULL.

#ifdef USE_DSOUND
    if( !SUCCEEDED(gpPerformance->Init(&gpDirectMusic,
           lpDS, hWndMain)))
    {
        return CleanupAndExit("Couldn't initialize the performance");
    }
#else
    if( !SUCCEEDED(gpPerformance->Init(&gpDirectMusic,
            NULL, hWndMain)))
    {
        return CleanupAndExit("Couldn't initialize the performance");
    }
#endif

The application now gets the default port, creates an instance of it with one channel group, and retrieves its capabilities:

IDirectMusicPort* pPort = NULL;
DMUS_PORTPARAMS dmos;
DMUS_PORTCAPS dmpc;
GUID guidSynthGUID;
HRESULT hr = S_OK;

if ( !SUCCEEDED(gpDirectMusic->GetDefaultPort(&guidSynthGUID)))
{
    return CleanupAndExit("Could't GetDefaultPort on IDirectMusic");
}

ZeroMemory(&dmos, sizeof(dmos));
dmos.dwSize = sizeof(DMUS_PORTPARAMS);
dmos.dwChannelGroups = 1;
dmos.dwValidParams = DMUS_PORTPARAMS_CHANNELGROUPS;

if( !SUCCEEDED(gpDirectMusic->CreatePort(guidSynthGUID,
            &dmos,
            &pPort,
            NULL)))
{
    return CleanupAndExit("Couldn't CreatePort on IDirectMusic");
}

ZeroMemory(&dmpc, sizeof(dmpc));
dmpc.dwSize = sizeof(DMUS_PORTCAPS);

if( !SUCCEEDED(pPort->GetCaps(&dmpc)))
{
    if (pPort) pPort->Release();
    return CleanupAndExit("Couldn't GetCaps on IDirectMusicPort");
}

The behavior of the application now varies depending on whether _SOFTWARE_SYNTH_ is defined. If it is, a synthesizer with DLS capabilities is wanted, so the application checks for the DMUS_PC_DLS capabilities flag on the default port. If it fails to find that flag, it goes on to free the default port and enumerate available ports until if finds an output port that has the DMUS_PC_DLS capability. Finally, it creates an instance of that port.

if ((dmpc.dwClass != DMUS_PC_OUTPUTCLASS)
        || !(dmpc.dwFlags & DMUS_PC_DLS))
{
    pPort->Release();
    pPort = NULL;
}

if (!pPort)
{
    for (DWORD index = 0; hr == S_OK; index++)
    {
        ZeroMemory(&dmpc, sizeof(dmpc));
        dmpc.dwSize = sizeof(DMUS_PORTCAPS);

        hr = gpDirectMusic->EnumPort(index, &dmpc);
        if(hr == S_OK)
        {
            if ( (dmpc.dwClass == DMUS_PC_OUTPUTCLASS) &&
                 (dmpc.dwFlags & DMUS_PC_DLS) )
            {
                CopyMemory(&guidSynthGUID, &dmpc.guidPort,
                        sizeof(GUID));

                ZeroMemory(&dmos, sizeof(dmos));
                dmos.dwSize = sizeof(DMUS_PORTPARAMS);
                dmos.dwChannelGroups = 1;
                dmos.dwValidParams = DMUS_PORTPARAMS_CHANNELGROUPS;

                hr = gpDirectMusic->CreatePort(guidSynthGUID,
                        &dmos, &pPort, NULL);
                break;
            }
        }
    }
    if (hr != S_OK)
    {
        if (pPort) pPort->Release();
        return CleanupAndExit("Couldn't initialize the Synth port");
    }
}

If, on the other hand, _SOFTWARE_SYNTH_ is not defined, a legacy hardware port is wanted, and the application goes on to enumerate ports until it finds the MIDI mapper. (That code is omitted here.)

Now the port is activated and attached to the performance.

pPort->Activate(TRUE);
gpPerformance->AddPort(pPort);

The next call maps PChannels 0-15 to the first group of MIDI channels on the port. Note that this step is necessary because the application did not pass NULL to AddPort.

gpPerformance->AssignPChannelBlock(0, pPort, 1);

The original reference to the port can now be released. This call doesn't remove the port from the performance.

if (pPort) pPort->Release();

Next: Step 3: Load the Music Elements


Step 3: Load the Music Elements

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectMusic Visual Basic Tutorials.

[C++]

The next step in setting up the DirectMusic functionality of the DMDonuts sample application is to load the music elements—styles, templates, motifs, chordmaps, and bands—from file. Like the previous step, this one is carried out in the InitializeGame function.

First the application creates the loader object:

if (!SUCCEEDED(::CoCreateInstance(
            CLSID_DirectMusicLoader,
            NULL,
            CLSCTX_INPROC,
            IID_IDirectMusicLoader,
            (void**)&gpLoader
        )))
{
    return CleanupAndExit("Couldn't create a loader object");
}

Then it sets the search directory for all object types and enables the object cache. This second call simply confirms the default cache status.

hr = E_FAIL;

/ * The GetSearchPath function gets the media directory
    from the registry and returns it in wszSearchPath. */

if (GetSearchPath(wszSearchPath))
{
    hr = gpLoader->SetSearchDirectory(
           GUID_DirectMusicAllTypes, wszSearchPath, FALSE);
}

/* If that directory doesn't exist, try the current directory. */

if (FAILED(hr))
{
    hr = gpLoader->SetSearchDirectory(GUID_DirectMusicAllTypes,
            L".", FALSE);
}
if (FAILED(hr))
{
    return CleanupAndExit("Couldn't set the search directory \
            for the DirectMusic loader");
}
gpLoader->EnableCache(GUID_DirectMusicAllTypes, TRUE);

The following code snippet loads the style named "Donuts", which is in the Donuts.sty file. Note that because the application hasn't called IDirectMusicLoader::ScanDirectory to build a database of objects that can be loaded by internal name, the first call to IDirectMusicLoader::GetObject will fail. The fallback procedure is to identify the object by file name and call GetObject again.

IDirectMusicObject* pObject = NULL;
DMUS_OBJECTDESC ObjectDescript;

ObjectDescript.dwSize = sizeof(DMUS_OBJECTDESC);
ObjectDescript.guidClass = CLSID_DirectMusicStyle;
wcscpy(ObjectDescript.wszName, L"Donuts");
ObjectDescript.dwValidData = DMUS_OBJ_CLASS | DMUS_OBJ_NAME;

if (!SUCCEEDED(gpLoader->GetObject(&ObjectDescript,
        IID_IDirectMusicStyle, (void**)&gapStyle[1])))
{
    wcscpy(ObjectDescript.wszFileName, L"Donuts.sty");
    ObjectDescript.dwValidData = DMUS_OBJ_CLASS | DMUS_OBJ_FILENAME;
    if (!SUCCEEDED(gpLoader->GetObject(&ObjectDescript,
            IID_IDirectMusicStyle, (void**)&gapStyle[1])))
    {
        return CleanupAndExit("Couldn't load style object 1");
    }
}

The InitializeGame function then goes on to load another style and two templates in similar fashion.

The next step is to initialize an array of motifs that will be used to mark certain events in the game. Each motif is contained in a style and is obtained by calling the IDirectMusicStyle::GetMotif method, which creates a segment for the motif. The method must be supplied with the internal name of the motif, as in the following example from Donuts.cpp.

WCHAR awszMotifs[NUM_MOTIFS][64];

wcscpy(awszMotifs[MOTIF_BOUNCE], L"Bounce");
.
.
.
hr = gapStyle[0]->GetMotif(awszMotifs[MOTIF_BOUNCE],
        &(gapMotif[0][MOTIF_BOUNCE]));

If you look at the complete code, you'll see that the application loads two sets of motifs with the same names, one set from the "Donuts" style and the other from "Donutz." DMDonuts switches between these two styles as the player moves from level to level. When a gapMotif is played, its first index is determined by the value of the global gnCurrentStyle, ensuring that it is the correct motif for that level.

The application now initializes four chordmaps for each style. These are obtained from separate files.

WCHAR awszChordMap[NUM_STYLES][NUM_CHORDMAP][64];
wcscpy(awszChordMap[0][0], L"minaeo.per");
wcscpy(awszChordMap[0][1], L"minfunc.per");
wcscpy(awszChordMap[0][2], L"mipedpt.per");
wcscpy(awszChordMap[0][3], L"tension.per");
wcscpy(awszChordMap[1][0], L"dianoble.per");
wcscpy(awszChordMap[1][1], L"minpedpt.per");
wcscpy(awszChordMap[1][2], L"mippjazz.per");
wcscpy(awszChordMap[1][3], L"minjazz.per");

ObjectDescript.guidClass = CLSID_DirectMusicChordMap;
ObjectDescript.dwValidData = DMUS_OBJ_CLASS | DMUS_OBJ_FILENAME;

for (short n = 0; n < NUM_STYLES; n++)
{
    for (short m = 0; m < NUM_CHORDMAP; m++)
    {
        if (hr == S_OK)
        {
            wcscpy(ObjectDescript.wszFileName,
                    awszChordMap[n][m]);
            hr = gpLoader->GetObject(&ObjectDescript,
                    IID_IDirectMusicChordMap,
                   (void**)&gapChordMap[n][m]);
        }
    }
}

if (hr != S_OK)
{
    return CleanupAndExit("Couldn't load a ChordMap");
}

The last elements to be retrieved from the styles are the bands. Each style has two different bands: one for when the player's ship isn't shielded and one for when it is. Note that the names of the bands are allocated differently than were the motifs and chordmaps—each is a BSTR rather than a local array of WCHAR—but the effect is the same, because in the Win32® API a BSTR is a pointer to a WCHAR array.

As each band is loaded, it is downloaded to the performance, making available the DLS data for its instruments.

BSTR bstrDefault = SysAllocString(L"Default 2");
BSTR bstrShields = SysAllocString(L"Shields");

for (n = 0; n < NUM_STYLES; n++)
{
    if (hr == S_OK)
    {
        hr = gapStyle[n]->GetBand(bstrShields, &gapShieldBand[n]);
    }
    if (hr == S_OK)
    {
        hr = gapShieldBand[n]->Download(gpPerformance);
    }
    if (hr == S_OK)
    {
        hr = gapStyle[n]->GetBand(bstrDefault, &gapDefaultBand[n]);
    }
    if (hr == S_OK)
    {
        hr = gapDefaultBand[n]->Download(gpPerformance);
    }
}

SysFreeString(bstrDefault);
SysFreeString(bstrShields);

After some error-checking code, the InitializeGame function goes on to create segments from the four bands it has obtained. These segments will be used to "play" the band changes at the appropriate times. Once the segments have been created, the band interfaces are released.

for (n = 0; n < NUM_STYLES; n++)
{
    if (hr == S_OK)
    {
        hr = gapShieldBand[n]->CreateSegment(&gapShieldSegment[n]);
    }
    if (hr == S_OK)
    {
        hr = gapDefaultBand[n]->CreateSegment(&gapDefaultSegment[n]);
    }
    apShieldBand[n]->Release();
    apDefaultBand[n]->Release();
}

Next: Step 4: Set Up Notifications


Step 4: Set Up Notifications

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectMusic Visual Basic Tutorials.

[C++]

The last bit of DirectMusic code inside the InitializeGame function is a request for notification when playback of the primary segment reaches a beat boundary or the end of the segment. As you'll see later in this tutorial, the notification mechanism is used to limit the number of "blowup" motifs that can be played at the same time.

The following code adds the notification types. Note that the notification GUIDs have to be placed in a variable, because they are passed by reference.

GUID guid;
guid = GUID_NOTIFICATION_SEGMENT;
gpPerformance->AddNotificationType( guid );
guid = GUID_NOTIFICATION_MEASUREANDBEAT;
gpPerformance->AddNotificationType( guid );

Next: Step 5: Create the Primary Segments


Step 5: Create the Primary Segments

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectMusic Visual Basic Tutorials.

[C++]

The one-time initialization of DirectMusic in the DMDonuts sample application is now complete. Further initialization is done in the setup_game function each time the game is started or the player advances to the next level.

The setup_game function first calls another function called ComposeNewSegments, which selects a style and chordmap based on the current game level, releases any previously created segments, and then composes two new segments based on the templates previously loaded from file. One of these segments is an introductory theme that plays until a donut has been hit; the other plays from that point until the player beats the level. The snSubLevel variable tracks which part of the level we are in and is used elsewhere to determine which segment should be played when music is toggled on with the F7 key.

snSubLevel = 1;
snLastTempo = 0;
gnLastStyle = gnCurrentStyle;
gnLastChordMap = gnCurrentChordMap;
gnCurrentStyle = level % NUM_STYLES;
gnCurrentChordMap = ((level - 1) / 2) % NUM_CHORDMAP;
HRESULT hr = S_OK;
MUSIC_TIME mtSegmentLength;
if (gapSegment[SEGMENT_1])
{
    gapSegment[SEGMENT_1]->Release();
}
hr = gpComposer->ComposeSegmentFromTemplate(
        gapStyle[gnCurrentStyle],
        gpIntroTemplate, 0,
        gapChordMap[gnCurrentStyle][gnCurrentChordMap],
        &gapSegment[SEGMENT_1]
);
if (!SUCCEEDED(hr))
{
    CleanupAndExit("Segment 1 composition failed");
}

We happen to know that the template has a signpost on the last measure that matches the signpost on the first measure, for graceful looping. Once the segment is composed, the last measure is lopped off. Note that the value of MEASURE_LENGTH was calculated in Step 1: Defines and Globals as (DMUS_PPQ * 4)—that is, four quarter-notes of music time. This is valid because the time signature is 4/4.

gapSegment[SEGMENT_1]->GetLength(&mtSegmentLength);
gapSegment[SEGMENT_1]->SetLength(
        mtSegmentLength - MEASURE_LENGTH);

Finally, the segment is set to loop repeatedly.

gapSegment[SEGMENT_1]->SetRepeats(999);

The second segment, based on gpGameTemplate, is composed and set up the same way.

Next: Step 6: Play a Primary Segment


Step 6: Play a Primary Segment

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectMusic Visual Basic Tutorials.

[C++]

In the previous step, the setup_game function in Donuts.cpp called the ComposeNewSegments function, which created two primary segments to be used for the current game level. Now the setup_game function plays the first of these segments:

gpPerformance->PlaySegment(
    gapSegment[SEGMENT_1], 0, 0, NULL);

Note that the absence of any flag causes the segment to be played immediately.

The function now plays the default band segment that was created for the current style. (Remember, there are two different styles that alternate when the game level changes. Each style has two bands, the default band and the "shield" band.) Playing the band segment ensures that the correct set of instruments is playing the music. Note that the band segment must be flagged as secondary. No start time is given in the third parameter because the changes are to be made immediately, and the last parameter is NULL because we don't require a pointer to the segment state.

gpPerformance->PlaySegment(
    gapDefaultSegment[gnCurrentStyle],
    DMUS_SEGF_SECONDARY,
    0, NULL);

The default band for the style is used when the player's ship is unshielded, which is always the case at the beginning of a level. The application plays the second band inside the UpdateDisplayList function in response to the shields being turned on, and plays the default band again when the shields are turned off.

Next: Step 7: Transition to Another Primary Segment


Step 7: Transition to Another Primary Segment

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectMusic Visual Basic Tutorials.

[C++]

DMDonuts cues a different primary segment in two places: when the game level changes, and when the first hit is made on a donut on any level. The following code is from the CheckForHits function. When the function finds that a hit is the first to have occurred on this level, it tells the DirectMusic composer to create a transition from the current (introductory) theme to the action theme. The call to IDirectMusicComposer::AutoTransition also cues the transition and the following action segment so that they play automatically; in this case, the transition will start on the next measure boundary.

if (gapSegment[SEGMENT_TRANS_1])
{
    gapSegment[SEGMENT_TRANS_1]->Release();
}
gpComposer->AutoTransition(
        gpPerformance,                 // The performance
        gapSegment[SEGMENT_2],         // The next primary segment
        DMUS_COMMANDT_FILL,            // Embellishment type
        DMUS_COMPOSEF_MODULATE |       // Modulate to new key
        DMUS_COMPOSEF_MEASURE,         // and start on measure
        gapChordMap[gnCurrentStyle] [gnCurrentChordMap],
                                       // Use current chordmap
        &gapSegment[SEGMENT_TRANS_1],  // Created transition segment
        NULL, NULL                     // No segment states needed
);

Note that you don't have to stop the first segment. It stops automatically when a transition or new primary segment is played.

Next: Step 8: Play a Motif


Step 8: Play a Motif

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectMusic Visual Basic Tutorials.

[C++]

DMDonuts uses several motifs to accent the game action: for example, when the player's ship bounces off the edge of the screen and when an object is hit by the player's fire.

Playing a motif is very simple, as the following code from the CheckForHits function shows. The MOTIF_BLOWUP motif is played whenever a donut is hit.

gpPerformance->PlaySegment(
        gapMotif[gnCurrentStyle][MOTIF_BLOWUP],
        DMUS_SEGF_SECONDARY | DMUS_SEGF_GRID, 0, NULL);

The motif must be played as a secondary segment so that it does not interrupt the main theme being played as the primary segment. It is cued to play on a grid boundary, the lowest resolution at which it can play without being out of step with the primary segment. The rtStartTime parameter is 0, indicating that the segment should play as soon as the first boundary is reached, and the ppSegmentState parameter is NULL because there's no need to access the segment while it is playing.

Next: Step 9: Handle Notifications


Step 9: Handle Notifications

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectMusic Visual Basic Tutorials.

[C++]

Back in Step 4: Set Up Notifications we saw how DMDonuts requests notification whenever a segment ends and whenever a beat or measure boundary is reached. The purpose of this notification is to help limit the number of "blowup" motifs playing at any one time.

Notifications are retrieved in the WinMain function. After dealing with any messages in the queue, the application checks to see if there are any pending notifications. It does this by calling the IDirectMusicPerformance::GetNotificationPMsg method. If no notification message is pending, the method returns S_FALSE and no further action is needed. A return of S_OK indicates that a notification message has been placed in *pEvent. Because it has only requested notifications relevant to the beat, the application doesn't actually need to examine the message, which is immediately discarded. It then resets snMaxBlowUps, which tracks how many more blowup motifs can be played till the next beat.

if (gpPerformance)
{
    DMUS_NOTIFICATION_PMSG* pEvent;
    while ( S_OK == gpPerformance->GetNotificationPMsg(&pEvent))
    {
        gpPerformance->FreePMsg((DMUS_PMSG*)pEvent);
        snMaxBlowUps = BLOWUPS_PER_BEAT;
    }
}

Next: Step 10: Shut Down DirectMusic


Step 10: Shut Down DirectMusic

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectMusic Visual Basic Tutorials.

[C++]

Closing down DirectMusic is a matter of clearing the loader cache, stopping the performance, releasing all the objects that have been created, and finally dereferencing COM (remember, every call to CoInitialize must have a matching call to CoUninitialize).

The following function performs the necessary cleanup in Donuts.cpp:

void CleanUpDMusic()
{
    if (gpLoader)
    {
        gpLoader->ClearCache(GUID_DirectMusicAllTypes);
        gpLoader->Release();
    }

    if (gpComposer)
    {
        gpComposer->Release();
    }

    if (gpIntroTemplate)
    {
        gpIntroTemplate->Release();
    }

    if (gpGameTemplate)
    {
        gpGameTemplate->Release();
    }

    for (short n = 0; n < NUM_STYLES; n++)
    {
        if (gapShieldBand[n])
        {
            gapShieldBand[n]->Unload(gpPerformance);
            gapShieldBand[n]->Release();
        }
        if (gapDefaultBand[n])
        {
            gapDefaultBand[n]->Unload(gpPerformance);
            gapDefaultBand[n]->Release();
        }
        if (gapShieldSegment[n])
        {
            gapShieldSegment[n]->Release();
        }

        if (gapDefaultSegment[n])
        {
            gapDefaultSegment[n]->Release();
        }

        if (gapStyle[n])
        {
            gapStyle[n]->Release();
        }

        for (short m = 0; m < NUM_CHORDMAP; m++)
        {
            if (gapChordMap[n][m])
            {
                gapChordMap[n][m]->Release();
            }
        }

        for (m = 0; m < NUM_MOTIFS; m++)
        {
            if (gapMotif[n][m])
            {
                gapMotif[n][m]->Release();
            }
        }
    }

    if (gpPerformance)
    {
        gpPerformance->Stop( NULL, NULL, 0, 0 );
        gpPerformance->CloseDown();
        gpPerformance->Release();
    }

    for (n = 0; n < NUM_SEGMENTS; n++)
    {
        if (gapSegment[n])
        {
            gapSegment[n]->Release();
        }
    }

    if (gpDirectMusic)
    {
        gpDirectMusic->Release();
    }

    CoUninitialize();
}


DirectMusic Visual Basic Tutorials

[C++]

This section pertains only to DirectX for Visual Basic. See DirectMusic C/C++ Tutorials.

[Visual Basic]

This section contains the following tutorials showing how to implement DirectMusic in a Visual Basic application:

  • Tutorial 1: Playing a MIDI File
  • Tutorial 2: Using DLS Sound Effects


Tutorial 1: Playing a MIDI File

[C++]

This section pertains only to DirectX for Visual Basic. A similar tutorial is available for C/C++; see Tutorial 1: Playing a MIDI File.

[Visual Basic]

This tutorial is a guide to setting up the simplest possible DirectMusic application, one that just plays a primary segment. In this example, the segment represents a MIDI file, but the process of loading and playing the data would be exactly the same if the source were a segment authored in a tool such as DirectMusic Producer.

The tutorial is divided into the following steps:

  • Step 1: Create the Performance and Loader
  • Step 2: Load the MIDI File
  • Step 3: Play the MIDI File


Step 1: Create the Performance and Loader

[C++]

This topic pertains only to DirectX for Visual Basic. See DirectMusic C/C++ Tutorials.

[Visual Basic]

The central object of any DirectMusic application is an instance of the DirectMusicPerformance class. Most applications require only a single performance object, although it is possible to have multiple performances playing to different ports, with different tempos, and so on. To load any musical data, the application also needs a DirectMusicLoader object.

To create these objects, you must first declare a global DirectX7 object.

The following global declarations create the DirectX7 object and variables for the other necessary objects:

Public gObjDX As New DirectX7
Public gObjDMLoader As DirectMusicLoader
Public gObjDMPerformance As DirectMusicPerformance

In the startup code, create the performance and loader objects as follows:

Set gObjDMLoader = gObjDX.DirectMusicLoaderCreate
Set gObjDMPerformance = gObjDX.DirectMusicPerformanceCreate

You must also initialize the performance and assign a port to it. The following code has the performance create its own DirectSound object and assigns the default port, which is always either the Microsoft Software Synthesizer or a DLS-capable hardware synthesizer. A single channel group is assigned to the port because a MIDI file requires a maximum of 16 channels. If you are writing an application that plays other kinds of segments as well, you might need to increase this number.

' hWnd is the window handle of the main form
Call gObjDMPerformance.Init(Nothing, hWnd)
Call gObjDMPerformance.SetPort(-1, 1)

Next: Step 2: Load the MIDI File


Step 2: Load the MIDI File

[C++]

This topic pertains only to DirectX for Visual Basic. See DirectMusic C/C++ Tutorials.

[Visual Basic]

To load a MIDI file, you need three things:

  • The DirectMusicLoader object created in the previous step.
  • A DirectMusicSegment variable.
  • The name of the MIDI file.

If your music files are not in the working directory of the application, call DirectMusicLoader.SetSearchDirectory so that the loader knows where to look, or provide a full path for each file.

The following code sets the search directory for the loader and loads a file from that directory.

Call gObjDMLoader.SetSearchDirectory("c:\midiplay\media")
' This needs to be done only once.

Dim objSeg As DirectMusicSegment

' FileName is a string containing the short name of the file
Set objSeg = gObjDMLoader.LoadSegment(FileName)

Next: Step 3: Play the MIDI File


Step 3: Play the MIDI File

[C++]

This topic pertains only to DirectX for Visual Basic. See DirectMusic C/C++ Tutorials.

[Visual Basic]

Now that you have a DirectMusicSegment object representing the MIDI file, you need to do a little more preparation before you can play it.

First, let the segment know that it represents a standard MIDI file. Although the segment can be played without this step, certain details of playback might not be handled properly. The following code performs this step for files with the conventional MIDI file extension:

If StrConv(Right(FileName, 4), vbLowerCase) = ".mid" Then
    Call objSeg.SetStandardMidiFile
End If

Second, ensure that the DLS data for the instruments is downloaded to the port. The simplest way to do this is to turn on automatic downloading for the entire performance, as might be done in the setup code, as follows:

Call gObjDMPerformance.SetMasterAutoDownload(True)

The disadvantage of this method is that the instruments are unloaded from the port as soon as the segment stops, and must then be downloaded again. If your application is playing different segments in rapid succession, this behavior might cause unacceptable delays. For greater control, you can download the instruments each time a segment is about to be played. The instruments remain on the port until you choose to unload them, or until the performance is closed down. Any redundant downloads are ignored.

Call objSeg.Download(gObjDMPerformance)

Now, the segment can be played:

Call gObjDMPerformance.PlaySegment(objSeg, 0, 0)

If you want to track the state of playback (for example, to be able to pause and resume), you can save the return value of DirectMusicPerformance.PlaySegment in a DirectMusicSegmentState object:

Dim objSegState as DirectMusicSegmentState
Set objSegState = gObjDMPerformance.PlaySegment(gObjPrimarySeg, 0, 0)


Tutorial 2: Using DLS Sound Effects

[C++]

This topic pertains only to application development in DirectX for Visual Basic.

[Visual Basic]

This tutorial shows how to use DLS to create nonmusical sound effects, using DirectMusic. The code example is based on the DLSEffects sample, which uses the DLS collection file Boids.dls. If you like, you can use DirectMusic Producer to examine this collection to better understand some of the concepts discussed in the tutorial. Consult the DirectMusic Producer documentation for more information on how to view and edit a DLS collection.

The tutorial is divided into the following steps:

  • Step 1: Load the Sounds
  • Step 2: Play Effects
  • Step 3: Modify and Stop Effects


Step 1: Load the Sounds

[C++]

This topic pertains only to application development in DirectX for Visual Basic.

[Visual Basic]

After creating and initializing the performance, the DLSEffects sample loads the DLS file and a segment file, both from the directory represented by mediapath.

' dx is a DirectX7 object.
' perf is an initialized DirectMusicPerformance object.
' seg is declared as DirectMusicSegment.

mediapath = FindMediaDir("sample.sgt", "dmusic")
If mediapath <> vbNullString Then ChDir mediapath

Dim loader As DirectMusicLoader
Set loader = dx.DirectMusicLoaderCreate
Set coll = loader.LoadCollection(mediapath & "boids.dls")
Set seg = loader.LoadSegment(mediapath & "sample.sgt")

It does not matter what segment is loaded. The application does not play the segment, but it is necessary to have a DirectMusicSegment object to download DLS data.

Now, the application associates the DirectMusicCollection object with the segment and downloads it to the port. Any other instruments referred to by the segment are downloaded as well.

Call seg.ConnectToCollection(coll)
Call seg.Download(perf)

The Boids.dls collection contains only a single instrument, called Vocals, which has patch number 127. You can assign this instrument to any channel by sending a MIDI patch message. The application assigns the instrument to two channels so that one of the samples that is to be played, the heartbeat sound, can be given a pitch bend without affecting other samples.

Const channel = 1
Const hbchannel = 2
Const patch = 127
Call perf.SendPatchPMSG(0, DMUS_PMSGF_REFTIME, channel, patch, 0, 0)
Call perf.SendPatchPMSG(0, DMUS_PMSGF_REFTIME, hbchannel, patch, 0, 0)

Now, any note played on channels 1 or 2 uses the Vocals instrument. How this instrument is used to get different sound effects is covered in Step 2: Play Effects.


Step 2: Play Effects

[C++]

This topic pertains only to application development in DirectX for Visual Basic.

[Visual Basic]

In the DLSEffects sample, the user can hear a variety of sound effects, including laughter, fragments of speech in several languages, and an infant's heartbeat. All these sounds are contained in a single DLS instrument.

Completely different sounds can be played by a single instrument because different note ranges, or regions, can be associated with different wave samples. In Boids.dls, for example, the first speech fragment is assigned to the pitch range from C0 through B3. Any note in that range is based on the same wave sample. The root note is C3, meaning that when a C3 note is played, the wave is heard at its original frequency. All other notes cause the pitch of the wave to be modified.

The following procedure sends a note at the volume indicated by the global variable gVelocity:

Private Sub SendNote(chan As Integer, pitch As Byte, dur As Long)

  Dim noteMsg As DMUS_NOTE_PMSG
  noteMsg.velocity = gVelocity
  noteMsg.flags = DMUS_NOTEF_NOTEON
  noteMsg.midiValue = pitch
  noteMsg.mtDuration = dur
  Call perf.SendNotePMSG(0, DMUS_PMSGF_REFTIME, chan, noteMsg)

 End Sub

All but one of the waves in Boids.dls are one-shot samples. This means that when a note is played, the wave sample plays only once, regardless of the duration of the note. The exception is the heartbeat sample, which is looped so that it plays as long as the note is playing. This looping behavior was specified by the author of the instrument collection.

The following procedure sends a C3 note. C3 is the root note of the first speech sample, so it plays at the correct pitch. The constant NoteDur is 6000 milliseconds, allowing enough time for this or any of the other waves to play completely before DirectMusic generates a note-off MIDI message. (If you click the button and send an identical note before this time has elapsed, the note-off message might cancel the new note as well, so it might not play fully.)

Private Sub cmdC3_Click()
  SendNote channel, 36, NoteDur
End Sub

The DLSEffects application plays most of the samples at their root note. However, the heartbeat sample is treated a little differently, as an illustration of how the pitch of sound effects can be modified programmatically. This topic is covered in Step 3: Modify and Stop Effects.


Step 3: Modify and Stop Effects

[C++]

This topic pertains only to application development in DirectX for Visual Basic.

[Visual Basic]

In the definition of the Vocals instrument in Boids.dls, the region of the heart sample is in the range from B7 through B8. As the sound is playing in the sample application, the user can choose a note within this region by using the Note slider. Each time the slider is changed, the existing note is stopped, and a new one is sent.

Because the duration of the note is indefinite, it is sent in the form of a standard MIDI note-on message by using DirectMusicPerformance.SendMIDIPMSG. (You could also use DirectMusicPerformance.SendNotePMSG, specifying a very large number for the duration of the note.) The current frequency and velocity are given in the last two parameters. Because the method accepts the channel as a separate parameter, the MIDI status byte (&H90) does not contain the channel number in the 4 lower bits, as it would in a standard MIDI message.

Call perf.SendMIDIPMSG(0, DMUS_PMSGF_REFTIME, hbchannel, _
        &H90, B7Freq, gVelocity)

In addition to changing the note for the heartbeat, the user can also assign a pitch bend to the channel on which the note is played. The pitch bend is also sent as a standard MIDI message:

Call perf.SendMIDIPMSG(0, DMUS_PMSGF_REFTIME, hbchannel, _
        &HE0, lo, hi)

The lo and hi parameters are 7-bit values, so there are 16,384 possible settings for a pitch bend. For more information, see the MIDI specification.

To stop the heartbeat note, the sample application sends a note of the same pitch as the currently playing note, using the SendNotePMSG method, with the flags member of the DMUS_NOTE_PMSG type set to 0, instead of the usual DMUS_NOTEF_NOTEON.

Private Sub B7NoteOff()

  Dim noteMsg As DMUS_NOTE_PMSG
  noteMsg.flags = 0
  noteMsg.midiValue = B7Freq  ' B7Freq is pitch of last note-on
  Call perf.SendNotePMSG(0, DMUS_PMSGF_REFTIME, hbchannel, noteMsg)
End Sub

The pitch bend on the channel does not affect this operation.


DirectMusic Reference

This section contains reference information for the application programming interface (API) elements provided by Microsoft® DirectMusic® in C/C++ and Microsoft® Visual Basic®. Reference material is organized by language:

  • DirectMusic C/C++ Reference
  • DirectMusic Visual Basic Reference


DirectMusic C/C++ Reference

This section contains reference information for the API elements of DirectMusic. Reference material is divided into the following categories.

  • Interfaces
  • Messages
  • Structures
  • File Structures
  • DLS Structures
  • Enumerated Types
  • Return Values


Interfaces

This section contains references for the following DirectMusic interfaces:

  • IDirectMusic
  • IDirectMusicBand
  • IDirectMusicBuffer
  • IDirectMusicChordMap
  • IDirectMusicCollection
  • IDirectMusicComposer
  • IDirectMusicDownload
  • IDirectMusicDownloadedInstrument
  • IDirectMusicGetLoader
  • IDirectMusicGraph
  • IDirectMusicInstrument
  • IDirectMusicLoader
  • IDirectMusicObject
  • IDirectMusicPerformance
  • IDirectMusicPort
  • IDirectMusicPortDownload
  • IDirectMusicSegment
  • IDirectMusicSegmentState
  • IDirectMusicStyle
  • IDirectMusicThru
  • IDirectMusicTool
  • IDirectMusicTrack
  • IKsControl
  • IReferenceClock


IDirectMusic

The IDirectMusic interface provides methods for managing buffers, ports, and the master clock. There should not be more than one instance of this interface per application.

Note There is no helper function to create this interface. Applications use the COM CoCreateInstance function or the IDirectMusicPerformance::Init method to create a DirectMusic object.

The methods of the IDirectMusic interface can be organized into the following groups:

Activation | Activate
Buffers | CreateMusicBuffer
Linkage | SetDirectSound
Ports | CreatePort
 | EnumPort
 | GetDefaultPort
Timing | EnumMasterClock
 | GetMasterClock
 | SetMasterClock

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.


IDirectMusic::Activate

The IDirectMusic::Activate method activates or deactivates all output ports created from this interface.

HRESULT Activate(
  BOOL fEnable
);

Parameters

fEnable
Switch to activate (TRUE) or deactivate (FALSE) all port objects created in this instance of DirectMusic.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return DSERR_NODRIVER, indicating that no sound driver is present.

Remarks

Applications should call IDirectMusic::Activate(FALSE) when they lose input focus if they do not need to play music in the background. This allows another application that has the input focus to have access to the ports. Once the application has input focus again, it should call Activate(TRUE) to enable all its allocated ports.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

IDirectMusicPort::Activate


IDirectMusic::CreateMusicBuffer

The IDirectMusic::CreateMusicBuffer method creates a DirectMusicBuffer object to hold music messages being sequenced to the port. Most applications do not need to call this method directly because buffer management is handled by the performance when a port is added.

HRESULT CreateMusicBuffer(
  LPDMUS_BUFFERDESC pBufferDesc,
  LPDIRECTMUSICBUFFER *ppBuffer,
  LPUNKNOWN pUnkOuter
);

Parameters

pBufferDesc
Address of the DMUS_BUFFERDESC structure that contains the description of the music buffer to be created. The application must initialize the dwSize member of this structure before passing the pointer. See Remarks.
ppBuffer
Address of a variable to receive the IDirectMusicBuffer interface pointer.
pUnkOuter
Address of the controlling object's IUnknown interface for COM aggregation. Aggregration is not currently supported, so this value must be set to NULL.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_INVALIDARG
E_NOAGGREGATION
E_NOINTERFACE
E_OUTOFMEMORY
E_POINTER

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.


IDirectMusic::CreatePort

The IDirectMusic::CreatePort method is used to create an object for a particular DirectMusic port.

HRESULT CreatePort(
  REFCLSID rclsidPort,
  LPDMUS_PORTPARAMS pPortParams,
  LPDIRECTMUSICPORT *ppPort,
  LPUNKNOWN pUnkOuter
);

Parameters

rclsidPort
Reference to (C++) or address of (C) the GUID that identifies the port for which the IDirectMusicPort interface is to be created. The GUID is retrieved through the IDirectMusic::EnumPort method. If it is GUID_NULL, the returned port is the default port. For more information, see Default Port.
pPortParams
Address of a DMUS_PORTPARAMS structure that contains parameters for the port. The dwSize member of this structure must be initialized before the method is called.
ppPort
Address of a variable to receive an IDirectMusicPort interface pointer.
pUnkOuter
Address of the controlling object's IUnknown interface for COM aggregation. Aggregation is not currently supported, so this value must be NULL.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if a requested parameter is not available.

If it fails, the method can return one of the following error values:

DMUS_E_DSOUND_NOT_SET
E_INVALIDARG
E_NOAGGREGATION
E_NOINTERFACE
E_OUTOFMEMORY
E_POINTER

Remarks

By default, the port is inactive when it is created. It must be activated by a call to IDirectMusic::Activate or IDirectMusicPort::Activate.

If not all parameters could be obtained, the DMUS_PORTPARAMS structure is changed as follows to match the available parameters of the port.

On entry, the dwValidParams member of the structure indicates which members in the structure are valid. If the flag is not set for a member of the structure, a default value is set for that parameter when the port is created.

On return, the flags in dwValidParams show which port parameters were set. If a particular parameter was not requested but was set to the default, that flag is added to those passed in.

If the port supports a specified parameter but the given value for the parameter is out of range, the parameter value in *pPortParams is changed. In this case, the flag in dwValidParams remains set, but S_FALSE is returned to indicate that the value has been changed.

The following code example shows how an application can request reverb capabilities and determine if they were obtained. (For an alternative way of checking and setting port properties, see Port Property Sets.)

DMUS_PORTPARAMS params;

ZeroMemory(&params, sizeof(params));
params.dwSize = sizeof(params);
params.dwValidParams = DMUS_PORTPARAMS_EFFECTS;
params.dwEffectFlags = DMUS_EFFECT_REVERB;
HRESULT hr = pDirectMusic->CreatePort(guidPort, &params,
        &port, NULL);
if (SUCCEEDED(hr))
{
    fGotReverb = TRUE;
    if (hr == S_FALSE)
    {
        if (!(params.dwValidParams & DMUS_PORTPARAMS_EFFECTS))
        {
            // Device does not support any effects.
            fGotReverb = FALSE;
        }
        else if (!(params.dwEffectFlags & DMUS_EFFECT_REVERB))
        {
            // Device understands effects,
            // but could not allocate reverb.
            fGotReverb = FALSE;
        }
    }
}

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.


IDirectMusic::EnumMasterClock

The IDirectMusic::EnumMasterClock method is used to enumerate and get the description of the clocks that DirectMusic can use as the master clock. Each time that it is called, this method retrieves information about a single clock.

HRESULT EnumMasterClock(
  DWORD dwIndex,
  LPDMUS_CLOCKINFO lpClockInfo
);

Parameters

dwIndex
Index of the clock for which the description is to be returned. This parameter should be 0 on the first call, and then incremented in each subsequent call until S_FALSE is returned.
lpClockInfo
Address of a DMUS_CLOCKINFO structure to receive the description of the clock. The application must initialize the dwSize member of this structure before passing the pointer.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if there is no clock with that index number.

If it fails, the method can return one of the following error values:

E_INVALIDARG
E_NOINTERFACE
E_POINTER

Remarks

Applications should not rely on or store the index number of a clock. Rebooting or adding and removing hardware could cause the index number of a clock to change.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

IDirectMusic::SetMasterClock, IDirectMusic::GetMasterClock


IDirectMusic::EnumPort

The IDirectMusic::EnumPort method is used to enumerate and get the capabilities of the DirectMusic ports connected to the system. Each time it is called, this method retrieves information about a single port.

HRESULT EnumPort(
  DWORD dwIndex,
  LPDMUS_PORTCAPS pPortCaps
);

Parameters

dwIndex
Index of the port for which the capabilities are to be returned. This parameter should be 0 on the first call, and then incremented in each subsequent call until S_FALSE is returned.
pPortCaps
Address of the DMUS_PORTCAPS structure to receive the capabilities of the port. The dwSize member of this structure must be initialized before the pointer is passed.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if there is no port with that index value.

If it fails, the method can return one of the following error values:

E_INVALIDARG
E_NOINTERFACE
E_POINTER

Remarks

Applications should not rely on or store the index number of a port. Rebooting or adding or removing ports could cause the index number of a port to change.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.


IDirectMusic::GetDefaultPort

The IDirectMusic::GetDefaultPort method retrieves the GUID of the default output port. This is the port to be created if GUID_NULL is passed to IDirectMusic::CreatePort.

HRESULT GetDefaultPort(
  LPGUID pguidPort
);

Parameters

pguidPort
Address of a variable to receive the default port GUID.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

Default Port


IDirectMusic::GetMasterClock

The IDirectMusic::GetMasterClock method returns the GUID and a pointer to the IReferenceClock interface for the clock that is currently set as the DirectMusic master clock.

HRESULT GetMasterClock(
  LPGUID pguidClock,
  IReferenceClock **ppReferenceClock
);

Parameters

pguidClock
Address of a variable to receive the master clock's GUID. The application can pass NULL if this value is not desired.
ppReferenceClock
Address of a variable to receive the IReferenceClock interface pointer for this clock. The application can pass NULL if this value is not desired.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_NOINTERFACE
E_POINTER

Remarks

The IReferenceClock interface pointer must be released once the application has finished using the interface.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

IDirectMusic::SetMasterClock


IDirectMusic::SetDirectSound

The IDirectMusic::SetDirectSound method connects DirectMusic to a DirectSound object for wave output.

HRESULT SetDirectSound(
  LPDIRECTSOUND pDirectSound,
  HWND hWnd
);

Parameters

pDirectSound
Address of the IDirectSound interface to use for output. If this parameter is NULL, the method creates a DirectSound object and sets the DSSCL_PRIORITY cooperative level. (See Remarks.) If this parameter contains an IDirectSound pointer, the caller is responsible for setting the cooperative level.
hWnd
Window handle to the DirectSound object created by this call. If this value is NULL, the current foreground window is set as the focus window. See Remarks.

If pDirectSound is a valid interface, this parameter is ignored because it is the caller's responsibility to supply a valid window handle in the call to IDirectSound::SetCooperativeLevel.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return DMUS_E_DSOUND_ALREADY_SET.

Remarks

The specified DirectSound object is the one used for rendering audio on all ports. This default can be overridden by using the IDirectMusicPort::SetDirectSound method.

Whenever the IDirectMusic::SetDirectSound method is called, any existing DirectSound object is released.

When pDirectSound is NULL, a new DirectSound object is not created until a port that uses DirectSound is activated, and the DirectSound object is automatically released when the last port using it is deactivated.

If you created the DirectSound object yourself, you can release it by calling this method with NULL in the pDirectSound parameter after deactivating all ports. (It is an error to call SetDirectSound on an active port.)

You can pass NULL in the hWnd parameter to pass the current foreground window handle to DirectSound. However, it is not wise to assume that the application window is in the foreground during initialization. In general, the top-level application window handle should be passed to DirectMusic, DirectSound, and DirectDraw. See the Remarks for IDirectSound::SetCooperativeLevel.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

Integrating DirectMusic and DirectSound


IDirectMusic::SetMasterClock

The IDirectMusic::SetMasterClock method sets the DirectMusic master clock to a clock identified by a GUID obtained through the IDirectMusic::EnumMasterClock call. There is only one master clock for all DirectMusic applications.

HRESULT SetMasterClock(
  REFGUID rguidClock
);

Parameters

rguidClock
Reference to (C++) or address of (C) the GUID that identifies the clock to set as the master clock for DirectMusic. This parameter must be a GUID returned by the IDirectMusic::EnumMasterClock method.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return DMUS_E_PORTS_OPEN.

Remarks

If another running application is also using DirectMusic, it is not possible to change the master clock until that application is shut down.

Most applications do not need to call SetMasterClock. It should not be called unless there is a need to synchronize tightly with a hardware timer other than the system clock.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

IDirectMusic::GetMasterClock, IDirectMusic::EnumMasterClock


IDirectMusicBand

The IDirectMusicBand interface represents a DirectMusic band object. A band is used to set the instrument choices and mixer settings for a set of PChannels. For an overview, see Using Bands.

Bands can come from several places. They can be stored directly in their own files or embedded in a style's band list or a segment's band track.

The DirectMusicBand object also supports the IPersistStream and IDirectMusicObject interfaces for loading its data.

The IDirectMusicBand interface has the following methods:

Segment creation | CreateSegment
Instrument data | Download
 | Unload

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDMUS_BAND type is defined as a pointer to the IDirectMusicBand interface.

typedef IDirectMusicBand __RPC_FAR *LPDMUS_BAND;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


IDirectMusicBand::CreateSegment

The IDirectMusicBand::CreateSegment method creates a DirectMusicSegment object that can be used to perform the volume, pan, transposition, and patch change commands in the band dynamically, using the IDirectMusicPerformance::PlaySegment method.

HRESULT CreateSegment(
  IDirectMusicSegment** ppSegment
);

Parameters

ppSegment
Address of a variable to receive a pointer to the created segment.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_FAIL
E_OUTOFMEMORY
E_POINTER

Remarks

For an example of creating a segment from a band, see Making Band Changes Programmatically.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


IDirectMusicBand::Download

The IDirectMusicBand::Download method downloads the DLS data for instruments in the band to a performance object. The method downloads each instrument in the band by calling the IDirectMusicPerformance::DownloadInstrument method. DownloadInstrument, in turn, uses the PChannel of the instrument to find the appropriate port, and then calls the IDirectMusicPort::DownloadInstrument method on that port.

Once a band has been downloaded, the instruments in the band can be selected, either individually with program-change MIDI messages, or all at once by playing a band segment created through a call to the IDirectMusicBand::CreateSegment method.

HRESULT Download(
  IDirectMusicPerformance* pPerformance
);

Parameters

pPerformance
Performance to which instruments are to be downloaded. The performance manages the mapping of PChannels to DirectMusic ports.

Return Values

If the method succeeds, the return value is S_OK, or DMUS_S_PARTIALDOWNLOAD. (See Remarks.)

If it fails, the method can return one of the following error values:

DMUS_E_NOT_INIT
E_OUTOFMEMORY
E_POINTER

Remarks

Because a downloaded band uses synthesizer resources, it should be unloaded when no longer needed by using the IDirectMusicBand::Unload method.

In the current version of DirectMusic, this method may return S_OK even though the port does not support DLS.

If the download completely fails, DMUS_E_NOT_INIT is returned. This usually means that the performance was not properly connected up to an initialized port. Since this is a complete failure, there is no need to call IDirectMusicBand::Unload later.

If the download partially succeeds, DMUS_S_PARTIALDOWNLOAD is returned. This means that some of the instruments successfully downloaded while others did not. This usually occurs because of programming error setting up the performance and port. The best way to find the problem is to set debug traces to 1 for Dmime.dll, Dmband.dll, and Dmsynth.dll. (See Debugging DirectMusic Projects.)

The following are some common causes of a partial download:

  • The band has instruments on PChannels that have not been set up on the performance (by using IDirectMusicPerformance::AssignPChannelBlock).
  • The band has instruments on PChannels that are on channel groups not allocated on the port.
  • The band has instruments in a DLS format incompatible with the synthesizer they are being downloaded to.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicBand::Unload


IDirectMusicBand::Unload

The IDirectMusicBand::Unload method unloads the DLS data for instruments in the band previously downloaded by IDirectMusicBand::Download.

HRESULT Unload(
  IDirectMusicPerformance* pPerformance
);

Parameters

pPerformance
Performance from which to unload instruments.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicBand::Download, IDirectMusicPort::UnloadInstrument


IDirectMusicBuffer

The IDirectMusicBuffer interface represents a buffer containing time-stamped data (typically in the form of MIDI messages) to be sequenced by a port. Unlike a segment, the buffer contains a small amount of data (typically less than 200 milliseconds) over which the application has control at event granularity.

Unless your application is doing its own sequencing, you do not need to use the methods of this interface.

Buffer objects are completely independent of port objects until the buffer is passed to the port by a call to the IDirectMusicPort::PlayBuffer or the IDirectMusicPort::Read method. The application is then free to reuse the buffer.

The methods of the IDirectMusicBuffer interface can be organized in the following groups:

Data | Flush
 | GetNextEvent
 | GetRawBufferPtr
 | PackStructured
 | PackUnstructured
 | ResetReadPtr
Parameters | GetBufferFormat
 | GetMaxBytes
 | GetUsedBytes
 | SetUsedBytes
Time | GetStartTime
 | SetStartTime
 | TotalTime

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECTMUSICBUFFER type is defined as a pointer to the IDirectMusicBuffer interface:

typedef IDirectMusicBuffer *LPDIRECTMUSICBUFFER;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.


IDirectMusicBuffer::Flush

The IDirectMusicBuffer::Flush method discards all data in the buffer.

HRESULT Flush();

Parameters

None.

Return Values

The method always returns S_OK.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.


IDirectMusicBuffer::GetBufferFormat

The IDirectMusicBuffer::GetBufferFormat method retrieves the GUID representing the buffer format.

HRESULT GetBufferFormat(
  LPGUID pGuidFormat
);

Parameters

pGuidFormat
Address of a variable to receive the GUID of the buffer format.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

If the format was not specified when the buffer was created, KSDATAFORMAT_SUBTYPE_DIRECTMUSIC is returned in *pGuidFormat.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

IDirectMusic::CreateMusicBuffer, DMUS_EVENTHEADER


IDirectMusicBuffer::GetMaxBytes

The IDirectMusicBuffer::GetMaxBytes method retrieves the number of bytes that can be stored in the buffer.

HRESULT GetMaxBytes(
  LPDWORD pcb
);

Parameters

pcb
Address of a variable to contain the maximum number of bytes that the buffer can hold.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.


IDirectMusicBuffer::GetNextEvent

The IDirectMusicBuffer::GetNextEvent method returns information about the next message in the buffer and advances the read pointer.

HRESULT GetNextEvent(
  LPREFERENCE_TIME prt,
  LPDWORD pdwChannelGroup,
  LPDWORD pdwLength,
  LPBYTE* ppData
);

Parameters

prt
Address of a variable to receive the time of the message.
pdwChannelGroup
Address of a variable to receive the channel group of the message.
pdwLength
Address of a variable to receive the length, in bytes, of the message.
ppData
Address of a variable to receive a pointer to the message data.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if there are no messages in the buffer.

If it fails, the method can return E_POINTER.

Remarks

Any of the passed pointers can be NULL if the item is not needed.

The pointer returned in ppData is valid only for the lifetime of the buffer object.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

IDirectMusicBuffer::ResetReadPtr


IDirectMusicBuffer::GetRawBufferPtr

The IDirectMusicBuffer::GetRawBufferPtr method returns a pointer to the underlying buffer data structure.

HRESULT GetRawBufferPtr(
  LPBYTE* ppData
);

Parameters

ppData
Address of a variable to receive a pointer to the buffer's data.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

This method returns a pointer to the raw data of the buffer. The format of the data depends on the implementation. The lifetime of the data is the same as the lifetime of the buffer object; therefore, the returned pointer should not be held after the next call to the IDirectMusicBuffer::Release method.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.


IDirectMusicBuffer::GetStartTime

The IDirectMusicBuffer::GetStartTime method retrieves the start time of the data in the buffer, relative to the master clock.

HRESULT GetStartTime(
  LPREFERENCE_TIME prt
);

Parameters

prt
Address of a variable to receive the start time.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_BUFFER_EMPTY
E_POINTER

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

IDirectMusicBuffer::SetStartTime, IDirectMusicBuffer::TotalTime


IDirectMusicBuffer::GetUsedBytes

The IDirectMusicBuffer::GetUsedBytes method retrieves the number of bytes of data in the buffer.

HRESULT GetUsedBytes(
  LPDWORD pcb
);

Parameters

pcb
Address of a variable to receive the number of used bytes.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

IDirectMusicBuffer::SetUsedBytes


IDirectMusicBuffer::PackStructured

The IDirectMusicBuffer::PackStructured method inserts fixed-length data (typically a MIDI channel message), along with timing and routing information, into the buffer.

HRESULT PackStructured(
  REFERENCE_TIME rt,
  DWORD dwChannelGroup,
  DWORD dwChannelMessage
);

Parameters

rt
Absolute time of the message. See Remarks.
dwChannelGroup
Channel group to which the data belongs.
dwChannelMessage
Data (MIDI message) to pack.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_INVALID_EVENT
E_OUTOFMEMORY

Remarks

At least 32 bytes (the size of DMUS_EVENTHEADER plus dwChannelMessage) must be free in the buffer.

The rt parameter must contain the absolute time at which the data is to be sent to the port. To play a message immediately, retrieve the time from the latency clock, and use this as rt. See IDirectMusicPort::GetLatencyClock.

Messages stamped with the same time do not necessarily play in the same order in which they were placed in the buffer.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

IDirectMusicBuffer::PackUnstructured


IDirectMusicBuffer::PackUnstructured

The IDirectMusicBuffer::PackUnstructured method inserts unstructured data (typically a MIDI system-exclusive message), along with timing and routing information, into the buffer.

HRESULT PackUnstructured(
  REFERENCE_TIME rt,
  DWORD dwChannelGroup,
  DWORD cb,
  LPBYTE lpb
);

Parameters

rt
Absolute time of the message.
dwChannelGroup
Channel group to which the message belongs.
cb
Size of the data, in bytes.
lpb
Pointer to the data.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_OUTOFMEMORY
E_POINTER

Remarks

This method can be used to send any kind of data to the port.

At least 28 bytes (the size of DMUS_EVENTHEADER) plus the size of the data, padded to a multiple of 4 bytes, must be free in the buffer. The buffer space required can be obtained by using the DMUS_EVENT_SIZE(cb) macro, where cb is the size of the data.

The rt parameter must contain the absolute time at which the data is to be sent to the port. To play a message immediately, retrieve the time from the latency clock, and use this as rt. See IDirectMusicPort::GetLatencyClock.

Messages stamped with the same time do not necessarily play in the same order in which they were placed in the buffer.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

IDirectMusicBuffer::PackStructured


IDirectMusicBuffer::ResetReadPtr

The IDirectMusicBuffer::ResetReadPtr method sets the read pointer to the start of the data in the buffer.

HRESULT ResetReadPtr()

Parameters

None.

Return Values

The method always returns S_OK.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

IDirectMusicBuffer::GetNextEvent


IDirectMusicBuffer::SetStartTime

The IDirectMusicBuffer::SetStartTime method sets the start time of the data in the buffer, relative to the master clock.

HRESULT SetStartTime(
  REFERENCE_TIME rt
);

Parameters

rt
New start time for the buffer.

Return Values

The method always returns S_OK.

Remarks

Events already in the buffer are time stamped relative to the start time and play at the same offset from the new start time.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

IDirectMusicBuffer::GetStartTime


IDirectMusicBuffer::SetUsedBytes

The IDirectMusicBuffer::SetUsedBytes method sets the number of bytes of data in the buffer.

HRESULT SetUsedBytes(
  DWORD cb
);

Parameters

cb
Number of valid data bytes in the buffer.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return DMUS_E_BUFFER_FULL.

Remarks

This method allows an application to repack a buffer manually. Normally, this should only be done if the data format in the buffer is different from the default format provided by DirectMusic.

The method fails if the specified number of bytes exceeds the maximum buffer size, as returned by the IDirectMusicBuffer::GetMaxBytes method.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

IDirectMusicBuffer::GetUsedBytes


IDirectMusicBuffer::TotalTime

The IDirectMusicBuffer::TotalTime method returns the total time spanned by the data in the buffer.

HRESULT TotalTime(
  LPREFERENCE_TIME prtTime
);

Parameters

prtTime
Address of a variable to receive the total time spanned by the buffer, in units of 100 nanoseconds.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

IDirectMusicBuffer::GetStartTime


IDirectMusicChordMap

The IDirectMusicChordMap interface represents a chord map. Chord maps provide the composer (represented by the IDirectMusicComposer interface) with the information needed to create chord progressions for segments to be composed. Chord maps can also be used to change the chords in an existing segment.

The DirectMusicChordMap object also supports the IDirectMusicObject and IPersistStream interfaces for loading its data.

The interface has the following method:

IDirectMusicChordMap GetScale

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


IDirectMusicChordMap::GetScale

The IDirectMusicChordMap::GetScale method retrieves the scale associated with the chord map.

HRESULT GetScale(
  DWORD* pdwScale
);

Parameters

pdwScale
Address of a variable to receive the scale value.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be E_POINTER.

Remarks

The scale is defined by the bits in a DWORD, split into a scale pattern (lower 24 bits) and a root (upper 8 bits). For the scale pattern, the low bit (0x0001) is the lowest note in the scale, the next higher (0x0002) is a semitone higher, and so on for two octaves. The upper 8 bits give the root of the scale as an integer between 0 and 23 (low C to middle B).

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


IDirectMusicCollection

The IDirectMusicCollection interface manages an instance of a DLS file. The collection provides methods to access instruments and download them to the synthesizer by means of the IDirectMusicPort interface.

The DirectMusicCollection object also supports the IDirectMusicObject and IPersistStream interfaces for loading its data.

For more information on how to work with collections, see Using Downloadable Sounds.

The IDirectMusicCollection interface has the following methods:

Instruments | EnumInstrument
 | GetInstrument

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.


IDirectMusicCollection::EnumInstrument

The IDirectMusicCollection::EnumInstrument method retrieves the patch and name of an instrument by its index in the collection.

HRESULT EnumInstrument(
  DWORD dwIndex,
  DWORD* pdwPatch,
  LPWSTR pwszName,
  DWORD dwNameLen
);

Parameters

dwIndex
Index of the instrument in the collection.
pdwPatch
Address of a variable to receive the patch number.
pwszName
Address of a buffer to receive the instrument name. Can be NULL if the name is not wanted.
dwNameLen
Size of the instrument name buffer, in WCHARs.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if there is no instrument with that index number.

If it fails, the method can return one of the following error values:

E_FAIL
E_OUTOFMEMORY
E_POINTER

Remarks

To enumerate all instruments in a collection, start with a dwIndex of 0 and increment until EnumInstrument returns S_FALSE.

The patch number returned in pdwPatch describes the full patch address, including the MIDI parameters for MSB and LSB bank select. For more information, see MIDI Channel Messages.

Although the ordering of the enumeration is consistent within one instance of a DLS collection, it has no relationship to the ordering of instruments in the file, their patch numbers, or their names.

For an example of instrument enumeration, see Working with Instruments.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.


IDirectMusicCollection::GetInstrument

The IDirectMusicCollection::GetInstrument method retrieves an instrument from a collection by its patch number.

HRESULT GetInstrument(
  DWORD dwPatch,
  IDirectMusicInstrument** ppInstrument
);

Parameters

dwPatch
Instrument patch number.
ppInstrument
Address of a variable to receive a pointer to the IDirectMusicInstrument interface.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_INVALIDPATCH
E_FAIL
E_OUTOFMEMORY
E_POINTER

Remarks

The patch number passed in dwPatch describes the full patch address, including the MIDI parameters for MSB and LSB bank select. MSB is shifted left 16 bits, and LSB is shifted left 8 bits. For more information, see MIDI Channel Messages.

In addition, the high bit must be set (0x80000000) if the instrument is specifically a drum kit intended to be played on MIDI channel 10. This a special tag for DLS Level 1, which always puts drums on MIDI channel 10.

For an example of how this method is used, see Working with Instruments.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.


IDirectMusicComposer

The IDirectMusicComposer interface permits access to the composition engine. In addition to building new segments from templates and chord maps, the composer can generate transitions between different segments. It can also apply a chord map to an existing segment, thus altering the chord progression and the mood of the music.

For an overview, see Music Composition.

The methods of the IDirectMusicComposer interface can be grouped as follows:

Changing chord maps | ChangeChordMap
Composing ordinary segments | ComposeSegmentFromShape
 | ComposeSegmentFromTemplate
Composing template segments | ComposeTemplateFromShape
Composing transition segments | AutoTransition
 | ComposeTransition

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


IDirectMusicComposer::AutoTransition

The IDirectMusicComposer::AutoTransition method composes a transition from inside a performance's primary segment (or from silence) to another segment, and then cues the transition and the second segment to play.

HRESULT AutoTransition(
  IDirectMusicPerformance* pPerformance,
  IDirectMusicSegment* pToSeg,
  WORD wCommand,
  DWORD dwFlags,
  IDirectMusicChordMap* pChordMap,
  IDirectMusicSegment** ppTransSeg,
  IDirectMusicSegmentState** ppToSegState,
  IDirectMusicSegmentState** ppTransSegState
);

Parameters

pPerformance
Performance in which to make the transition.
pToSeg
Segment to which the transition should smoothly flow. See Remarks.
wCommand
Embellishment to use when composing the transition. See DMUS_COMMANDT_TYPES. If this value is DMUS_COMMANDT_ENDANDINTRO, the method composes a segment containing both an ending to the primary segment and an introduction to pToSeg.
dwFlags
Composition options. See DMUS_COMPOSEF_FLAGS.
pChordMap
Chord map to be used when composing the transition.
ppTransSeg
Address of a variable to receive a pointer to the created segment. This value can be NULL, in which case the pointer is not returned.
ppToSegState
Address of a variable to receive a pointer to the segment state created by the performance (pPerformance) for the segment following the transition (pToSeg). See Remarks.
ppTransSegState
Address of a variable to receive a pointer to the segment state created by the performance (pPerformance) for the created segment (ppTransSeg). See Remarks.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

The value in pToSeg can be NULL as long as dwFlags does not include DMUS_COMPOSEF_MODULATE. If pToSeg is NULL or does not contain a style track (as would be the case if it is based on a MIDI file), intro embellishments are not valid. If the currently playing segment is NULL or does not contain a style track, then fill, break, end, and groove embellishments are not valid. If no style track is available either in the currently playing segment or in the one represented by pToSeg, all embellishments are invalid, and no transition occurs. In that case, both ppTransSeg and ppTransSegState return NULL, but the method succeeds and cues the segment represented by pToSeg, if that pointer is not NULL.

The value in pChordMap can be NULL. If it is, an attempt is made to obtain a chord map from a chord-map track, first from pToSeg, and then from the performance's primary segment. If neither of these segments contains a chord-map track, the chord occurring at the current time in the primary segment is used as the chord in the transition.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicComposer::ComposeTransition, Using Transitions


IDirectMusicComposer::ChangeChordMap

The IDirectMusicComposer::ChangeChordMap method modifies the chords and scale pattern of an existing segment to reflect a new chord map.

HRESULT ChangeChordMap(
  IDirectMusicSegment* pSegment,
  BOOL fTrackScale,
  IDirectMusicChordMap* pChordMap
);

Parameters

pSegment
Segment in which to change the chord map.
fTrackScale
If TRUE, the method transposes all the chords to be relative to the root of the new chord map's scale, rather than leaving their roots as they were.
pChordMap
New chord map for the segment.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

The method can be called while the segment is playing.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


IDirectMusicComposer::ComposeSegmentFromShape

The IDirectMusicComposer::ComposeSegmentFromShape method creates an original segment from a style and a chord map, based on a predefined shape. The shape represents the way chords and embellishments occur over time across the segment.

HRESULT ComposeSegmentFromShape(
  IDirectMusicStyle* pStyle,
  WORD wNumMeasures,
  WORD wShape,
  WORD wActivity,
  BOOL fIntro,
  BOOL fEnd,
  IDirectMusicChordMap* pChordMap,
  IDirectMusicSegment** ppSegment
);

Parameters

pStyle
Style from which to compose the segment.
wNumMeasures
Length, in measures, of the segment to be composed.
wShape
Shape of the segment to be composed. Possible values are of the DMUS_SHAPET_TYPES enumerated type.
wActivity
Rate of harmonic motion. Valid values are from 0 through 3. Lower values mean more chord changes.
fIntro
TRUE if an introduction is to be composed for the segment.
fEnd
TRUE if an ending is to be composed for the segment.
pChordMap
Chord map from which to create the segment.
ppSegment
Address of a variable to receive a pointer to the created segment.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicComposer::ComposeSegmentFromTemplate, IDirectMusicComposer::ComposeTemplateFromShape


IDirectMusicComposer::ComposeSegmentFromTemplate

The IDirectMusicComposer::ComposeSegmentFromTemplate method creates an original segment from a style, a chord map, and a template.

HRESULT ComposeSegmentFromTemplate(
  IDirectMusicStyle* pStyle,
  IDirectMusicSegment* pTemplate,
  WORD wActivity,
  IDirectMusicChordMap* pChordMap,
  IDirectMusicSegment** ppSegment
);

Parameters

pStyle
Style from which to create the segment.
pTemplate
Template from which to create the segment.
wActivity
Rate of harmonic motion. Valid values are 0 through 3. Lower values mean more chord changes.
pChordMap
Chord map from which to create the segment.
ppSegment
Address of a variable to receive a pointer to the created segment.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_INVALIDARG
E_POINTER

Remarks

If pStyle is non-NULL, it is used in composing the segment; if it is NULL, a style is retrieved from the template specified in pTempSeg. Similarly, if pChordMap is non-NULL, it is used in composing the segment; if it is NULL, a chord map is retrieved from the template.

If pStyle is NULL and there is no style track in the template, or pChordMap is NULL and there is no chord-map track, the method returns E_INVALIDARG.

The length of the segment is equal to the length of the template passed in.

The default start point and loop points of the created segment are 0, regardless of the values in the template segment.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicComposer::ComposeSegmentFromShape, IDirectMusicComposer::ComposeTemplateFromShape, Using Templates


IDirectMusicComposer::ComposeTemplateFromShape

The IDirectMusicComposer::ComposeTemplateFromShape method creates a new template segment, based on a predefined shape.

HRESULT ComposeTemplateFromShape(
  WORD wNumMeasures,
  WORD wShape,
  BOOL fIntro,
  BOOL fEnd,
  WORD wEndLength,
  IDirectMusicSegment** ppTemplate
);

Parameters

wNumMeasures
Length, in measures, of the segment to be composed. This value must be greater than 0.
wShape
Shape of the segment to be composed. Possible values are of the DMUS_SHAPET_TYPES enumerated type.
fIntro
TRUE if an introduction is to be composed for the segment.
fEnd
TRUE if an ending is to be composed for the segment.
wEndLength
Length in measures of the ending, if one is to be composed. If fEnd is TRUE, this value must be greater than 0 and equal to or less than the number of measures available (that is, not used in the introduction). See also Remarks.
ppTemp;ate
Address of a variable to receive a pointer to the created template segment.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_INVALIDARG
E_OUTOFMEMORY
E_POINTER

Remarks

The value of wEndLength should not be greater than the length of the longest ending available in any style likely to be associated with this template through the IDirectMusicComposer::ComposeSegmentFromTemplate method. The ending starts playing at wEndLength measures before the end of the segment. If the ending is less than wEndLength measures long, the music then reverts to the basic groove level.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicComposer::ComposeSegmentFromShape, IDirectMusicComposer::ComposeSegmentFromTemplate, Using Templates


IDirectMusicComposer::ComposeTransition

The IDirectMusicComposer::ComposeTransition method composes a transition from a measure inside one segment to another.

HRESULT ComposeTransition(
  IDirectMusicSegment* pFromSeg,
  IDirectMusicSegment* pToSeg,
  MUSIC_TIME mtTime,
  WORD wCommand,
  DWORD dwFlags,
  IDirectMusicChordMap* pChordMap,
  IDirectMusicSegment** ppTransSeg
);

Parameters

pFromSeg
Segment from which to compose the transition.
pToSeg
Segment to which the transition should smoothly flow. Can be NULL if dwFlags does not include DMUS_COMPOSEF_MODULATE.
mtTime
Time in pFromSeg from which to compose the transition.
wCommand
Embellishment to use when composing the transition. See DMUS_COMMANDT_TYPES. If this value is DMUS_COMMANDT_ENDANDINTRO, the method composes a segment containing both an ending to pFromSeg and an introduction to pToSeg.
dwFlags
Composition options. This parameter can contain one or more of the DMUS_COMPOSEF_FLAGS enumerated type values.
pChordMap
Chord map to be used when composing the transition. See Remarks.
ppTransSeg
Address of a variable to receive a pointer to the created segment.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_INVALIDARG
E_OUTOFMEMORY
E_POINTER

Remarks

The value in pChordMap can be NULL. If it is, an attempt is made to obtain a chord map from a chord-map track, first from pToSeg, and then from pFromSeg. If neither of these segments contains a chord-map track, the chord occurring at mtTime in pFromSeg is used as the chord in the transition.

The composer looks for a tempo, first in pFromSeg, and then in pToSeg. If neither of those segments contains a tempo track, the tempo for the transition segment is taken from the style.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicComposer::AutoTransition, Using Transitions


IDirectMusicDownload

The IDirectMusicDownload interface represents a contiguous memory chunk used for downloading to a DLS synthesizer port.

The IDirectMusicDownload interface and its contained memory chunk are created by the IDirectMusicPortDownload::AllocateBuffer method. The memory can then be accessed by using the single method of this interface.

The interface has the following method:

IDirectMusicDownload GetBuffer

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.


IDirectMusicDownload::GetBuffer

The IDirectMusicDownload::GetBuffer method retrieves a pointer to a buffer containing data to be downloaded.

HRESULT GetBuffer(
  void** ppvBuffer,
  DWORD* pdwSize
);

Parameters

ppvBuffer
Address of a variable to receive a pointer to the data buffer.
pdwSize
Address of a variable to receive the size of the returned buffer, in bytes.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_BUFFERNOTAVAILABLE
E_POINTER

Remarks

The method returns DMUS_E_BUFFERNOTAVAILABLE if the buffer has already been downloaded.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.


IDirectMusicDownloadedInstrument

The IDirectMusicDownloadedInstrument interface is used to identify an instrument that has been downloaded to the synthesizer by using the IDirectMusicPort::DownloadInstrument or the IDirectMusicPerformance::DownloadInstrument method. The interface is then used to unload the instrument through a call to IDirectMusicPort::UnloadInstrument. Once the instrument has been unloaded, the interface pointer must be released by the application.

For an example, see Working with Instruments.

The IDirectMusicDownloadedInstrument interface has no methods of its own. Like all COM interfaces, it inherits the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.


IDirectMusicGetLoader

The IDirectMusicGetLoader interface is used by an object parsing a stream when the object needs to load another object referenced by the stream. If a stream supports the loader, it must provide an IDirectMusicGetLoader interface.

For an example of how to obtain the IDirectMusicGetLoader interface from the stream, see IDirectMusicGetLoader::GetLoader.

The IDirectMusicGetLoader interface has the following method:

IDirectMusicGetLoader GetLoader

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicLoader, DirectMusic Loader, Custom Loading


IDirectMusicGetLoader::GetLoader

The IDirectMusicGetLoader::GetLoader method retrieves a pointer to the loader object that created the stream.

HRESULT GetLoader(
  IDirectMusicLoader ** ppLoader
);

Parameters

ppLoader
Address of a variable to receive the IDirectMusicLoader interface pointer. The reference count of the interface is incremented.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_NOINTERFACE.

Remarks

The following code example is from a file parser that finds a reference to an object that needs to be accessed by the loader.

HRESULT myGetReferencedObject(
    DMUS_OBJECTDESC *pDesc,          // Descriptor already prepared
    IStream *pIStream,               // Stream being parsed
    IDirectMusicObject **ppIObject)  // Object to be accessed
{
    IDirectMusicGetLoader *pIGetLoader;
    IDirectMusicLoader *pILoader;
    ppIObject = NULL;
    HRESULT hr = pIStream->QueryInterface(
           IID_IDirectMusicGetLoader,
           (void **) &pIGetLoader );
    if (SUCCEEDED(hr))
    {
        hr = pIGetLoader->GetLoader(&pILoader);
        if (SUCCEEDED(hr))
        {
            hr = pILoader->GetObject(pDesc, IID_DirectMusicLoader,
                  (void**) ppIObject);
            pILoader->Release();
        }
        pIGetLoader->Release();
    }
    return hr;
}

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

Custom Loading


IDirectMusicGraph

The IDirectMusicGraph interface manages the loading and message flow of tools.

Graphs can occur in two places: performances and segments. The graph of tools in a performance is global in nature; it processes messages from all segments. A graph in a segment exists only for playback of that segment.

The IDirectMusicGraph interface has the following methods:

Routing | StampPMsg
Tools | GetTool
 | InsertTool
 | RemoveTool

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


IDirectMusicGraph::GetTool

The IDirectMusicGraph::GetTool method retrieves a tool by index.

HRESULT GetTool(
  DWORD dwIndex,
  IDirectMusicTool** ppTool
);

Parameters

dwIndex
Zero-based index of the requested tool in the graph.
ppTool
Address of a variable to receive a pointer to the tool.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following values:

DMUS_E_NOT_FOUND
E_POINTER

Remarks

The application is responsible for releasing the retrieved tool.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


IDirectMusicGraph::InsertTool

The IDirectMusicGraph::InsertTool method inserts a tool in the graph.

HRESULT InsertTool(
  IDirectMusicTool * pTool,
  DWORD * pdwPChannels,
  DWORD cPChannels,
  LONG lIndex
);

Parameters

pTool
Tool to insert.
pdwPChannels
Address of an array of PChannels on which the tool accepts messages. If the tool accepts messages on all PChannels, pass NULL.
cPChannels
Count of how many PChannels are pointed to by pdwPChannels. Ignored if pdwPChannels is NULL.
lIndex
Position at which to place the tool. This is a zero-based index from either the start or (if it is negative) the end of the current tool list. If lIndex is out of range, the tool is placed at the beginning or end of the list. To place a tool at the end of the list, use a number for lIndex that is larger than the number of tools in the current tool list.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_ALREADY_EXISTS
E_OUTOFMEMORY
E_POINTER

Remarks

The reference count of the tool is incremented.

This method calls IDirectMusicTool::Init.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


IDirectMusicGraph::RemoveTool

The IDirectMusicGraph::RemoveTool method removes a tool from the graph.

HRESULT RemoveTool(
  IDirectMusicTool * pTool
);

Parameters

pTool
Address of a variable that contains the tool to be removed.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_NOT_FOUND
E_POINTER

Remarks

The graph's reference to the tool object is released.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


IDirectMusicGraph::StampPMsg

The IDirectMusicGraph::StampPMsg method stamps a message with a pointer to the next tool that is to receive it. After processing a message, a tool must call this method.

HRESULT StampPMsg(
  DMUS_PMSG* pPMSG
);

Parameters

pPMSG
Address of a structure that contains the message to stamp. This structure is of a type derived from DMUS_PMSG. For an overview of message types, see Messages.

Return Values

If the method succeeds, the return value is S_OK or DMUS_S_LAST_TOOL. See Remarks.

If it fails, the method can return E_POINTER.

Remarks

On entry, pPMSG->pTool (see DMUS_PMSG) points to the current tool. StampPMsg uses this member to determine the current tool to find the next tool in the graph. A value of NULL represents the first tool in the graph.

The object pointed to by pPMSG->pGraph represents the graph that contains the tool. This is stamped inside StampPMsg, along with the tool itself, and can change while the message travels from the segment state to the performance because there can be multiple tool graphs.

The value of pPMSG->dwType equals the media type of the message, and is also used to find the next tool. The media types supported are those returned by the IDirectMusicTool::GetMediaTypes method.

The value of pPMSG->dwPChannel is used to determine which track the tool must be capable of processing. Tracks are identified by unique numbers when a segment is authored.

This method calls Release on the current IDirectMusicTool pointed to by pPMSG->pTool, replaces it with the next tool in the graph and calls AddRef on the new tool.

It also flags the message with the correct delivery type, according to what type the next tool returns in its IDirectMusicTool::GetMsgDeliveryType method. This flag determines when the message is delivered to the next tool.

The implementations of this method in the DirectMusicSegmentState and DirectMusicPerformance objects always return S_OK on success. The implementation in DirectMusicGraph returns DMUS_S_LAST_TOOL if there is no tool other than the output tool waiting to receive the message.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

DirectMusic Tools


IDirectMusicInstrument

The IDirectMusicInstrument interface represents an individual instrument from a DLS collection.

The only way to create a DirectMusicInstrument object to download an instrument is to first create a DirectMusicCollection object, and then call the IDirectMusicCollection::GetInstrument method. GetInstrument creates a DirectMusicInstrument object and returns its IDirectMusicInstrument interface pointer.

To download the instrument, pass its interface pointer to the IDirectMusicPort::DownloadInstrument or the IDirectMusicPerformance::DownloadInstrument method. If the method succeeds, it returns a pointer to an IDirectMusicDownloadedInstrument interface, which is used only to unload the instrument.

The methods of IDirectMusicInstrument operate only on an instrument that has not been downloaded. Any instances of the instrument that have been downloaded to a port are not affected by the IDirectMusicInstrument::GetPatch and IDirectMusicInstrument::SetPatch methods.

The interface has the following methods:

IDirectMusicInstrument | GetPatch
 | SetPatch

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.


IDirectMusicInstrument::GetPatch

The IDirectMusicInstrument::GetPatch method retrieves the patch number for the instrument. The patch number is an address composed of the MSB and LSB bank selects and the MIDI patch (program change) number. An optional flag bit indicates that the instrument is a drum, rather than a melodic instrument.

HRESULT GetPatch(
  DWORD* pdwPatch
);

Parameters

pdwPatch
Address of a variable to receive the patch number.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

The patch number returned at pdwPatch describes the full patch address, including the MIDI parameters for MSB and LSB bank select. In addition, the high bit is set if the instrument is specifically a drum kit, intended to be played on MIDI channel 10. This is a special tag for DLS Level 1, since DLS Level 1 always plays drums on MIDI channel 10. For more information, see MIDI Channel Messages.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.


IDirectMusicInstrument::SetPatch

The IDirectMusicInstrument::SetPatch method sets the patch number for the instrument. Although each instrument in a DLS collection has a predefined patch number, the patch number can be reassigned once the IDirectMusicCollection::GetInstrument method has been used to retrieve the instrument from the collection. For more information on DirectMusic patch numbers, see IDirectMusicInstrument::GetPatch.

HRESULT SetPatch(
  DWORD dwPatch
);

Parameters

dwPatch
New patch number to assign to instrument.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return DMUS_E_INVALIDPATCH.

Remarks

The following code example gets an instrument from a collection, remaps its MSB bank select to a different bank, then downloads the instrument.

HRESULT myRemappedDownload(
    IDirectMusicCollection *pCollection,
    IDirectMusicPort *pPort,
    IDirectMusicDownloadedInstrument **ppDLInstrument,
    BYTE bMSB,       // Requested MIDI MSB for patch bank select
    DWORD dwPatch)   // Requested patch

{
    HRESULT hr;
    IDirectMusicInstrument* pInstrument;
    hr = pCollection->GetInstrument(dwPatch, &pInstrument);
    if (SUCCEEDED(hr))
    {
        dwPatch &= 0xFF00FFFF;  // Clear MSB.
        dwPatch |= bMSB << 16;  // Insert new MSB value.
        pInstrument->SetPatch(dwPatch);
        hr = pPort->DownloadInstrument(pInstrument,
                ppDLInstrument,
                NULL, 0);       // Download all regions.
        pInstrument->Release();
    }
    return hr;
}

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.


IDirectMusicLoader

The IDirectMusicLoader interface is used for finding, enumerating, caching, and loading objects. For an overview, see DirectMusic Loader.

The methods of the IDirectMusicLoader interface can be organized into the following groups:

Searching | EnumObject
 | ScanDirectory
 | SetSearchDirectory
Caching | CacheObject
 | ClearCache
 | EnableCache
Object management | GetObject
 | ReleaseObject
 | SetObject

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDMUS_LOADER type is defined as a pointer to the IDirectMusicLoader interface.

typedef IDirectMusicLoader __RPC_FAR *LPDMUS_LOADER;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


IDirectMusicLoader::CacheObject

The IDirectMusicLoader::CacheObject method tells the loader to keep a reference to the object. This guarantees that the object is not loaded twice.

HRESULT CacheObject(
  IDirectMusicObject * pObject
);

Parameters

pObject
Address of the IDirectMusicObject interface of the object to cache.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if the object is already cached.

If it fails, the method can return one of the following error values:

E_POINTER
DMUS_E_LOADER_OBJECTNOTFOUND

Remarks

If you have an object that is accessed in multiple places throughout the life of your application, letting the loader cache the object can significantly speed up performance. For an overview, see Caching Objects.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicLoader::EnableCache, IDirectMusicLoader::ClearCache, IDirectMusicLoader::ReleaseObject


IDirectMusicLoader::ClearCache

The IDirectMusicLoader::ClearCache method tells the loader to release all references to a particular type of object.

HRESULT ClearCache(
  REFGUID rguidClass
);

Parameters

rguidClass
Reference to (C++) or address of (C) the identifier of the class of objects to clear. You can specify all types with GUID_DirectMusicAllTypes.

Return Values

The method returns S_OK.

Remarks

This method clears all objects that are currently being held, but does not turn off caching. Use the IDirectMusicLoader::EnableCache method to turn off automatic caching.

To clear a single object from the cache, call the IDirectMusicLoader::ReleaseObject method.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicLoader::CacheObject, Caching Objects


IDirectMusicLoader::EnableCache

The IDirectMusicLoader::EnableCache method tells the loader to enable or disable automatic caching of all objects it loads. By default, caching is enabled for all classes.

HRESULT EnableCache(
  REFGUID rguidClass,
  BOOL fEnable
);

Parameters

rguidClass
Reference to (C++) or address of (C) the identifier of the class of objects to cache. You can specify all types with GUID_DirectMusicAllTypes.
fEnable
TRUE to enable caching; FALSE to clear and disable.

Return Values

The method returns S_OK if the cache state is changed, or S_FALSE if the cache is already in the desired state.

Remarks

To clear the cache without disabling caching, call the IDirectMusicLoader::ClearCache method.

The following code example disables caching only for segment objects so that they do not stay in memory after the application releases them. Other objects that should be shared, such as styles, chord maps and DLS collections, continue to be cached. The first call to EnableCache would normally be unnecessary because caching is enabled for all objects by default.

void myPrepareLoader(IDirectMusicLoader *pILoader)

{
    pILoader->EnableCache(GUID_DirectMusicAllTypes, TRUE);
    pILoader->EnableCache(CLSID_DirectMusicSegment, FALSE);
}

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicLoader::CacheObject, IDirectMusicLoader::ClearCache, Caching Objects


IDirectMusicLoader::EnumObject

The IDirectMusicLoader::EnumObject method enumerates all available objects of the requested type. Objects are available if they have been loaded or if IDirectMusicLoader::ScanDirectory has been called on the search directory.

HRESULT EnumObject(
  REFGUID rguidClass,
  DWORD dwIndex,
  LPDMUS_OBJECTDESC pDesc
);

Parameters

rguidClass
Reference to (C++) or address of (C) the identifier for the class of objects to view.
dwIndex
Index into the list. Typically, starts with 0 and increments.
pDesc
Address of a DMUS_OBJECTDESC structure to be filled with data about the object.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if dwIndex is past the end of the list.

Remarks

For an example of the use of this method, see Enumerating Objects.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicLoader::ScanDirectory


IDirectMusicLoader::GetObject

The IDirectMusicLoader::GetObject method retrieves the specified object from a file or resource and returns the desired interface.

HRESULT GetObject(
  LPDMUS_OBJECTDESC pDESC,
  REFIID riid,
  LPVOID FAR * ppv
);

Parameters

pDESC
Address of a DMUS_OBJECTDESC structure describing the object.
riid
Unique identifier of the interface. See the IID defines in Dmusici.h. All the standard interfaces have a defined identifier consisting of "IID_" plus the name of the interface. For example, the identifier of IDirectMusicTrack is IID_IDirectMusicTrack.
ppv
Address of a variable to receive a pointer to the desired interface of the object.

Return Values

If the method succeeds, the return value is S_OK or DMUS_S_PARTIALLOAD.

If it fails, the method can return one of the following error values:

E_FAIL
E_INVALIDARG
E_OUTOFMEMORY
E_POINTER
DMUS_E_LOADER_NOCLASSID
DMUS_E_LOADER_FAILEDOPEN
DMUS_E_LOADER_FAILEDCREATE
DMUS_E_LOADER_FORMATNOTSUPPORTED
REGDB_E_CLASSNOTREG

Remarks

A return value of DMUS_S_PARTIALLOAD can mean that the default instrument collection file, Gm.dls, is not available.

The current version of DirectMusic does not support loading from URLs. If the dwValidData member of the DMUS_OBJECTDESC structure contains DMUS_OBJ_URL, the method returns DMUS_E_LOADER_FORMATNOTSUPPORTED.

The method does not require that all valid members of the DMUS_OBJECTDESC structure match before retrieving an object. It searches in the following order:

  1. DMUS_OBJ_OBJECT
  2. DMUS_OBJ_MEMORY
  3. DMUS_OBJ_FILENAME and DMUS_OBJ_FULLPATH
  4. DMUS_OBJ_NAME and DMUS_OBJ_CATEGORY
  5. DMUS_OBJ_NAME
  6. DMUS_OBJ_FILENAME

In other words, the highest priority goes to a unique GUID, followed by a resource, followed by the full file path name, followed by an internal name plus category, followed by an internal name, followed by a local file name.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicLoader::ReleaseObject, IDirectMusicLoader::ScanDirectory


IDirectMusicLoader::ReleaseObject

The IDirectMusicLoader::ReleaseObject method releases the loader's reference to the object.

HRESULT ReleaseObject(
  IDirectMusicObject * pObject
);

Parameters

pObject
Address of a variable that contains the object to release.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_POINTER
DMUS_E_LOADER_OBJECTNOTFOUND

Remarks

ReleaseObject is the reciprocal of IDirectMusicLoader::CacheObject.

Objects can be cached explicitly by using the CacheObject method, or automatically by using the IDirectMusicLoader::EnableCache method.

To tell the loader to flush all objects of a particular type, call the IDirectMusicLoader::ClearCache method.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicLoader::GetObject, Caching Objects


IDirectMusicLoader::ScanDirectory

The IDirectMusicLoader::ScanDirectory method searches a directory on disk for all files of a requested class type and file extension. For each file found, it calls the IDirectMusicObject::ParseDescriptor method to extract the GUID and name of the object. This information is stored in an internal database. Once a directory has been scanned, all files of the requested type become available for enumeration through the IDirectMusicLoader::EnumObject method; in addition, an object can be retrieved by using IDirectMusicLoader::GetObject, even without a file name.

HRESULT ScanDirectory(
  REFGUID rguidClass,
  WCHAR* pwzFileExtension,
  WCHAR* pwzScanFileName
);

Parameters

rguidClass
Reference to (C++) or address of (C) the identifier of the class of objects.
pwzFileExtension
File extension for the type of file to look for—for example, L"sty" for style files. Use L"*" to look in files with any or no extension.
pwzScanFileName
Name of an optional storage file to store and retrieve cached file information. This file is created by the first call to ScanDirectory and used by subsequent calls. Pass NULL if a cache file is not wanted.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if no files were found.

If it fails, the method can return one of the following error values:

DMUS_E_NOT_FOUND
E_FAIL
E_OUTOFMEMORY
E_POINTER
REGDB_E_CLASSNOTREG

Remarks

The IDirectMusicLoader::SetSearchDirectory method must be called first to set the location to search.

The scanned information can be stored in a cache file defined by pwzScanFileName. Once it has been so stored, subsequent calls to ScanDirectory are much quicker because only files that have changed are scanned (the cache file stores the file size and date for each object, so it can tell if a file has changed).

If the file type has more than one extension, call ScanDirectory once for each file extension.

GUID_DirectMusicAllTypes is not a valid value for rguidClass.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

Scanning a Directory for Objects


IDirectMusicLoader::SetObject

The IDirectMusicLoader::SetObject method tells the loader where to find an object when it is later referenced by another object being loaded, and adds attributes to an object so that it can be referred to by those attributes. For an overview, see Setting Objects.

HRESULT SetObject(
  LPDMUS_OBJECTDESC pDESC
);

Parameters

pDESC
Address of a DMUS_OBJECTDESC structure describing the object.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_FAIL
E_INVALIDARG
E_OUTOFMEMORY
E_POINTER
DMUS_E_LOADER_NOCLASSID
DMUS_E_LOADER_FAILEDOPEN
DMUS_E_LOADER_FAILEDCREATE
DMUS_E_LOADER_FORMATNOTSUPPORTED
REGDB_E_CLASSNOTREG

Remarks

This method can be used to set attributes that are not currently valid for an object. For example, you can supply a value in the wszName member of the DMUS_OBJECTDESC structure to assign an internal name to an unnamed object, such as a segment based on a MIDI file. However, it cannot be used to change existing attributes. Most authored segments, for example, already have names, and these cannot be changed by the application.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicLoader::GetObject


IDirectMusicLoader::SetSearchDirectory

The IDirectMusicLoader::SetSearchDirectory method sets a search path for finding object files. The search path can be set for one object file type or for all files.

HRESULT SetSearchDirectory(
  REFGUID rguidClass,
  WCHAR* pwszPath,
  BOOL fClear
);

Parameters

rguidClass
Reference to (C++) or address of (C) the identifier of the class of objects that the call pertains to. GUID_DirectMusicAllTypes specifies all objects.
pwszPath
File path for directory. Must be a valid directory and must be less than MAX_PATH in length.
fClear
If TRUE, clears all information about objects before setting the directory. This avoids accessing objects from the previous directory that might have the same name. However, objects are not removed from the cache.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if the search directory is already set to pwszPath.

If it fails, the method can return one of the following error values:

E_OUTOFMEMORY
E_POINTER
DMUS_E_LOADER_BADPATH

Remarks

Once a search path is set, the loader does not need a full path every time it is given an object to load by file name. This enables objects that refer to other objects to find them by file name without knowing the full path.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicLoader::ScanDirectory, Setting the Loader's Search Directory


IDirectMusicObject

All DirectMusic objects that can be loaded from a file support the IDirectMusicObject interface so that they can work with the DirectMusic loader. New types of objects need to implement this interface. For more information, see Custom Loading.

Most applications do not use the methods of this interface directly. However, IDirectMusicObject::GetDescriptor can be used to query an object for information, including its name, GUID, file path, and version.

The IDirectMusicObject interface must be obtained by calling another interface's QueryInterface method. It cannot be obtained by using CoCreateInstance.

The IDirectMusicObject interface has the following methods:

Descriptor | GetDescriptor
 | ParseDescriptor
 | SetDescriptor

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDMUS_OBJECT type is defined as a pointer to the IDirectMusicObject interface.

typedef IDirectMusicObject __RPC_FAR *LPDMUS_OBJECT;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

DirectMusic Loader, Custom Loading


IDirectMusicObject::GetDescriptor

The IDirectMusicObject::GetDescriptor method retrieves the object's internal description.

The method takes a DMUS_OBJECTDESC structure and fills in everything the object knows about itself.

HRESULT GetDescriptor(
  LPDMUS_OBJECTDESC pDesc
);

Parameters

pDesc
Address of a DMUS_OBJECTDESC structure to be filled with data about the object. Depending on the implementation of the object and how it was loaded from a file, some or all of the standard parameters are filled by GetDescriptor. Check the flags in the dwValidData member to know which other members are valid.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

For an example, see Getting Object Descriptors.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicObject::SetDescriptor


IDirectMusicObject::ParseDescriptor

Given a file stream, the IDirectMusicObject::ParseDescriptor method scans the file for data that it can store in the DMUS_OBJECTDESC structure. All members that are supplied are marked with the appropriate flags in dwValidData.

This method is primarily used by the loader when scanning a directory for objects, and is not normally used directly by an application. However, if an application implements an object type in DirectMusic, it should support this method.

HRESULT ParseDescriptor(
  LPSTREAM pStream,
  LPDMUS_OBJECTDESC pDesc
);

Parameters

pStream
Stream source for the file.
pDesc
Address of a DMUS_OBJECTDESC structure to receive data about the file.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_CHUNKNOTFOUND
DMUS_E_INVALID_BAND
DMUS_E_INVALIDFILE
DMUS_E_NOTADLSCOL
E_POINTER

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicObject::SetDescriptor


IDirectMusicObject::SetDescriptor

The IDirectMusicObject::SetDescriptor method sets some or all members of the object's internal description.

This method is primarily used by the loader when creating an object, and is not normally used directly by an application. However, if an application implements an object type in DirectMusic, it should support this method.

HRESULT SetDescriptor(
  LPDMUS_OBJECTDESC pDesc
);

Parameters

pDesc
Address of a DMUS_OBJECTDESC structure to receive data about the object. Data is copied to all members that are enabled in the dwValidData member

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE (see Remarks).

If it fails, the method can return one of the following error values:

E_INVALIDARG
E_POINTER

Remarks

Applications do not normally call this method on standard objects. Although it is possible to change the object descriptor returned by IDirectMusicObject::GetDescriptor, the new description cannot successfully be passed to the IDirectMusicLoader::GetObject method. For example, you could change the name of an object, but GetObject still find the object only under its original name, since it relies on the object's own implementation of SetDescriptor.

Members that are not copied keep their previous values. For example, an object might already have its name and GUID stored internally. A call to its SetDescriptor method with a new name and file path (and DMUS_OBJ_NAME | DMUS_OBJ_FILENAME in the dwValidData member) would replace the name, supply a file name, and leave the GUID as it is.

If the object is unable to set one or more members, it sets the members that it does support, clears the flags in dwValidData that it does not support, and returns S_FALSE. An application-defined object should support at least DMUS_OBJ_NAME and DMUS_OBJ_OBJECT.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicObject::ParseDescriptor, IDirectMusicObject::GetDescriptor


IDirectMusicPerformance

The IDirectMusicPerformance interface is the overall manager of music playback. It is used for adding and removing ports, mapping performance channels to ports, playing segments, dispatching messages and routing them through tools, requesting and receiving event notification, and setting and retrieving music parameters. It also has several methods for getting information about timing and for converting time and music values from one system to another.

If an application needs two complete sets of music playing at the same time, it can do so by creating more than one performance. Separate performances obey separate tempo maps, and so play completely asynchronously, whereas all segments within one performance play in lock step.

The methods of the IDirectMusicPerformance interface can be organized into the following groups:

Channels | AssignPChannel
 | AssignPChannelBlock
 | PChannelInfo
Instruments | DownloadInstrument
Messages | AllocPMsg
 | FreePMsg
 | SendPMsg
MIDI conversion | MIDIToMusic
 | MusicToMIDI
Notification | AddNotificationType
 | GetNotificationPMsg
 | RemoveNotificationType
 | SetNotificationHandle
Parameters | GetGlobalParam
 | GetParam
 | SetGlobalParam
 | SetParam
Ports | AddPort
 | RemovePort
Segments | GetSegmentState
 | IsPlaying
 | PlaySegment
 | Stop
Timing | AdjustTime
 | GetBumperLength
 | GetLatencyTime
 | GetPrepareTime
 | GetQueueTime
 | GetResolvedTime
 | GetTime
 | MusicToReferenceTime
 | ReferenceToMusicTime
 | RhythmToTime
 | SetBumperLength
 | SetPrepareTime
 | TimeToRhythm
Tools | GetGraph
 | SetGraph
Miscellaneous | CloseDown
 | Init
 | Invalidate

All COM interfaces inherit the IUnknown interface methods. This interface supports the following methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


IDirectMusicPerformance::AddNotificationType

The IDirectMusicPerformance::AddNotificationType method adds a notification type to the performance. All segments and tracks are automatically updated with the new notification by calling their AddNotificationType methods.

HRESULT AddNotificationType(
  REFGUID rguidNotificationType
);

Parameters

rguidNotificationType
Reference to (C++) or address of (C) the identifier of the notification type to add. For the defined types, see DMUS_NOTIFICATION_PMSG. Applications can also define their own types for custom tracks.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_OUTOFMEMORY
E_POINTER

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::RemoveNotificationType, IDirectMusicSegment::AddNotificationType, IDirectMusicTrack::AddNotificationType, Notification and Event Handling


IDirectMusicPerformance::AddPort

The IDirectMusicPerformance::AddPort method assigns a port to the performance.

HRESULT AddPort(
  IDirectMusicPort* pPort
);

Parameters

pPort
Address of a variable that contains the port to add. If NULL, the default port is added. See Remarks.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_NOT_INIT
DMUS_E_CANNOT_OPEN_PORT
E_OUTOFMEMORY
E_POINTER

Remarks

If you want to pass NULL to this method, you must first pass NULL to IDirectMusicPerformance::Init.

When the default port is specified by passing NULL in pPort, it is assigned one channel group. If no PChannels have been set up for any other port, PChannels from 0 through 15 are assigned to MIDI channels from 0 through 15.

If pPort is not NULL, the port must be activated by a call to IDirectMusicPort::Activate, and a block of channels must be assigned by a call to IDirectMusicPerformance::AssignPChannelBlock.

This method creates a reference to IDirectMusicPort that is released by IDirectMusicPerformance::RemovePort or IDirectMusicPerformance::CloseDown.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::RemovePort, Default Port


IDirectMusicPerformance::AdjustTime

The IDirectMusicPerformance::AdjustTime method adjusts the internal performance time forward or backward. This is mostly used to compensate for drift when synchronizing to another source.

HRESULT AdjustTime(
  REFERENCE_TIME rtAmount
);

Parameters

rtAmount
Amount of time to add or subtract. This can be a number from –10,000,000 through 10,000,000 (–1 second through +1 second).

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_INVALIDARG.

Remarks

The adjusted time is used internally by DirectMusic. It is not reflected in the time retrieved by the IDirectMusicPerformance::GetTime method.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::GetTime, Timing


IDirectMusicPerformance::AllocPMsg

The IDirectMusicPerformance::AllocPMsg method allocates a performance message.

HRESULT AllocPMsg(
  ULONG cb,
  DMUS_PMSG** ppPMSG
);

Parameters

cb
Size of the message structure. For the various types, see Messages.
ppPMSG
Address of a variable to receive the pointer to the allocated message structure.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_INVALIDARG
E_OUTOFMEMORY
E_POINTER

Remarks

The memory returned is not initialized to any particular state, with the exception of the pTool member of the DMUS_PMSG structure, which is initialized to 0, and the dwSize member, which is set to the value of cb.

Once the message is sent by IDirectMusicPerformance::SendPMsg, the application no longer owns the memory and is not responsible for freeing the message. However, a tool can free a message within its IDirectMusicTool::Flush or its IDirectMusicTool::ProcessPMsg method. Applications are also responsible for freeing notification messages.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::FreePMsg, IDirectMusicPerformance::SendPMsg, DirectMusic Messages


IDirectMusicPerformance::AssignPChannel

The IDirectMusicPerformance::AssignPChannel method assigns a single performance channel (PChannel) to the performance and maps it to a port, group, and MIDI channel.

HRESULT AssignPChannel(
  DWORD dwPChannel,
  IDirectMusicPort* pPort,
  DWORD dwGroup,
  DWORD dwMChannel
);

Parameters

dwPChannel
PChannel to assign.
pPort
Address of a variable that contains the port to which the PChannel is assigned.
dwGroup
Channel group on the port.
dwMChannel
Channel in the group. Must be in the range from 0 through 15.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE (see Remarks).

If it fails, the method can return one of the following error values:

E_INVALIDARG
E_POINTER

Remarks

The method returns S_FALSE if dwGroup is out of the range of the port. The channel has been assigned, but the port cannot play this group.

The method returns E_INVALIDARG if dwMChannel is out of range or the port has not been added to the performance through a call to the IDirectMusicPerformance::AddPort method.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::AssignPChannelBlock, IDirectMusicPerformance::PChannelInfo, Channels


IDirectMusicPerformance::AssignPChannelBlock

The IDirectMusicPerformance::AssignPChannelBlock method assigns a block of 16 performance channels (PChannels) to the performance and maps them to a port and a channel group. This method must be called when a port has been added to a performance, except when the default port has been added by passing NULL to IDirectMusicPerformance::AddPort.

HRESULT AssignPChannelBlock(
  DWORD dwBlockNum,
  IDirectMusicPort* pPort,
  DWORD dwGroup
);

Parameters

dwBlockNum
Block number, in which 0 represents channels 0 through 15, 1 represents channels 16 through 31, and so on.
pPort
Address of a variable that contains the port to which the channels are assigned.
dwGroup
Channel group on the port. Must be 1 or greater.

Return Values

If the method succeeds, the return value is S_OK or S_FALSE (see Remarks).

If it fails, the method can return one of the following error values:

E_INVALIDARG
E_POINTER

Remarks

The method returns S_FALSE if dwGroup is out of the range of the port. The channels have been assigned, but the port cannot play this group.

The method returns E_INVALIDARG if the port has not been added to the performance through a call to the IDirectMusicPerformance::AddPort method.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::AssignPChannel, IDirectMusicPerformance::PChannelInfo, Channels


IDirectMusicPerformance::CloseDown

The IDirectMusicPerformance::CloseDown method closes down the performance object. An application that created the performance object and called IDirectMusicPerformance::Init on it must call CloseDown before the performance is released.

HRESULT CloseDown();

Parameters

None.

Return Values

The method returns S_OK.

Remarks

Failure to call CloseDown can cause memory leaks or program failures.

CloseDown handles the release of the IDirectMusic interface if the application passed NULL, or a pointer to NULL, to IDirectMusicPerformance::Init, causing a DirectMusic object to be created. In cases in which the application explicitly created the DirectMusic object and passed the pointer to Init, the application is responsible for releasing the IDirectMusic interface.

CloseDown also releases any downloaded instruments that have not been unloaded.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::Init


IDirectMusicPerformance::DownloadInstrument

The IDirectMusicPerformance::DownloadInstrument method downloads DLS data for an instrument to a port.

HRESULT DownloadInstrument(
  IDirectMusicInstrument* pInst,
  DWORD dwPChannel,
  IDirectMusicDownloadedInstrument** ppDownInst,
  DMUS_NOTERANGE* pNoteRanges,
  DWORD dwNumNoteRanges,
  IDirectMusicPort** ppPort,
  DWORD* pdwGroup,
  DWORD* pdwMChannel
);

Parameters

pInst
Address of a variable that contains the instrument to download.
dwPChannel
PChannel to which the instrument is assigned.
ppDownInst
Address of a variable to receive a pointer to the downloaded instrument.
pNoteRanges
Address of an array of DMUS_NOTERANGE structures. Each entry in the array specifies a contiguous range of MIDI note messages to which the instrument must respond. An instrument region is downloaded only if at least one note in that region is specified in the DMUS_NOTERANGE structures.
dwNumNoteRanges
Number of DMUS_NOTERANGE structures in the array pointed to by pNoteRanges. If this value is set to 0, the pNoteRanges parameter is ignored, and all regions and wave data for the instrument are downloaded.
ppPort
Address of a variable to receive a pointer to the port to which the instrument was downloaded.
pdwGroup
Address of a variable to receive the group to which the instrument is assigned.
pdwMChannel
Address of a variable to receive the MIDI channel to which the instrument is assigned.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_INVALIDARG
E_POINTER

Remarks

Most applications do not need to use this method because instrument downloading is normally handled by bands. See Downloading and Unloading Bands.

The method returns E_INVALIDARG if the PChannel is not assigned to a port.

To prevent loss of resources, unload the instrument by using the IDirectMusicPort::UnloadInstrument method when the instrument is no longer needed.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPort::DownloadInstrument, IDirectMusicPort::UnloadInstrument, Working with Instruments


IDirectMusicPerformance::FreePMsg

The IDirectMusicPerformance::FreePMsg method frees a message.

HRESULT FreePMsg(
  DMUS_PMSG* pPMSG
);

Parameters

pPMSG
Address of a variable that contains a message to free. This message must have been allocated using the IDirectMusicPerformance::AllocPMsg method.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_CANNOT_FREE
E_POINTER

Remarks

Most messages are released automatically by the performance once they have been processed, and IDirectMusicPerformance::FreePMsg must not be called on a message that has been sent by using IDirectMusicPerformance::SendPMsg. However, IDirectMusicPerformance::FreePMsg can be used within IDirectMusicTool::ProcessPMsg or IDirectMusicTool::Flush to free a message that is no longer needed. It must also be used to free notification messages.

The method returns DMUS_E_CANNOT_FREE in the following cases:

  • If pPMSG is not a message allocated by AllocPMsg.
  • If it is currently in the performance queue because IDirectMusicPerformance::SendPMsg was called on it.
  • If it has already been freed.

If there is a value in the pTool, pGraph, or punkUser members (see DMUS_PMSG), each referenced object is released.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::AllocPMsg, DirectMusic Messages


IDirectMusicPerformance::GetBumperLength

The IDirectMusicPerformance::GetBumperLength method retrieves the amount of time between the time at which messages are placed in the port buffer and the time at which they begin to be processed by the port. For an overview of this topic, see Timing.

HRESULT GetBumperLength(
  DWORD* pdwMilliSeconds
);

Parameters

pdwMilliSeconds
Address of a variable that contains the amount of preplay time.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

The default value is 50 milliseconds.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::SetBumperLength


IDirectMusicPerformance::GetGlobalParam

The IDirectMusicPerformance::GetGlobalParam method retrieves global values from the performance.

HRESULT GetGlobalParam(
  REFGUID rguidType,
  void* pParam,
  DWORD dwSize
);

Parameters

rguidType
Reference to (C++) or address of (C) the identifier of the type of data.
pParam
Pointer to the allocated memory to receive a copy of the data. This must be the correct size, which is constant for each type of data. This parametercontains information that was passed in to the IDirectMusicPerformance::SetGlobalParam method.
dwSize
Size of the data. This is constant for each rguidType.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_INVALIDARG
E_POINTER

Remarks

If SetGlobalParam has never been called for rguidType, the parameter might not be in the list of global data being handled by this performance, and the method might return E_INVALIDARG. In other words, do not assume that any parameter has a default value that can be retrieved by using GetGlobalParam.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::SetGlobalParam, IDirectMusicPerformance::GetParam, Music Parameters


IDirectMusicPerformance::GetGraph

The IDirectMusicPerformance::GetGraph method retrieves the tool graph of a performance.

HRESULT GetGraph(
  IDirectMusicGraph** ppGraph
);

Parameters

ppGraph
Address of a variable to receive a pointer to the tool graph.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_NOT_FOUND
E_POINTER

Remarks

The reference count of the graph is incremented.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::SetGraph, IDirectMusicSegment::GetGraph, IDirectMusicPerformance::SendPMsg


IDirectMusicPerformance::GetLatencyTime

The IDirectMusicPerformance::GetLatencyTime method retrieves the current latency time. Latency time is the time being heard from the speakers plus the time required to queue and render messages into the IDirectMusicPort. For an overview of this topic, see Timing.

HRESULT GetLatencyTime(
  REFERENCE_TIME * prtTime
);

Parameters

prtTime
Address of a variable to receive the current latency time.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_POINTER
DMUS_E_NO_MASTER_CLOCK

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


IDirectMusicPerformance::GetNotificationPMsg

The IDirectMusicPerformance::GetNotificationPMsg method retrieves a pending notification message.

HRESULT GetNotificationPMsg(
  DMUS_NOTIFICATION_PMSG** ppNotificationPMsg
);

Parameters

ppNotificationPMsg
Address of a variable to receive a pointer to a DMUS_NOTIFICATION_PMSG structure. The application retrieving this message is responsible for calling IDirectMusicPerformance::FreePMsg on it.

Return Values

If the method succeeds, the return value is S_OK or, S_FALSE if there are no more notification events to return.

If it fails, the method can return E_POINTER.

Remarks

For an example, see Handle Notifications in the tutorial on using compositions.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

Notification and Event Handling


IDirectMusicPerformance::GetParam

The IDirectMusicPerformance::GetParam method retrieves data from a track inside the control segment.

HRESULT GetParam(
  REFGUID rguidType,
  DWORD dwGroupBits,
  DWORD dwIndex,
  MUSIC_TIME mtTime,
  MUSIC_TIME* pmtNext,
  void* pParam
);

Parameters

rguidType
Reference to (C++) or address of (C) the identifier of the type of data to obtain. See Track Parameter Types.
dwGroupBits
Group that the desired track is in (see Remarks). Set this value to 0xFFFFFFFF for all groups.
dwIndex
Index of the track in the group from which to obtain the data.
mtTime
Time from which to obtain the data, in performance time.
pmtNext
Address of a variable to receive the time (relative to mtTime) until which the data is valid. If this returns a value of 0, either the data is always valid, or it is not known when it might become invalid. If this information is not needed, pmtNext can be set to NULL. See Remarks.
pParam
Address of an allocated structure in which the data is to be returned. The structure must be of the appropriate kind and size for the data type identified by rguidType.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_GET_UNSUPPORTED
DMUS_E_NO_MASTER_CLOCK
DMUS_E_NOT_FOUND
DMUS_E_TRACK_NOT_FOUND
E_POINTER

Remarks

Normally, the primary segment is the control segment. However, a secondary segment can be designated as a control segment when it is played. For more information on control segments, see Segments and DMUS_SEGF_FLAGS.

The data returned in *pParam can become invalid before the time returned in *pmtNext if another control segment is cued.

Each track belongs to one or more groups, and each group is represented by a bit in dwGroupBits. For more information, see IDirectMusicSegment::InsertTrack and Identifying the Track.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::SetParam, IDirectMusicSegment::GetParam, IDirectMusicTrack::GetParam, IDirectMusicPerformance::SetGlobalParam, IDirectMusicPerformance::GetTime, Music Parameters


IDirectMusicPerformance::GetPrepareTime

The IDirectMusicPerformance::GetPrepareTime method retrieves the amount of time ahead that IDirectMusicTrack::Play is called before the messages is heard through the speakers. This interval allows sufficient time for the message to be processed by tools.

HRESULT GetPrepareTime(
  DWORD* pdwMilliSeconds
);

Parameters

pdwMilliSeconds
Address of a variable to receive the amount of prepare time.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

The default value is 1000 milliseconds.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::SetPrepareTime, Timing


IDirectMusicPerformance::GetQueueTime

The IDirectMusicPerformance::GetQueueTime method retrieves the current flush time, which is the earliest time in the queue at which messages can be flushed. Messages that have time stamps earlier than this time have already been sent to the port and cannot be invalidated.

HRESULT GetQueueTime(
  REFERENCE_TIME * prtTime
);

Parameters

prtTime
Address of a variable to receive the current flush time.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_POINTER
DMUS_E_NO_MASTER_CLOCK

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

Latency and Bumper Time


IDirectMusicPerformance::GetResolvedTime

The IDirectMusicPerformance::GetResolvedTime method resolves a given time to a given boundary.

HRESULT GetResolvedTime(
  REFERENCE_TIME rtTime,
  REFERENCE_TIME* prtResolved,
  DWORD dwTimeResolveFlags
);

Parameters

rtTime
Time to resolve. If this is less than the current time, the current time is used.
prtResolved
Address of a variable to receive the resolved time.
dwTimeResolveFlags
One or more DMUS_TIME_RESOLVE_FLAGS describing the resolution desired.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

Timing


IDirectMusicPerformance::GetSegmentState

The IDirectMusicPerformance::GetSegmentState method retrieves the currently playing primary segment state or the primary segment state that is playing at a given time.

HRESULT GetSegmentState(
  IDirectMusicSegmentState ** ppSegmentState,
  MUSIC_TIME mtTime
);

Parameters

ppSegmentState
Address of a variable to receive a pointer to the segment state. The caller is responsible for calling Release on this pointer.
mtTime
Time for which the segment state is to be retrieved.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_NOT_FOUND
E_POINTER

Remarks

To get the currently playing segment state, pass the time returned by the IDirectMusicPerformance::GetTime method. The currently playing segment state represents the segment currently generating messages. Because of latency, the currently playing segment state is not necessarily the one being heard.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


IDirectMusicPerformance::GetTime

The IDirectMusicPerformance::GetTime method retrieves the current time of the performance.

HRESULT GetTime(
  REFERENCE_TIME* prtNow,
  MUSIC_TIME* pmtNow
);

Parameters

prtNow
Address of a variable to receive the current time in REFERENCE_TIME format. Can be NULL.
pmtNow
Address of a variable to receive the current time in MUSIC_TIME format. Can be NULL.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_NO_MASTER_CLOCK
E_POINTER

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

Timing


IDirectMusicPerformance::Init

The IDirectMusicPerformance::Init method associates the performance with a DirectMusic object and a DirectSound object.

HRESULT Init(
  IDirectMusic** ppDirectMusic,
  LPDIRECTSOUND pDirectSound,
  HWND hWnd
);

Parameters

ppDirectMusic
Address of a variable containing the IDirectMusic interface pointer to be assigned to the performance, if one already exists. The reference count of the interface is incremented. Ports passed to the IDirectMusicPerformance::AddPort method must be created from this DirectMusic object.

If the variable contains NULL, a DirectMusic object is created, and the interface pointer is returned.

If ppDirectMusic is NULL, a DirectMusic object is created and used internally by the performance.

See Remarks.

pDirectSound
Address of a IDirectSound interface to use by default for wave output. If this value is NULL, DirectMusic creates a DirectSound object. There should, however, only be one DirectSound object per process. If your application uses DirectSound separately, it should pass in that interface here, or to IDirectMusic::SetDirectSound if the application creates the DirectMusic object explicitly.
hWnd
Window handle to be used for the creation of DirectSound. This parameter can be NULL, in which case the foreground window is used. See Remarks.

This parameter is ignored if pDirectSound is not NULL, in which case the application is responsible for setting the window handle in a call to IDirectSound::SetCooperativeLevel.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_ALREADY_INITED
E_OUTOFMEMORY
E_POINTER

Remarks

This method should be called only once; it must be called before the performance can play.

A DirectMusic object can be associated with the performance in any of the following ways:

  • The application creates its own DirectMusic object and gives it to the performance by passing the address of the IDirectMusic pointer in ppDirectMusic. In this case, the pDirectSound and hWnd parameters are ignored because the application is responsible for calling IDirectMusic::SetDirectSound.
  • The application allows the performance to create the DirectMusic object and wants a pointer to that object. In this case, *ppDirectMusic is NULL on entry, and contains the IDirectMusic pointer on exit.
  • The application allows the performance to initialize itself and does not need a DirectMusic object pointer. In this case, ppDirectMusic is NULL.

The performance must be terminated by using the IDirectMusicPerformance::CloseDown method before being released.

You can pass NULL in the hWnd parameter to pass the current foreground window handle to DirectSound. However, do not assume that the application window will be in the foreground during initialization. In general, the top-level application window handle is passed to DirectMusic, DirectSound, and DirectDraw. See the Remarks for IDirectSound::SetCooperativeLevel.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

Creating the Performance, Integrating DirectMusic and DirectSound


IDirectMusicPerformance::Invalidate

The IDirectMusicPerformance::Invalidate method flushes all queued messages from the supplied time forward and causes all tracks of all segments to resend their data from the given time forward.

HRESULT Invalidate(
  MUSIC_TIME mtTime,
  DWORD dwFlags
);

Parameters

mtTime
Time from which to invalidate, adjusted by dwFlags. Setting this value to 0 causes immediate invalidation.
dwFlags
Flags that adjust mtTime to align to measures, beats, or grids. This value can be 0 or one of the following members of the DMUS_SEGF_FLAGS enumeration:

DMUS_SEGF_MEASURE
DMUS_SEGF_BEAT
DMUS_SEGF_GRID

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return DMUS_E_NO_MASTER_CLOCK.

Remarks

If mtTime is so long ago that it is impossible to invalidate that time, the earliest possible time is used.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

Prepare Time, Segment Timing


IDirectMusicPerformance::IsPlaying

The IDirectMusicPerformance::IsPlaying method determines whether a particular segment or segment state is currently being heard from the speakers.

HRESULT IsPlaying(
  IDirectMusicSegment* pSegment,
  IDirectMusicSegmentState* pSegState
);

Parameters

pSegment
Segment to check. If NULL, check only pSegState.
pSegState
Segment state to check. If NULL, check only pSegment.

Return Values

If the method succeeds and the requested segment or segment state is playing, the return value is S_OK. If neither is playing or only one was requested and it is not playing, the return value is S_FALSE.

If it fails, the method can return one of the following error values:

E_POINTER
DMUS_E_NO_MASTER_CLOCK

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


IDirectMusicPerformance::MIDIToMusic

The IDirectMusicPerformance::MIDIToMusic method converts a MIDI note value to a DirectMusic music value, using a supplied chord, subchord level, and play mode.

HRESULT MIDIToMusic(
  BYTE bMIDIValue,
  DMUS_CHORD_KEY* pChord,
  BYTE bPlayMode,
  BYTE bChordLevel,
  WORD *pwMusicValue
);

Parameters

bMIDIValue
MIDI note value to convert, in the range from 0 through 127.
pChord
Address of a DMUS_CHORD_KEY structure containing information about the chord and key structure to be used in translating the note. This includes the underlying scale. For example, if the chord is a CM7, the note is interpreted against the chord positions for root note C, chord intervals of a major seventh. The structure carries up to eight parallel subchords, with chord intervals, root, scale, and inversion flags for each. It also carries the overall key root.
bPlayMode
Play mode determining how the music value is derived from the chord. For a list of values, see DMUS_PLAYMODE_FLAGS.
bChordLevel
Subchord level, defining which subchords can be used. See DMUS_SUBCHORD.
pwMusicValue
Address of a variable to receive the music value. For information on this value, see DMUS_NOTE_PMSG.

Return Values

If the method succeeds, the return value is one of the following. See Remarks.

S_OK
DMUS_S_DOWN_OCTAVE
DMUS_S_UP_OCTAVE

If it fails, the method can return one of the following error values:

DMUS_E_CANNOT_CONVERT
E_INVALIDARG

Remarks

If the method fails, *pwMusicValue is not changed.

If the return value is DMUS_S_UP_OCTAVE or DMUS_DOWN_OCTAVE, the note conversion generated a note value that is less than 0 or greater than 127, so it has been bumped up or down one or more octaves to be in the proper MIDI range of from 0 through 127. This can occur when using play modes DMUS_PLAYMODE_FIXEDTOCHORD and DMUS_PLAYMODE_FIXEDTOKEY, both of which return MIDI values in *pwMusicValue.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::MusicToMIDI, Music Values and MIDI Notes


IDirectMusicPerformance::MusicToMIDI

The IDirectMusicPerformance::MusicToMIDI method converts a DirectMusic music value to a MIDI note value.

HRESULT MusicToMIDI(
  WORD wMusicValue,
  DMUS_CHORD_KEY* pChord,
  BYTE bPlayMode,
  BYTE bChordLevel,
  BYTE *pbMIDIValue
);

Parameters

wMusicValue
Music value to convert. For information on music values, see DMUS_NOTE_PMSG.
pChord
Address of a DMUS_CHORD_KEY structure containing information about the chord and key structure to be used in translating the note. This includes the underlying scale. For example, if the chord is a CM7, the note is interpreted against the chord positions for root note C, chord intervals of a major seventh. The structure carries up to eight parallel subchords, with chord intervals, root, scale, and inversion flags for each. It also carries the overall key root.
bPlayMode
Play mode determining how the music value is related to the chord. For a list of values, see DMUS_PLAYMODE_FLAGS.
bChordLevel
Subchord level, defining which subchords can be used. See DMUS_SUBCHORD.
pbMIDIValue
Address of a variable to receive the MIDI value, in the range from 0 through 127.

Return Values

If the method succeeds, the return value is one of the following. See Remarks.

S_OK
DMUS_S_OVER_CHORD
DMUS_S_DOWN_OCTAVE
DMUS_S_UP_OCTAVE

If it fails, the method can return one of the following error values:

DMUS_E_CANNOT_CONVERT
E_INVALIDARG

Remarks

If the method fails or returns DMUS_S_OVER_CHORD, *pwMIDIValue is not changed.

The method returns DMUS_S_OVER_CHORD if no note has been calculated because the music value has the note at a position higher than the top note of the chord. This applies only to DMUS_PLAYMODE_NORMALCHORD play mode. The caller should not do anything with the note, which is not meant to be played against this chord.

If the return value is DMUS_S_UP_OCTAVE or DMUS_DOWN_OCTAVE, the note conversion generated a note value that is less than 0 or greater than 127, so it has been bumped up or down one or more octaves to be in the proper MIDI range of 0 through 127. This can occur when using any play mode except DMUS_PLAYMODE_FIXED.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::MIDIToMusic, Music Values and MIDI Notes


IDirectMusicPerformance::MusicToReferenceTime

The IDirectMusicPerformance::MusicToReferenceTime method converts time in MUSIC_TIME format to time in REFERENCE_TIME format.

HRESULT MusicToReferenceTime(
  MUSIC_TIME mtTime,
  REFERENCE_TIME* prtTime
);

Parameters

mtTime
Time in MUSIC_TIME format to convert.
prtTime
Address of a variable to receive the converted time in REFERENCE_TIME format.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_POINTER
DMUS_E_NO_MASTER_CLOCK

Remarks

Because reference time has a greater precision than music time, a time that has been converted from reference time to music time, and then back again, probably does not have its original value.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::ReferenceToMusicTime, Clock Time vs. Music Time


IDirectMusicPerformance::PChannelInfo

The IDirectMusicPerformance::PChannelInfo method retrieves the port, group, and MIDI channel for a given performance channel.

HRESULT PChannelInfo(
  DWORD dwPChannel,
  IDirectMusicPort** ppPort,
  DWORD* pdwGroup,
  DWORD* pdwMChannel
);

Parameters

dwPChannel
PChannel for which information is desired.
ppPort
Address of a variable to receive an IDirectMusicPort pointer. This value can be NULL if the pointer is not wanted. If a non-NULL pointer is returned, the reference count is incremented, and it is the responsibility of the application to call Release on the pointer. See also Remarks.
pdwGroup
Address of a variable to receive the group on the port. Can be NULL if this value is not wanted.
pdwMChannel
Address of a variable to receive the MIDI channel on the group. Can be NULL if this value is not wanted.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_INVALIDARG
E_POINTER

Remarks

A NULL pointer is returned in *ppPort if the port has been removed by a call to IDirectMusicPerformance::RemovePort, but the method succeeds.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::AssignPChannel, IDirectMusicPerformance::AssignPChannelBlock


IDirectMusicPerformance::PlaySegment

The IDirectMusicPerformance::PlaySegment method begins playback of a segment.

HRESULT PlaySegment(
  IDirectMusicSegment* pSegment,
  DWORD dwFlags,
  __int64 i64StartTime,
  IDirectMusicSegmentState** ppSegmentState
);

Parameters

pSegment
Segment to play.
dwFlags
Flags that modify the method's behavior. See DMUS_SEGF_FLAGS.
i64StartTime
Time at which to begin playing the segment, adjusted to any resolution boundary specified in dwFlags. The time is in music time unless the DMUS_SEGF_REFTIME flag is set. A value of 0 causes the segment to start playing as soon as possible.
ppSegmentState
Address of a variable to receive a pointer to the segment state for this instance of the playing segment. This field can be NULL. If it is non-NULL, the segment state pointer is returned, and the application must call Release on it.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_OUTOFMEMORY
E_POINTER
DMUS_E_NO_MASTER_CLOCK
DMUS_E_SEGMENT_INIT_FAILED
DMUS_E_TIME_PAST

Remarks

Segments should be greater than 250 milliseconds in length.

The boundary resolutions in dwFlags are relative to the currently playing primary segment.

If a primary segment is scheduled to play while another primary segment is playing, the first one stops unless you set the DMUS_SEGF_QUEUE flag for the second segment, in which case it plays as soon as the first one finishes.

For more information on the exact start time of segments, see Segment Timing. For information on how the start time of segments can be affected by tempo changes, see Clock Time vs. Music Time.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

Segments


IDirectMusicPerformance::ReferenceToMusicTime

The IDirectMusicPerformance::ReferenceToMusicTime method converts time in REFERENCE_TIME format to time in MUSIC_TIME format.

HRESULT ReferenceToMusicTime(
  REFERENCE_TIME rtTime,
  MUSIC_TIME* pmtTime
);

Parameters

rtTime
Time in REFERENCE_TIME format.
pmtTime
Address of a variable to receive the converted time in MUSIC_TIME format.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_POINTER
DMUS_E_NO_MASTER_CLOCK

Remarks

If a master tempo has been set for the performance, it is taken into account when converting to music time. See Setting and Retrieving Global Parameters.

Because music time is less precise than reference time, rounding off occurs.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::MusicToReferenceTime, Clock Time vs. Music Time


IDirectMusicPerformance::RemoveNotificationType

The IDirectMusicPerformance::RemoveNotificationType method removes a previously added notification type from the performance. All segments and tracks are updated by a call to their RemoveNotificationType methods.

HRESULT RemoveNotificationType(
  REFGUID rguidNotificationType
);

Parameters

rguidNotificationType
Reference to (C++) or address of (C) the identifier of the notification type to remove. (For the defined types, see DMUS_NOTIFICATION_PMSG.) If this value is GUID_NULL, all notifications are to be removed.

Return Values

If the method succeeds, the return value is S_OK or S_FALSE (see Remarks).

If it fails, the method can return E_POINTER.

Remarks

S_FALSE is returned when rguidNotificationType is not an active notification.

If a notification was added to a segment that has stopped playing, the performance cannot remove the notification type from that segment because it no longer has a reference to the segment.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::AddNotificationType, IDirectMusicSegment::RemoveNotificationType, IDirectMusicTrack::RemoveNotificationType, Notification and Event Handling


IDirectMusicPerformance::RemovePort

The IDirectMusicPerformance::RemovePort method removes a port from the performance. Any PChannels that map to this port are invalidated, and messages stamped with them do not play.

HRESULT RemovePort(
  IDirectMusicPort* pPort
);

Parameters

pPort
Port to remove.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_INVALIDARG
E_POINTER

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::AddPort


IDirectMusicPerformance::RhythmToTime

The IDirectMusicPerformance::RhythmToTime method converts rhythm time to music time.

HRESULT RhythmToTime(
  WORD wMeasure,
  BYTE bBeat,
  BYTE bGrid,
  short nOffset,
  DMUS_TIMESIGNATURE *pTimeSig,
  MUSIC_TIME *pmtTime)
);

Parameters

wMeasure
Measure of the time to convert.
bBeat
Beat of the time to convert.
bGrid
Grid of the time to convert.
nOffset
Offset from the grid, in music-time ticks, of the time to convert.
pTimeSig
Address of a DMUS_TIMESIGNATURE structure containing information about the time signature.
pmtTime
Address of a variable to receive the music time.

Return Values

If the method succeeds, the return value is S_OK.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::TimeToRhythm


IDirectMusicPerformance::SendPMsg

The IDirectMusicPerformance::SendPMsg method sends a performance message. This method is called by tracks when they are played. It might also be called by a tool to inject new data into a performance.

HRESULT SendPMsg(
  DMUS_PMSG* pPMSG
);

Parameters

pPMSG
Message allocated by IDirectMusicPerformance::AllocPMsg.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_NO_MASTER_CLOCK
DMUS_E_ALREADY_SENT
E_INVALIDARG
E_POINTER

Remarks

The dwFlags member (see DMUS_PMSG) must contain either DMUS_PMSGF_MUSICTIME or DMUS_PMSGF_REFTIME, depending on the time stamp in either rtTime or mtTime. The dwFlags member should also contain the appropriate delivery type—DMUS_PMSGF_TOOL_QUEUE, DMUS_PMSGF_TOOL_ATTIME, or DMUS_PMSGF_TOOL_IMMEDIATE—depending on the type of message. If none is selected, DMUS_PMSGF_TOOL_IMMEDIATE is used by default.

If the time of the message is set to 0 and the dwFlags member contains DMUS_PMSGF_REFTIME, it is assumed that this message is cued to go out immediately

In most cases, the IDirectMusicGraph::StampPMsg method should be called on the message before SendPMsg is called. However, when sending a message directly to the main output tool, this step can be skipped. If you want the message to pass only through the performance graph, obtain the IDirectMusicGraph interface by calling IDirectMusicPerformance::QueryInterface. Otherwise, obtain it by calling IDirectMusicSegment::QueryInterface. Do not attempt to obtain the interface by calling IDirectMusicPerformance::GetGraph or IDirectMusicSegment::GetGraph; these methods return a pointer to the graph object, rather than to the implementation of the IDirectMusicGraph interface on the performance or segment.

Normally, the performance frees the message after it has been processed. For more information, see the Remarks for IDirectMusicPerformance::FreePMsg.

The follow code example shows how to allocate and send a system-exclusive message and a tempo message:

/* Assume that pPerformance is a valid IDirectMusicPerformance
   pointer and that mtTime is an initialized MUSIC_TIME
   variable. */

IDirectMusicGraph* pGraph;

/# Get the graph pointer from the performance. If you wanted the
   message to go through a segment graph, you would
   QueryInterface a segment object instead. */

if ( SUCCEEDED( pPerformance->QueryInterface(
        IID_IDirectMusicGraph, (void**)&pGraph )))
{
    // Allocate a DMUS_SYSEX_PMSG of the appropriate size,
    // and read the system-exclusive data into it.

    DMUS_SYSEX_PMSG* pSysEx;

    if ( SUCCEEDED( pPerformance->AllocPMsg(
            sizeof(DMUS_SYSEX_PMSG) + m_dwSysExLength,
            (DMUS_PMSG**)&pSysEx )))
    {
        // All fields are initialized to 0 from the
        // AllocPMsg method.
        // Assume that m_pbSysExData is a pointer to an array
        // containing data of length m_dwSysExLength.

        memcpy( pSysEx->abData, m_pbSysExData, m_dwSysExLength );
        pSysEx->dwSize = sizeof(DMUS_SYSEX_PMSG);
        pSysEx->dwLen = dwSysExLength;
        pSysEx->mtTime = mtTime;
        pSysEx->dwFlags = DMUS_PMSGF_MUSICTIME;
        pSysEx->dwType = DMUS_PMSGT_SYSEX;

        pGraph->StampPMsg( (DMUS_PMSG*)pSysEx );
        if (FAILED(pPerformance->SendPMsg( (DMUS_PMSG*)pSysEx )))
        {
            pPerformance->FreePMsg( (DMUS_PMSG*)pSysEx );
        }
    }

    // Change the tempo at time mtTime to 120 bpm.

    DMUS_TEMPO_PMSG* pTempo;

    if( SUCCEEDED( pPerformance->AllocPMsg(
            sizeof(DMUS_TEMPO_PMSG),
            (DMUS_PMSG**)&pTempo )))
    {
        pTempo->dwSize = sizeof(DMUS_TEMPO_PMSG);
        pTempo->dblTempo = 120;
        pTempo->mtTime = mtTime;
        pTempo->dwFlags = DMUS_PMSGF_MUSICTIME;
        pTempo->dwType = DMUS_PMSGT_TEMPO;
        pGraph->StampPMsg( (DMUS_PMSG*)pTempo );
        if (FAILED(pPerformance->SendPMsg( (DMUS_PMSG*)pTempo )))
        {
            pPerformance->FreePMsg( (DMUS_PMSG*)pTempo );
        }
    }

    pGraph->Release();
}

The next code example shows a function that sends a note message associated with the track identified by dwTrackID. The virtual track ID should be 0 if the message is not being generated from a DirectMusicTrack object.

HRESULT CreateNotePMsg(IDirectMusicPerformance* pPerformance,
        MUSIC_TIME mtTime, DWORD dwTrackID)
{

    // Allocate a Note PMessage.
    DMUS_NOTE_PMSG* pNote = NULL;
    HRESULT hr = pPerformance->AllocPMsg( sizeof(DMUS_NOTE_PMSG),
            (DMUS_PMSG**) &pNote);
    if (FAILED(hr)) return hr;

    pNote->dwSize = sizeof(DMUS_NOTE_PMSG); // Size of a Note PMessage
    pNote->rtTime = 0;                      // Ignored
    pNote->mtTime = mtTime;                 // When to play the note
    pNote->dwFlags = DMUS_PMSGF_MUSICTIME;  // Use the mtTime field.
    pNote->dwPChannel = 5;                  // Play on PChannel 5.
    pNote->dwVirtualTrackID = dwTrackID;    // Track ID from parameter.

    // The following two fields should be set to NULL when a
    // message is initially sent. They will be updated in
    // IDirectMusicGraph::StampPMsg.
    pNote->pTool = NULL;
    pNote->pGraph = NULL;
    pNote->dwType = DMUS_PMSGT_NOTE;
    pNote->dwVoiceID = 0;           // For DirectX 6.1, always 0
    pNote->dwGroupID = 0xFFFFFFFF;  // All track groups
    pNote->punkUser = NULL;         // Always NULL

    // Get the current time signature from the performance
    // to compute measure and beat information.
    DMUS_TIMESIGNATURE TimeSig;
    MUSIC_TIME mtNext;
    hr = pPerformance->GetParam(GUID_TimeSignature, 0xFFFFFFFF,
            0, mtTime, &mtNext, &TimeSig);
    if (FAILED(hr)) return hr;

    // Recompute TimeSig.mtTime to have the value expected
    // by pPerformance->TimeToRhythm.
    TimeSig.mtTime += mtTime;

    // Get the current chord from the performance
    // to create a note value.
    DMUS_CHORD_KEY Chord;
    hr = pPerformance->GetParam(GUID_ChordParam, 0xFFFFFFFF, 0,
            mtTime, &mtNext, &Chord);
    if (FAILED(hr)) return hr;

    // Create a note with octave 5, chord tone 2 (fifth), scale
    // offset 1 (=> sixth), and no accidentals.
    WORD wMusicValue = 0x5210;

    // Use DMUS_PLAYMODE_PEDALPOINT as your play mode
    // in pPerformance->MusicToMIDI.
    BYTE bPlayModeFlags = DMUS_PLAYMODE_PEDALPOINT;

    // Fill in the fields specific to DMUS_NOTE_PMSG.
    pNote->wMusicValue = wMusicValue;
    hr = pPerformance->MusicToMIDI(
        wMusicValue,
        &Chord,
        bPlayModeFlags,
        0,
        &(pNote->bMidiValue));
    if (FAILED(hr)) return hr;

    hr = pPerformance->TimeToRhythm(
        TimeSig.mtTime,
        &TimeSig,
        &(pNote->wMeasure),
        &(pNote->bBeat),
        &(pNote->bGrid),
        &(pNote->nOffset));
    if (FAILED(hr)) return hr;

    pNote->mtDuration = DMUS_PPQ;       // Quarter note duration
    pNote->bVelocity = 120;             // MIDI velocity (0 to 127)
    pNote->bFlags = DMUS_NOTEF_NOTEON;  // Always set to this value.
    pNote->bTimeRange = 250;            // Randomize start time a lot.
    pNote->bDurRange = 5;               // Randomize duration a little.
    pNote->bVelRange = 0;               // Don't randomize velocity.
    pNote->bPlayModeFlags = bPlayModeFlags;
    pNote->bSubChordLevel = 0;          // Note uses subchord level 0.
    pNote->cTranspose = 0;              // No transposition

    // Stamp the message with the performance graph.
    IDirectMusicGraph* pGraph;
    hr = pPerformance->QueryInterface( IID_IDirectMusicGraph,
            (void**)&pGraph );
    if (FAILED(hr)) return hr;

    pGraph->StampPMsg( (DMUS_PMSG*)pNote );
    pGraph->Release();

    // Finally, send the message.
    hr = pPerformance->SendPMsg( (DMUS_PMSG*)pNote);
    if (FAILED(hr))
    {
        pPerformance->FreePMsg( (DMUS_PMSG*)pNote);
        return hr;
    }

    return S_OK;

}

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicTool::ProcessPMsg, Messages, DirectMusic Messages, DirectMusic Tools


IDirectMusicPerformance::SetBumperLength

The IDirectMusicPerformance::SetBumperLength method sets the amount of time to buffer ahead of the port's latency for messages to be sent to the port for rendering. For an overview of this topic, see Timing.

HRESULT SetBumperLength(
  DWORD dwMilliSeconds
);

Parameters

dwMilliSeconds
Amount of preplay time, in milliseconds. The default value is 50.

Return Values

The method returns S_OK.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::GetBumperLength, IDirectMusicPerformance::SetPrepareTime


IDirectMusicPerformance::SetGlobalParam

The IDirectMusicPerformance::SetGlobalParam method sets global values for the performance.

HRESULT SetGlobalParam(
  REFGUID rguidType,
  void* pParam,
  DWORD dwSize
);

Parameters

rguidType
Reference to (C++) or address of (C) the identifier of the type of data.
pParam
Pointer to the data to be copied and stored by the performance.
dwSize
Size of the data. This is constant for each rguidType.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_FAIL
E_POINTER
E_OUTOFMEMORY

Remarks

The dwSize parameter is needed because the performance does not know about all types of data. New types can be created as needed.

For the parameters defined by DirectMusic and their associated data types, see Setting and Retrieving Global Parameters.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::GetGlobalParam, IDirectMusicPerformance::SetParam, Music Parameters


IDirectMusicPerformance::SetGraph

The IDirectMusicPerformance::SetGraph method replaces the performance's tool graph.

HRESULT SetGraph(
  IDirectMusicGraph* pGraph
);

Parameters

pGraph
Tool graph to be set. Can be set to NULL to clear the graph from the performance.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

Any messages flowing through tools in the current tool graph are deleted.

The graph's reference count is incremented by this method, so it is safe to release the original reference.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicSegment::SetGraph, IDirectMusicPerformance::GetGraph, IDirectMusicPerformance::SendPMsg


IDirectMusicPerformance::SetNotificationHandle

The IDirectMusicPerformance::SetNotificationHandle method sets the event handle (created by the Microsoft® Win32® CreateEvent function) for notifications. The application should use the Win32 WaitForSingleObject function on this handle. When signaled, the application should call the IDirectMusicPerformance::GetNotificationPMsg method to retrieve the notification event.

HRESULT SetNotificationHandle(
  HANDLE hNotification,
  REFERENCE_TIME rtMinimum
);

Parameters

hNotification
Event handle created by CreateEvent, or 0 to clear out an existing handle.
rtMinimum
Minimum time that the performance should hold onto old notify events before discarding them. The value 0 means to use the default minimum time of 20,000,000 reference time units, which is 2 seconds, or the previous value if this method has been called previously. If the application has not called GetNotificationPMsg by this time, the event is discarded to free the memory.

Return Values

The method returns S_OK.

Remarks

It is the application's responsibility to call the Win32 CloseHandle function on the notification handle when it is no longer needed.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

Notification and Event Handling


IDirectMusicPerformance::SetParam

The IDirectMusicPerformance::SetParam method sets data on a track inside the control segment.

HRESULT SetParam(
  REFGUID rguidType,
  DWORD dwGroupBits,
  DWORD dwIndex,
  MUSIC_TIME mtTime,
  void* pParam
);

Parameters

rguidType
Reference to (C++) or address of (C) the identifier of the type of data to set. See Track Parameter Types.
dwGroupBits
Group that the desired track is in.
dwIndex
Index of the track in the group identified by dwGroupBits in which data is to be set.
mtTime
Time at which to set the data. Unlike IDirectMusicSegment::SetParam, this time is in performance time. The start time of the segment is subtracted from this time, and the result is passed to IDirectMusicSegment::SetParam.
pParam
Address of a structure containing the data. This structure must be of the appropriate kind and size for the data type identified by rguidType.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_NO_MASTER_CLOCK
DMUS_E_SET_UNSUPPORTED
DMUS_E_TRACK_NOT_FOUND
E_POINTER

Remarks

Normally the primary segment is the control segment. However, a secondary segment can be designated as the control segment when it is played. See DMUS_SEGF_FLAGS.

For an explanation of dwGroupBits and dwIndex, see Identifying the Track.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::GetParam, IDirectMusicPerformance::SetGlobalParam, IDirectMusicSegment::SetParam, IDirectMusicTrack::SetParam, IDirectMusicPerformance::GetTime, Music Parameters


IDirectMusicPerformance::SetPrepareTime

The IDirectMusicPerformance::SetPrepareTime method sets the interval between the time that the IDirectMusicTrack::Play method is called and the time at which the messages should be heard through the speakers.

HRESULT SetPrepareTime(
  DWORD dwMilliSeconds
);

Parameters

dwMilliSeconds
Amount of prepare time, in milliseconds. The default value is 1000.

Return Values

The method returns S_OK.

Remarks

For an overview, see Timing.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::GetPrepareTime, IDirectMusicPerformance::SetBumperLength


IDirectMusicPerformance::Stop

The IDirectMusicPerformance::Stop method stops playback of one or more segments.

HRESULT Stop(
  IDirectMusicSegment* pSegment,
  IDirectMusicSegmentState* pSegmentState,
  MUSIC_TIME mtTime,
  DWORD dwFlags
);

Parameters

pSegment
Segment to stop playing. All segment states based on this segment are stopped at mtTime. See Remarks.
pSegmentState
Segment state to stop playing. See Remarks.
mtTime
Time at which to stop the segment, segment state, or both. If the time is in the past or 0 is passed in this parameter, the requested segments and segment states stop playing immediately.
dwFlags
Flag that indicates when the stop should occur. Boundaries are in relation to the current primary segment. Must be one of the following values:
0
Stop immediately.
DMUS_SEGF_GRID
Stop on the next grid boundary at or after mtTime.
DMUS_SEGF_MEASURE
Stop on the next measure boundary at or after mtTime.
DMUS_SEGF_BEAT
Stop on the next beat boundary at or after mtTime.
DMUS_SEGF_DEFAULT
Stop on the default boundary, as set by the IDirectMusicSegment::SetDefaultResolution method.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

If pSegment and pSegmentState are both NULL, all music stops, and all currently cued segments are released. If either pSegment or pSegmentState is not NULL, only the requested segment states are removed from the performance. If both are non-NULL and DMUS_SEGF_DEFAULT is used, the default resolution from the pSegment is used.

If you set all parameters to NULL or 0, everything stops immediately, and controller reset messages and note-off messages are sent to all mapped PChannels.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::PlaySegment, DMUS_SEGF_FLAGS


IDirectMusicPerformance::TimeToRhythm

The IDirectMusicPerformance::TimeToRhythm method converts music time to rhythm time.

HRESULT TimeToRhythm(
  MUSIC_TIME mtTime,
  DMUS_TIMESIGNATURE *pTimeSig,
  WORD *pwMeasure,
  BYTE *pbBeat,
  BYTE *pbGrid,
  short *pnOffset
);

Parameters

mtTime
Time to convert.
pTimeSig
Address of a DMUS_TIMESIGNATURE structure that contains information about the time signature.
pwMeasure
Address of a variable to receive the measure in which the time falls.
pbBeat
Address of a variable to receive the beat at which the time falls.
pbGrid
Address of a variable to receive the grid at which the time falls.
pnOffset
Address of a variable to receive the offset from the grid (in music-time ticks) at which the time falls.

Return Values

If the method succeeds, the return value is S_OK.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::RhythmToTime


IDirectMusicPort

The IDirectMusicPort interface provides access to a DirectMusicPort object, which represents a device that sends or receives music data. The input port of an MPU-401, the output port of an MPU-401, the Microsoft Software Synthesizer, and an IHV-provided filter are all ports. A physical device such as an MPU-401 might provide multiple ports. A single port, however, cannot both capture and render data.

For an overview, see Using Ports.

The methods of the IDirectMusicPort interface can be organized into the following groups:

Buffers | PlayBuffer
 | Read
 | SetReadNotificationHandle
Channels | GetChannelPriority
 | GetNumChannelGroups
 | SetChannelPriority
 | SetNumChannelGroups
Device management | Activate
 | DeviceIoControl
 | SetDirectSound
Information | GetCaps
 | GetFormat
 | GetLatencyClock
 | GetRunningStats
Downloadable sounds | Compact
 | DownloadInstrument
 | UnloadInstrument

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECTMUSICPORT type is defined as a pointer to the IDirectMusicPort interface:

typedef IDirectMusicPort *LPDIRECTMUSICPORT;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.


IDirectMusicPort::Activate

The IDirectMusicPort::Activate method activates or deactivates the port.

HRESULT Activate(
  BOOL fActive
);

Parameters

fActive
Switch to activate (TRUE) or deactivate (FALSE) the port.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return DSERR_NODRIVER, indicating that no sound driver is present.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

IDirectMusic::Activate, Using Ports


IDirectMusicPort::Compact

The IDirectMusicPort::Compact method is used to instruct the port to compact DLS or wave-table memory, thus making the largest possible contiguous chunk of memory available for new instruments to be downloaded.

HRESULT Compact();

Parameters

None.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_FAIL
E_INVALIDARG
E_NOTIMPL
E_OUTOFMEMORY

Remarks

This method only affects DLS devices that need to manage their own DLS wavetable memory. On ports that do not manage their own memory (such as software synthesizers or hardware synthesizers that utilize host system memory), the method will return E_NOTIMPL.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.


IDirectMusicPort::DeviceIoControl

The IDirectMusicPort::DeviceIoControl method calls the Win32 DeviceIoControl function on the underlying file handle implementing the port.

HRESULT DeviceIoControl(
  DWORD dwIoControlCode,
  LPVOID lpInBuffer,
  DWORD nInBufferSize,
  LPVOID lpOutBuffer,
  DWORD nOutBufferSize,
  LPDWORD lpBytesReturned,
  LPOVERLAPPED lpOverlapped
);

Parameters

dwIoControlCode
Control code of the operation to perform.
lpInBuffer
Pointer to the buffer that contains input data.
nInBufferSize
Size of input buffer.
lpOutBuffer
Pointer to the buffer to receive output data.
nOutBufferSize
Size of the output buffer.
lpBytesReturned
Address of a variable to receive the output byte count.
lpOverlapped
Address of an overlapped structure for asynchronous operation.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_POINTER
E_NOTIMPL

Remarks

This method is supported only on ports implemented by a Windows Driver Model (WDM) filter graph. In the case of a WDM filter graph, the file handle used is the topmost pin in the graph.

DirectMusic can refuse to perform defined kernel streaming operations on a pin that might collide with operations that it is performing on the filter graph. User-defined operations, however, are never blocked.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.


IDirectMusicPort::DownloadInstrument

The IDirectMusicPort::DownloadInstrument method is used to download an instrument to the DLS device. Downloading an instrument means handing the data that makes up the instrument to the DLS device. This includes articulation data and all waves needed by the instrument. To save wave space, only waves and articulation required for a range are downloaded. The method returns an IDirectMusicDownloadedInstrument interface pointer, which is later used to unload the instrument.

HRESULT DownloadInstrument(
  IDirectMusicInstrument *pInstrument,
  IDirectMusicDownloadedInstrument **ppDownloadedInstrument,
  DMUS_NOTERANGE *pNoteRanges,
  DWORD dwNumNoteRanges;
  );

Parameters

pInstrument
Instrument from which the method extracts the data to be downloaded.
ppDownloadedInstrument
Address of a variable to receive a pointer to the IDirectMusicDownloadedInstrument interface.
pNoteRanges
Address of an array of DMUS_NOTERANGE structures. Each entry in the array specifies a contiguous range of MIDI note messages to which the instrument must respond. An instrument region is downloaded only if at least one note in that region is specified in the DMUS_NOTERANGE structures.
dwNumNoteRanges
Number of DMUS_NOTERANGE structures in the array pointed to by pNoteRanges. If this value is set to 0, the pNoteRanges parameter is ignored, and all regions and wave data for the instrument are downloaded.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_POINTER
E_OUTOFMEMORY
E_NOTIMPL

Remarks

To prevent memory loss, the instrument must be unloaded by calling both IDirectMusicPort::UnloadInstrument and IDirectMusicDownloadedInstrument::Release when it is no longer needed.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

IDirectMusicPort::Compact, Working with Instruments


IDirectMusicPort::GetCaps

The IDirectMusicPort::GetCaps method retrieves the port's capabilities.

HRESULT GetCaps(
  LPDMUS_PORTCAPS pPortCaps
);

Parameters

pPortCaps
Address of a DMUS_PORTCAPS structure to receive the capabilities of the port. The dwSize member of this structure must be properly initialized before the method is called.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_POINTER
E_INVALIDARG

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.


IDirectMusicPort::GetChannelPriority

The IDirectMusicPort::GetChannelPriority method is used to retrieve the priority of a MIDI channel. For an overview, see Channels.

HRESULT GetChannelPriority(
  DWORD   dwChannelGroup,
  DWORD   dwChannel,
  LPDWORD pdwPriority
);

Parameters

dwChannelGroup
Group that the channel is in.
dwChannel
Index of the channel on the group.
pdwPriority
Address of a variable to receive the priority ranking. See Remarks.

Return Values

If the method succeeds, the return value is S_OK.

Remarks

The following values, defined in Dmusicc.h, each represent a range of priorities. They are listed here in descending order of priority.

DAUD_CRITICAL_VOICE_PRIORITY
DAUD_HIGH_VOICE_PRIORITY
DAUD_STANDARD_VOICE_PRIORITY
DAUD_LOW_VOICE_PRIORITY

The following values express the default ranking of the channels within a range, according to the DLS Level 1 standard. They are listed here in descending order. Channel 10, the percussion channel, has the highest priority.

DAUD_CHAN10_DEF_VOICE_PRIORITY_OFFSET
DAUD_CHAN1_DEF_VOICE_PRIORITY_OFFSET
DAUD_CHAN2_DEF_VOICE_PRIORITY_OFFSET
DAUD_CHAN3_DEF_VOICE_PRIORITY_OFFSET
DAUD_CHAN4_DEF_VOICE_PRIORITY_OFFSET
DAUD_CHAN5_DEF_VOICE_PRIORITY_OFFSET
DAUD_CHAN6_DEF_VOICE_PRIORITY_OFFSET
DAUD_CHAN7_DEF_VOICE_PRIORITY_OFFSET
DAUD_CHAN8_DEF_VOICE_PRIORITY_OFFSET
DAUD_CHAN9_DEF_VOICE_PRIORITY_OFFSET
DAUD_CHAN11_DEF_VOICE_PRIORITY_OFFSET
DAUD_CHAN12_DEF_VOICE_PRIORITY_OFFSET
DAUD_CHAN13_DEF_VOICE_PRIORITY_OFFSET
DAUD_CHAN14_DEF_VOICE_PRIORITY_OFFSET
DAUD_CHAN15_DEF_VOICE_PRIORITY_OFFSET
DAUD_CHAN16_DEF_VOICE_PRIORITY_OFFSET

The priority of a channel is represented by a range plus an offset. For example, DAUD_STANDARD_VOICE_PRIORITY plus DAUD_CHAN10_DEF_VOICE_PRIORITY represents the highest priority within the standard range.

Channels that have the same priority value have equal priority, regardless of which channel group they belong to.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

IDirectMusicPort::SetChannelPriority


IDirectMusicPort::GetFormat

The IDirectMusicPort::GetFormat method retrieves information about the wave format specified in the DMUS_PORTPARAMS structure passed to IDirectMusic::CreatePort, and the recommended size of the buffer to use for wave output. The information can be used to create a compatible IDirectSoundBuffer for the port.

HRESULT GetFormat(
  LPWAVEFORMATEX pWaveFormatEx,
  LPDWORD pdwWaveFormatExSize
  LPDWORD pdwBufferSize
);

Parameters

pWaveFormatEx
Address of the WAVEFORMATEX structure to receive information about the format. This value can be NULL. See Remarks.
pdwWaveFormatExSize
Address of a variable that contains, or is to receive, the size of the structure. See Remarks.
pdwBufferSize
Address of a variable to receive the recommended size of the DirectSound buffer.

Return Values

Return values are determined by the implementation. If the method succeeds, it returns S_OK.

If it fails, the method can return E_POINTER.

Remarks

The WAVEFORMATEX structure can have a variable length that depends on the details of the format. Before retrieving the format description, the application should query the synthesizer object for the size of the format by calling this method and specifying NULL for the pWaveFormatEx parameter. The size of the structure is returned in the variable pointed to by pdwWaveFormatExSize. The application can then allocate sufficient memory and call GetFormat again to retrieve the format description.

If pWaveFormatEx is not NULL, DirectMusic writes, at most, pdwWaveFormatExSize bytes to the structure.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

IDirectMusicPort::SetDirectSound


IDirectMusicPort::GetLatencyClock

The IDirectMusicPort::GetLatencyClock method is used to get an IReferenceClock interface pointer to the port's latency clock. The latency clock specifies the nearest time in the future at which a message can be played on time. The latency clock is based on the DirectMusic master clock, which is set by using the IDirectMusic::SetMasterClock method.

HRESULT GetLatencyClock(
  IReferenceClock** ppClock
);

Parameters

ppClock
Address of a variable to receive the latency clock's IReferenceClock interface pointer.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

In accordance with COM rules, GetLatencyClock increments the reference count of the returned interface. Therefore, the application must call Release on the IReferenceClock interface at some point.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

Latency and Bumper Time


IDirectMusicPort::GetNumChannelGroups

The IDirectMusicPort::GetNumChannelGroups method retrieves the number of channel groups on the port.

HRESULT GetNumChannelGroups
  LPDWORD pdwChannelGroups
);

Parameters

pdwChannelGroups
Address of a variable to receive the number of channel groups.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_FAIL
E_INVALIDARG
E_NOTIMPL
E_OUTOFMEMORY

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

IDirectMusicPort::SetNumChannelGroups, Channels


IDirectMusicPort::GetRunningStats

The IDirectMusicPort::GetRunningStats method retrieves information about the state of the port's synthesizer.

HRESULT GetRunningStats(
  LPDMUS_SYNTHSTATS pStats
);

Parameters

pStats
Address of a DMUS_SYNTHSTATS structure to receive running statistics of the synthesizer. The dwSize member of this structure must be properly initialized before the method is called.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_POINTER
E_INVALIDARG
E_NOTIMPL

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.


IDirectMusicPort::PlayBuffer

The IDirectMusicPort::PlayBuffer method is used to cue a buffer for playback by the port.

HRESULT PlayBuffer(
  IDIRECTMUSICBUFFER* pBuffer
);

Parameters

pBuffer
Address of a DirectMusicBuffer object to be added to the port's playback queue.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_FAIL
E_INVALIDARG
E_NOTIMPL
E_OUTOFMEMORY

Remarks

The buffer is in use by the system only for the duration of this method and can be reused after the method returns.

If no start time has been set by using the IDirectMusicBuffer::SetStartTime method, the start time is the time of the earliest event in the buffer, as set by the IDirectMusicBuffer::PackStructured or the IDirectMusicBuffer::PackUnstructured method.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

IDirectMusicBuffer, IDirectMusic::CreateMusicBuffer


IDirectMusicPort::Read

The IDirectMusicPort::Read method fills a buffer with incoming MIDI data. The method should be called with new buffer objects until no more data is available to be read.

HRESULT Read(
  IDirectMusicBuffer *pBuffer
);

Parameters

pBuffer
Address of a DirectMusicBuffer object to be filled with the incoming MIDI data.

Return Values

If the method succeeds, the return value is S_OK or S_FALSE.

If it fails, the method can return one of the following error values:

E_POINTER
E_NOTIMPL

Remarks

When there is no more data to read, the method returns S_FALSE.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

Capturing Music


IDirectMusicPort::SetChannelPriority

The IDirectMusicPort::SetChannelPriority method is used to set the priority of a MIDI channel. For an overview, see Channels.

HRESULT SetChannelPriority(
  DWORD  dwChannelGroup,
  DWORD  dwChannel,
  DWORD  dwPriority
);

Parameters

dwChannelGroup
Group that the channel is in. This value must be 1 or greater.
dwChannel
Index of the channel on the group.
dwPriority
The priority ranking. See Remarks for IDirectMusicPort::GetChannelPriority.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_FAIL
E_INVALIDARG
E_OUTOFMEMORY
E_NOTIMPL

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

IDirectMusicPort::GetChannelPriority, DMUS_CHANNEL_PRIORITY_PMSG.


IDirectMusicPort::SetDirectSound

The IDirectMusicPort::SetDirectSound method is used to override the default DirectSound object or buffer, or both, to which a port's wave data is streamed. It is also used to disconnect the port from DirectSound.

HRESULT SetDirectSound(
  LPDIRECTSOUND pDirectSound,
  LPDIRECTSOUNDBUFFER pDirectSoundBuffer
);

Parameters

pDirectSound
Address of the IDirectSound interface of the DirectSound object to which the port is to be connected, or NULL to disconnect and release the existing DirectSound object.
pDirectSoundBuffer
Address of the IDirectSoundBuffer interface to connect the port to. This value can be NULL.

Return Values

If the method succeeds, the return value is S_OK or DMUS_S_NOBUFFERCONTROL. See Remarks.

If it fails, the method can return one of the following error values:

DMUS_E_ALREADY_ACTIVATED
E_INVALIDARG

Remarks

If a valid pointer is passed in pDirectSoundBuffer, the method returns DMUS_S_NOBUFFERCONTROL if control changes in the buffer such as pan and volume do not affect DirectMusic playback. This affects only WDM ports.

When the port is activated, the primary DirectSound buffer is upgraded, if necessary, to support the sample rate and channel information for this port (specified in the DMUS_PORTPARAMS structure passed to IDirectMusic::CreatePort).

The buffer pointed to by pDirectSoundBuffer must be a secondary streaming buffer with a format that matches the sample rate and channel information for this port. If this parameter is NULL, an appropriate IDirectSoundBuffer instance is created internally.

Neither the IDirectSound nor the IDirectSoundBuffer can be changed once the port has been activated.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

IDirectMusicPort::Activate, IDirectMusicPort::GetFormat, Integrating DirectMusic and DirectSound


IDirectMusicPort::SetNumChannelGroups

The IDirectMusicPort::SetNumChannelGroups method changes the number of channel groups that the application needs on the port.

HRESULT SetNumChannelGroups(
  DWORD dwChannelGroups
);

Parameters

dwChannelGroups
Number of channel groups on this port that the application wants to allocate.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_FAIL
E_INVALIDARG
E_NOTIMPL
E_OUTOFMEMORY

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

IDirectMusicPort::GetNumChannelGroups, Channels


IDirectMusicPort::SetReadNotificationHandle

The IDirectMusicPort::SetReadNotificationHandle method specifies an event that is to be set when MIDI messages are available to be read with the IDirectMusicPort::Read method. The event is signaled whenever new data is available. To turn off event notification, call SetReadNotificationHandle with a NULL value for the hEvent parameter.

HRESULT SetReadNotificationHandle(
  HANDLE hEvent
);

Parameters

hEvent
Event handle obtained from a call to the the Win32 CreateEvent function. It is the application's responsibility to close this handle once the port has been released.

Return Values

The method returns S_OK.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

Capturing Music


IDirectMusicPort::UnloadInstrument

The IDirectMusicPort::UnloadInstrument method is used to unload a previously downloaded DLS instrument.

HRESULT UnloadInstrument(
  IDirectMusicDownloadedInstrument *pDownloadedInstrument
);

Parameters

pDownloadedInstrument
Address of an IDirectMusicDownloadedInstrument interface, obtained when the instrument was downloaded by calling the IDirectMusicPort::DownloadInstrument method.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_NOT_DOWNLOADED_TO_PORT
E_POINTER
E_NOTIMPL

Remarks

This method must be called to free memory allocated by IDirectMusicPort::DownloadInstrument.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

Working with Instruments


IDirectMusicPortDownload

The IDirectMusicPortDownload interface allows an application to communicate directly with a port that supports DLS downloading and to download memory chunks directly to the port. The interface is used primarily by authoring applications that edit DLS instruments directly. For an overview, see Low-Level DLS.

To obtain the IDirectMusicPortDownload interface, call the IDirectMusicPort::QueryInterface method, passing in IID_IDirectMusicPortDownload as the interface GUID. If the port does not support DLS downloading, this call might fail.

The methods of the IDirectMusicPortDownload interface can be grouped as follows:

Buffer management | AllocateBuffer
 | GetAppend
 | GetBuffer
 | GetDLId
Loading | Download
 | Unload

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.


IDirectMusicPortDownload::AllocateBuffer

The IDirectMusicPortDownload::AllocateBuffer method allocates a chunk of memory for downloading DLS data to the port and returns an IDirectMusicDownload interface pointer that allows access to this buffer.

HRESULT AllocateBuffer(
  DWORD dwSize,
  IDirectMusicDownload** ppIDMDownload
);

Parameters

dwSize
Requested size of buffer.
ppIDMDownload
Address of a variable to receive the IDirectMusicDownload interface pointer.

Return Values

If the method succeeds, it returns S_OK.

If it fails, the method can return one of the following error values:

E_POINTER
E_INVALIDARG
E_OUTOFMEMORY

Remarks

Once a buffer has been allocated, its size cannot change.

The buffer is freed when the IDirectMusicDownload interface is released.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

IDirectMusicPortDownload::GetBuffer, Low-Level DLS


IDirectMusicPortDownload::Download

The IDirectMusicPortDownload::Download method downloads a wave or instrument definition to the port. The memory must first be allocated by using the IDirectMusicPortDownload::AllocateBuffer method.

HRESULT Download(
  IDirectMusicDownload* pIDMDownload
);

Parameters

pIDMDownload
Address of the IDirectMusicDownload interface for the buffer.

Return Values

Return values are determined by the implementation of the port.

If the method succeeds, it returns S_OK.

If the method fails, it can return one of the following values:

E_POINTER
E_FAIL
DMUS_E_ALREADY_DOWNLOADED
DMUS_E_BADARTICULATION
DMUS_E_BADINSTRUMENT
DMUS_E_BADOFFSETTABLE
DMUS_E_BADWAVE
DMUS_E_BADWAVELINK
DMUS_E_BUFFERNOTSET
DMUS_E_NOARTICULATION
DMUS_E_NOTMONO
DMUS_E_NOTPCM
DMUS_E_UNKNOWNDOWNLOAD

Remarks

For more information on how to prepare the data to be downloaded, see Low-Level DLS.

Once the memory has been downloaded, you cannot do anything more with it. To update the download, you must create a new buffer and assign it a new download ID obtained by using the IDirectMusicPortDownload::GetDLId method, then send it down.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

IDirectMusicPortDownload::Unload, DMUS_DOWNLOADINFO, DMUS_OFFSETTABLE


IDirectMusicPortDownload::GetAppend

The IDirectMusicPortDownload::GetAppend method retrieves the amount of memory that the port needs to be appended to the end of a download buffer. This extra memory can be used by the port to interpolate across a loop boundary.

HRESULT GetAppend(
  DWORD* pdwAppend
);

Parameters

pdwAppend
Address of a variable to receive the number of appended samples for which memory is required. The amount of memory can be calculated from the wave format.

Return Values

Return values are determined by the port implementation.

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_POINTER
E_NOTIMPL

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.


IDirectMusicPortDownload::GetBuffer

The IDirectMusicPortDownload::GetBuffer method retrieves the IDirectMusicDownload interface pointer of a buffer whose unique identifier is known.

HRESULT GetBuffer(
  DWORD dwDLId,
  IDirectMusicDownload** ppIDMDownload
);

Parameters

dwDLId
Download identifier of the buffer. See DMUS_DOWNLOADINFO.
ppIDMDownload
Address of a variable to receive the IDirectMusicDownload interface pointer for the buffer.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_POINTER
DMUS_E_INVALID_DOWNLOADID
DMUS_E_NOT_DOWNLOADED_TO_PORT

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

IDirectMusicPortDownload::GetDLId, IDirectMusicDownload::GetBuffer, Low-Level DLS.


IDirectMusicPortDownload::GetDLId

The IDirectMusicPortDownload::GetDLId method obtains sequential identifiers for one or more download buffers.

Every memory chunk downloaded to the synthesizer must have a unique identifier placed in its DMUS_DOWNLOADINFO structure. The GetDLId method guarantees that no two downloads have the same identifier.

HRESULT GetDLId(
  DWORD* pdwStartDLId,
  DWORD dwCount
);

Parameters

pdwStartDLId
Address of a variable to receive the first identifier.
dwCount
Number of identifiers to reserve. You might plan to download a whole series of chunks at once. Instead of calling GetDLId for each chunk, set dwCount to the number of chunks. GetDLId returns the first ID of the set, and the additional identifiers are automatically reserved up through *pdwStartDLId plus dwCount. A subsequent call to GetDLId would skip past the reserved values.

Return Values

If the method succeeds, it returns S_OK.

If it fails, the method can return one of the following error values:

E_POINTER
E_INVALIDARG

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

IDirectMusicPortDownload::GetBuffer, Low-Level DLS


IDirectMusicPortDownload::Unload

The IDirectMusicPortDownload::Unload method unloads a buffer that was previously downloaded by using IDirectMusicPortDownload::Download.

HRESULT Unload(
  IDirectMusicDownload* pIDMDownload
);

Parameters

pIDMDownload
Address of the IDirectMusicDownload interface for the buffer.

Return Values

Return values are determined by the port implementation.

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following values:

E_NOINTERFACE
DMUS_E_SYNTHNOTCONFIGURED

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.


IDirectMusicSegment

The IDirectMusicSegment interface represents a segment, a chunk of music made up of multiple tracks. Because almost all the information that defines a segment is stored in the tracks, and because tracks can be nearly anything, the segment itself is a relatively simple object. There are methods to access data in tracks, even though the segment object has no knowledge of the nature of the data.

The DirectMusicSegment object also supports the IDirectMusicObject and IPersistStream interfaces for loading its data.

The methods of the IDirectMusicSegment interface can be grouped as follows:

Timing and looping | GetDefaultResolution
 | GetLength
 | GetLoopPoints
 | GetRepeats
 | GetStartPoint
 | SetDefaultResolution
 | SetLength
 | SetLoopPoints
 | SetRepeats
 | SetStartPoint
Tracks | GetTrack
 | GetTrackGroup
 | InsertTrack
 | RemoveTrack
Notification | AddNotificationType
 | RemoveNotificationType
Parameters | GetParam
 | SetParam
Tools | GetGraph
 | SetGraph
Miscellaneous | Clone
 | InitPlay
 | SetPChannelsUsed

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

Segments


IDirectMusicSegment::AddNotificationType

The IDirectMusicSegment::AddNotificationType method is similar to and called from the IDirectMusicPerformance::AddNotificationType method, allowing the segment to respond to notifications. The segment calls each track's IDirectMusicTrack::AddNotificationType method.

HRESULT AddNotificationType(
  REFGUID rguidNotificationType
);

Parameters

rguidNotificationType
Reference to (C++) or address of (C) the identifier of the notification type to add. For the defined types, see DMUS_NOTIFICATION_PMSG. Applications can also define their own types for custom tracks.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_POINTER
E_OUTOFMEMORY

Remarks

Segments cannot generate notifications of type GUID_NOTIFICATION_PERFORMANCE. To get notifications of this type, you must call IDirectMusicPerformance::AddNotificationType.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

Notification and Event Handling


IDirectMusicSegment::Clone

The IDirectMusicSegment::Clone method copies all or part of the segment and the tracks that it contains.

HRESULT Clone(
  MUSIC_TIME mtStart,
  MUSIC_TIME mtEnd,
  IDirectMusicSegment** ppSegment
);

Parameters

mtStart
Start of the part to copy. If less than 0 or greater than the length of the segment, 0 is used.
mtEnd
End of the part to copy. If this value is past the end of the segment, the segment is copied to the end. A value of 0 or anything less than mtStart also copies to the end.
ppSegment
Address of a variable to receive a pointer to the created segment, if successful. It is the caller's responsibility to call Release when finished with the segment.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if some tracks failed to copy.

If it fails, the method can return one of the following error values:

E_OUTOFMEMORY
E_POINTER

Remarks

If an IDirectMusicGraph interface exists in the segment, a copy of the pointer is included in the clone, and the reference count is incremented. The start point and loop points set by the IDirectMusicSegment::SetStartPoint and IDirectMusicSegment::SetLoopPoints methods are set to their default values (0, and 0 to the end of the segment, respectively) inside the clone. The number of repeats is also reset to 0. The resolution set by the IDirectMusicSegment::SetDefaultResolution method is copied into the clone.

For style-based segments, if mtStart is greater than 0, it should be on a measure boundary.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


IDirectMusicSegment::GetDefaultResolution

The IDirectMusicSegment::GetDefaultResolution method retrieves the default resolution for synchronization.

HRESULT GetDefaultResolution(
  DWORD* pdwResolution
);

Parameters

pdwResolution
Address of a variable to receive the default resolution. See DMUS_SEGF_FLAGS.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicSegment::SetDefaultResolution, Segment Timing


IDirectMusicSegment::GetGraph

The IDirectMusicSegment::GetGraph method retrieves the segment's tool graph.

HRESULT GetGraph(
  IDirectMusicGraph** ppGraph
);

Parameters

ppGraph
Address of a variable to receive a pointer to the tool graph.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_FAIL
E_POINTER

Remarks

If there is no graph in the segment, the method returns E_FAIL.

The reference count of the tool graph is incremented.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicSegment::SetGraph


IDirectMusicSegment::GetLength

The IDirectMusicSegment::GetLength method retrieves the length of the segment.

HRESULT GetLength(
  MUSIC_TIME* pmtLength
);

Parameters

pmtLength
Address of a variable to receive the segment's length in music time.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

If for some reason the segment's length was never set, *pmtLength is set to 0.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicSegment::SetLength


IDirectMusicSegment::GetLoopPoints

The IDirectMusicSegment::GetLoopPoints method retrieves the start and end loop points inside the segment that repeat the number of times set by the IDirectMusicSegment::SetRepeats method.

HRESULT GetLoopPoints(
  MUSIC_TIME* pmtStart,
  MUSIC_TIME* pmtEnd
);

Parameters

pmtStart
Address of a variable to receive the start point of the loop.
pmtEnd
Address of a variable to receive the end point of the loop. A value of 0 indicates that the entire segment loops.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicSegment::SetLoopPoints, Segment Timing


IDirectMusicSegment::GetParam

The IDirectMusicSegment::GetParam method retrieves data from a track inside this segment.

HRESULT GetParam(
  REFGUID rguidType,
  DWORD dwGroupBits,
  DWORD dwIndex,
  MUSIC_TIME mtTime,
  MUSIC_TIME* pmtNext,
  void* pParam
);

Parameters

rguidType
Reference to (C++) or address of (C) the identifier of the type of data to obtain. See Track Parameter Types.
dwGroupBits
Group that the desired track is in. Use 0xFFFFFFFF for all groups. For more information, see Identifying the Track.
dwIndex
Index of the track in the group identified by dwGroupBits from which to obtain the data.
mtTime
Time from which to obtain the data.
pmtNext
Address of a variable to receive the segment time (relative to mtTime) until which the data is valid. If this returns a value of 0, it means either that the data is always valid, or that it is unknown when it might become invalid. If this information is not needed, pmtNext can be set to NULL. See Remarks.
pParam
Address of an allocated structure in which the data is to be returned. The structure must be of the appropriate kind and size for the data type identified by rguidType.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_GET_UNSUPPORTED
DMUS_E_TRACK_NOT_FOUND
E_POINTER

Remarks

The data can become invalid before the time returned in *pmtNext if another control segment is cued. For more information on control segments, see Segments.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::GetParam, IDirectMusicSegment::SetParam, IDirectMusicTrack::GetParam, Music Parameters


IDirectMusicSegment::GetRepeats

The IDirectMusicSegment::GetRepeats method retrieves the number of times the looping portion of the segment is set to repeat.

HRESULT GetRepeats(
  DWORD* pdwRepeats
);

Parameters

pdwRepeats
Address of a variable to receive the number of times that the looping portion of the segment is set to repeat.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicSegment::SetRepeats


IDirectMusicSegment::GetStartPoint

The IDirectMusicSegment::GetStartPoint method retrieves the point at which the segment starts playing in response to the IDirectMusicPerformance::PlaySegment method.

HRESULT GetStartPoint(
  MUSIC_TIME* pmtStart
);

Parameters

pmtStart
Address of a variable to receive the time within the segment at which it starts playing.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicSegment::SetStartPoint


IDirectMusicSegment::GetTrack

The IDirectMusicSegment::GetTrack method searches the list of tracks for the one with the supplied type, group, and index, and retrieves a pointer to the DirectMusicTrack object.

HRESULT GetTrack(
  REFGUID rguidType,
  DWORD dwGroupBits,
  DWORD dwIndex,
  IDirectMusicTrack** ppTrack
);

Parameters

rguidType
Reference to (C++) or address of (C) the identifier of the track to find (for example, CLSID_DirectMusicChordTrack). A value of GUID_NULL retrieves any track. For the track identifiers, see IDirectMusicTrack.
dwGroupBits
Track groups in which to scan for the track. A value of 0 is invalid. Each bit in dwGroupBits corresponds to a track group. To scan all tracks, regardless of groups, set this parameter to 0xFFFFFFFF.
dwIndex
Zero-based index into the list of tracks of type rguidType and in group dwGroupBits to return. If multiple groups are selected in dwGroupBits, this index indicates the nth track of type rguidType encountered in the union of the groups selected.
ppTrack
Address of a variable to receive a pointer to the track. The variable is set to NULL if the track is not found.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_FAIL.

Remarks

To enumerate all tracks, use GUID_NULL for the rguidType and 0xFFFFFFFF for dwGroupBits. Call GetTrack starting with 0 for dwIndex, incrementing dwIndex until the method no longer returns a success code.

For more information on track groups, see Identifying the Track.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicSegment::InsertTrack


IDirectMusicSegment::GetTrackGroup

The IDirectMusicSegment::GetTrackGroup method retrieves the group bits set on a track inside the segment.

HRESULT GetTrackGroup(
  IDirectMusicTrack* pTrack,
  DWORD* pdwGroupBits
);

Parameters

pTrack
Track for which to find the group bits.
pdwGroupBits
Address of a variable to receive the groups. Each bit in *pdwGroupBits corresponds to a track group.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_FAIL
E_INVALIDARG

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicSegment::InsertTrack, Identifying the Track


IDirectMusicSegment::InitPlay

The IDirectMusicSegment::InitPlay method is called by the performance when the segment is about to be played.

HRESULT InitPlay(
  IDirectMusicSegmentState** ppSegState,
  IDirectMusicPerformance* pPerformance,
  DWORD dwFlags
);

Parameters

ppSegState
Address of a variable to receive a pointer to the IDirectMusicSegmentState interface, which is created in response to this method call and is used to hold state data. It is returned with a reference count of 1, so a call to its Release method fully releases it.
pPerformance
Address of the IDirectMusicPerformance interface. This is needed by the segment and segment state to call methods on the performance object.
dwFlags
DMUS_SEGF_FLAGS that modify the track's behavior. See Remarks.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_POINTER
E_OUTOFMEMORY

Remarks

This method is for internal use by DirectMusic and should not be called by applications. It will not be supported in future versions.

The InitPlay method is called by the performance engine when the segment is about to be played. The segment, in turn, collects state objects for each of the tracks by calling their IDirectMusicTrack::InitPlay methods and stores the result in a segment state object, accessed by using the IDirectMusicSegmentState interface.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


IDirectMusicSegment::InsertTrack

The IDirectMusicSegment::InsertTrack method inserts the supplied track into the segment's list of tracks.

HRESULT InsertTrack(
  IDirectMusicTrack* pTrack,
  DWORD dwGroupBits
);

Parameters

pTrack
Track to add to the segment.
dwGroupBits
Group or groups into which to insert the track. This value cannot be 0.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_FAIL
E_INVALIDARG
E_OUTOFMEMORY
E_POINTER

Remarks

Tracks are put in groups to link them correctly. For example, a segment might contain two style tracks and two mute tracks. Each style track would be put in a different group, along with its associated mute track. For more information on track groups, see Identifying the Track.

If the segment is currently playing, the new track is not included in playback because the segment state was not initialized with the new track.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicSegment::RemoveTrack, IDirectMusicSegment::GetTrackGroup


IDirectMusicSegment::RemoveNotificationType

The IDirectMusicSegment::RemoveNotificationType method is similar to and is called from the IDirectMusicPerformance::RemoveNotificationType method, allowing the segment to remove notifications. The segment calls each track's IDirectMusicTrack::RemoveNotificationType method.

HRESULT RemoveNotificationType(
  REFGUID rguidNotificationType
);

Parameters

rguidNotificationType
Reference to (C++) or address of (C) the identifier of the notification type to remove. (For the defined types, see DMUS_NOTIFICATION_PMSG.) Setting this value to GUID_NULL causes all notifications to be removed.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

Notification and Event Handling


IDirectMusicSegment::RemoveTrack

The IDirectMusicSegment::RemoveTrack method removes a track from the segment's track list.

HRESULT RemoveTrack(
  IDirectMusicTrack* pTrack
);

Parameters

pTrack
Track to remove from the segment's track list.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if the specified track is not in the track list.

If the method fails, the return value can be E_POINTER.

Remarks

The track is released when removed.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicSegment::InsertTrack


IDirectMusicSegment::SetDefaultResolution

The IDirectMusicSegment::SetDefaultResolution method sets the default resolution for synchronization.

HRESULT SetDefaultResolution(
  DWORD dwResolution
);

Parameters

dwResolution
Desired default resolution. This value can be 0 or one of the following members of the DMUS_SEGF_FLAGS enumeration:

DMUS_SEGF_MEASURE
DMUS_SEGF_BEAT
DMUS_SEGF_GRID

Return Values

The method returns S_OK.

Remarks

This method is used primarily by secondary segments (motifs) to define whether they are synchronized to the measure, beat, or grid resolutions.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicSegment::GetDefaultResolution, Segment Timing


IDirectMusicSegment::SetGraph

The IDirectMusicSegment::SetGraph method assigns a tool graph to the segment.

HRESULT SetGraph(
  IDirectMusicGraph* pGraph
);

Parameters

pGraph
Tool graph to be set. Can be set to NULL to clear the segment graph.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

Any messages flowing through tools in the current tool graph are deleted.

The graph's reference count is incremented, so it is safe to release the original reference.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::SetGraph, DirectMusic Tools


IDirectMusicSegment::SetLength

The IDirectMusicSegment::SetLength method sets the length, in music time, of the segment. This method is usually called by the loader, which retrieves the segment length from the file and passes it to the segment object.

HRESULT SetLength(
  MUSIC_TIME mtLength
);

Parameters

mtLength
Desired length. Must be greater than 0.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_INVALIDARG
DMUS_E_OUT_OF_RANGE

Remarks

Neglecting to set a primary segment length can cause problems when cuing other primary segments with the DMUS_SEGF_QUEUE flag.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicSegment::GetLength


IDirectMusicSegment::SetLoopPoints

The IDirectMusicSegment::SetLoopPoints method sets the start and end points of the part of the segment that repeats. It repeats the number of times set by the IDirectMusicSegment::SetRepeats method.

HRESULT SetLoopPoints(
  MUSIC_TIME mtStart,
  MUSIC_TIME mtEnd
);

Parameters

mtStart
Point at which to begin the loop.
mtEnd
Point at which to end the loop. A value of 0 loops the entire segment.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return DMUS_E_OUT_OF_RANGE.

Remarks

When the segment is played, it plays from the segment start time until mtEnd, then loops to mtStart, plays the looped portion the number of times set by IDirectMusicSegment::SetRepeats, then plays to the end.

The default values are set to loop the entire segment from beginning to end.

The method fails if mtStart is greater than or equal to the length of the segment, or if mtEnd is greater than the length of the segment. If mtEnd is 0, mtStart must be 0, as well.

This method does not affect any currently playing segment states created from this segment.

The loop points of a cached segment persist even if the segment is released, and then reloaded. To ensure that a segment is not subsequently reloaded from the cache, call IDirectMusicLoader::ReleaseObject on it before releasing it.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicSegment::GetLoopPoints, Segment Timing


IDirectMusicSegment::SetParam

The IDirectMusicSegment::SetParam method sets data on a track inside this segment.

HRESULT SetParam(
  REFGUID rguidType,
  DWORD dwGroupBits,
  DWORD dwIndex,
  MUSIC_TIME mtTime,
  void* pParam
);

Parameters

rguidType
Reference to (C++) or address of (C) the type of data to set. See Track Parameter Types.
dwGroupBits
Group that the desired track is in. Use 0xFFFFFFFF for all groups. For more information, see the Remarks for IDirectMusicPerformance::SetParam.
dwIndex
Index of the track in the group identified by dwGroupBits in which to set the data.
mtTime
Time at which to set the data.
pParam
Address of a structure containing the data, or NULL if no data is required. The structure must be of the appropriate kind and size for the data type identified by rguidType.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_SET_UNSUPPORTED
DMUS_E_TRACK_NOT_FOUND
E_POINTER

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::SetParam, IDirectMusicSegment::GetParam, IDirectMusicTrack::SetParam, Music Parameters


IDirectMusicSegment::SetPChannelsUsed

The IDirectMusicSegment::SetPChannelsUsed method sets the performance channels (PChannels) that this segment uses. This method is usually called by a track in the IDirectMusicTrack::Init method to inform the segment of which PChannels the track uses.

HRESULT SetPChannelsUsed(
  DWORD dwNumPChannels,
  DWORD* paPChannels
);

Parameters

dwNumPChannels
Number of PChannels to set. This must be equal to the number of members in the array pointed to by paPChannels.
paPChannels
Address of an array of PChannels.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_INVALIDARG
E_OUTOFMEMORY
E_POINTER

Remarks

This method allows the performance to know which ports are being used by the segment so that it can determine the actual latency, rather than providing for the worst case.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

Latency and Bumper Time, Channels


IDirectMusicSegment::SetRepeats

The IDirectMusicSegment::SetRepeats method sets the number of times the looping portion of the segment is to repeat. By default, the entire segment is looped.

HRESULT SetRepeats(
  DWORD dwRepeats
);

Parameters

dwRepeats
Number of times that the looping portion of the segment is to repeat. A value of 0 indicates a single play with no repeats.

Return Values

The method returns S_OK.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicSegment::GetRepeats, IDirectMusicSegment::SetLoopPoints, Segment Timing


IDirectMusicSegment::SetStartPoint

The IDirectMusicSegment::SetStartPoint method sets the point at which the segment starts playing in response to a call to the IDirectMusicPerformance::PlaySegment method.

HRESULT SetStartPoint(
  MUSIC_TIME mtStart
);

Parameters

mtStart
Point within the segment at which it is to start playing. If this value is less than 0 or greater than the length of the segment, the start point is set to 0.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return DMUS_E_OUT_OF_RANGE.

Remarks

By default, the start point is 0, meaning that the segment starts from the beginning.

The method fails if mtStart is greater than or equal to the length of the segment. If the segment does not already have a length, IDirectMusicSegment::SetLength must be called before this method.

The method does not affect any currently playing segment states created from this segment.

The start point of a cached segment persists even if the segment is released, and then reloaded. To ensure that a segment is not subsequently reloaded from the cache, call IDirectMusicLoader::ReleaseObject on it before releasing it.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicSegment::GetStartPoint, IDirectMusicSegmentState::GetStartPoint, IDirectMusicSegment::SetLength, IDirectMusicSegment::SetLoopPoints, Segment Timing


IDirectMusicSegmentState

When the IDirectMusicPerformance::PlaySegment method is called, the performance engine generates a segment-state object that tracks the state of the playing segment. It also provides the application with a handle to the segment, in the form of the IDirectMusicSegmentState interface, which can be used to track the playback status of the segment. This method can also be used directly to stop playback or remove the segment from the performance, using methods of IDirectMusicPerformance.

The interface has the following methods:

Information | GetRepeats
 | GetSeek
 | GetSegment
 | GetStartPoint
 | GetStartTime

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


IDirectMusicSegmentState::GetRepeats

The IDirectMusicSegmentState::GetRepeats method returns the number of times that the looping portion of the segment is set to repeat.

HRESULT GetRepeats(
  DWORD* pdwRepeats
);

Parameters

pdwRepeats
Address of a variable to receive the repeat count. A value of 0 indicates that the segment is to play through only once, with no portion repeated.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be E_POINTER.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicSegment::SetRepeats


IDirectMusicSegmentState::GetSeek

The IDirectMusicSegmentState::GetSeek method retrieves the current seek pointer in the segment state. This is the value that is passed in the mtStart parameter of IDirectMusicTrack::Play the next time that method is called. It does not take into account looping and repeating; if the entire segment state repeats to the beginning, the seek pointer is reset to 0.

HRESULT GetSeek(
  MUSIC_TIME* pmtSeek
);

Parameters

pmtSeek
Address of a variable to receive the current seek pointer.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be E_POINTER.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


IDirectMusicSegmentState::GetSegment

The IDirectMusicSegmentState::GetSegment method returns a pointer to the segment that owns this segment state.

HRESULT GetSegment(
  IDirectMusicSegment** ppSegment
);

Parameters

ppSegment
Address of a variable to receive a pointer to the IDirectMusicSegment interface.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

The pointer returned in ppSegment must be released by the application.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


IDirectMusicSegmentState::GetStartPoint

The IDirectMusicSegmentState::GetStartPoint method returns the offset into the segment at which play begins or began.

HRESULT GetStartPoint(
  MUSIC_TIME * pmtStart
);

Parameters

pmtStart
Address of a variable to receive the music-time offset from the start of the segment at which the segment state initially plays.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicSegment::SetStartPoint, IDirectMusicSegmentState::GetStartTime


IDirectMusicSegmentState::GetStartTime

The IDirectMusicSegmentState::GetStartTime method gets the performance time at which the segment started or will start playing.

HRESULT GetStartTime(
  MUSIC_TIME* pmtStart
);

Parameters

pmtStart
Address of a variable to receive the music-time offset stored in this segment state.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

If the segment was started from some point other than the beginning, you can retrieve the time at which the beginning of the segment would have fallen by subtracting the time returned by IDirectMusicSegmentState::GetStartPoint from the value returned by this method.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicSegment::SetStartPoint, IDirectMusicSegment::GetStartPoint, IDirectMusicSegmentState::GetStartPoint


IDirectMusicStyle

The IDirectMusicStyle interface provides access to a style object. The style object provides the performance with the information that it needs to play musical patterns. For an overview, see Using Styles.

Since styles usually include bands and motifs, the IDirectMusicStyle interface provides methods for accessing these objects.

The DirectMusicStyle object also supports the IDirectMusicObject and IPersistStream interfaces for loading its data.

The methods of the IDirectMusicStyle interface can be organized in the following groups:

Enumeration | EnumBand
 | EnumChordMap
 | EnumMotif
Information | GetBand
 | GetChordMap
 | GetDefaultBand
 | GetDefaultChordMap
 | GetEmbellishmentLength
 | GetMotif
 | GetTempo
 | GetTimeSignature

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


IDirectMusicStyle::EnumBand

The IDirectMusicStyle::EnumBand method retrieves the name of the band with a given index value.

HRESULT EnumBand(
  DWORD dwIndex,
  WCHAR * pwszName
);

Parameters

dwIndex
Zero-based index into the style's band list.
pwszName
Address of a buffer to receive the band name. This should be of size MAX_PATH.

Return Values

If the method succeeds, it returns S_OK, S_FALSE if there is no band with the given index value, or DMUS_S_STRING_TRUNCATED if the length of the name is greater than MAX_PATH.

If it fails, the method can return one of the following error values:

DMUS_E_TYPE_UNSUPPORTED
E_POINTER

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


IDirectMusicStyle::EnumChordMap

The IDirectMusicStyle::EnumChordMap method retrieves the name of the chord map with the given index value.

HRESULT EnumChordMap(
  DWORD dwIndex,
  WCHAR * pwszName
);

Parameters

dwIndex
Zero-based index of the chord map in the style's chord-map list.
pwszName
Address of a buffer to receive the chord-map name. This should be of size MAX_PATH.

Return Values

If the method succeeds, the return value is S_OK, S_FALSE if there is no chord map with the given index value, or DMUS_S_STRING_TRUNCATED if the length of the name is greater than MAX_PATH.

If it fails, the method can return one of the following error values:

DMUS_E_TYPE_UNSUPPORTED
E_POINTER

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


IDirectMusicStyle::EnumMotif

The IDirectMusicStyle::EnumMotif method retrieves the name of a motif with a given index value.

HRESULT EnumMotif(
  DWORD dwIndex,
  WCHAR * pwszName
);

Parameters

dwIndex
Zero-based index into the style's motif list.
pwszName
Address of a buffer to receive the motif name. This should be of size MAX_PATH.

Return Values

If the method succeeds, the return value is S_OK, S_FALSE if there is no motif with the given index value, or DMUS_S_STRING_TRUNCATED if the length of the motif name is greater than MAX_PATH.

If it fails, the method can return E_POINTER.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicStyle::GetMotif, Using Motifs


IDirectMusicStyle::GetBand

The IDirectMusicStyle::GetBand method retrieves the named band.

HRESULT GetBand(
  WCHAR* pwszName,
  IDirectMusicBand** ppBand
);

Parameters

pwszName
Name of the band to be retrieved. This name is assigned by the author of the style.
ppBand
Address of a variable to receive a pointer to the band.

Return Values

If the method succeeds, the return value is S_OK if a band is returned, or S_FALSE if there is no band with that name.

If the method fails, the return value can be E_POINTER.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicStyle::GetDefaultBand, Using Bands


IDirectMusicStyle::GetChordMap

The IDirectMusicStyle::GetChordMap method retrieves a named chord map.

HRESULT GetChordMap(
  WCHAR* pwszName,
  IDirectMusicChordMap** ppChordMap
);

Parameters

pwszName
Name of the chord map to be retrieved.
ppChordMap
Address of a variable to receive a pointer to the IDirectMusicChordMap interface.

Return Values

If the method succeeds, the return value is S_OK if a chord map is returned, or S_FALSE if there is no chord map by that name.

If ppChordMap is not a valid pointer, the method returns E_POINTER.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicStyle::GetDefaultChordMap, Using Chord Maps


IDirectMusicStyle::GetDefaultBand

The IDirectMusicStyle::GetDefaultBand method retrieves the style's default band.

HRESULT GetDefaultBand(
  IDirectMusicBand ** ppBand
);

Parameters

ppBand
Address of a variable to receive a pointer to the default band.

Return Values

If the method succeeds, the return value is S_OK if a band is returned, or S_FALSE if the style does not have a default band.

If it fails, the method can return E_POINTER.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicStyle::GetBand, Using Bands


IDirectMusicStyle::GetDefaultChordMap

The IDirectMusicStyle::GetDefaultChordMap method retrieves the style's default chord map.

HRESULT GetDefaultChordMap(
  IDirectMusicChordMap** ppChordMap
);

Parameters

ppChordMap
Address of a variable to receive a pointer to the IDirectMusicChordMap interface.

Return Values

If the method succeeds, the return value is S_OK if a chord map is returned, or S_FALSE if the style does not have a default chord map.

If it fails, the method can return E_POINTER.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicStyle::GetChordMap, Using Chord Maps


IDirectMusicStyle::GetEmbellishmentLength

The IDirectMusicStyle::GetEmbellishmentLength method finds the shortest and longest lengths for patterns of the specified embellishment type and groove level.

HRESULT GetEmbellishmentLength(
  DWORD dwType,
  DWORD dwLevel,
  DWORD* pdwMin,
  DWORD* pdwMax
);

Parameters

dwType
Embellishment type. See DMUS_COMMANDT_TYPES.
dwLevel
Groove level in the range from 1 through 100. Ignored for nongroove embellishments.
pdwMin
Address of a variable to receive the length of the shortest pattern of the specified type and groove level.
pdwMax
Address of a variable to receive the length of the longest pattern of the specified type and groove level.

Return Values

If the method succeeds, the return value is S_OK or S_FALSE.

If it fails, the method can return E_POINTER.

Remarks

If there are no patterns of the specified type and groove level, the method returns S_FALSE.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


IDirectMusicStyle::GetMotif

The IDirectMusicStyle::GetMotif method creates a segment containing the named motif.

HRESULT GetMotif(
  WCHAR* pwszName,
  IDirectMusicSegment** ppSegment
);

Parameters

pwszName
Name of the motif to be retrieved.
ppSegment
Address of a variable to receive a pointer to a segment containing the named motif.

Return Values

If the method succeeds, the return value is S_OK or S_FALSE.

If it fails, the method can return E_POINTER.

Remarks

The method searches the style's list of motifs for one whose name matches pwszName. If one is found, a segment is created containing a motif track. The track references the style as its associated style and the motif as its pattern.

If there is no motif with the name, the method returns S_FALSE.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

Using Motifs


IDirectMusicStyle::GetTempo

The IDirectMusicStyle::GetTempo method retrieves the recommended tempo of the style.

HRESULT GetTempo(
  double* pTempo
);

Parameters

pTempo
Address of a variable to receive the recommended tempo of the style.

Return Values

If the method succeeds, the return value is S_OK.

If pTempo is not a valid pointer, the method returns E_POINTER.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


IDirectMusicStyle::GetTimeSignature

The IDirectMusicStyle::GetTimeSignature method retrieves the style's time signature.

HRESULT GetTimeSignature(
  DMUS_TIMESIGNATURE* pTimeSig
);

Parameters

pTimeSig
Address of a DMUS_TIMESIGNATURE structure to receive data.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


IDirectMusicThru

The IDirectMusicThru interface supports thruing of music messages from a capture port to another port. It is obtained by calling QueryInterface on the IDirectMusicPort interface for the capture port. For an example, see the Remarks for IDirectMusicThru::ThruChannel.

The interface has the following method:

IDirectMusicThru ThruChannel

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

Capturing Music


IDirectMusicThru::ThruChannel

The IDirectMusicThru::ThruChannel method establishes or breaks a thruing connection between a channel on a capture port and a channel on another port.

HRESULT ThruChannel(
  DWORD dwSourceChannelGroup,
  DWORD dwSourceChannel,
  DWORD dwDestinationChannelGroup,
  DWORD dwDestinationChannel,
  LPDIRECTMUSICPORT pDestinationPort
);

Parameters

dwSourceChannelGroup
Channel group on the capture port. In the current version of DirectMusic, this value is always 1.
dwSourceChannel
Source channel.
dwDestinationChannelGroup
Channel group on the destination port.
dwDestinationChannel
Destination channel.
pDestinationPort
Address of the IDirectMusicPort interface for the destination channel. Set this value to NULL to break an existing thruing connection.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_NOTIMPL
E_INVALIDARG
DMUS_E_PORT_NOT_RENDER

Remarks

System-exclusive messages are not transmitted to the destination port.

Thruing to the Microsoft Software Synthesizer or other synthesizers that do not have a constant latency is not recommended. Thruing is done as soon as possible upon reception of the incoming MIDI events. Because of the comparatively high latency of the software synthesizer (compared with a hardware port) and the fact that it renders blocks of audio data at the same time, each event is delayed by a small, essentially random amount of time before it plays. This random offset shows up as jitter in the playback of the data. Latency of other devices (such as an MPU-401 port) is small enough that jitter does not occur.

If an application needs to thru to the software synthesizer, it should add a small offset to the incoming note event time stamps to compensate for the rendering latency of the synthesizer.

The following code example obtains the IDirectMusicThru interface and establishes a thru connection between all channels on group 1 of the capture port and the equivalent channels on a destination port.

HRESULT SetupOneToOneThru(
    IDirectMusicPort *pCapturePort,
    IDirectMusicPort *pRenderPort)
{
    HRESULT hr;
    IDirectMusicThru *pThru;

    hr = pCapturePort->QueryInterface(IID_IDirectMusicThru,
            (void**)&pThru);
    if (FAILED(hr))
        return hr;

    for (DWORD dwChannel = 0; dwChannel < 16; dwChannel++)
    {
        hr = pThru->ThruChannel(1, dwChannel,
            1, dwChannel, pRenderPort);
        if (FAILED(hr))
            break;
    }

    pThru->Release();
    return hr;
}

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.


IDirectMusicTool

Tools are objects that implement the IDirectMusicTool interface. They are used inside graphs (see IDirectMusicGraph). When a message is sent using IDirectMusicPerformance::SendPMsg, the message flows through tools inside graphs. The tools can modify the message, make additional messages, remove messages, and so on.

This interface is of most interest to developers who want to create their own tools.

The methods of the IDirectMusicTool interface can be organized in the following groups:

Initialization | Init
Message management | Flush
 | GetMediaTypeArraySize
 | GetMediaTypes
 | GetMsgDeliveryType
 | ProcessPMsg

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

Overview of DirectMusic Data Flow, Message Creation and Delivery, DirectMusic Tools


IDirectMusicTool::Flush

The IDirectMusicTool::Flush method is called for each message in the queue when the performance stops. The tool can use the method to do whatever is necessary to flush the message. For instance, the output tool uses this method to ensure that any pending note-off messages are processed immediately.

HRESULT Flush(
  IDirectMusicPerformance* pPerf,
  DMUS_PMSG* pPMSG,
  REFERENCE_TIME rtTime
);

Parameters

pPerf
Address of the IDirectMusicPerformance interface.
pPMSG
Message to flush.
rtTime
Time at which to flush.

Return Values

Return values are determined by the implementation. If the method succeeds, the return value can be one of the following:

DMUS_S_REQUEUE
DMUS_S_FREE
S_OK

If it fails, the method can return E_POINTER.

Remarks

The message will have DMUS_PMSGF_TOOL_FLUSH set in its dwFlags member. See DMUS_PMSG.

If the method returns DMUS_S_REQUEUE, the tool wants the message to be requeued. This allows the tool to put a new time stamp and parameters on the message and requeue it, or to requeue the message with a different delivery type.

If the return value is DMUS_S_FREE, the tool wants the message freed automatically and does not want to requeue the message.

If S_OK is returned, the tool does not want the message to be freed automatically. Perhaps the tool is holding onto the message for some reason, or has freed it itself.

Be sure not to create a circular reference to the performance represented by pPerf. For more information, see DirectMusic Tools.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


IDirectMusicTool::GetMediaTypeArraySize

The IDirectMusicTool::GetMediaTypeArraySize method retrieves the size of the array that must be passed in to the IDirectMusicTool::GetMediaTypes method. A return value of 0 indicates that the tool handles all types, and it is unnecessary to call GetMediaTypes.

HRESULT GetMediaTypeArraySize(
  DWORD* pdwNumElements
);

Parameters

pdwNumElements
Address of a variable to receive the number of media types. If 0 is returned in this field, all types are supported.

Return Values

Return values are determined by the implementation. If the method succeeds, it returns S_OK. If it fails, the method can return E_POINTER.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


IDirectMusicTool::GetMediaTypes

The IDirectMusicTool::GetMediaTypes method retrieves a list of the types of messages that this tool supports.

HRESULT GetMediaTypes(
  DWORD** padwMediaTypes,
  DWORD dwNumElements
);

Parameters

padwMediaTypes
Address of an array of DWORDs. The method fills this array with the media types supported by this tool. For media types, see DMUS_PMSGT_TYPES.
dwNumElements
Number of elements in the padwMediaTypes array. This value is equal to the number returned by the IDirectMusicTool::GetMediaTypeArraySize method. If dwNumElements is less than this number, the method cannot return all the message types that are supported. If it is greater than this number, the extra elements in the array should be set to 0.

Return Values

Return values are determined by the implementation. If the method succeeds, it returns S_OK, or S_FALSE if the method could not fill in all values because dwNumElements was too small. If it fails, the method can return one of the following error values:

E_POINTER
E_INVALIDARG
E_NOTIMPL

Remarks

If the method returns E_NOTIMPL, the tool processes all media types.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


IDirectMusicTool::GetMsgDeliveryType

The IDirectMusicTool::GetMsgDeliveryType method retrieves the tool's delivery type, which determines when messages are to be delivered to the tool.

HRESULT GetMsgDeliveryType(
  DWORD* pdwDeliveryType
);

Parameters

pdwDeliveryType
Address of a variable to receive the delivery type. The returned value must be DMUS_PMSGF_TOOL_IMMEDIATE, DMUS_PMSGF_TOOL_QUEUE, or DMUS_PMSGF_TOOL_ATTIME. An unrecognized value in *pdwDeliveryType is treated as DMUS_PMSGF_TOOL_IMMEDIATE by the graph.

Return Values

Return values are determined by the implementation. If the method succeeds, it returns S_OK. If it fails, the method can return E_POINTER.

Remarks

For an overview of the delivery mechanism, see Message Creation and Delivery.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


IDirectMusicTool::Init

The IDirectMusicTool::Init method is called when the tool is inserted into the graph, giving the tool an opportunity to perform any necessary initialization.

HRESULT Init(
  IDirectMusicGraph* pGraph
);

Parameters

pGraph
Calling graph.

Return Values

Return values are determined by the implementation. If the method succeeds, it returns S_OK. If it fails, the method can return one of the following error values:

E_FAIL
E_NOTIMPL

Remarks

Because a tool can be inserted into more than one graph, this method must be able to deal gracefully with multiple calls.

Be sure not to create a circular reference to the graph represented by pGraph. For more information, see DirectMusic Tools.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicGraph::InsertTool


IDirectMusicTool::ProcessPMsg

The IDirectMusicTool::ProcessPMsg method performs the main task of the tool. It is called from inside the performance's real-time thread for all messages that match the types specified by IDirectMusicTool::GetMediaTypes.

HRESULT ProcessPMsg(
  IDirectMusicPerformance* pPerf,
  DMUS_PMSG* pPMSG
);

Parameters

pPerf
Performance that is generating messages.
pPMSG
Message to process.

Return Values

Return values are determined by the implementation. If the method succeeds, the return value can be one of the following:

DMUS_S_REQUEUE
DMUS_S_FREE
S_OK

If it fails, the method can return E_POINTER.

Remarks

If the method returns DMUS_S_REQUEUE, the tool wants the message to be requeued. This allows the tool to put a new time stamp and parameters on the message and requeue it, or to requeue the message with a different delivery type.

If the return value is DMUS_S_FREE, the tool wants the message freed automatically, and does not want to requeue the message.

If S_OK is returned, the tool does not want the message to be freed automatically. Perhaps the tool is holding onto the message for some reason, or has freed it itself.

Tools should not perform time-consuming activities because doing so can severely affect overall performance. Also be sure not to create a circular reference to the performance represented by pPerf. For more information, see DirectMusic Tools.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::SendPMsg, Messages, Message Creation and Delivery


IDirectMusicTrack

The IDirectMusicTrack interface represents a track object. Almost everything that has to do with the definition of a segment is stored in its tracks. The track mechanism allows segments to be infinitely extensible, and the segment does not need any knowledge of any of the music and audio technologies that it employs.

If you plan to install your own music playback mechanism in DirectMusic, you need to create a DirectMusicTrack object to represent it. Otherwise, the methods of this interface are typically not called directly from the application.

Note When implementing methods of the IDirectMusicTrack interface, be sure not to hold onto references to objects passed in. For example, if IDirectMusicTrack::Init adds a reference to the IDirectMusicSegment interface that it receives as a parameter, ensure that this reference is released.

The IDirectMusicTrack interface has the following methods:

Initialization | Init
Playback | EndPlay
 | InitPlay
 | Play
Notification | AddNotificationType
 | RemoveNotificationType
Parameters | GetParam
 | IsParamSupported
 | SetParam
Miscellaneous | Clone

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The DirectMusicTrack object also supports the IDirectMusicObject and IPersistStream interfaces for loading its data.

The following table shows which methods are supported by the standard track types. For a general description of the standard types, see Tracks.

Track | IDirectMusicTrack methods |  | IPersistStream methods
Band (CLSID_DirectMusicBandTrack)
 | AddNotificationType | No | IsDirty | Yes
 | Clone | Yes | GetSizeMax | No
 | EndPlay | Yes | Load | Yes
 | GetParam | No | Save | Yes
 | Init | Yes |  |
 | InitPlay | Yes
 | IsParamSupported | Yes
 | Play | Yes
 | SetParam | Yes
 | RemoveNotificationType | No
Chord (CLSID_DirectMusicChordTrack)
 | AddNotificationType | Yes | IsDirty | Yes
 | Clone | Yes | GetSizeMax | No
 | EndPlay | Yes | Load | Yes
 | GetParam | Yes | Save | Yes
 | Init | Yes |  |
 | InitPlay | Yes
 | IsParamSupported | Yes
 | Play | Yes
 | SetParam | Yes
 | RemoveNotificationType | Yes
Chord map (CLSID_DirectMusicChordMapTrack)
 | AddNotificationType | No | IsDirty | No
 | Clone | Yes | GetSizeMax | No
 | EndPlay | Yes* | Load | Yes
 | GetParam | Yes | Save | No
 | Init | Yes* |  |
 | InitPlay | Yes*
 | IsParamSupported | Yes
 | Play | Yes*
 | SetParam | Yes
 | RemoveNotificationType | No
Command (CLSID_DirectMusicCommandTrack)
 | AddNotificationType | Yes | IsDirty | Yes
 | Clone | Yes | GetSizeMax | No
 | EndPlay | Yes | Load | Yes
 | GetParam | Yes | Save | Yes
 | Init | Yes |  |
 | InitPlay | Yes
 | IsParamSupported | Yes
 | Play | Yes
 | SetParam | Yes
 | RemoveNotificationType | Yes
Motif (CLSID_DirectMusicMotifTrack)
 | AddNotificationType | Yes | IsDirty | No
 | Clone | Yes | GetSizeMax | No
 | EndPlay | Yes | Load | No
 | GetParam | No | Save | No
 | Init | Yes |  |
 | InitPlay | Yes
 | IsParamSupported | Yes
 | Play | Yes
 | SetParam | Yes
 | RemoveNotificationType | Yes
Mute (CLSID_DirectMusicMuteTrack)
 | AddNotificationType | No | IsDirty | Yes
 | Clone | Yes | GetSizeMax | No
 | EndPlay | Yes* | Load | Yes
 | GetParam | Yes | Save | Yes
 | Init | Yes* |  |
 | InitPlay | Yes*
 | IsParamSupported | Yes
 | Play | Yes*
 | SetParam | Yes
 | RemoveNotificationType | No
Sequence (CLSID_DirectMusicSeqTrack)
 | AddNotificationType | No | IsDirty | No
 | Clone | Yes | GetSizeMax | No
 | EndPlay | Yes | Load | Yes
 | GetParam | No | Save | No
 | Init | Yes |  |
 | InitPlay | Yes
 | IsParamSupported | No
 | Play | Yes
 | SetParam | No
 | RemoveNotificationType | No
Signpost (CLSID_DirectMusicSignPostTrack)
 | AddNotificationType | No | IsDirty | Yes
 | Clone | Yes | GetSizeMax | No
 | EndPlay | Yes* | Load | Yes
 | GetParam | No | Save | Yes
 | Init | Yes* |  |
 | InitPlay | Yes*
 | IsParamSupported | No
 | Play | Yes*
 | SetParam | No
 | RemoveNotificationType | No
Style (CLSID_DirectMusicStyleTrack)
 | AddNotificationType | Yes | IsDirty | No
 | Clone | Yes | GetSizeMax | No
 | EndPlay | Yes | Load | Yes
 | GetParam | Yes | Save | No
 | Init | Yes |  |
 | InitPlay | Yes
 | IsParamSupported | Yes
 | Play | Yes
 | SetParam | Yes
 | RemoveNotificationType | Yes
SysEx (CLSID_DirectMusicSysExTrack)
 | AddNotificationType | No | IsDirty | No
 | Clone | Yes | GetSizeMax | No
 | EndPlay | Yes | Load | Yes
 | GetParam | No | Save | No
 | Init | Yes |  |
 | InitPlay | Yes
 | IsParamSupported | No
 | Play | Yes
 | SetParam | No
 | RemoveNotificationType | No
Tempo (CLSID_DirectMusicTempoTrack)
 | AddNotificationType | No | IsDirty | No
 | Clone | Yes | GetSizeMax | No
 | EndPlay | Yes | Load | Yes
 | GetParam | Yes | Save | No
 | Init | Yes |  |
 | InitPlay | Yes
 | IsParamSupported | Yes
 | Play | Yes
 | SetParam | Yes
 | RemoveNotificationType | No
Time signature** (CLSID_DirectMusicTimeSigTrack)
 | AddNotificationType | Yes | IsDirty | No
 | Clone | Yes | GetSizeMax | No
 | EndPlay | Yes | Load | Yes
 | GetParam | Yes | Save | No
 | Init | Yes |  |
 | InitPlay | Yes
 | IsParamSupported | Yes
 | Play | Yes
 | SetParam | Yes
 | RemoveNotificationType | Yes

Notes

* The method returns a value other than E_NOTIMPL but does not do anything else.

** The time-signature track exists in imported MIDI files and DirectMusic Producer segments specifically created with one. In most cases, the style track implements the time-signature track's functionality, so it is not necessary for a segment that contains a style track to contain a time-signature track, as well.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

Tracks, Setting and Retrieving Track Parameters


IDirectMusicTrack::AddNotificationType

The IDirectMusicTrack::AddNotificationType method enables event notification for a track. It is similar to and called from the IDirectMusicSegment::AddNotificationType method.

HRESULT AddNotificationType(
  REFGUID rguidNotificationType
);

Parameters

rguidNotificationType
Reference to (C++) or address of (C) the identifier of the notification type to add. For the defined types, see DMUS_NOTIFICATION_PMSG. Applications can also define their own types for custom tracks.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if the track does not support the notification type.

If the track does not support notifications, the method returns E_NOTIMPL.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicTrack::RemoveNotificationType, Notification and Event Handling


IDirectMusicTrack::Clone

The IDirectMusicTrack::Clone method makes a copy of a track.

HRESULT Clone(
  MUSIC_TIME mtStart,
  MUSIC_TIME mtEnd,
  IDirectMusicTrack** ppTrack
 );

Parameters

mtStart
Start of the part to clone. It should be 0 or greater and less than the length of the track.
mtEnd
End of the part to clone. It should be greater than mtStart and less than the length of the track.
ppTrack
Address of a variable to receive a pointer to the created track, if successful.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_FAIL
E_INVALIDARG
E_OUTOFMEMORY
E_POINTER

Remarks

It is the caller's responsibility to call Release when finished with the track.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


IDirectMusicTrack::EndPlay

The IDirectMusicTrack::EndPlay method is called when the object that originally called IDirectMusicTrack::InitPlay is destroyed.

HRESULT EndPlay(
  void * pStateData
);

Parameters

pStateData
State data returned from IDirectMusicTrack::InitPlay. This data should be freed in the EndPlay method.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


IDirectMusicTrack::GetParam

The IDirectMusicTrack::GetParam method retrieves data from a track.

HRESULT GetParam(
  REFGUID rguidType,
  MUSIC_TIME mtTime,
  MUSIC_TIME* pmtNext,
  void* pParam
);

Parameters

rguidType
Reference to (C++) or address of (C) the identifier of the type of data to obtain. See Track Parameter Types.
mtTime
Time, in track time, from which to obtain the data.
pmtNext
Address of a variable to receive the track time (relative to the current time) until which the data is valid. If this returns a value of 0, either the data is always valid, or it is unknown when it might become invalid. If this information is not needed, pmtNext can be set to NULL.
pParam
Address of an allocated structure in which the data is to be returned. The structure must be of the appropriate kind and size for the data type identified by rguidType.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_NOT_FOUND
DMUS_E_NOT_INIT
DMUS_E_TYPE_DISABLED
DMUS_E_GET_UNSUPPORTED
E_POINTER

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicTrack::SetParam, IDirectMusicTrack::IsParamSupported, IDirectMusicPerformance::GetParam, IDirectMusicSegment::GetParam, Music Parameters


IDirectMusicTrack::Init

The IDirectMusicTrack::Init method is called by a segment when a track is added and performs any necessary initialization.

HRESULT Init(
  IDirectMusicSegment* pSegment
);

Parameters

pSegment
Segment to which this track belongs.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_NOT_INIT
E_OUTOFMEMORY
E_POINTER

Remarks

If the track plays messages, it should call IDirectMusicSegment::SetPChannelsUsed in the Init method.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


IDirectMusicTrack::InitPlay

The IDirectMusicTrack::InitPlay method is called when a track is ready to start playing. It returns a pointer to state data, which is sent in to IDirectMusicTrack::Play and IDirectMusicTrack::EndPlay.

HRESULT InitPlay(
  IDirectMusicSegmentState* pSegmentState,
  IDirectMusicPerformance* pPerformance,
  void** ppStateData,
  DWORD dwVirtualTrackID,
  DWORD dwFlags
);

Parameters

pSegmentState
Address of the calling IDirectMusicSegmentState interface.
pPerformance
Address of the calling IDirectMusicPerformance interface.
ppStateData
Address of a variable to receive a pointer to state information. The format and use of the data is specific to the track. The data should be created in the InitPlay method and freed in the IDirectMusicTrack::EndPlay method. The pointer is passed to the IDirectMusicTrack::Play method.
dwVirtualTrackID
Virtual track ID assigned to this track instance.
dwFlags
DMUS_SEGF_FLAGS that control the track's behavior. See Remarks.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_NOT_INIT
E_OUTOFMEMORY
E_POINTER

Remarks

The track must store the pSegmentState, pPerformance, or dwTrackID parameters because they are also sent in to IDirectMusicTrack::Play.

The dwFlags parameter passes the flags that were handed to the performance in the call to IDirectMusicPerformance::PlaySegment. The track determines how it should perform, based on the DMUS_SEGF_CONTROL and DMUS_SEGF_SECONDARY flags. For example, the tempo track automatically plays the tempo changes only if it is part of a primary segment or a secondary control segment (DMUS_SEGF_SECONDARY is not set, or DMUS_SEGF_CONTROL is set).

A track can return NULL in ppStateData.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


IDirectMusicTrack::IsParamSupported

The IDirectMusicTrack::IsParamSupported method determines whether the track supports a given data type in the IDirectMusicTrack::GetParam and IDirectMusicTrack::SetParam methods.

HRESULT IsParamSupported(
  REFGUID rguidType
);

Parameters

rguidType
Reference to (C++) or address of (C) the identifier of the type of data. See Track Parameter Types.

Return Values

If the method succeeds and the type is supported, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_TYPE_DISABLED
DMUS_E_TYPE_UNSUPPORTED
E_POINTER
E_NOTIMPL

Remarks

If a message type has been disabled by using one of the SetParam methods (see Disabling and Enabling Messages), the IDirectMusicTrack::IsParamSupported method returns DMUS_E_TYPE_DISABLED when passed the corresponding parameter type (either GUID_TempoParam or GUID_TimeSignature).

The method also returns DMUS_E_TYPE_DISABLED if passed GUID_DisableTempo when that message type has already been disabled, or if passed GUID_EnableTempo when that message type is currently enabled. The same is true for GUID_DisableTimeSig and GUID_EnableTimeSig.

The method returns DMUS_E_TYPE_UNSUPPORTED when the track does not support the message type referred to by a GUID_EnableTempo, GUID_EnableTimeSig, GUID_DisableTempo, or GUID_DisableTimeSig parameter type.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicTrack::GetParam, IDirectMusicTrack::SetParam, Music Parameters


IDirectMusicTrack::Play

The IDirectMusicTrack::Play method causes the track to play. It performs any work that the track must do when the segment is played, such as creating and sending messages.

HRESULT Play(
  void* pStateData,
  MUSIC_TIME mtStart,
  MUSIC_TIME mtEnd,
  MUSIC_TIME mtOffset
  DWORD dwFlags,
  IDirectMusicPerformance* pPerf,
  IDirectMusicSegmentState* pSegSt,
  DWORD dwVirtualID
);

Parameters

pStateData
State data from the IDirectMusicTrack::InitPlay method. The format and use of the data is specific to the track.
mtStart
Start time.
mtEnd
End time.
mtOffset
Offset to add to all messages sent to IDirectMusicPerformance::SendPMsg.
dwFlags
Flags that indicate the state of this call. See DMUS_TRACKF_FLAGS. A value of 0 indicates that this call to Play continues playback from the previous call.
pPerf
Performance used to allocate and send the message.
pSegSt
Segment state that this track belongs to. The IDirectMusicSegmentState::QueryInterface method can be called to obtain an IDirectMusicGraph interface—to call IDirectMusicGraph::StampPMsg, for instance.
dwVirtualID
Virtual identifier of the track. This value must be put in the dwVirtualTrackID member of any message (see DMUS_PMSG) that is sent by IDirectMusicPerformance::SendPMsg.

Return Values

If the method succeeds, the return value can be S_OK or DMUS_S_END.

If it fails, the method can return one of the following error values:

DMUS_E_NOT_INIT
E_POINTER

Remarks

If the track is empty, the method returns DMUS_S_END.

Tracks generate messages in a medium-priority thread. You can call time-consuming functions, such as code to stream data from a file, from within a track's Play method. However, be sure to follow the guidelines for safe multithreading.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


IDirectMusicTrack::RemoveNotificationType

The IDirectMusicTrack::RemoveNotificationType method removes an event notification from a track. It is similar to and called from the IDirectMusicSegment::RemoveNotificationType method.

HRESULT RemoveNotificationType(
  REFGUID rguidNotificationType
);

Parameters

rguidNotificationType
Reference to (C++) or address of (C) the identifier of the notification type to remove. For the defined types, see DMUS_NOTIFICATION_PMSG.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if the track does not support the notification type.

If the track does not support notifications, the method returns E_NOTIMPL.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicTrack::AddNotificationType, Notification and Event Handling


IDirectMusicTrack::SetParam

The IDirectMusicTrack::SetParam method sets data on a track.

HRESULT SetParam(
  REFGUID rguidType,
  MUSIC_TIME mtTime,
  void* pParam
);

Parameters

rguidType
Reference to (C++) or address of (C) the identifier of the type of data to set. See Track Parameter Types.
mtTime
Time, in track time, at which to set the data.
pParam
Address of a structure containing the data, or NULL if no data is required. The structure must be of the appropriate kind and size for the data type identified by rguidType.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_SET_UNSUPPORTED
DMUS_E_TYPE_DISABLED
E_OUTOFMEMORY
E_POINTER

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicTrack::GetParam, IDirectMusicTrack::IsParamSupported, IDirectMusicPerformance::SetParam, IDirectMusicSegment::SetParam, Setting and Retrieving Track Parameters


IKsControl

The IKsControl interface is used to get, set, or query the support of properties, events, and methods. This interface is part of the Windows Driver Model kernel streaming architecture, but is also used by DirectMusic to expose properties of DirectMusic ports. To retrieve this interface, call the IDirectMusicPort::QueryInterface method with IID_IKsControl in the riid parameter.

Routing of the property item request to the port varies, depending on the port implementation. No properties are supported by ports that represent DirectMusic emulation on top of the Win32 handle-based multimedia calls (midiOut and midiIn functions).

Property item requests to a port that represents a pluggable software synthesizer are answered totally in user mode. The topology of this type of port is a synthesizer (represented by an IDirectMusicSynth interface) connected to a sink node (an IDirectMusicSynthSink interface). The property request is given first to the synthesizer node, and then to the sink node if it is not recognized by the synthesizer.

The interface has the following methods. At present, only KsProperty is supported by DirectMusic.

IKsControl | KsProperty
 | KsEvent
 | KsMethod

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmksctrl.h.

See Also

Port Property Sets


IKsControl::KsProperty

The IKsControl::KsProperty method gets or sets the value of a property. For an overview, see Port Property Sets.

HRESULT KsProperty(
  PKSPROPERTY pProperty,
  ULONG ulPropertyLength,
  LPVOID pvPropertyData,
  ULONG ulDataLength,
  PULONG pulBytesReturned
);

Parameters

pProperty
Address of a KSPROPERTY structure that gives the property set, item, and operation to perform. If this property contains instance data, that data should reside in memory immediately following the structure.
ulPropertyLength
Length of the memory pointed to by pProperty, including any instance data.
pvPropertyData
For a set operation, the address of a memory buffer containing data representing the new value of the property. For a get operation, the address of a memory buffer big enough to hold the value of the property. For a basic support query, the address of a buffer at least a DWORD in size.
ulDataLength
Length of the buffer pointed to by pvPropertyData.
pulBytesReturned
On a KSPROPERTY_TYPE_GET or KSPROPERTY_TYPE_BASICSUPPORT call, address of a variable to receive the number of bytes returned in pvPropertyData by the port.

Return Values

If the method succeeds, it returns S_OK.

If it fails, the method can return one of the following error values:

E_FAIL
E_INVALIDARG
E_NOTIMPL
E_OUTOFMEMORY
E_POINTER
DMUS_E_UNKNOWN_PROPERTY

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmksctrl.h.

See Also

Port Property Sets


IReferenceClock

The IReferenceClock interface represents a system reference clock. The DirectMusic master clock and a port's latency clock implement this interface.

The interface has the following methods:

IReferenceClock | GetTime
 | AdviseTime
 | AdvisePeriodic
 | Unadvise

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

IDirectMusic::GetMasterClock, IDirectMusicPort::GetLatencyClock, Timing


IReferenceClock::AdvisePeriodic

The IReferenceClock::AdvisePeriodic method requests an asynchronous, periodic notification that a duration has elapsed.

HRESULT AdvisePeriodic(
  REFERENCE_TIME rtStartTime,
  REFERENCE_TIME rtPeriodTime,
  HSEMAPHORE hSemaphore,
  DWORD * pdwAdviseCookie
);

Parameters

rtStartTime
Time that the notification should begin.
rtPeriodTime
Period of time between notifications.
hSemaphore
Handle of a semaphore through which to advise.
pdwAdviseCookie
Address of a variable to receive the identifier of the request. This is used to identify this call to AdvisePeriodic in the future—for example, to cancel it.

Return Values

Return values are determined by the implementation. If the method succeeds, it returns S_OK.

If it fails, the method can return one of the following error values:

E_FAIL
E_POINTER
E_INVALIDARG
E_NOTIMPL

Remarks

When the time indicated by rtStartTime is reached, the semaphore whose handle is set as hSemaphore is released. Thereafter, the semaphore is released repetitively with a period of rtPeriodTime.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

IReferenceClock::Unadvise


IReferenceClock::AdviseTime

The IReferenceClock::AdviseTime method requests an asynchronous notification that a time has elapsed.

HRESULT AdviseTime(
  REFERENCE_TIME rtBaseTime,
  REFERENCE_TIME rtStreamTime,
  HEVENT hEvent,
  DWORD * pdwAdviseCookie
);

Parameters

rtBaseTime
Base reference time.
rtStreamTime
Stream offset time.
hEvent
Handle to an event through which to advise.
pdwAdviseCookie
Address of a variable to receive the identifier of the request. This is used to identify this call to AdviseTime in the future—for example, to cancel it.

Return Values

Return values are determined by the implementation. If the method succeeds, it returns S_OK.

If it fails, the method can return one of the following error values:

E_FAIL
E_POINTER
E_INVALIDARG
E_NOTIMPL

Remarks

When the time rtBaseTime plus rtStreamTime is reached, the event whose handle is hEvent is set. If the time has already passed, the event is set immediately.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

IReferenceClock::Unadvise


IReferenceClock::GetTime

The IReferenceClock::GetTime method retrieves the current time.

HRESULT GetTime(
  REFERENCE_TIME * pTime
);

Parameters

pTime
Address of a variable to receive the current time.

Return Values

Return values are determined by the implementation. If the method succeeds, it returns S_OK.

If it fails, the method can return one of the following error values:

E_FAIL
E_POINTER
E_INVALIDARG
E_NOTIMPL

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.


IReferenceClock::Unadvise

The IReferenceClock::Unadvise method cancels a request for notification.

HRESULT Unadvise(
  DWORD dwAdviseCookie
);

Parameters

dwAdviseCookie
Identifier of the request that is to be canceled, as set in the IReferenceClock::AdviseTime or the IReferenceClock::AdvisePeriodic method.

Return Values

Return values are determined by the implementation. If the method succeeds, it returns S_OK.

If it fails, the method can return one of the following error values:

E_FAIL
E_POINTER
E_INVALIDARG
E_NOTIMPL

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.


Messages

DirectMusic message structures are all based on the DMUS_PMSG structure. Because C does not support inheritance, the members of this structure are included in each derived structure as the DMUS_PMSG_PART macro.

For an overview of messages, see DirectMusic Messages.

This section contains information about the following structures used to contain message information:

  • DMUS_PMSG
  • DMUS_CHANNEL_PRIORITY_PMSG
  • DMUS_CURVE_PMSG
  • DMUS_MIDI_PMSG
  • DMUS_NOTE_PMSG
  • DMUS_NOTIFICATION_PMSG
  • DMUS_PATCH_PMSG
  • DMUS_SYSEX_PMSG
  • DMUS_TEMPO_PMSG
  • DMUS_TIMESIG_PMSG
  • DMUS_TRANSPOSE_PMSG

See Also

IDirectMusicPerformance::AllocPMsg, IDirectMusicPerformance::SendPMsg, IDirectMusicPerformance::FreePMsg, IDirectMusicTool::ProcessPMsg


DMUS_PMSG

The DMUS_PMSG structure contains information common to all DirectMusic messages. Because C does not support inheritance, the members of this structure are included in all message types (including DMUS_PMSG itself) by the inclusion of the DMUS_PMSG_PART macro, which expands to the syntax shown here.

typedef struct DMUS_PMSG {
    DWORD              dwSize;
    REFERENCE_TIME     rtTime;
    MUSIC_TIME         mtTime;
    DWORD              dwFlags;
    DWORD              dwPChannel;
    DWORD              dwVirtualTrackID;
    IDirectMusicTool*  pTool;
    IDirectMusicGraph* pGraph;
    DWORD              dwType;
    DWORD              dwVoiceID;
    DWORD              dwGroupID;
    IUnknown*          punkUser;
} DMUS_PMSG;
dwSize
Size of the structure, in bytes. This member is initialized by IDirectMusicPerformance::AllocPMsg.
rtTime
Reference time at which the message is to be played, modified by dwFlags. Used only if DMUS_PMSGF_REFTIME is present in dwFlags.
mtTime
Music time at which the message is to be played, modified by dwFlags. Used only if DMUS_PMSGF_MUSICTIME is present in dwFlags.
dwFlags
Various bits (see DMUS_PMSGF_FLAGS and DMUS_TIME_RESOLVE_FLAGS). Must contain DMUS_PMSGF_REFTIME or DMUS_PMSGF_MUSICTIME.
dwPChannel
Performance channel (PChannel). The port, channel group, and MIDI channel can be derived from this value by using the IDirectMusicPerformance::PChannelInfo method. Set this value to 0 for messages that are not channel-specific, such as tempo messages.
dwVirtualTrackID
Identifier of the track. Set to 0 if the message is not being sent by a track.
pTool
Address of the tool interface. Can be set by using IDirectMusicGraph::StampPMsg, or can be NULL if the message is not to go to tools other than the output tool.
pGraph
Address of the tool graph interface. Can be set by using IDirectMusicGraph::StampPMsg, or can be NULL if the message is not to go to tools other than the output tool.
dwType
Message type (see DMUS_PMSGT_TYPES).
dwVoiceID
Reserved for future use. Should be set to 0.
dwGroupID
Identifier of the track group or groups that the message belongs to if the message is being generated by a track. (Tracks are assigned to groups in the IDirectMusicSegment::InsertTrack method.) For most purposes, this value can be 0xFFFFFFF.
punkUser
Address of an IUnknown interface supplied by the application. This pointer is always released when the message is freed. If the application wants to retain the object, it should call AddRef before the message is freed. If the message does not need a COM pointer, this value should be NULL.

Remarks

The DMUS_PMSG structure is used by itself for messages containing the following values in the dwType member:

DMUS_PMSGT_STOP
Sending a message of this type stops the performance at the specified time.
DMUS_PMSGT_DIRTY
When a control segment starts or ends, all tools in the segment and performance graphs receive a message of this type, indicating that if they cache data from GetParam calls, they must call GetParam again to refresh their data. Tools that want to receive this message type must indicate this through a call to IDirectMusicTool::GetMediaTypes. Tools in the performance graph receive one copy of the message for each segment in the performance. Such tools can safely ignore the extra messages with the same time stamp.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::SendPMsg


DMUS_CHANNEL_PRIORITY_PMSG

The DMUS_CHANNEL_PRIORITY_PMSG message structure contains data about a channel priority change.

typedef struct _DMUS_CHANNEL_PRIORITY_PMSG {
    DMUS_PMSG_PART
    DWORD dwChannelPriority;
} DMUS_CHANNEL_PRIORITY_PMSG;
DMUS_PMSG_PART
Macro for common message members. See DMUS_PMSG.
dwChannelPriority
Priority of the channel. For a list of defined values, see the Remarks for IDirectMusicPort::GetChannelPriority.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPort::SetChannelPriority, IDirectMusicPerformance::SendPMsg


DMUS_CURVE_PMSG

DMUS_CURVE_PMSG is a message structure that represents a curve (for example, a sequence of continuous controller events).

typedef struct DMUS_CURVE_PMSG {
    DMUS_PMSG_PART
    MUSIC_TIME mtDuration;
    MUSIC_TIME mtOriginalStart;
    MUSIC_TIME mtResetDuration;
    short      nStartValue;
    short      nEndValue;
    short      nResetValue;
    WORD       wMeasure;
    short      nOffset;
    BYTE       bBeat;
    BYTE       bGrid;
    BYTE       bType;
    BYTE       bCurveShape;
    BYTE       bCCData;
    BYTE       bFlags;
} DMUS_CURVE_PMSG;
DMUS_PMSG_PART
Macro for common message members. See DMUS_PMSG.
mtDuration
Duration of the curve.
mtOriginalStart
Original start time. Must be set to either 0 when this message is created, or to the original start time of the curve.
mtResetDuration
How long after the curve is finished until the reset value is set. Ignored if DMUS_CURVE_RESET is not in bFlags.
nStartValue
Start value of the curve.
nEndValue
End value of the curve.
nResetValue
Reset value of the curve, set after mtResetDuration or upon a flush or invalidation. Ignored if DMUS_CURVE_RESET is not in bFlags.
wMeasure
Measure in which this curve occurs.
nOffset
Offset from the grid at which this curve occurs, in music time.
bBeat
Beat count (within a measure) at which this curve occurs.
bGrid
Grid offset from the beat at which this curve occurs.
bType
Type of curve. This can be one of the following values:
DMUS_CURVET_CCCURVE
Continuous controller curve (MIDI Control Change channel voice message; status byte &HBn, where n is the channel number).
DMUS_CURVET_MATCURVE
Monophonic aftertouch curve (MIDI Channel Pressure channel voice message; status byte &HDn).
DMUS_CURVET_PATCURVE
Polyphonic aftertouch curve (MIDI Poly Key Pressure channel voice message, status byte &HDn).
DMUS_CURVET_PBCURVE
Pitch-bend curve (MIDI Pitch Bend channel voice message; status byte &HEn).
bCurveShape
Shape of curve. This can be one of the following values:
DMUS_CURVES_EXP
Exponential curve shape.
DMUS_CURVES_INSTANT
Instant curve shape (beginning and end of curve happen at essentially the same time).
DMUS_CURVES_LINEAR
Linear curve shape.
DMUS_CURVES_LOG
Logarithmic curve shape.
DMUS_CURVES_SINE
Sine curve shape.
bCCData
CC number if this is a control change type.
bFlags
Set to DMUS_CURVE_RESET if nResetValue must be set when the time is reached or an invalidation occurs because of a transition. If 0, the curve stays permanently at the new value. All other bits are reserved.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::SendPMsg


DMUS_MIDI_PMSG

The DMUS_MIDI_PMSG structure contains data for a standard MIDI message not represented by another message type, such as a control change or pitch bend.

typedef struct DMUS_MIDI_PMSGG {
    DMUS_PMSG_PART
    BYTE  bStatus;
    BYTE  bByte1;
    BYTE  bByte2;
    BYTE  bPad[1];
} DMUS_MIDI_PMSG;
DMUS_PMSG_PART
Macro for common message members. See DMUS_PMSG.
bStatus
Standard MIDI status byte.
bByte1
First byte of the MIDI message. Ignored for MIDI messages that do not require it.
bByte2
Second byte of the MIDI message. Ignored for MIDI messages that do not require it.
bPad
Padding to a WORD boundary.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

MIDI Messages, IDirectMusicPerformance::SendPMsg


DMUS_NOTE_PMSG

The DMUS_NOTE_PMSG structure contains data for a music-note event.

typedef struct DMUS_NOTE_PMSG {
    DMUS_PMSG_PART
    MUSIC_TIME mtDuration;
    WORD       wMusicValue;
    WORD       wMeasure;
    short      nOffset;
    BYTE       bBeat;
    BYTE       bGrid;
    BYTE       bVelocity;
    BYTE       bFlags;
    BYTE       bTimeRange;
    BYTE       bDurRange;
    BYTE       bVelRange;
    BYTE       bPlayModeFlags;
    BYTE       bSubChordLevel;
    BYTE       bMidiValue;
} DMUS_NOTE_PMSG;
DMUS_PMSG_PART
Macro for common message members. See DMUS_PMSG.
mtDuration
Duration of the note.
wMusicValue
Description of the note. In most play modes, this is a packed array of 4-bit values, as follows:
Octave
In the range from –2 through 14. The note is transposed up or down by the octave times 12.
Chord position
In the range from 0 through 15, although it should never be above 3. The first position in the chord is 0.
Scale position
In the range from 0 through 15. Typically it is only from 0 through 2, but it is possible to have a one-note chord and have everything above the chord be interpreted as a scale position.
Accidental
In the range from –8 through 7, but typically in the range from –2 through 2. This represents an offset that takes the note out of the scale.

In the fixed-play modes, the music value is a MIDI note value in the range from 0 through 127.

wMeasure
Measure in which this note occurs.
nOffset
Offset from the grid at which this note occurs, in music time.
bBeat
Beat (in measure) at which this note occurs.
bGrid
Grid offset from the beat at which this note occurs.
bVelocity
Note velocity.
bFlags
See DMUS_NOTEF_FLAGS.
bTimeRange
Range by which to randomize time.
bDurRange
Range by which to randomize duration.
bVelRange
Range by which to randomize velocity.
bPlayModeFlags
Play mode determining how the music value is related to the chord and subchord. For a list of values, see DMUS_PLAYMODE_FLAGS.
bSubChordLevel
Subchord level that the note uses. See DMUS_SUBCHORD.
bMidiValue
MIDI note value, converted from wMusicValue.

Remarks

When a note is to be played, the DMUS_NOTE_PMSG flows through the graph and any tools in the graph until it reaches the final MIDI output tool. When the tool recognizes that DMUS_NOTEF_NOTEON is set in the bFlags member, it sends a MIDI note-on message to the correct port (according to the dwPChannel member of the DMUS_PMSG part). It then clears the flag, adds mtDuration to the time stamp, and requeues the message so that the note is turned off at the appropriate time.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::SendPMsg, Music Values and MIDI Notes


DMUS_NOTIFICATION_PMSG

The DMUS_NOTIFICATION_PMSG structure is a DMUS_PMSG that represents a notification.

typedef struct DMUS_NOTIFICATION_PMSG {
    DMUS_PMSG_PART
    GUID   guidNotificationType;
    DWORD  dwNotificationOption;
    DWORD  dwField1;
    DWORD  dwField2;
} DMUS_NOTIFICATION_PMSG;
DMUS_PMSG_PART
Macro for common message members. See DMUS_PMSG.
guidNotificationType
Identifier of the notification type. The following types are defined:
GUID_NOTIFICATION_CHORD
Chord change.
GUID_NOTIFICATION_COMMAND
Command event.
GUID_NOTIFICATION_MEASUREANDBEAT
Measure and beat event.
GUID_NOTIFICATION_PERFORMANCE
Performance event, further defined in dwNotificationOption.
GUID_NOTIFICATION_SEGMENT
Segment event, further defined in dwNotificationOption.
dwNotificationOption
Identifier of the notification subtype.

If the notification type is GUID_NOTIFICATION_SEGMENT, this member can contain one of the following values:

DMUS_NOTIFICATION_SEGABORT
The segment was stopped by IDirectMusicPerformance::Stop.
DMUS_NOTIFICATION_SEGALMOSTEND
The segment has reached the end minus the prepare time.
DMUS_NOTIFICATION_SEGEND
The segment has ended.
DMUS_NOTIFICATION_SEGLOOP
The segment has looped.
DMUS_NOTIFICATION_SEGSTART
The segment has started.

If the notification type is GUID_NOTIFICATION_COMMAND, this member can contain one of the following values:

DMUS_NOTIFICATION_GROOVE
Groove change.
DMUS_NOTIFICATION_EMBELLISHMENT
Embellishment command (intro, fill, break, or end).

If the notification type is GUID_NOTIFICATION_PERFORMANCE, this member can contain one of the following values:

DMUS_NOTIFICATION_MUSICSTARTED
Playback has started.
DMUS_NOTIFICATION_MUSICSTOPPED
Playback has stopped.

If the notification type is GUID_NOTIFICATION_MEASUREANDBEAT, this member contains DMUS_NOTIFICATION_MEASUREBEAT. No other subtypes are defined.

If the notification type is GUID_NOTIFICATION_CHORD, this member contains DMUS_NOTIFICATION_CHORD. No other subtypes are defined.

dwField1
Extra data specific to the type of notification. For GUID_NOTIFICATION_MEASUREANDBEAT notifications, this member returns the beat number within the measure.
dwField2
Extra data specific to the type of notification. Reserved for future or application-defined use.

Remarks

For most notifications, the punkUser member (see DMUS_PMSG) contains the IUnknown pointer of the segment state. This is especially useful in the cases of chords and commands, in which you can query for the IDirectMusicSegmentState interface, call IDirectMusicSegmentState::GetSegment to get the IDirectMusicSegment pointer, and then call the IDirectMusicSegment::GetParam method to get the chord or command at the time given in the notification message's mtTime member.

For notifications of type GUID_NOTIFICATION_PERFORMANCE, the punkUser member is always NULL.

Applications can define their own notification message types and subtypes and use dwField1 and dwField2 for extra data. Such custom notification messages can be allocated and sent like any other message. Application-defined tracks can send messages of a particular type after the GUID (guidNotificationType) has been handed to IDirectMusicTrack::AddNotificationType.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

Notification and Event Handling, IDirectMusicPerformance::SendPMsg


DMUS_PATCH_PMSG

The DMUS_PATCH_PMSG structure contains data for a program-change message.

typedef struct DMUS_PATCH_PMSG {
    DMUS_PMSG_PART
    BYTE  byInstrument;
    BYTE  byMSB;
    BYTE  byLSB;
    BYTE  byPad[1];
} DMUS_PATCH_PMSG;
DMUS_PMSG_PART
Macro for common message members. See DMUS_PMSG.
byInstrument
Patch number of the instrument.
byMSB
Most significant byte of bank select.
byLSB
Least significant byte of bank select.
byPad
Padding to a WORD boundary. This value is ignored.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

DMUS_MIDI_PMSG, IDirectMusicPerformance::SendPMsg, MIDI Messages


DMUS_SYSEX_PMSG

The DMUS_SYSEX_PMSG structure is a DMUS_PMSG that represents a MIDI system-exclusive message.

typedef struct DMUS_SYSEX_PMSG {
    DMUS_PMSG_PART
    DWORD dwLen;
    BYTE  abData[1];
} DMUS_SYSEX_PMSG;
DMUS_PMSG_PART
Macro for common message members. See DMUS_PMSG.
dwLen
Length of the data, in bytes.
abData
Array of data. For an example of how to allocate memory and copy data to this member, see the Remarks for IDirectMusicPerformance::SendPMsg.

Remarks

The data part of a system-exclusive message must begin with the System Exclusive identifier (0xF0) and end with EOX (0xF7).

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

DMUS_MIDI_PMSG, DMUS_PATCH_PMSG, MIDI Messages, IDirectMusicPerformance::SendPMsg


DMUS_TEMPO_PMSG

The DMUS_TEMPO_PMSG structure contains data for a message that controls the performance's tempo.

typedef struct DMUS_TEMPO_PMSG {
    DMUS_PMSG_PART
    double dblTempo;
} DMUS_TEMPO_PMSG;
DMUS_PMSG_PART
Macro for common message members. See DMUS_PMSG.
dblTempo
Tempo, in the range from DMUS_TEMPO_MIN through DMUS_TEMPO_MAX.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::SendPMsg


DMUS_TIMESIG_PMSG

The DMUS_TIMESIG_PMSG structure contains data for a message that controls the time signature of the performance.

typedef struct _DMUS_TIMESIG_PMSG {
    DMUS_PMSG_PART
    BYTE bBeatsPerMeasure;
    BYTE bBeat;
    WORD wGridsPerBeat;
} DMUS_TIMESIG_PMSG;
DMUS_PMSG_PART
Macro for common message members. See DMUS_PMSG.
bBeatsPerMeasure
Beats per measure (top of the time signature).
bBeat
Note that receives the beat (bottom of the time signature), where 1 is a whole note, 2 is a half note, 4 is a quarter note, and so on. Zero is a 256th note.
wGridsPerBeat
Grids (subdivisions) per beat. This value determines the timing resolution for certain music events—for example, segments cued with the DMUS_SEGF_GRID flag (see DMUS_SEGF_FLAGS).

Remarks

Time-signature messages are generated by the time-signature track and the style track. In general, a segment contains one or the other, but not both. A segment representing a MIDI file has a time-signature track, but most segments authored with a tool such as DirectMusic Producer contain time-signature information in the style track.

By default, only the primary segment sends time-signature messages. For information on how to change this behavior, see Disabling and Enabling Messages.

The time signature is used by the performance to resolve time to measure, beat, and grid boundaries in all methods in which the time can be adjusted by DMUS_SEGF_FLAGS or DMUS_TIME_RESOLVE_FLAGS. The time-signature and style tracks also use the time signature to generate notifications on measure and beat boundaries. See DMUS_NOTIFICATION_PMSG.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::SendPMsg, DMUS_TIMESIGNATURE


DMUS_TRANSPOSE_PMSG

The DMUS_TRANSPOSE_PMSG structure contains data for a message that controls a transposition.

typedef struct _DMUS_TRANSPOSE_PMSG {
    DMUS_PMSG_PART
    short nTranspose;
} DMUS_TRANSPOSE_PMSG;
DMUS_PMSG_PART
Macro for common message members. See DMUS_PMSG.
nTranspose
Number of semitones by which to transpose. This can be a negative value.

Remarks

If the transposition of a note puts it outside the standard MIDI range from 0 through 127, it does not play.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::SendPMsg


Structures

This section contains reference information for the following run-time structures used in DirectMusic:

  • DMUS_BUFFERDESC
  • DMUS_CHORD_KEY
  • DMUS_CHORD_PARAM
  • DMUS_CLOCKINFO
  • DMUS_COMMAND_PARAM
  • DMUS_COMMAND_PARAM2
  • DMUS_EVENTHEADER
  • DMUS_MUTE_PARAM
  • DMUS_NOTERANGE
  • DMUS_OBJECTDESC
  • DMUS_PORTCAPS
  • DMUS_PORTPARAMS
  • DMUS_RHYTHM_PARAM
  • DMUS_SUBCHORD
  • DMUS_SYNTHSTATS
  • DMUS_TEMPO_PARAM
  • DMUS_TIMESIGNATURE
  • DMUS_VERSION
  • DMUS_WAVES_REVERB_PARAMS
  • KSPROPERTY

Special categories of structures are contained in the following sections:

  • Messages
  • File Structures
  • DLS Structures

Note The memory for all DirectX structures must be initialized to 0 before use. In addition, all structures that contain a dwSize member must set the member to the size of the structure, in bytes, before use. The following DirectDraw example performs these tasks on a common structure, DDCAPS:

DDCAPS ddcaps; // Can't use this yet.

ZeroMemory(&ddcaps, sizeof(ddcaps));
ddcaps.dwSize = sizeof(ddcaps);

// Now the structure can be used.
.
.


DMUS_BUFFERDESC

The DMUS_BUFFERDESC structure is used to describe a buffer for the IDirectMusic::CreateMusicBuffer method.

typedef struct _DMUS_BUFFERDESC {
    DWORD dwSize;
    DWORD dwFlags;
    GUID  guidBufferFormat;
    DWORD cbBuffer;
} DMUS_BUFFERDESC, *LPDMUS_BUFFERDESC;

Members

dwSize
Size of this structure, in bytes. This member must be initialized before the structure is used.
dwFlags
No flags are defined.
guidBufferFormat
Identifier of the KS format of the buffer. The value GUID_NULL represents KSDATAFORMAT_SUBTYPE_DIRECTMUSIC.

If guidBufferFormat represents a KS format other than KSDATAFORMAT_SUBTYPE_DIRECTMUSIC, the application must verify that the port playing back the data understands the specified format; if not, the buffer is ignored. To find out if the port supports a specific KS format, use the IKsControl::KsProperty method.

cbBuffer
Minimum size of the buffer, in bytes. The amount of memory allocated can be slightly higher because the system pads the buffer to a multiple of 4 bytes. The buffer must be at least 32 bytes to accommodate a single MIDI channel message, and at least 28 bytes plus the size of the data to accommodate a system-exclusive message or other unstructured data.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

DMUS_EVENTHEADER, IDirectMusicBuffer::PackStructured, IDirectMusicBuffer::PackUnstructured


DMUS_CHORD_KEY

The DMUS_CHORD_KEY structure is used to describe a chord in the IDirectMusicPerformance::MIDIToMusic and IDirectMusicPerformance::MusicToMIDI methods.

typedef struct _DMUS_CHORD_KEY {
    WCHAR         wszName[16];
    WORD          wMeasure;
    BYTE          bBeat;
    BYTE          bSubChordCount;
    DMUS_SUBCHORD SubChordList[DMUS_MAXSUBCHORD];
    DWORD         dwScale;
    BYTE          bKey;
} DMUS_CHORD_KEY;

Members

wszName
Name of the chord.
wMeasure
Measure that the chord falls on.
bBeat
Beat that the chord falls on.
bSubChordCount
Number of chords in the chord's list of subchords.
SubChordList
Array of DMUS_SUBCHORD structures, describing the components that make up the chord.
dwScale
Scale underlying the entire chord.
bKey
Key underlying the entire chord.

Remarks

This structure is also defined as a DMUS_CHORD_PARAM structure for use in setting and retrieving the GUID_ChordParam track parameter.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::GetParam, IDirectMusicPerformance::SetParam, IDirectMusicSegment::GetParam, IDirectMusicSegment::SetParam, IDirectMusicTrack::GetParam, IDirectMusicTrack::SetParam, Music Parameters


DMUS_CHORD_PARAM

The DMUS_CHORD_PARAM structure is used as the pParam parameter in calls to the various GetParam and SetParam methods when the track is a chord track and rguidType is GUID_ChordParam.

typedef DMUS_CHORD_KEY DMUS_CHORD_PARAM;

See DMUS_CHORD_KEY.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.

See Also

IDirectMusicPerformance::GetParam, IDirectMusicPerformance::SetParam, IDirectMusicSegment::GetParam, IDirectMusicSegment::SetParam, IDirectMusicTrack::GetParam, IDirectMusicTrack::SetParam, Music Parameters


DMUS_CLOCKINFO

The DMUS_CLOCKINFO structure reports information about a clock enumerated by using the IDirectMusic::EnumMasterClock method.

typedef struct _DMUS_CLOCKINFO{
    DWORD           dwSize;
    DMUS_CLOCKTYPE  ctType;
    GUID            guidClock;
    WCHAR           wszDescription[DMUS_MAX_DESCRIPTION];
} DMUS_CLOCKINFO, *LPDMUS_CLOCKINFO;

Members

dwSize
Size of the structure, in bytes This member must be initialized to sizeof(DMUS_CLOCKINFO) before the structure is passed to a method.
ctType
Member of the DMUS_CLOCKTYPE enumeration specifying the type of clock.
guidClock
Identifier of the clock. This value can be passed to the IDirectMusic::SetMasterClock method to set the master clock for DirectMusic.
wszDescription
Description of the clock.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


DMUS_COMMAND_PARAM

The DMUS_COMMAND_PARAM structure is used as the pParam parameter in calls to various GetParam and SetParam methods when the track is a command track and the rguidType parameter is GUID_CommandParam.

typedef struct {
    BYTE bCommand;
    BYTE bGrooveLevel;
    BYTE bGrooveRange;
} DMUS_COMMAND_PARAM;

Members

bCommand
Command type. See DMUS_COMMANDT_TYPES.
bGrooveLevel
Groove level of the command. The groove level is a value in the range from 1 through 100.
bGrooveRange
Amount by which the groove level can be randomized. For instance, if the groove level is 35 and the range is 4, the actual groove level could be anywhere from 33 through 37. Not currently implemented.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.

See Also

IDirectMusicPerformance::GetParam, IDirectMusicPerformance::SetParam, IDirectMusicSegment::GetParam, IDirectMusicSegment::SetParam, IDirectMusicTrack::GetParam, IDirectMusicTrack::SetParam


DMUS_COMMAND_PARAM2

The DMUS_COMMAND_PARAM2 structure is used as the pParam parameter in calls to various GetParam and SetParam methods when the track is a command track and the rguidType parameter is GUID_CommandParam2.

typedef struct {
    MUSIC_TIME mtTime;
    BYTE bCommand;
    BYTE bGrooveLevel;
    BYTE bGrooveRange;
} DMUS_COMMAND_PARAM2;

Members

mtTime
Time of the command.
bCommand
Command type. See DMUS_COMMANDT_TYPES.
bGrooveLevel
Groove level of the command. The groove level is a value in the range from 1 through 100.
bGrooveRange
Amount by which the groove level can be randomized. For instance, if the groove level is 35 and the range is 4, the groove level could be anywhere from 33 through 37. Not currently implemented.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.

See Also

IDirectMusicPerformance::GetParam, IDirectMusicPerformance::SetParam, IDirectMusicSegment::GetParam, IDirectMusicSegment::SetParam, IDirectMusicTrack::GetParam, IDirectMusicTrack::SetParam


DMUS_EVENTHEADER

The DMUS_EVENTHEADER structure precedes and describes an event in a port buffer.

typedef struct _DMUS_EVENTHEADER {
    DWORD           cbEvent;
    DWORD           dwChannelGroup;
    REFERENCE_TIME  rtDelta;
    DWORD           dwFlags;
} DMUS_EVENTHEADER, *LPDMUS_EVENTHEADER;

Members

cbEvent
Number of bytes in the event.
dwChannelGroup
Group to which the event belongs.
rtDelta
Offset from the start time of the buffer.
dwFlags
Set to DMUS_EVENT_STRUCTURED if the event is parsable MIDI data.

Remarks

The Pshpack4.h header file is included before the declaration of this structure to turn off automatic alignment of structures so that the data immediately follows the header. (For more information, see the comments in Pshpack4.h.) Poppack.h is then included to turn alignment back on, and the entire structure (header plus event) is padded to an 8-byte boundary.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusbuff.h.

See Also

IDirectMusicBuffer::GetNextEvent, IDirectMusicBuffer::PackStructured, IDirectMusicBuffer::PackUnstructured


DMUS_NOTERANGE

The DMUS_NOTERANGE structure specifies a range of notes that an instrument must respond to. An array of these structures is passed to the IDirectMusicPerformance::DownloadInstrument and IDirectMusicPort::DownloadInstrument methods to specify what notes the instrument should respond to and, therefore, what instrument regions need to be downloaded.

typedef struct _DMUS_NOTERANGE {
    DWORD dwLowNote;
    DWORD dwHighNote;
} DMUS_NOTERANGE, *LPDMUS_NOTERANGE;

Members

dwLowNote
Low note for this range of MIDI notes to which the instrument must respond.
dwHighNote
High note for this range of MIDI notes to which the instrument must respond.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmdls.h.


DMUS_MUTE_PARAM

The DMUS_MUTE_PARAM structure is used as the pParam parameter in calls to the various GetParam and SetParam methods when the track is a mute track and rguidType is GUID_MuteParam.

typedef struct _DMUS_MUTE_PARAM {
    DWORD  dwPChannel;
    DWORD  dwPChannelMap;
    BOOL   fMute;
} DMUS_MUTE_PARAM;

Members

dwPChannel
Performance channel to mute or remap. If the structure is being passed to GetParam, this member must be initialized.
dwPChannelMap
Channel to which dwPChannel is being mapped. This member is ignored if fMute is TRUE.
fMute
TRUE if dwPChannel is being muted.

Remarks

If you wanted all the notes on PChannel 3 to play on PChannel 9 instead, you would set dwPChannel to 3 and dwPChannelMap to 9 before passing the structure to one of the SetParam methods. If you wanted to mute the notes on PChannel 8, you would set dwPChannel to 8 and dwPChannelMap to 0xFFFFFFFF.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.

See Also

IDirectMusicPerformance::GetParam, IDirectMusicPerformance::SetParam, IDirectMusicSegment::GetParam, IDirectMusicSegment::SetParam, IDirectMusicTrack::GetParam, IDirectMusicTrack::SetParam


DMUS_OBJECTDESC

The DMUS_OBJECTDESC structure is used to describe a DirectMusic object. It is passed to the IDirectMusicLoader::GetObject method to identify the object that the loader should retrieve from storage. Information about an object is retrieved in this structure by the IDirectMusicLoader::EnumObject and IDirectMusicObject::GetDescriptor methods.

typedef struct _DMUS_OBJECTDESC {
    DWORD         dwSize;
    DWORD         dwValidData;
    GUID          guidObject;
    GUID          guidClass;
    FILETIME      ftDate;
    DMUS_VERSION  vVersion;
    WCHAR         wszName[DMUS_MAX_NAME];
    WCHAR         wszCategory[DMUS_MAX_CATEGORY];
    WCHAR         wszFileName[DMUS_MAX_FILENAME];
    LONGLONG      llMemLength;
    PBYTE         pbMemData;
} DMUS_OBJECTDESC, *LPDMUS_OBJECTDESC;

Members

dwSize
Size of the structure, in bytes. This member must be initialized to sizeof(DMUS_OBJECTDESC) before the structure is passed to any method.
dwValidData
Flags describing which members are valid and giving further information about some members. The following values are defined:
DMUS_OBJ_OBJECT
The guidObject member is valid.
DMUS_OBJ_CLASS
The guidClass member is valid.
DMUS_OBJ_NAME
The wszName member is valid.
DMUS_OBJ_CATEGORY
The wszCategory member is valid.
DMUS_OBJ_FILENAME
The wszFileName member is valid.
DMUS_OBJ_FULLPATH
The wszFileName member contains the full path. If this flag is set, the loader assumes that wszFileName is valid even if DMUS_OBJ_FILENAME has not been set.
DMUS_OBJ_MEMORY
The object is in memory, and llMemLength and pbMemData are valid.
DMUS_OBJ_URL
The wszFileName member contains a URL. (URLs are not currently supported by the DirectMusic loader.)
DMUS_OBJ_VERSION
The vVersion member is valid.
DMUS_OBJ_DATE
The ftDate member is valid.
DMUS_OBJ_LOADED
The object is currently loaded in memory.
guidObject
Unique identifier for this object.
guidClass
Unique identifier for the class of object. All the standard objects have defined identifiers consisting of "CLSID_" plus the name of the object. For example, a segment object is identified as CLSID_DirectMusicSegment. See the defines in the Dmusici.h header file.
ftDate
Date that the object was last edited.
vVersion
DMUS_VERSION structure containing version information.
wszName
Name of the object.
wszCategory
Category for the object.
wszFileName
File path. If DMUS_OBJ_FULLPATH is set, this is the full path; otherwise, it is the file name.
llMemLength
Size of data in memory.
pbMemData
Data in memory.

Remarks

At least one of wszName, guidObject, and wszFileName must be filled with valid data to retrieve the object by using the IDirectMusicLoader::GetObject method.

The name and category strings use 16-bit characters in the WCHAR format, not 8-bit ANSI chars. Be sure to convert as appropriate. You can use the C-library mbstowcs functionto convert from multibyte to Unicode and the wcstombs functionto convert from Unicode back to multibyte.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

DirectMusic Loader


DMUS_PORTCAPS

The DMUS_PORTCAPS structure receives information about a port enumerated by a call to the IDirectMusic::EnumPort method. The structure is also used to return information through the IDirectMusicPort::GetCaps method.

typedef struct _DMUS_PORTCAPS {
    DWORD dwSize;
    DWORD dwFlags;
    GUID  guidPort;
    DWORD dwClass;
    DWORD dwType;
    DWORD dwMemorySize;
    DWORD dwMaxChannelGroups;
    DWORD dwMaxVoices;
    DWORD dwMaxAudioChannels;
    DWORD dwEffectFlags;
    WCHAR wszDescription[DMUS_MAX_DESCRIPTION];
} DMUS_PORTCAPS, *LPDMUS_PORTCAPS;

Members

dwSize
Size of the structure, in bytes. This member must be initialized to sizeof(DMUS_PORTCAPS) before the structure is passed to any method.
dwFlags
Flags describing various capabilities of the port. This field can contain one or more of the following values:
DMUS_PC_DIRECTSOUND
The port supports streaming wave data to DirectSound.
DMUS_PC_DLS
The port supports DLS Level 1 sample collections.
DMUS_PC_DLS2
The port supports DLS Level 2 sample collections.
DMUS_PC_EXTERNAL
The port connects to devices outside the host—for example, devices connected over an external MIDI port such as the MPU-401.
DMUS_PC_GMINHARDWARE
The synthesizer has its own GM instrument set, so GM instruments do not need to be downloaded.
DMUS_PC_GSINHARDWARE
This port contains the Roland GS sound set in hardware.
DMUS_PC_MEMORYSIZEFIXED
Memory available for DLS instruments cannot be adjusted.
DMUS_PC_SHAREABLE
More than one port can be created that uses the same range of channel groups on the device. Unless this bit is set, the port can be opened only in exclusive mode. In exclusive mode, an attempt to create a port fails unless free channel groups are available to assign to the create request.
DMUS_PC_SOFTWARESYNTH
The port is a software synthesizer.
DMUS_PC_XGINHARDWARE
The port contains the Yamaha XG extensions in hardware.
guidPort
Identifier of the port. This value can be passed to the IDirectMusic::CreatePort method to get an IDirectMusicPort interface for the port.
dwClass
Class of this port. The following classes are defined:
DMUS_PC_INPUTCLASS
Input port.
DMUS_PC_OUTPUTCLASS
Output port.
dwType
Type of this port. The following types are defined:
DMUS_PORT_WINMM_DRIVER
Windows multimedia driver.
DMUS_PORT_USER_MODE_SYNTH
User-mode synthesizer.
DMUS_PORT_KERNEL_MODE
WDM driver.
dwMemorySize
Amount of memory available to store DLS instruments. If the port is using system memory and the amount is therefore limited only by the available system memory, this field contains DMUS_PC_SYSTEMMEMORY.
dwMaxChannelGroups
Maximum number of channel groups supported by this port. A channel group is a set of 16 MIDI channels.
dwMaxVoices
Maximum number of voices that can be allocated when this port is opened. The value can be –1 if the driver does not support returning this parameter.
dwMaxAudioChannels
Maximum number of audio channels that can be rendered by the port. The value can be –1 if the driver does not support returning this parameter.
dwEffectFlags
Flags indicating what audio effects are available on the port.

The following flags are defined:

DMUS_EFFECT_NONE
No effects are supported.
DMUS_EFFECT_REVERB
The port supports reverb.
DMUS_EFFECT_CHORUS
The port supports chorus.
wszDescription
Description of the port. This can be a system-generated name, such as L"MPU-401 Output Port [330]", or a user-specified friendly name, such as L"Port w/ External SC-55".

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.


DMUS_PORTPARAMS

The DMUS_PORTPARAMS structure contains parameters for the opening of a DirectMusic port. These parameters are passed in when the IDirectMusic::CreatePort method is called.

typedef struct _DMUS_PORTPARAMS {
    DWORD dwSize;
    DWORD dwValidParams;
    DWORD dwVoices;
    DWORD dwChannelGroups;
    DWORD dwAudioChannels;
    DWORD dwSampleRate;
    DWORD dwEffectFlags;
    DWORD fShare;
} DMUS_PORTPARAMS, *LPDMUS_PORTPARAMS;

Members

dwSize
Size of the structure, in bytes. This member must be initialized to sizeof(DMUS_PORTPARAMS) before the structure is passed to a method.
dwValidParams
Specifies which port parameters in this structure have been filled in. Setting the flag for a particular parameter means that you want to have this parameter set on the method call or want to override the default value when the port is created. The following flags have been defined:

DMUS_PORTPARAMS_VOICES
DMUS_PORTPARAMS_CHANNELGROUPS
DMUS_PORTPARAMS_AUDIOCHANNELS
DMUS_PORTPARAMS_SAMPLERATE
DMUS_PORTPARAMS_EFFECTS
DMUS_PORTPARAMS_SHARE

dwVoices
Number of voices required on this port. This is not an absolute maximum; the port can create additional temporary voices to enable smooth transitions when lower-priority voices have to be dropped.
dwChannelGroups
Number of channel groups to be allocated on this port. Must be less than or equal to the number of channel groups specified in the DMUS_PORTCAPS structure returned by the IDirectMusic::EnumPort and IDirectMusicPort::GetCaps methods.
dwAudioChannels
Desired number of output channels.
dwSampleRate
Desired sample rate, in hertz.
dwEffectFlags
Flags indicating which special effects are desired. The following flags are defined:

DMUS_EFFECT_NONE
DMUS_EFFECT_REVERB
DMUS_EFFECT_CHORUS

fShare
If TRUE, all ports use the channel groups assigned to this port. If FALSE, the port is opened in exclusive mode, and the use of the same channel groups by other ports is forbidden.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.

See Also

DMUS_PORTCAPS


DMUS_RHYTHM_PARAM

The DMUS_RHYTHM_PARAM structure is used as the pParam parameter in calls to the various GetParam methods when the track is a chord track and rguidType is GUID_RhythmParam.

typedef struct {
    DMUS_TIMESIGNATURE  TimeSig;
    DWORD               dwRhythmPattern;
} DMUS_RHYTHM_PARAM;

Members

TimeSig
DMUS_TIMESIGNATURE structure containing the time signature of the rhythm parameter. This structure must be initialized before the DMUS_RHYTHM_PARAM structure is passed to GetParam.
dwRhythmPattern
Rhythm pattern for a sequence of chords. Each bit represents a beat in one or more measures, with 1 signifying a chord on the beat and 0 signifying no chord.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.

See Also

IDirectMusicPerformance::GetParam, IDirectMusicPerformance::SetParam, IDirectMusicSegment::GetParam, IDirectMusicSegment::SetParam, IDirectMusicTrack::GetParam, IDirectMusicTrack::SetParam


DMUS_SUBCHORD

The DMUS_SUBCHORD structure is used in the SubChordList member of a DMUS_CHORD_PARAM structure.

typedef struct {
    DWORD dwChordPattern;
    DWORD dwScalePattern;
    DWORD dwInversionPoints;
    DWORD dwLevels;
    BYTE  bChordRoot;
    BYTE  bScaleRoot;
} DMUS_SUBCHORD;

Members

dwChordPattern
Notes in the subchord. Each of the lower 24 bits represents a semitone, starting with the root at the least significant bit, and the bit is set if the note is in the chord.
dwScalePattern
Notes in the scale. Each of the lower 24 bits represents a semitone, starting with the root at the least significant bit, and the bit is set if the note is in the scale.
dwInversionPoints
Points in the scale at which inversions can occur. Bits that are off signify that the notes in the interval cannot be inverted. Thus, the pattern 100001111111 indicates that inversions are allowed anywhere except between the fifth and seventh degrees of a major scale.
dwLevels
Bit field showing which levels are supported by this subchord. Each part in a style is assigned a level, and this chord is used only for parts whose levels are contained in this member.
bChordRoot
Root of the subchord, in which 0 is the bottom C in the range and 23 is the top B.
bScaleRoot
Root of the scale, in which 0 is the bottom C in the range and 23 is the top B.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


DMUS_SYNTHSTATS

The DMUS_SYNTHSTATS structure is used by the IDirectMusicPort::GetRunningStats method to return the current running status of a synthesizer.

typedef struct DMUS_SYNTHSTATS {
    DWORD dwSize;
    DWORD dwValidStats;
    DWORD dwVoices;
    DWORD dwTotalCPU;
    DWORD dwCPUPerVoice;
    DWORD dwLostNotes;
    DWORD dwFreeMemory;
    long  lPeakVolume;
} DMUS_SYNTHSTATS, *LPDMUS_SYNTHSTATS;

Members

dwSize
Size of the structure, in bytes. This member must be initialized to sizeof(DMUS_SYNTHSTATS) before the structure is passed to a method.
dwValidStats
Flags that specify which fields in this structure have been filled in by the synthesizer. The following flags have been defined:

DMUS_SYNTHSTATS_VOICES
DMUS_SYNTHSTATS_TOTAL_CPU
DMUS_SYNTHSTATS_CPU_PER_VOICE
DMUS_SYNTHSTATS_FREE_MEMORY
DMUS_SYNTHSTATS_LOST_NOTES
DMUS_SYNTHSTATS_PEAK_VOLUME

dwVoices
Average number of voices playing.
dwTotalCPU
Total percentage of the CPU being consumed, multiplied by 100.
dwCPUPerVoice
Percentage of the CPU being consumed per voice, multiplied by 100.
dwLostNotes
Number of notes lost. Notes can be dropped because of voice-stealing or because too much of the CPU is being consumed.
dwFreeMemory
Amount of memory currently available to store DLS instruments. If the synthesizer is using system memory and the amount is therefore limited only by the available system memory, this value is set to DMUS_SYNTHSTATS_SYSTEMMEMORY.
lPeakVolume
Peak volume, measured in hundredths of decibels.

Remarks

All the running status parameters, with the exception of dwFreeMemory, are refreshed every second. For example, dwLostNotes provides the total number of notes lost over a one-second period.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


DMUS_TEMPO_PARAM

The DMUS_TEMPO_PARAM structure is used as the pParam parameter in calls to the various GetParam and SetParam methods when the track is a tempo track and rguidType is GUID_TempoParam.

typedef struct _DMUS_TEMPO_PARAM {
    MUSIC_TIME  mtTime;
    double      dblTempo;
} DMUS_TEMPO_PARAM;

Members

mtTime
Time for which the tempo was retrieved. (This member is not used in SetParam methods, which use their mtTime parameter instead.)
dblTempo
The tempo, in the range from DMUS_TEMPO_MIN through DMUS_TEMPO_MAX.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.

See Also

IDirectMusicPerformance::GetParam, IDirectMusicPerformance::SetParam, IDirectMusicSegment::GetParam, IDirectMusicSegment::SetParam, IDirectMusicTrack::GetParam, IDirectMusicTrack::SetParam


DMUS_TIMESIGNATURE

The DMUS_TIMESIGNATURE structure is passed to the IDirectMusicStyle::GetTimeSignature method to retrieve information about a style's time signature. It is also used in the DMUS_RHYTHM_PARAM structure and in the various GetParam methods when the rguidType parameter is GUID_TimeSignature and the track is a time signature or style track.

typedef struct _DMUS_TIMESIGNATURE {
    MUSIC_TIME mtTime;
    BYTE  bBeatsPerMeasure;
    BYTE  bBeat;
    WORD  wGridsPerBeat;
} DMUS_TIMESIGNATURE;

Members

mtTime
Music time at which this time signature occurs.
bBeatsPerMeasure
Top of time signature.
bBeat
Bottom of time signature.
wGridsPerBeat
Grids (subdivisions) per beat. This value determines the timing resolution for certain music events—for example, segments cued with the DMUS_SEGF_GRID flag (see DMUS_SEGF_FLAGS).

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::GetParam, IDirectMusicPerformance::SetParam, IDirectMusicSegment::GetParam, IDirectMusicSegment::SetParam, IDirectMusicTrack::GetParam, IDirectMusicTrack::SetParam, DMUS_TIMESIG_PMSG


DMUS_VERSION

The DMUS_VERSION structure contains version information for an object described in the DMUS_OBJECTDESC structure.

typedef struct _DMUS_VERSION {
    DWORD  dwVersionMS;
    DWORD  dwVersionLS;
} DMUS_VERSION, FAR *LPDMUS_VERSION;

Members

dwVersionMS
Most significant DWORD of the version number.
dwVersionLS
Least significant DWORD of the version number.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


DMUS_WAVES_REVERB_PARAMS

The DMUS_WAVES_REVERB_PARAMS structure contains information about reverberation effects.

typedef struct _DMUS_WAVES_REVERB_PARAMS {
    float  fInGain;
    float  fReverbMix;
    float  fReverbTime;
    float  fHighFreqRTRatio;
} DMUS_WAVES_REVERB_PARAMS;

Members

fInGain
Input gain, in decibels (to avoid output overflows). The default value is 0.
fReverbMix
Reverb mix, in decibels. A value of 0 means 100 percent wet reverb (no direct signal). Negative values gives less wet signal. The coefficients are calculated so that the overall output level stays approximately constant, regardless of the amount of reverb mix. The default value is –10.0.
fReverbTime
Reverb decay time, in milliseconds. The default value is 1000.
fHighFreqRTRatio
Ratio of the high frequencies to the global reverb time. Unless very bright reverbs are wanted, this should be set to a value less than 1. For example, if fReverbTime is 1000 ms and dHighFreqRTRatio is 0.1, the decay time for high frequencies is 100 ms. The default value is 0.001.

Remarks

The TrueVerb reverberation technology from Waves is licensed to Microsoft as the SimpleVerb implementation for use in the Microsoft Software Synthesizer.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.


KSPROPERTY

The KSPROPERTY structure is passed to the IKsControl::KsProperty method to identify a property and operation.

KSPROPERTY is defined as a KSIDENTIFIER structure, which is declared as follows:

typedef struct {
    union {
        struct {
            GUID   Set;
            ULONG  Id;
            ULONG  Flags;
        };
        LONGLONG    Alignment;
    };
} KSIDENTIFIER, *PKSIDENTIFIER;

Members

Set
Identifier of the property set. The following property-set GUIDs are predefined by DirectMusic:
GUID_DMUS_PROP_DLS1
Item 0 is a Boolean indicating whether or not this port supports downloading DLS samples.
GUID_DMUS_PROP_Effects
Item 0 contains DMUS_EFFECT_NONE or one or more effects flags (see the dwEffectFlags member of DMUS_PORTCAPS). This property is used to set or retrieve the current state of the effects.
GUID_DMUS_PROP_GM_Hardware
Item 0 is a Boolean indicating whether or not this port supports GM in hardware.
GUID_DMUS_PROP_GS_Capable
Item 0 is a Boolean indicating whether or not this port supports the minimum requirements for Roland GS extensions.
GUID_DMUS_PROP_GS_Hardware
Item 0 is a Boolean indicating whether or not this port supports Roland GS extensions in hardware.
GUID_DMUS_PROP_LegacyCaps
Item 0 is the MIDIINCAPS or MIDIOUTCAPS structure that describes the underlying Windows multimedia device implementing this port. A MIDIINCAPS structure is returned if dwClass is DMUS_PC_INPUTCLASS in this port's capabilities structure. Otherwise, a MIDIOUTCAPS structure is returned.
GUID_DMUS_PROP_MemorySize
Item 0 is a Boolean indicating how many bytes of sample RAM are available on this device.
GUID_DMUS_PROP_SynthSink_DSOUND
Item 0 is a Boolean indicating whether or not this port supports DirectSound.
GUID_DMUS_PROP_SynthSink_WAVE
Item 0 is a Boolean indicating whether or not this port supports wave output using the waveOut functions.
GUID_DMUS_PROP_Volume
Item 1 (DMUS_ITEM_Volume) is a LONG in the range from DMUS_VOLUME_MAX through DMUS_VOLUME_MIN. This is the signed value, in hundredths of a decibel, which is added to the gain of all voices after all DLS articulation has been performed. By default, when a port is added to the performance, this property is set to the master volume. For master volume, see Setting and Retrieving Global Parameters.
GUID_DMUS_PROP_WavesReverb
Item 0 is a DMUS_WAVES_REVERB_PARAMS structure containing reverb parameters.
GUID_DMUS_PROP_WriteLatency
Item 0 is the write latency of the user-mode synthesizer (the dwType member of the DMUS_PORTCAPS structure is DMUS_PORT_USER_MODE_SYNTH) that streams its output to DirectSound. The write latency is the delay between when the synthesizer creates a buffer of sound and when it is heard. By adjusting this value, an application can fine-tune the synthesizer for minimum latency without sound breakup. On some computers, in particular ones without hardware support for DirectSound, the initial latency is much larger than on others, so the value should always be read first, and then adjusted with a relative value. The write latency can have different values for each port instance. This property must be set each time the port is activated.
GUID_DMUS_PROP_WritePeriod
Item 0 is the write period, in milliseconds, of the user-mode synthesizer (the dwType member of the DMUS_PORTCAPS structure is DMUS_PORT_USER_MODE_SYNTH) that streams its output to DirectSound. The write period controls how frequently the synthesizer sink allows the synthesizer to mix. By reducing this value, the application can reduce the overall latency of the synthesizer. However, values under 10 milliseconds increase the CPU load. The write period has the same value for all port instances that use the standard DirectSound sink. This property must be set each time the port is activated.
GUID_DMUS_PROP_XG_Capable
Item 0 is a Boolean indicating whether or not this port supports the minimum requirements for Yamaha XG extensions.
GUID_DMUS_PROP_XG_Hardware
Item 0 is a Boolean indicating whether or not this port supports Yamaha XG extensions in hardware.
Id
Item within the property set.
Flags
One of the following flags to specify the operation:
KSPROPERTY_TYPE_GET
To retrieve the given property item's value.
KSPROPERTY_TYPE_SET
To set the given property item's value.
KSPROPERTY_TYPE_BASICSUPPORT
To determine the type of support available for the property set. The data returned by IKsControl::KsProperty in *pvPropertyData is a DWORD containing one or both of KSPROPERTY_TYPE_GET and KSPROPERTY_TYPE_SET, indicating which operations are possible.
Alignment
Not used in DirectMusic.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmksctrl.h.

See Also

Port Property Sets


File Structures

This section contains reference information for data structures used in DirectMusic files. Most applications do not need to know about these structures because each standard DirectMusic object handles the loading of its own data through its IPersistStream interface. The structures are chiefly of interest for music-authoring applications that need to save data in a format compatible with DirectMusic.

The following structures are used in DirectMusic files:

  • DMUS_IO_BAND_ITEM_HEADER
  • DMUS_IO_BAND_TRACK_HEADER
  • DMUS_IO_CHORD
  • DMUS_IO_CHORDENTRY
  • DMUS_IO_CHORDMAP
  • DMUS_IO_CHORDMAP_SIGNPOST
  • DMUS_IO_CHORDMAP_SUBCHORD
  • DMUS_IO_COMMAND
  • DMUS_IO_CURVE_ITEM
  • DMUS_IO_INSTRUMENT
  • DMUS_IO_MOTIFSETTINGS
  • DMUS_IO_MUTE
  • DMUS_IO_NEXTCHORD
  • DMUS_IO_PARTREF
  • DMUS_IO_PATTERN
  • DMUS_IO_REFERENCE
  • DMUS_IO_SEGMENT_HEADER
  • DMUS_IO_SEQ_ITEM
  • DMUS_IO_SIGNPOST
  • DMUS_IO_STYLE
  • DMUS_IO_STYLECURVE
  • DMUS_IO_STYLENOTE
  • DMUS_IO_STYLEPART
  • DMUS_IO_SUBCHORD
  • DMUS_IO_SYSEX_ITEM
  • DMUS_IO_TEMPO_ITEM
  • DMUS_IO_TIMESIG
  • DMUS_IO_TIMESIGNATURE_ITEM
  • DMUS_IO_TOOL_HEADER
  • DMUS_IO_TRACK_HEADER
  • DMUS_IO_VERSION

See Also

DirectMusic File Format


DMUS_IO_BAND_ITEM_HEADER

The DMUS_IO_BAND_ITEM_HEADER structure contains information about a band change. It is used in the Band Track Form.

typedef struct _DMUS_IO_BAND_ITEM_HEADER {
    MUSIC_TIME lBandTime;
} DMUS_IO_BAND_ITEM_HEADER;
lBandTime
Time of the band change.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.


DMUS_IO_BAND_TRACK_HEADER

The DMUS_IO_BAND_TRACK_HEADER structure contains information about the default behavior of a band track. It is used in the Band Track Form.

typedef struct _DMUS_IO_BAND_TRACK_HEADER {
    BOOL bAutoDownload;
} DMUS_IO_BAND_TRACK_HEADER;
bAutoDownload
Flag for automatic downloading of instruments when a segment is played.

Remarks

For more information on automatic downloading, see Using Bands.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.


DMUS_IO_CHORD

The DMUS_IO_CHORD structure contains information about a chord change. It is used in the Chord Track List.

typedef struct _DMUS_IO_CHORD {
    WCHAR       wszName[16];
    MUSIC_TIME  mtTime;
    WORD        wMeasure;
    BYTE        bBeat;
} DMUS_IO_CHORD;
wszName
Name of the chord.
mtTime
Time of the chord.
wMeasure
Measure that the chord falls on.
bBeat
Beat that the chord falls on.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.


DMUS_IO_CHORDENTRY

The DMUS_IO_CHORDENTRY structure contains information about a chord entry. It is used in the Chord-map Form.

typedef struct _DMUS_IO_CHORDENTRY {
    DWORD   dwFlags;
    WORD    wConnectionID;
} DMUS_IO_CHORDENTRY;
dwFlags
Flag indicating whether the chord is a starting chord (bit 2 set) or an ending chord (bit 3 set) in the chord graph.
wConnectionID
Replaces the run-time pointer to this. Each chord entry is tagged with a unique connection identifier.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.


DMUS_IO_CHORDMAP

The DMUS_IO_CHORDMAP structure contains information about a chord map. It is used in the Chord-map Form.

typedef struct _DMUS_IO_CHORDMAP {
    WCHAR   wszLoadName[20];
    DWORD   dwScalePattern;
    DWORD   dwFlags;
} DMUS_IO_CHORDMAP;
wszLoadName
Name of the chord map, used in the object description when the chord map is loaded.
dwScalePattern
Scale associated with the chord map. Each of the lower 24 bits represents a semitone, starting with the root at the least significant bit, and the bit is set if the note is in the scale.
dwFlags
Reserved for future use.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.


DMUS_IO_CHORDMAP_SIGNPOST

The DMUS_IO_CHORDMAP_SIGNPOST structure contains information about a signpost chord in a chord map. It is used in the Chord-map Form.

typedef struct _DMUS_IO_CHORDMAP_SIGNPOST {
    DWORD   dwChords;
    DWORD   dwFlags;
} DMUS_IO_CHORDMAP_SIGNPOST;
dwChords
Types of signpost supported by this chord. The values are used to match against the same values as they appear in templates. Composing from template consists of (among other things) looking for these values in the template and finding actual chords in the chord map that match these values. The following flags are defined:
DMUS_SIGNPOSTF_A
DMUS_SIGNPOSTF_B
DMUS_SIGNPOSTF_C
DMUS_SIGNPOSTF_D
DMUS_SIGNPOSTF_E
DMUS_SIGNPOSTF_F
DMUS_SIGNPOSTF_LETTER
DMUS_SIGNPOSTF_1
DMUS_SIGNPOSTF_2
DMUS_SIGNPOSTF_3
DMUS_SIGNPOSTF_4
DMUS_SIGNPOSTF_5
DMUS_SIGNPOSTF_6
DMUS_SIGNPOSTF_7
DMUS_SIGNPOSTF_ROOT
DMUS_SIGNPOSTF_CADENCE
dwFlags
Flags defining whether this chord is to be preceded by cadence chords. Signpost chords can have up to two cadence chords. This value can be SPOST_CADENCE1 (first cadence), SPOST_CADENCE2 (second cadence), or a combination of these two flags.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.

See Also

DMUS_IO_SIGNPOST


DMUS_IO_CHORDMAP_SUBCHORD

The DMUS_IO_CHORDMAP_SUBCHORD structure contains information about a subchord. It is used in the Chord-map Form.

typedef struct _DMUS_IO_CHORDMAP_SUBCHORD {
    DWORD   dwChordPattern;
    DWORD   dwScalePattern;
    DWORD   dwInvertPattern;
    BYTE    bChordRoot;
    BYTE    bScaleRoot;
    WORD    wCFlags;
    DWORD   dwLevels;
} DMUS_IO_CHORDMAP_SUBCHORD;
dwChordPattern
Notes in the subchord. Each of the lower 24 bits represents a semitone, starting with the root at the least significant bit, and the bit is set if the note is in the chord.
dwScalePattern
Notes in the scale. Each of the lower 24 bits represents a semitone, starting with the root at the least significant bit, and the bit is set if the note is in the scale.
dwInvertPattern
Points in the scale at which inversions can occur. Bits that are off signify that the notes in the interval cannot be inverted. Thus, the pattern 100001111111 indicates that inversions are allowed anywhere except between the fifth and seventh degrees of a major scale.
bChordRoot
Root of the subchord, where 0 is the bottom C in the range and 23 is the top B.
bScaleRoot
Root of the scale, where 0 is the bottom C in the range and 23 is the top B.
wCFlags
Reserved for future use.
dwLevels
Bit field showing which levels are supported by this subchord. Each part in a style is assigned a level, and this chord is used only for parts whose levels are contained in this member.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.

See Also

DMUS_SUBCHORD


DMUS_IO_COMMAND

The DMUS_IO_COMMAND structure contains information about a command event. It is used in the Command Track Chunk.

typedef struct _DMUS_IO_COMMAND {
    MUSIC_TIME  mtTime;
    WORD        wMeasure;
    BYTE        bBeat;
    BYTE        bCommand;
    BYTE        bGrooveLevel;
    BYTE        bGrooveRange;
} DMUS_IO_COMMAND;
mtTime
Time of the command.
wMeasure
Measure that the command falls on.
bBeat
Beat that the command falls on.
bCommand
Command type. See DMUS_COMMANDT_TYPES.
bGrooveLevel
Groove level, or 0 if the command is not a groove command.
bGrooveRange
Amount by which the groove level can be randomized. For instance, if the groove level is 35 and the range is 4, the actual groove level could be anywhere from 33 through 37.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.


DMUS_IO_CURVE_ITEM

The DMUS_IO_CURVE_ITEM structure contains information about a curve event in a track. It is used in the Sequence Track List.

typedef struct _DMUS_IO_CURVE_ITEM {
    MUSIC_TIME  mtStart;
    MUSIC_TIME  mtDuration;
    MUSIC_TIME  mtResetDuration;
    DWORD       dwPChannel;
    short       nOffset;
    short       nStartValue;
    short       nEndValue;
    short       nResetValue;
    BYTE        bType;
    BYTE        bCurveShape;
    BYTE        bCCData;
    BYTE        bFlags;
} DMUS_IO_CURVE_ITEM;
mtStart
Start time of the curve.
mtDuration
Duration of the curve.
mtResetDuration
Time after the curve is finished until the reset value is set.
dwPChannel
Performance channel for the event.
nOffset
Offset from the grid boundary at which the curve occurs, in music time. MIDI curves are associated with the closest grid when loaded, so this value can be positive or negative.
nStartValue
Start value.
nEndValue
End value.
nResetValue
Reset value, set after mtResetDuration or upon a flush or invalidation.
bType
Type of curve. The following types are defined:
DMUS_CURVET_CCCURVE
Continuous controller curve (MIDI Control Change channel voice message; status byte &HBn, where n is the channel number).
DMUS_CURVET_MATCURVE
Monophonic aftertouch curve (MIDI Channel Pressure channel voice message; status byte &HDn).
DMUS_CURVET_PATCURVE
Polyphonic aftertouch curve (MIDI Poly Key Pressure channel voice message, status byte &HDn).
DMUS_CURVET_PBCURVE
Pitch-bend curve (MIDI Pitch Bend channel voice message; status byte &HEn).
bCurveShape
Shape of curve. The following shapes are defined:
DMUS_CURVES_EXP
Exponential curve shape.
DMUS_CURVES_INSTANT
Instant curve shape (beginning and end of curve happen at essentially the same time).
DMUS_CURVES_LINEAR
Linear curve shape.
DMUS_CURVES_LOG
Logarithmic curve shape.
DMUS_CURVES_SINE
Sine curve shape.
bCCData
CC number if this is a control change type.
bFlags
Set to DMUS_CURVE_RESET if the nResetValue must be set when the time is reached or an invalidation occurs because of a transition. If 0, the curve stays permanently at the new value. All other bits are reserved.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.

See Also

DMUS_IO_SEQ_ITEM


DMUS_IO_INSTRUMENT

The DMUS_IO_INSTRUMENT structure contains information about an instrument. It is used in the Band Form.

typedef struct _DMUS_IO_INSTRUMENT {
    DWORD  dwPatch;
    DWORD  dwAssignPatch;
    DWORD  dwNoteRanges[4];
    DWORD  dwPChannel;
    DWORD  dwFlags;
    BYTE   bPan;
    BYTE   bVolume;
    short  nTranspose;
    DWORD  dwChannelPriority;
} DMUS_IO_INSTRUMENT;
dwPatch
MSB, LSB, and program change to define instrument.
dwAssignPatch
MSB, LSB, and program change to assign to instrument when downloading.
dwNoteRanges
128 bits; one for each MIDI note that the instrument must be able to play.
dwPChannel
Performance channel that the instrument plays on.
dwFlags
Control flags. The following values are defined:
DMUS_IO_INST_ASSIGN_PATCH
The dwAssignPatch member is valid.
DMUS_IO_INST_BANKSELECT
The dwPatch member contains a valid bank select, both MSB and LSB.
DMUS_IO_INST_CHANNEL_PRIORITY
The dwChannelPriority member is valid.
DMUS_IO_INST_GM
Instrument is from the General MIDI collection.
DMUS_IO_INST_GS
Instrument is from the Roland GS collection.
DMUS_IO_INST_NOTERANGES
The dwNoteRanges member is valid.
DMUS_IO_INST_PAN
The bPan member is valid.
DMUS_IO_INST_PATCH
The dwPatch member is valid.
DMUS_IO_INST_TRANSPOSE
The nTranspose member is valid.
DMUS_IO_INST_USE_DEFAULT_GM_SET
The default General MIDI instrument set should be downloaded to the port, even if the port has GM in hardware. If a MIDI file with the XG or GS reset system-exclusive message is parsed, the bank-select message is sent, whether or not GUID_StandardMIDIFile was commanded on the band. In other words, GUID_StandardMIDIFile is effective only for pure GM files.
DMUS_IO_INST_VOLUME
The bVolume member is valid.
DMUS_IO_INST_XG
Instrument is from the Yamaha XG collection.
bPan
Pan for the instrument.
bVolume
Volume for the instrument.
nTranspose
Number of semitones to transpose notes.
dwChannelPriority
Channel priority. For a list of defined values, see IDirectMusicPort::GetChannelPriority.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.


DMUS_IO_MOTIFSETTINGS

The DMUS_IO_MOTIFSETTINGS structure contains information about a motif. It is used in the Style Form.

typedef struct _DMUS_IO_MOTIFSETTINGS {
    DWORD       dwRepeats;
    MUSIC_TIME  mtPlayStart;
    MUSIC_TIME  mtLoopStart;
    MUSIC_TIME  mtLoopEnd;
    DWORD       dwResolution;
} DMUS_IO_MOTIFSETTINGS;
dwRepeats
Number of repetitions.
mtPlayStart
Start of playback, normally 0.
mtLoopStart
Start of looping portion, normally 0.
mtLoopEnd
End of looping portion.
dwResolution
Default resolution. See DMUS_TIME_RESOLVE_FLAGS.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.

See Also

IDirectMusicSegment::SetLoopPoints


DMUS_IO_MUTE

The DMUS_IO_MUTE structure contains information about a mute event on a channel. It is used in the Mute Track Chunk.

typedef struct _DMUS_IO_MUTE {
    MUSIC_TIME  mtTime;
    DWORD       dwPChannel;
    DWORD       dwPChannelMap;
} DMUS_IO_MUTE;
mtTime
Time of the event.
dwPChannel
Performance channel to mute or remap.
dwPChannelMap
Channel to which dwPChannel is being mapped, or 0xFFFFFFFF if dwPChannel is to be muted.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.

See Also

DMUS_MUTE_PARAM


DMUS_IO_NEXTCHORD

The DMUS_IO_NEXTCHORD stucture contains information about the next chord in a chord graph. It is used in the Chord-map Form.

typedef struct _DMUS_IO_NEXTCHORD {
    DWORD   dwFlags;
    WORD    nWeight;
    WORD    wMinBeats;
    WORD    wMaxBeats;
    WORD    wConnectionID;
} DMUS_IO_NEXTCHORD;
dwFlags
Reserved for future use.
nWeight
Likelihood (in the range from 1 through 100) that this link is followed when traversing the chord graph.
wMinBeats
Smallest number of beats that this chord is allowed to play in a composed segment.
wMaxBeats
Largest number of beats that this chord is allowed to play in a composed segment.
wConnectionID
Refers to the wConnectionID member of a DMUS_IO_CHORDENTRY structure.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.


DMUS_IO_PARTREF

The DMUS_IO_PARTREF structure contains information about a part reference. It is used in the Style Form.

typedef struct _DMUS_IO_PARTREF {
    GUID  guidPartID;
    WORD  wLogicalPartID;
    BYTE  bVariationLockID;
    BYTE  bSubChordLevel;
    BYTE  bPriority;
    BYTE  bRandomVariation;
} DMUS_IO_PARTREF;
guidPartID
Identifier of the part.
wLogicalPartID
Identifier corresponding to a particular MIDI channel on a port.
bVariationLockID
Parts with the same value in this member always play the same variation.
bSubChordLevel
Subchord level that this part wants. See Remarks.
bPriority
Priority of the part. For information on priorities, see Channels.
bRandomVariation
When set, matching variations play in random order. When clear, matching variations play sequentially.

Remarks

The bSubChordLevel member contains a zero-based index value. At run time, 1 is shifted left by this value to yield a 1-bit value for comparison with the dwLevels member of a DMUS_SUBCHORD structure. Thus, a part with a bSubChordLevel of 0 would be mapped to any subchord that contained 1 in dwLevels.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.


DMUS_IO_PATTERN

The DMUS_IO_PATTERN structure contains information about a pattern. It is used in the Style Form.

typedef struct _DMUS_IO_PATTERN {
    DMUS_IO_TIMESIG  timeSig;
    BYTE             bGrooveBottom;
    BYTE             bGrooveTop;
    WORD             wEmbellishment;
    WORD             wNbrMeasures;
} DMUS_IO_PATTERN;
timeSig
DMUS_IO_TIMESIG structure containing a time signature to override the style's default time signature.
bGrooveBottom
Bottom of the groove range.
bGrooveTop
Top of the groove range.
wEmbellishment
Type of embellishment. See DMUS_COMMANDT_TYPES.
wNbrMeasures
Length of the pattern in measures.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.


DMUS_IO_REFERENCE

The DMUS_IO_REFERENCE structure contains information about a reference to another object that might be stored in another file. It is used in the reference list chunk. See Common Chunks.

typedef struct _DMUS_IO_REFERENCE {
    GUID    guidClassID;
    DWORD   dwValidData;
} DMUS_IO_REFERENCE;
guidClassID
Class identifier.
dwValidData
Flags to indicate which data chunks for the reference are present. For a list of values, see the corresponding member of DMUS_OBJECTDESC.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.


DMUS_IO_SEGMENT_HEADER

The DMUS_IO_SEGMENT_HEADER structure contains information about a segment. It is used in the Segment Form.

typedef struct _DMUS_IO_SEGMENT_HEADER {
    DWORD       dwRepeats;
    MUSIC_TIME  mtLength;
    MUSIC_TIME  mtPlayStart;
    MUSIC_TIME  mtLoopStart;
    MUSIC_TIME  mtLoopEnd;
    DWORD       dwResolution;
} DMUS_IO_SEGMENT_HEADER;
dwRepeats
Number of repetitions.
mtLength
Length of the segment.
mtPlayStart
Start of playback, normally 0.
mtLoopStart
Start of the looping portion, normally 0.
mtLoopEnd
End of the looping portion.
dwResolution
Default resolution. See DMUS_TIME_RESOLVE_FLAGS.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.

See Also

DMUS_IO_MOTIFSETTINGS, IDirectMusicSegment::SetLoopPoints.


DMUS_IO_SEQ_ITEM

The DMUS_IO_SEQ_ITEM structure contains information about an item of data in a sequence track. It is used in the Sequence Track List.

typedef struct _DMUS_IO_SEQ_ITEM {
    MUSIC_TIME  mtTime;
    MUSIC_TIME  mtDuration;
    DWORD       dwPChannel;
    short       nOffset
    BYTE        bStatus;
    BYTE        bByte1;
    BYTE        bByte2;
} DMUS_IO_SEQ_ITEM;
mtTime
Time of the event.
mtDuration
Duration for which the event is valid.
dwPChannel
Performance channel for the event.
nOffset
Offset from the grid boundary at which the note is played, in music time. MIDI notes are associated with the closest grid when loaded, so this value can be positive or negative.
bStatus
MIDI event type. Equivalent to the MIDI status byte, but without channel information.
bByte1
First byte of the MIDI data.
bByte2
Second byte of the MIDI data.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.

See Also

DMUS_IO_CURVE_ITEM, MIDI Messages


DMUS_IO_SIGNPOST

The DMUS_IO_SIGNPOST structure contains information about a signpost in a signpost track to associate it with signpost chords in a chord map. It is used in the Signpost Track Chunk.

typedef struct _DMUS_IO_SIGNPOST {
    MUSIC_TIME  mtTime;
    DWORD       dwChords;
    WORD        wMeasure;
} DMUS_IO_SIGNPOST;
mtTime
Time of the signpost.
dwChords
Types of signpost chords allowed to be associated with this signpost. The values are used to match against the same values as they appear in templates. Composing from a template consists of (among other things) looking for these values in the template and finding actual chords in the chord map that match these values. The following flags are defined:
DMUS_SIGNPOSTF_A
DMUS_SIGNPOSTF_B
DMUS_SIGNPOSTF_C
DMUS_SIGNPOSTF_D
DMUS_SIGNPOSTF_E
DMUS_SIGNPOSTF_F
DMUS_SIGNPOSTF_LETTER
DMUS_SIGNPOSTF_1
DMUS_SIGNPOSTF_2
DMUS_SIGNPOSTF_3
DMUS_SIGNPOSTF_4
DMUS_SIGNPOSTF_5
DMUS_SIGNPOSTF_6
DMUS_SIGNPOSTF_7
DMUS_SIGNPOSTF_ROOT
DMUS_SIGNPOSTF_CADENCE
wMeasure
Measure on which the signpost falls.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.

See Also

DMUS_IO_CHORDMAP_SIGNPOST


DMUS_IO_STYLE

The DMUS_IO_STYLE structure contains information about the time signature and tempo of a style. It is used in the Style Form.

typedef struct _DMUS_IO_STYLE {
    DMUS_IO_TIMESIG  timeSig;
    double           dblTempo;
} DMUS_IO_STYLE;
timeSig
DMUS_IO_TIMESIG structure containing the default time signature for the style.
dblTempo
Tempo of the style.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.


DMUS_IO_STYLECURVE

The DMUS_IO_STYLECURVE structure contains information about a curve in a style. It is used in the Style Form.

typedef struct _DMUS_IO_STYLECURVE {
    MUSIC_TIME  mtGridStart;
    DWORD       dwVariation;
    MUSIC_TIME  mtDuration;
    MUSIC_TIME  mtResetDuration;
    short       nTimeOffset;
    short       nStartValue;
    short       nEndValue;
    short       nResetValue;
    BYTE        bEventType;
    BYTE        bCurveShape;
    BYTE        bCCData;
    BYTE        bFlags;
} DMUS_IO_STYLECURVE;
mtGridStart
Start time of the grid in which the curve occurs.
dwVariation
Variations that this curve belongs to. Each bit corresponds to one of 32 variations.
mtDuration
Duration of the curve.
mtResetDuration
How long after the curve is finished until the reset value is set.
nTimeOffset
Offset from mtGridStart at which the curve occurs.
nStartValue
Start value.
nEndValue
End value.
nResetValue
Reset value, set after mtResetDuration or upon a flush or invalidation.
bEventType
Type of curve. See DMUS_IO_CURVE_ITEM.
bCurveShape
Shape of curve. See DMUS_IO_CURVE_ITEM.
bCCData
CC number if this is a control change type.
bFlags
Set to DMUS_CURVE_RESET if the nResetValue must be set when the time is reached or an invalidation occurs because of a transition. If 0, the curve stays permanently at the new value. All other bits are reserved.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.

See Also

DMUS_CURVE_PMSG, DMUS_IO_CURVE_ITEM


DMUS_IO_STYLENOTE

The DMUS_IO_STYLENOTE structure contains information about a note in a style. It is used in the Style Form.

typedef struct _DMUS_IO_STYLENOTE {
    MUSIC_TIME  mtGridStart;
    DWORD       dwVariation;
    MUSIC_TIME  mtDuration;
    short       nTimeOffset;
    WORD        wMusicValue;
    BYTE        bVelocity;
    BYTE        bTimeRange;
    BYTE        bDurRange;
    BYTE        bVelRange;
    BYTE        bInversionID;
    BYTE        bPlayModeFlags;
} DMUS_IO_STYLENOTE;
mtGridStart
When the note occurs.
dwVariation
Variations that this note belongs to. Each bit corresponds to one of 32 variations.
mtDuration
Duration of the note.
nTimeOffset
Offset from mtGridStart.
wMusicValue
Position in the scale.
bVelocity
Note velocity.
bTimeRange
Range within which to randomize start time.
bDurRange
Range within which to randomize duration.
bVelRange;
Range within which to randomize velocity.
bInversionID
Identifier of inversion group to which this note belongs.
bPlayModeFlags
Flags to override the play mode of the part. For a list of values, see DMUS_PLAYMODE_FLAGS.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.


DMUS_IO_STYLEPART

The DMUS_IO_STYLEPART structure contains information about a musical part. It is used in the Style Form.

typedef struct _DMUS_IO_STYLEPART {
    DMUS_IO_TIMESIG  timeSig;
    DWORD            dwVariationChoices[32];
    GUID             guidPartID;
    WORD             wNbrMeasures;
    BYTE             bPlayModeFlags;
    BYTE             bInvertUpper;
    BYTE             bInvertLower;
} DMUS_IO_STYLEPART;
timeSig
DMUS_IO_TIMESIG structure containing a time signature to override the style's default time signature.
dwVariationChoices
Each WORD corresponds to one of 32 possible variations. The flags set in each WORD indicate which types of chord are supported by that variation (see Remarks). The following flags are defined:
DMUS_VARIATIONF_MAJOR
Seven positions in the scale for major chords.
DMUS_VARIATIONF_MINOR
Seven positions in the scale for minor chords.
DMUS_VARIATIONF_OTHER
Seven positions in the scale for other chords.
DMUS_VARIATIONF_ROOT_SCALE
Handles chord roots in the scale.
DMUS_VARIATIONF_ROOT_FLAT
Handles flat chord roots (based on scale notes).
DMUS_VARIATIONF_ROOT_SHARP
Handles sharp chord roots (based on scale notes).
DMUS_VARIATIONF_TYPE_TRIAD
Handles simple chords for triads.
DMUS_VARIATIONF_TYPE_6AND7
Handles simple chords for 6 and 7.
DMUS_VARIATIONF_TYPE_COMPLEX
Handles complex chords.
DMUS_VARIATIONF_DEST_TO1
Handles transitions to the 1 chord.
DMUS_VARIATIONF_DEST_TO5
Handles transitions to the 5 chord.
DMUS_VARIATIONF_MODES
DMUS_VARIATIONF_IMA25_MODE
DMUS_VARIATIONF_DMUS_MODE
One of these flags is set to indicate the mode. For DirectMusic, this value should always be DMUS_VARIATIONF_DMUS_MODE.
guidPartID
Unique identifier of the part.
wNbrMeasures
Length of the part, in measures.
bPlayModeFlags
Flags to define the play mode. For a list of values, see DMUS_PLAYMODE_FLAGS.
bInvertUpper
Upper limit of inversion.
bInvertLower
Lower limit of inversion.

Remarks

The flags in dwVariationChoices determine the types of chords supported by a given variation in DirectMusic mode. The first seven flags (bits 1 through 7) are set if the variation supports major chords rooted in scale positions. For example, if bits 1, 2, and 4 are set, the variation supports major chords rooted in the tonic, second, and fourth scale positions. The next seven flags serve the same purpose, but for minor chords, and the following seven flags serve the same purpose for chords that are not major or minor (for example, SUS 4 chords). Bits 22, 23, and 24 are set if the variation supports chords rooted in the scale, chords rooted sharp of scale tones, and chords rooted flat of scale tones, respectively. For example, to support a C# minor chord in the scale of C major, bits 8 (for tonic minor) and 24 (for sharp) must be set. Bits 25, 26, and 27 handle chords that are triads, sixth or seventh chords, and chords with extensions, respectively. Bits 28 and 29 handle chords that are followed by tonic and dominant chords, respectively.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.


DMUS_IO_SUBCHORD

The DMUS_IO_SUBCHORD structure contains information about a subchord. It is used in the Chord Track List.

typedef struct _DMUS_IO_SUBCHORD {
    DWORD   dwChordPattern;
    DWORD   dwScalePattern;
    DWORD   dwInversionPoints;
    DWORD   dwLevels;
    BYTE    bChordRoot;
    BYTE    bScaleRoot;
} DMUS_IO_SUBCHORD;
dwChordPattern
Notes in the subchord. Each of the lower 24 bits represents a semitone, starting with the root at the least significant bit, and the bit is set if the note is in the chord.
dwScalePattern
Notes in the scale. Each of the lower 24 bits represents a semitone, starting with the root at the least significant bit, and the bit is set if the note is in the scale.
dwInversionPoints
Points in the scale at which inversions can occur. Bits that are off signify that the notes in the interval cannot be inverted. Thus, the pattern 100001111111 indicates that inversions are allowed anywhere except between the fifth and seventh degrees of a major scale.
dwLevels
Which levels are supported by this subchord. Certain instruments can be assigned different levels (such as to play only the lower subchords of a chord), and this value is a way of mapping subchords to those levels.
bChordRoot
Root of the subchord, where 0 is the bottom C in the range and 23 is the top B.
bScaleRoot
Root of the scale, where 0 is the bottom C in the range and 23 is the top B.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.

See Also

DMUS_SUBCHORD


DMUS_IO_SYSEX_ITEM

The DMUS_IO_SYSEX_ITEM structure contains information about a system-exclusive MIDI message. It is used in the Sysex Track Chunk.

typedef struct _DMUS_IO_SYSEX_ITEM {
    MUSIC_TIME  mtTime;
    DWORD       dwPChannel;
    DWORD       dwSysExLength;
} DMUS_IO_SYSEX_ITEM;
mtTime
Time of the message.
dwPChannel
Performance channel of the event.
dwSysExLength
Length of the data, in bytes.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.

See Also

MIDI System Messages


DMUS_IO_TEMPO_ITEM

The DMUS_IO_TEMPO_ITEM structure contains information about a tempo change in a track. It is used in the Tempo Track Chunk.

typedef struct _DMUS_IO_TEMPO_ITEM {
    MUSIC_TIME  mtTime;
    double      dblTempo;
} DMUS_IO_TEMPO_ITEM;
mtTime
Time of the tempo change.
dblTempo
Tempo, in beats per minute.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.


DMUS_IO_TIMESIG

The DMUS_IO_TIMESIG structure contains information about the time signature of a segment. It is used in the DMUS_IO_STYLE, DMUS_IO_VERSION, and DMUS_IO_PATTERN structures.

typedef struct _DMUS_IO_TIMESIG {
    BYTE  bBeatsPerMeasure;
    BYTE  bBeat;
    WORD  wGridsPerBeat;
} DMUS_IO_TIMESIG;
bBeatsPerMeasure
Beats per measure (top of time signature).
bBeat
Note that receives the beat (bottom of the time signature), where 1 is a whole note, 2 is a half note, 4 is a quarter note, and so on. Zero is a 256th note.
wGridsPerBeat
Grids (subdivisions) per beat.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.

See Also

DMUS_IO_TIMESIGNATURE_ITEM


DMUS_IO_TIMESIGNATURE_ITEM

The DMUS_IO_TIMESIGNATURE_ITEM structure contains information about a time signature change. It is used in the Time Signature Track Chunk.

typedef struct _DMUS_IO_TIMESIGNATURE_ITEM {
    MUSIC_TIME  mtTime;
    BYTE        bBeatsPerMeasure;
    BYTE        bBeat;
    WORD        wGridsPerBeat;
} DMUS_IO_TIMESIGNATURE_ITEM;
mtTime
Time of the event.
bBeatsPerMeasure
Beats per measure (top of time signature).
bBeat
Note that receives the beat (bottom of the time signature), where 1 is a whole note, 2 is a half note, 4 is a quarter note, and so on. Zero is a 256th note.
wGridsPerBeat
Grids (subdivisions) per beat.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.

See Also

DMUS_IO_TIMESIG, DMUS_TIMESIG_PMSG


DMUS_IO_TOOL_HEADER

The DMUS_IO_TOOL_HEADER structure contains information about a tool. It is used in the Tool Form.

typedef struct _DMUS_IO_TOOL_HEADER {
    GUID    guidClassID;
    long    lIndex;
    DWORD   cPChannels;
    FOURCC  ckid;
    FOURCC  fccType;
    DWORD   dwPChannels[1];
} DMUS_IO_TOOL_HEADER;
guidClassID
Class identifier of the tool.
lIndex
Position in the graph.
cPChannels
Number of items in the dwPChannels array.
ckid
Identifier of tool's data chunk. If this value is 0, it is assumed that the chunk is of type LIST, so fccType is valid and must be nonzero.
fccType
List type. If this value is 0, ckid is valid and must be nonzero.
dwPChannels
Array of performance channels for which the tool is valid.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.

See Also

IDirectMusicGraph::InsertTool


DMUS_IO_TRACK_HEADER

The DMUS_IO_TRACK_HEADER structure contains information about a track. It is used in the Track Form.

typedef struct _DMUS_IO_TRACK_HEADER {
    GUID     guidClassID;
    DWORD    dwPosition;
    DWORD    dwGroup;
    FOURCC   ckid;
    FOURCC   fccType;
} DMUS_IO_TRACK_HEADER;
guidClassID
Class identifier of the track.
dwPosition
Position in the track list.
dwGroup
Group bits for the track.
ckid
Identifier of the track's data chunk. If this value is 0, it is assumed that the chunk is of type LIST, so fccType is valid and must be nonzero.
fccType
List type. If this value is 0, ckid is valid and must be nonzero.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.

See Also

IDirectMusicSegment::GetTrackGroup, IDirectMusicSegment::InsertTrack, Track Form


DMUS_IO_VERSION

The DMUS_IO_VERSION structure contains the version number of the data. It is used in the version subchunk of various chunks. See Common Chunks.

typedef struct _DMUS_IO_VERSION {
    DWORD  dwVersionMS;
    DWORD  dwVersionLS;
} DMUS_IO_VERSION;
dwVersionMS
High-order 32 bits of the version number.
dwVersionLS
Low-order 32 bits of the version number.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicf.h.


DLS Structures

This section contains reference information for structures used with downloadable sounds. Most applications do not need to use these structures because DirectMusic handles the details of loading DLS collections and downloading instruments to the synthesizer. They are of interest chiefly for applications that edit DLS.

For an overview of using DLS data, see Low-Level DLS.

For more information on DLS data formats, see the specification from the MIDI Manufacturers Association.

The following structures are included in this section:

  • DMUS_ARTICPARAMS
  • DMUS_ARTICULATION
  • DMUS_ARTICULATION2
  • DMUS_COPYRIGHT
  • DMUS_DOWNLOADINFO
  • DMUS_EXTENSIONCHUNK
  • DMUS_INSTRUMENT
  • DMUS_LFOPARAMS
  • DMUS_MSCPARAMS
  • DMUS_OFFSETTABLE
  • DMUS_PEGPARAMS
  • DMUS_REGION
  • DMUS_VEGPARAMS
  • DMUS_WAVE
  • DMUS_WAVEDATA


DMUS_ARTICPARAMS

The DMUS_ARTICPARAMS structure describes parameters for a DLS articulation chunk. All parameters for articulation are stored in one chunk, which is composed of a series of structures that define each functional area of the articulation. If an instrument or region uses articulation, it references this chunk by index from the DMUS_ARTICULATION chunk.

typedef struct {
    DMUS_LFOPARAMS LFO;
    DMUS_VEGPARAMS VolEG;
    DMUS_PEGPARAMS PitchEG;
    DMUS_MSCPARAMS Misc;
} DMUS_ARTICPARAMS;
LFO
DMUS_LFOPARAMS structure containing parameters for a low-frequency oscillator.
VolEG
DMUS_VEGPARAMS structure containing parameters for a volume-envelope generator.
PitchEG
DMUS_PEGPARAMS structure containing parameters for a pitch-envelope generator.
Misc
DMUS_MSCPARAMS structure containing the initial pan position.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmdls.h.


DMUS_ARTICULATION

The DMUS_ARTICULATION structure describes a DLS instrument articulation chunk. This chunk connects all available DLS articulation data in one list. For example, it might have a DLS Level 1 chunk and a manufacturer's proprietary articulation chunk. The DLS chunk is referenced by ulArt1Idx, whereas all additional articulation chunks are referenced by the list that starts with ulFirstExtCkIdx.

typedef struct {
    ULONG ulArt1Idx;
    ULONG ulFirstExtCkIdx;
} DMUS_ARTICULATION;
ulArt1Idx
Index, in the DMUS_OFFSETTABLE structure, of the DLS articulation chunk. If 0, there is no DLS articulation.
ulFirstExtCkIdx
Index of the first third-party extension chunk. If 0, there are no third-party extension chunks associated with the articulation.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmdls.h.

See Also

DMUS_ARTICULATION2


DMUS_ARTICULATION2

The DMUS_ARTICULATION2 structure describes a DLS instrument-articulation chunk. It is used when the format is defined as DMUS_DOWNLOADINFO_INSTRUMENT2 (declared in the Dmdls.h header file). The DLS level 1 chunk is referenced by ulArt1Idx, and all additional articulation chunks are referenced by the list that starts with ulFirstExtCkIdx. DLS level 2 articulation chunks also use ulNextArtIdx.

typedef struct {
    ULONG ulArt1Idx;
    ULONG ulFirstExtCkIdx;
    ULONG ulNextArtIdx;

} DMUS_ARTICULATION;
ulArt1Idx
Index, in the DMUS_OFFSETTABLE structure, of the DLS articulation chunk. If 0, there is no DLS level 1 or 2 articulation.
ulFirstExtCkIdx
Index of the first third-party extension chunk. If 0, there are no third-party extension chunks associated with the articulation. DLS level 2 chunks can also be placed here.
ulNextArtIdx
Additional articulation chunks to better support DLS level 2 articulations

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmdls.h.

See Also

DMUS_ARTICULATION


DMUS_COPYRIGHT

The DMUS_COPYRIGHT structure describes an optional copyright chunk in DLS data.

typedef struct {
    ULONG cbSize;
    BYTE  byCopyright[ ];
} DMUS_COPYRIGHT;
cbSize
Size of data.
byCopyright[ ]
Copyright data.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmdls.h.


DMUS_DOWNLOADINFO

The DMUS_DOWNLOADINFO structure is used as a header for DLS data to be downloaded to a port. It defines the size and functionality of the download and is always followed by a DMUS_OFFSETTABLE chunk.

typedef struct _DMUS_DOWNLOADINFO {
    DWORD dwDLType;
    DWORD dwDLId;
    DWORD dwNumOffsetTableEntries;
    DWORD cbSize;
} DMUS_DOWNLOADINFO;
dwDLType
Type of data being downloaded. The following types are defined:
DMUS_DOWNLOADINFO_INSTRUMENT
Instrument definition, starting with the DMUS_INSTRUMENT structure
DMUS_DOWNLOADINFO_WAVE
PCM wave data, starting with the DMUS_WAVE structure.
dwDLId
Unique 32-bit identifier for the object. See Remarks.
dwNumOffsetTableEntries
Number of entries in the DMUS_OFFSETTABLE structure that follows.
cbSize
Total size of DMUS_DOWNLOADINFO, DMUS_OFFSETTABLE, and the actual data chunk

Remarks

The identifier in dwDLId is used to connect objects and is obtained by using the IDirectMusicPortDownload::GetDLId method. Primarily it connects the regions in an instrument to wave chunks. For example, if a wave download is given a dwDLId of 3, an instrument chunk downloads with the value 3 placed in the WaveLink.ulTableIndex member of one of its DMUS_REGION structures. This indicates that the region is connected to the wave chunk.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmdls.h.

See Also

Low-Level DLS


DMUS_EXTENSIONCHUNK

The DMUS_EXTENSIONCHUNK structure describes a DLS extension chunk. All extensions to the DLS file format that are unknown to DirectMusic are downloaded in this variable-size chunk.

typedef struct {
    ULONG  cbSize;
    ULONG  ulNextExtCkIdx;
    FOURCC ExtCkID;
    BYTE   byExtCk[ ];
} DMUS_EXTENSIONCHUNK;
cbSize
Size of chunk.
ulNextExtCkIdx
Index, in the DMUS_OFFSETTABLE structure, of the next extension chunk. If 0, there are no more third-party extension chunks
ExtCkID
Chunk identifier.
byExtCk[ ]
Data.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmdls.h.


DMUS_INSTRUMENT

The DMUS_INSTRUMENT structure contains an instrument definition in a DLS download chunk.

typedef struct {
    ULONG ulPatch;
    ULONG ulFirstRegionIdx;
    ULONG ulGlobalArtIdx;
    ULONG ulFirstExtCkIdx;
    ULONG ulCopyrightIdx;
    ULONG ulFlags;
} DMUS_INSTRUMENT;
ulPatch
Patch number of instrument.
ulFirstRegionIdx
Index of first region chunk (see DMUS_REGION) within the instrument. There should always be a region, but for compatibility with future synthesizer architectures, it is acceptable to have 0 in this member.
ulGlobalArtIdx
Index, in the DMUS_OFFSETTABLE structure, of the global articulation chunk (see DMUS_ARTICULATION) for the instrument. If 0, the instrument does not have global articulation.
ulFirstExtCkIdx
Index, in the DMUS_OFFSETTABLE structure, of the first extension chunk (see DMUS_EXTENSIONCHUNK) within the instrument. This is used to add new chunks that DirectMusic is unaware of. If 0, no third-party extension chunks associated with the instrument.
ulCopyrightIdx
Index, in the DMUS_OFFSETTABLE structure, of an optional copyright chunk (see DMUS_COPYRIGHT). If 0, no copyright information is associated with the instrument.
ulFlags
Additional flags for the instrument. The following flag is defined:
DMUS_INSTRUMENT_GM_INSTRUMENT
The instrument is a standard General MIDI instrument. In the case of patch overlap, GM instruments always have lower priority than other DLS instruments. For example, if a GM instrument is downloaded with patch 0 and a non-GM instrument is also downloaded at patch 0, the non-GM instrument is always selected for playback.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmdls.h.


DMUS_LFOPARAMS

The DMUS_LFOPARAMS structure defines the low-frequency oscillator for a DLS articulation chunk. It is used in the DMUS_ARTICPARAMS structure.

typedef struct {
    PCENT pcFrequency;
    TCENT tcDelay;
    GCENT gcVolumeScale;
    PCENT pcPitchScale;
    GCENT gcMWToVolume;
    PCENT pcMWToPitch;
} DMUS_LFOPARAMS;
pcFrequency
Frequency, in pitch units. See Remarks.
tcDelay
Initial delay, in time cents. See Remarks.
gcVolumeScale
Scaling of output to control tremolo, in attenuation units. See Remarks.
pcPitchScale
Scaling of LFO output to control vibrato, in pitch units. See Remarks.
gcMWToVolume
Modulation wheel range to control tremolo, in attenuation units. See Remarks.
pcMWToPitch
Modulation wheel range to control tremolo, in attenuation units. See Remarks.

Remarks

The DLS Level 1 specification defines time cents, pitch cents, and attenuation as 32-bit logarithmic values. See the specification from the MIDI Manufacturers Association for details.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmdls.h.

See Also

DMUS_ARTICPARAMS


DMUS_MSCPARAMS

The DMUS_MSCPARAMS structure defines the pan for a DLS articulation chunk. It is used in the DMUS_ARTICPARAMS structure.

typedef struct {
    PERCENT ptDefaultPan;
} DMUS_MSCPARAMS;
ptDefaultPan
Default pan, ranging from –50 through 50 percent, in units of 0.1 percent shifted left by 16.

Remarks

PERCENT is defined as long. For more information about pan values, see the DLS specification from the MIDI Manufacturers Association.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmdls.h.

See Also

DMUS_ARTICPARAMS


DMUS_OFFSETTABLE

The DMUS_OFFSETTABLE structure is used in the header of DLS instrument data being downloaded to a port.

typedef struct _DMUS_OFFSETTABLE {
    ULONG ulOffsetTable[DMUS_DEFAULT_SIZE_OFFSETTABLE];
} DMUS_OFFSETTABLE;
ulOffsetTable
Array of byte offsets into the data.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmdls.h.

See Also

Low-Level DLS


DMUS_PEGPARAMS

The DMUS_PEGPARAMS structure defines the pitch envelope for a DLS articulation chunk. It is used in the DMUS_ARTICPARAMS structure.

typedef struct {
    TCENT   tcAttack;
    TCENT   tcDecay;
    PERCENT ptSustain;
    TCENT   tcRelease;
    TCENT   tcVel2Attack;
    TCENT   tcKey2Decay;
    PCENT   pcRange;
} DMUS_PEGPARAMS;
tcAttack
Attack time, in time cents. See Remarks.
tcDecay
Decay time, in time cents. See Remarks.
ptSustain
Sustain, in hundredths of a percent shifted left by 16.
tcRelease
Release time, in time cents. See Remarks.
tcVel2Attack
Velocity to attack, in time cents. See Remarks.
tcKey2Decay
Key to decay, in time cents. See Remarks.
pcRange
Envelope range, in pitch units. See Remarks.

Remarks

The DLS Level 1 specification defines time cents and pitch cents as 32-bit logarithmic values. See the specification from the MIDI Manufacturers Association for details about the values in this structure.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmdls.h.

See Also

DMUS_ARTICPARAMS


DMUS_REGION

The DMUS_REGION structure defines a region for a DLS download. One or more regions can be embedded in an instrument buffer and referenced by the instrument header chunk, DMUS_INSTRUMENT.

typedef struct {
    RGNRANGE RangeKey;
    RGNRANGE RangeVelocity;
    USHORT   fusOptions;
    USHORT   usKeyGroup;
    ULONG    ulRegionArtIdx;
    ULONG    ulNextRegionIdx;
    ULONG    ulFirstExtCkIdx;
    WAVELINK WaveLink;
    WSMPL    WSMP;
    WLOOP    WLOOP[1];
} DMUS_REGION;
RangeKey
Key range for this region.
RangeVelocity
Velocity range for this region.
fusOptions
Options for the synthesis of this region. The following flag is defined:
F_RGN_OPTION_SELFNONEXCLUSIVE
If a second note-on for the same note is received by the synthesis engine, the second note is played, as well as the first. This option is off by default so that the synthesis engine forces a note-off of the first note.
usKeyGroup
Key group for a drum instrument. Key group values allow multiple regions within a drum instrument to belong to the same group. If a synthesis engine is instructed to play a note with a key group setting and any other notes are currently playing with this same key group, the synthesis engine turns off all notes with the same key group value as soon as possible. Currently, key groups from 1 through 15 are legal, and 0 indicates no key group.
ulRegionArtIdx
Index, in the DMUS_OFFSETTABLE structure, of the global articulation chunk for the region. If 0, the region does not have an articulation and relies on the instrument's global articulation.
ulNextRegionIdx
Index, in the DMUS_OFFSETTABLE structure, of the next region in the region list. If 0, there are no more regions.
ulFirstExtCkIdx
Index, in the DMUS_OFFSETTABLE structure, of the third-party extension chunk list. If 0, no extension chunks are associated with the region.
WaveLink
Standard DLS structure (declared in the Dls1.h header file) for managing a link from the region to a wave. The ulTableIndex member of the WAVELINK structure contains the download identifier of the associated wave buffer. (For more information, see DMUS_DOWNLOADINFO and Low-Level DLS.)
WSMP
Standard DLS structure (declared in Dls1.h) for managing the playback of the wave. If the cSampleLoops member is 1, the following WLOOP structure carries the loop start and end points.
WLOOP[ ]
Standard DLS structure (declared in Dls1.h) for describing a loop.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmdls.h.


DMUS_VEGPARAMS

The DMUS_VEGPARAMS structure defines a volume envelope for a DLS articulation chunk.

typedef struct {
    TCENT   tcAttack;
    TCENT   tcDecay;
    PERCENT ptSustain;
    TCENT   tcRelease;
    TCENT   tcVel2Attack;
    TCENT   tcKey2Decay;
} DMUS_VEGPARAMS;
tcAttack
Attack time, in time cents. See Remarks.
tcDecay
Decay time, in time cents. See Remarks.
ptSustain
Sustain, in hundredths of a percent and shifted left by 16.
tcRelease
Release time, in time cents. See Remarks.
tcVel2Attack
Velocity to attack, in time cents. See Remarks.
tcKey2Decay
Key to decay, in time cents. See Remarks.

Remarks

The DLS Level 1 specification defines time cents as a 32-bit logarithmic value. See the specification from the MIDI Manufacturers Association for details about the values in this structure.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmdls.h.

See Also

DMUS_ARTICPARAMS


DMUS_WAVE

The DMUS_WAVE structure defines a wave chunk for a DLS download.

typedef struct {
    ULONG  ulFirstExtCkIdx;
    ULONG  ulCopyrightIdx;
    ULONG  ulWaveDataIdx;
    WAVEFORMATEX   WaveformatEx;
} DMUS_WAVE;
ulFirstExtCkIdx
Index, in the DMUS_OFFSETTABLE structure, of third-party extension chunks. If 0, no extension chunks are associated with the wave.
ulCopyrightIdx
Index, in the DMUS_OFFSETTABLE structure, of copyright chunks. If 0, no copyright information is associated with the wave.
ulWaveDataIdx
Index, in the DMUS_OFFSETTABLE structure, of wave data. See DMUS_WAVEDATA.
WaveformatEx
Wave format of the chunk.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmdls.h.


DMUS_WAVEDATA

The DMUS_WAVEDATA structure comprises a data chunk for a DLS wave download. The nature of the wave data is defined by the WAVEFORMATEX chunk, embedded in the DMUS_WAVE structure.

typedef struct {
    ULONG cbSize;
    BYTE byData[ ];
} DMUS_WAVEDATA;
cbSize
Size of data.
byData[ ]
PCM wave data.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmdls.h.


Enumerated Types

This section contains references for the following enumerated types:

  • DMUS_CLOCKTYPE
  • DMUS_COMMANDT_TYPES
  • DMUS_COMPOSEF_FLAGS
  • DMUS_NOTEF_FLAGS
  • DMUS_PLAYMODE_FLAGS
  • DMUS_PMSGF_FLAGS
  • DMUS_PMSGT_TYPES
  • DMUS_SEGF_FLAGS
  • DMUS_SHAPET_TYPES
  • DMUS_TIME_RESOLVE_FLAGS
  • DMUS_TRACKF_FLAGS


DMUS_CLOCKTYPE

The members of the DMUS_CLOCKTYPE enumeration are used in the ctType member of the DMUS_CLOCKINFO structure.

typedef enum {
    DMUS_CLOCK_SYSTEM = 0,
    DMUS_CLOCK_WAVE   = 1
} DMUS_CLOCKTYPE;
DMUS_CLOCK_SYSTEM
Clock is the system clock.
DMUS_CLOCK_WAVE
Clock is on a wave-playback device.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusicc.h.


DMUS_COMMANDT_TYPES

The members of the DMUS_COMMANDT_TYPES enumeration are used in the wCommand parameter of the IDirectMusicComposer::AutoTransition and IDirectMusicComposer::ComposeTransition methods and in the bCommand member of the DMUS_COMMAND_PARAM structure.

enum enumDMUS_COMMANDT_TYPES {
    DMUS_COMMANDT_GROOVE      = 0,
    DMUS_COMMANDT_FILL        = 1,
    DMUS_COMMANDT_INTRO       = 2,
    DMUS_COMMANDT_BREAK       = 3,
    DMUS_COMMANDT_END         = 4,
    DMUS_COMMANDT_ENDANDINTRO = 5
} DMUS_COMMANDT_TYPES;
DMUS_COMMANDT_GROOVE
The command is a groove command.
DMUS_COMMANDT_FILL
The command is a fill.
DMUS_COMMANDT_INTRO
The command is an introduction.
DMUS_COMMANDT_BREAK
The command is a break.
DMUS_COMMANDT_END
The command is an ending.
DMUS_COMMANDT_ENDANDINTRO
The command is an ending and an introduction.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


DMUS_COMPOSEF_FLAGS

The DMUS_COMPOSEF_FLAGS are used in the dwFlags parameter of the IDirectMusicComposer::ComposeTransition and IDirectMusicComposer::AutoTransition methods.

typedef enum enumDMUS_COMPOSEF_FLAGS {
    DMUS_COMPOSEF_NONE                = 0,
    DMUS_COMPOSEF_ALIGN             = 0x1,
    DMUS_COMPOSEF_OVERLAP           = 0x2,
    DMUS_COMPOSEF_IMMEDIATE         = 0x4,
    DMUS_COMPOSEF_GRID              = 0x8,
    DMUS_COMPOSEF_BEAT             = 0x10,
    DMUS_COMPOSEF_MEASURE          = 0x20,
    DMUS_COMPOSEF_AFTERPREPARETIME = 0x40,
    DMUS_COMPOSEF_MODULATE       = 0x1000,
    DMUS_COMPOSEF_LONG           = 0x2000
}  DMUS_COMPOSEF_FLAGS;
DMUS_COMPOSEF_NONE
No flags. By default, the transition starts on a measure boundary.
DMUS_COMPOSEF_ALIGN
Align transition to the time signature of the currently playing segment. This flag is not currently implemented.
DMUS_COMPOSEF_OVERLAP
Overlap the transition into pToSeg. This flag is not currently implemented.
DMUS_COMPOSEF_IMMEDIATE
AutoTransition only. Start transition on a music or a reference-time boundary.
DMUS_COMPOSEF_GRID
AutoTransition only. Start transition on a grid boundary.
DMUS_COMPOSEF_BEAT
AutoTransition only. Start transition on a beat boundary.
DMUS_COMPOSEF_MEASURE
AutoTransition only. Start transition on a measure boundary.
DMUS_COMPOSEF_AFTERPREPARETIME
AutoTransition only. Use the DMUS_SEGF_AFTERPREPARETIME flag when cuing the transition.
DMUS_COMPOSEF_MODULATE
Compose a transition that modulates smoothly from pFromSeg to pToSeg, using the chord of pToSeg.
DMUS_COMPOSEF_LONG
Composes a long transition. If this flag is not set, the length of the transition is at most one measure unless the wCommand parameter of ComposeTransition or AutoTransition specifies an ending and the style contains an ending of greater than one measure. If this flag is set, the length of the transition increases by one measure.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

DMUS_SEGF_FLAGS


DMUS_NOTEF_FLAGS

The DMUS_NOTEF_FLAGS are used in the bFlags member of the DMUS_NOTE_PMSG structure.

typedef enum enumDMUS_NOTEF_FLAGS {
    DMUS_NOTEF_NOTEON = 1,
} DMUS_NOTEF_FLAGS;
DMUS_NOTEF_NOTEON
Set if this is a MIDI note-on; clear if it is a MIDI note-off. When a DMUS_NOTE_PMSG is first sent by the IDirectMusicPerformance::SendPMsg method, this flag should be set.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


DMUS_PLAYMODE_FLAGS

The DMUS_PLAYMODE_FLAGS are used in various structures for the basic play modes. The play mode determines how a music value is transposed to a MIDI note.

typedef enum enumDMUS_PLAYMODE_FLAGS {
    DMUS_PLAYMODE_KEY_ROOT          = 1,
    DMUS_PLAYMODE_CHORD_ROOT        = 2,
    DMUS_PLAYMODE_SCALE_INTERVALS   = 4,
    DMUS_PLAYMODE_CHORD_INTERVALS   = 8,
    DMUS_PLAYMODE_NONE              = 16,
} DMUS_PLAYMODE_FLAGS;
DMUS_PLAYMODE_KEY_ROOT
Transpose over the key root.
DMUS_PLAYMODE_CHORD_ROOT
Transpose over the chord root.
DMUS_PLAYMODE_SCALE_INTERVALS
Use scale intervals from a scale pattern.
DMUS_PLAYMODE_CHORD_INTERVALS
Use chord intervals from a chord pattern.
DMUS_PLAYMODE_NONE
No mode. Indicates that the parent part's mode should be used.

Remarks

The following defined values represent combinations of play mode flags:

DMUS_PLAYMODE_ALWAYSPLAY
Combination of DMUS_PLAYMODE_SCALE_INTERVALS, DMUS_PLAYMODE_CHORD_INTERVALS, and DMUS_PLAYMODE_CHORD_ROOT. If it is desirable to play a note that is above the top of the chord, this mode finds a position for the note by using intervals from the scale. Essentially, this mode is a combination of the normal and melodic playback modes, in which a failure in normal mode causes a second try in melodic mode.
DMUS_PLAYMODE_FIXED
Interpret the music value as a MIDI value. This is defined as 0 and signifies the absence of other flags. This flag is used for drums, sound effects, and sequenced notes that should not be transposed by the chord or scale.
DMUS_PLAYMODE_FIXEDTOCHORD
Same as DMUS_PLAYMODE_CHORD_ROOT. The music value is a fixed MIDI value, but it is transposed over the chord root.
DMUS_PLAYMODE_FIXEDTOKEY
Same as DMUS_PLAYMODE_KEY_ROOT. The music value is a fixed MIDI value, but it is transposed over the key root.
DMUS_PLAYMODE_MELODIC
Combination of DMUS_PLAYMODE_CHORD_ROOT and DMUS_PLAYMODE_SCALE_INTERVALS. The chord root is used, but the notes only track the intervals in the scale. The key root and chord intervals are ignored. This is useful for melodic lines that play relative to the chord root.
DMUS_PLAYMODE_NORMALCHORD
Combination of DMUS_PLAYMODE_CHORD_ROOT and DMUS_PLAYMODE_CHORD_INTERVALS. This is the prevalent playback mode. The notes track the intervals in the chord, which is based on the chord root. If there is a scale component to the music value, the additional intervals are pulled from the scale and added. If the chord does not have an interval to match the chord component of the music value, the note is silent.
DMUS_PLAYMODE_PEDALPOINT
Combination of DMUS_PLAYMODE_KEY_ROOT and DMUS_PLAYMODE_SCALE_INTERVALS. The key root is used, and the notes only track the intervals in the scale. The chord root and intervals are ignored. This is useful for melodic lines that play relative to the key root.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::MIDIToMusic, IDirectMusicPerformance::MusicToMIDI, DMUS_NOTE_PMSG, DMUS_IO_STYLENOTE, DMUS_IO_STYLEPART, Music Values and MIDI Notes


DMUS_PMSGF_FLAGS

The members of the DMUS_PMSGF_FLAGS enumeration are used in the dwFlags member of the DMUS_PMSG structure.

enum enumDMUS_PMSGF_FLAGS {
    DMUS_PMSGF_REFTIME        = 1,
    DMUS_PMSGF_MUSICTIME      = 2,
    DMUS_PMSGF_TOOL_IMMEDIATE = 4,
    DMUS_PMSGF_TOOL_QUEUE     = 8,
    DMUS_PMSGF_TOOL_ATTIME    = 16,
    DMUS_PMSGF_TOOL_FLUSH     = 32
} DMUS_PMSGF_FLAGS;
DMUS_PMSGF_REFTIME
The rtTime member is valid.
DMUS_PMSGF_MUSICTIME
The mtTime member is valid.
DMUS_PMSGF_TOOL_IMMEDIATE
Message should be processed immediately, regardless of its time stamp.
DMUS_PMSGF_TOOL_QUEUE
Message should be processed just before its time stamp, allowing for port latency.
DMUS_PMSGF_TOOL_ATTIME
Message should be processed at the time stamp.
DMUS_PMSGF_TOOL_FLUSH
Message is being flushed.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::SendPMsg, IDirectMusicTool::GetMsgDeliveryType


DMUS_PMSGT_TYPES

The members of the DMUS_PMSGT_TYPES enumeration are used in the dwType member of the DMUS_PMSG structure to identify the type of message.

typedef enum enumDMUS_PMSGT_TYPES {
    DMUS_PMSGT_MIDI             = 0,
    DMUS_PMSGT_NOTE             = 1,
    DMUS_PMSGT_SYSEX            = 2,
    DMUS_PMSGT_NOTIFICATION     = 3,
    DMUS_PMSGT_TEMPO            = 4,
    DMUS_PMSGT_CURVE            = 5,
    DMUS_PMSGT_TIMESIG          = 6,
    DMUS_PMSGT_PATCH            = 7,
    DMUS_PMSGT_TRANSPOSE        = 8,
    DMUS_PMSGT_CHANNEL_PRIORITY = 9,
    DMUS_PMSGT_STOP             = 10,
    DMUS_PMSGT_DIRTY            = 11,
    DMUS_PMSGT_USER             = 255
} DMUS_PMSGT_TYPES;
DMUS_PMSGT_MIDI
MIDI channel message. See DMUS_MIDI_PMSG.
DMUS_PMSGT_NOTE
Music note. See DMUS_NOTE_PMSG.
DMUS_PMSGT_SYSEX
MIDI system-exclusive message. See DMUS_SYSEX_PMSG.
DMUS_PMSGT_NOTIFICATION
Notification message. See DMUS_NOTIFICATION_PMSG.
DMUS_PMSGT_TEMPO
Tempo message. See DMUS_TEMPO_PMSG.
DMUS_PMSGT_CURVE
Control change and pitch-bend curve. See DMUS_CURVE_PMSG.
DMUS_PMSGT_TIMESIG
Time signature. See DMUS_TIMESIG_PMSG.
DMUS_PMSGT_PATCH
Patch change. See DMUS_PATCH_PMSG.
DMUS_PMSGT_TRANSPOSE
Transposition. See DMUS_TRANSPOSE_PMSG.
DMUS_PMSGT_CHANNEL_PRIORITY
Channel priority change. See DMUS_CHANNEL_PRIORITY_PMSG.
DMUS_PMSGT_STOP
Stop message. See DMUS_PMSG.
DMUS_PMSGT_DIRTY
A control segment has started or ended. See DMUS_PMSG.
DMUS_PMSGT_USER
User-defined message.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


DMUS_SEGF_FLAGS

The members of the DMUS_SEGF_FLAGS enumeration are passed to various methods of IDirectMusicPerformance to control the timing and other aspects of actions on a segment.

typedef enum enumDMUS_SEGF_FLAGS {
    DMUS_SEGF_REFTIME          = 64,
    DMUS_SEGF_SECONDARY        = 128,
    DMUS_SEGF_QUEUE            = 256,
    DMUS_SEGF_CONTROL          = 512
    DMUS_SEGF_AFTERPREPARETIME = 1<<10,
    DMUS_SEGF_GRID             = 1<<11,
    DMUS_SEGF_BEAT             = 1<<12,
    DMUS_SEGF_MEASURE          = 1<<13,
    DMUS_SEGF_DEFAULT          = 1<<14,
    DMUS_SEGF_NOINVALIDATE     = 1<<15,
} DMUS_SEGF_FLAGS;
DMUS_SEGF_REFTIME
Time parameter is in reference time.
DMUS_SEGF_SECONDARY
Secondary segment.
DMUS_SEGF_QUEUE
Put at the end of the primary segment queue (primary segment only).
DMUS_SEGF_CONTROL
Play as a control segment (secondary segments only). See Remarks.
DMUS_SEGF_AFTERPREPARETIME
Play after the prepare time. See IDirectMusicPerformance::GetPrepareTime.
DMUS_SEGF_GRID
Play on a grid boundary.
DMUS_SEGF_BEAT
Play on a beat boundary.
DMUS_SEGF_MEASURE
Play on a measure boundary.
DMUS_SEGF_DEFAULT
Use the segment's default boundary.
DMUS_SEGF_NOINVALIDATE
Setting this flag in IDirectMusicPerformance::PlaySegment for a primary or control segment causes the new segment not to cause an invalidation. Without this flag, an invalidation occurs, cutting off and resetting any currently playing curve or note. This flag should be combined with DMUS_SEGF_AFTERPREPARETIME so that notes in the new segment do not play over notes played by the old segment.

Remarks

Normally the primary segment is the control segment. The DMUS_SEGF_CONTROL flag can be used to make a secondary segment the control segment. There should be only one control segment at a time. (It is possible to create multiple control segments, but there is no guarantee of which one is actually used by DirectMusic as the control segment.) When a track calls GetParam on another track, it does so on the control segment. By default, only the control segment sends tempo messages.

If the DMUS_SEGF_CONTROL flag is set, DMUS_SEGF_SECONDARY is assumed.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance::Invalidate, IDirectMusicPerformance::PlaySegment, IDirectMusicPerformance::Stop, IDirectMusicSegment::GetDefaultResolution, IDirectMusicSegment::SetDefaultResolution, DMUS_TIME_RESOLVE_FLAGS


DMUS_SHAPET_TYPES

The members of the DMUS_SHAPET_TYPES enumeration are used in the wShape parameter of the IDirectMusicComposer::ComposeSegmentFromShape and IDirectMusicComposer::ComposeTemplateFromShape methods to specify the desired pattern of the groove level.

typedef enum enumDMUS_SHAPET_TYPES {
    DMUS_SHAPET_FALLING  = 0,
    DMUS_SHAPET_LEVEL    = 1,
    DMUS_SHAPET_LOOPABLE = 2,
    DMUS_SHAPET_LOUD     = 3,
    DMUS_SHAPET_QUIET    = 4,
    DMUS_SHAPET_PEAKING  = 5,
    DMUS_SHAPET_RANDOM   = 6,
    DMUS_SHAPET_RISING   = 7,
    DMUS_SHAPET_SONG     = 8
} DMUS_SHAPET_TYPES;
DMUS_SHAPET_FALLING
Groove level falls.
DMUS_SHAPET_LEVEL
Groove level remains even.
DMUS_SHAPET_LOOPABLE
Segment is arranged to loop back to the beginning.
DMUS_SHAPET_LOUD
Groove level is high.
DMUS_SHAPET_QUIET
Groove level is low.
DMUS_SHAPET_PEAKING
Groove level rises to a peak, then falls.
DMUS_SHAPET_RANDOM
Groove level is random.
DMUS_SHAPET_RISING
Groove level rises.
DMUS_SHAPET_SONG
Segment is in a song form. Several phrases of 6 to 8 bars are composed and put together to give a verse-chorus effect, with variations in groove level.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


DMUS_TIME_RESOLVE_FLAGS

The member of the DMUS_TIME_RESOLVE_FLAGS enumeration are used in the dwFlags member of the DMUS_PMSG structure and in the dwTimeResolveFlags parameter of the IDirectMusicPerformance::GetResolvedTime method.

typedef enum enumDMUS_TIME_RESOLVE_FLAGS {
    DMUS_TIME_RESOLVE_AFTERPREPARETIME = 1<<10,
    DMUS_TIME_RESOLVE_GRID             = 1<<11,
    DMUS_TIME_RESOLVE_BEAT             = 1<<12,
    DMUS_TIME_RESOLVE_MEASURE          = 1<<13
} DMUS_TIME_RESOLVE_FLAGS;
DMUS_TIME_RESOLVE_AFTERPREPARETIME
Resolve to a time after the prepare time.
DMUS_TIME_RESOLVE_GRID
Resolve to a time on a grid boundary.
DMUS_TIME_RESOLVE_BEAT
Resolve to a time on a beat boundary.
DMUS_TIME_RESOLVE_MEASURE
Resolve to a time on a measure boundary.

Remarks

These flags can be used interchangeably with the corresponding DMUS_SEGF_FLAGS.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


DMUS_TRACKF_FLAGS

The DMUS_TRACKF_FLAGS values are used in the dwFlags parameter of the IDirectMusicTrack::Play method.

typedef enum enumDMUS_TRACKF_FLAGS {
    DMUS_TRACKF_SEEK   = 1,
    DMUS_TRACKF_LOOP   = 2,
    DMUS_TRACKF_START  = 4,
    DMUS_TRACKF_FLUSH  = 8,
    DMUS_TRACKF_DIRTY  = 16
} DMUS_TRACKF_FLAGS;
DMUS_TRACKF_SEEK
IDirectMusicTrack::Play was called in response to seeking, meaning that the mtStart parameter is not necessarily the same as the mtEnd of the previous call.
DMUS_TRACKF_LOOP
Play was called in response to a loop.
DMUS_TRACKF_START
This is the first call to IDirectMusicTrack::Play. DMUS_TRACKF_SEEK can also be set if the track is not playing from the beginning.
DMUS_TRACKF_FLUSH
Play was called in response to a flush or invalidation that requires the track to replay something that it played previously. In this case, DMUS_TRACKF_SEEK is set, as well.
DMUS_TRACKF_DIRTY
A control segment has begun or ended. Tracks that normally wait until mtNext to call IDirectMusicTrack::GetParam should make the call right away, instead of waiting, because their data might now be invalid. For more information on setting control segments, see DMUS_SEGF_FLAGS.

Remarks

When Play is called in response to a repeat, DMUS_TRACKF_LOOP and DMUS_TRACKF_SEEK are set.

Tracks must support seeking to support invalidation.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dmusici.h.


Return Values

The following are the values typically returned by DirectMusic interface methods. For a list of the error codes that each method can return, see the individual method descriptions. These lists are not necessarily comprehensive.

DMUS_E_ALL_TOOLS_FAILED
The graph object was unable to load all tools from the IStream object data, perhaps because of errors in the stream or because the tools are incorrectly registered on the client.
DMUS_E_ALL_TRACKS_FAILED
The segment object was unable to load all tracks from the IStream object data, perhaps because of errors in the stream or because the tracks are incorrectly registered on the client.
DMUS_E_ALREADY_ACTIVATED
The port has been activated, and the parameter cannot be changed.
DMUS_E_ALREADY_DOWNLOADED
The buffer has already been downloaded.
DMUS_E_ALREADY_EXISTS
The tool is already contained in the graph. You must create a new instance.
DMUS_E_ALREADY_INITED
The object has already been initialized.
DMUS_E_ALREADY_LOADED
A DLS collection is already open.
DMUS_E_ALREADY_SENT
The message has already been sent.
DMUS_E_ALREADYCLOSED
The port is not open.
DMUS_E_ALREADYOPEN
The port was already opened.
DMUS_E_BADARTICULATION
Invalid articulation chunk in DLS collection.
DMUS_E_BADINSTRUMENT
Invalid instrument chunk in DLS collection.
DMUS_E_BADOFFSETTABLE
The offset table has errors.
DMUS_E_BADWAVE
Corrupt wave header.
DMUS_E_BADWAVELINK
The wave-link chunk in DLS collection points to invalid wave.
DMUS_E_BUFFER_EMPTY
There is no data in the buffer.
DMUS_E_BUFFER_FULL
The specified number of bytes exceeds the maximum buffer size.
DMUS_E_BUFFERNOTAVAILABLE
The buffer is not available for download.
DMUS_E_BUFFERNOTSET
No buffer was prepared for the data.
DMUS_E_CANNOT_CONVERT
The requested conversion between music and MIDI values could not be made. This usually occurs when the provided DMUS_CHORD_KEY structure has an invalid chord or scale pattern.
DMUS_E_CANNOT_FREE
The message could not be freed, either because it was not allocated or because it has already been freed.
DMUS_E_CANNOT_OPEN_PORT
The default system port could not be opened.
DMUS_E_CANNOTREAD
An error occurred when trying to read from the IStream object.
DMUS_E_CANNOTSEEK
The IStream object does not support Seek.
DMUS_E_CANNOTWRITE
The IStream object does not support Write.
DMUS_E_CHUNKNOTFOUND
A chunk with the specified header could not be found.
DMUS_E_DESCEND_CHUNK_FAIL
An attempt to descend into a chunk failed.
DMUS_E_DEVICE_IN_USE
The device is already in use (possibly by a non-DirectMusic client) and cannot be opened again.
DMUS_E_DMUSIC_RELEASED
The operation cannot be performed because the final instance of the DirectMusic object was released. Ports cannot be used after final release of the DirectMusic object.
DMUS_E_DRIVER_FAILED
An unexpected error was returned from a device driver, indicating possible failure of the driver or hardware.
DMUS_E_DSOUND_ALREADY_SET
A DirectSound object has already been set.
DMUS_E_DSOUND_NOT_SET
The port could not be created because no DirectSound object has been specified.
DMUS_E_GET_UNSUPPORTED
Getting the parameter is not supported.
DMUS_E_INSUFFICIENTBUFFER
The buffer is not large enough for the requested operation.
DMUS_E_INVALID_BAND
The file does not contain a valid band.
DMUS_E_INVALID_DOWNLOADID
An invalid download identifier was used in the process of creating a download buffer.
DMUS_E_INVALID_EVENT
The event either is not a valid MIDI message or makes use of running status and cannot be packed into the buffer.
DMUS_E_INVALID_TOOL_HDR
The IStream object's data contains an invalid tool header and, therefore, cannot be read by the graph object.
DMUS_E_INVALID_TRACK_HDR
The IStream object's data contains an invalid track header and, therefore, cannot be read by the segment object.
DMUS_E_INVALIDBUFFER
An invalid DirectSound buffer was handed to a port.
DMUS_E_INVALIDFILE
Not a valid file.
DMUS_E_INVALIDOFFSET
Wave chunks in the DLS collection file are at incorrect offsets.
DMUS_E_INVALIDPATCH
No instrument in the collection matches the patch number.
DMUS_E_INVALIDPOS
Error reading wave data from a DLS collection. Indicates bad file.
DMUS_E_LOADER_BADPATH
The file path is invalid.
DMUS_E_LOADER_FAILEDCREATE
The object could not be found or created.
DMUS_E_LOADER_FAILEDOPEN
File open failed because the file does not exist or is locked.
DMUS_E_LOADER_FORMATNOTSUPPORTED
The object cannot be loaded because the data format is not supported.
DMUS_E_LOADER_NOCLASSID
No class ID was supplied in DMUS_OBJECTDESC.
DMUS_E_LOADER_NOFILENAME
No file name was supplied in DMUS_OBJECTDESC.
DMUS_E_LOADER_OBJECTNOTFOUND
The object was not found.
DMUS_E_NO_MASTER_CLOCK
There is no master clock in the performance. Be sure to call the IDirectMusicPerformance::Init method.
DMUS_E_NOARTICULATION
Articulation missing from an instrument in the DLS collection.
DMUS_E_NOSYNTHSINK
No sink is connected to the synthesizer.
DMUS_E_NOT_DOWNLOADED_TO_PORT
The object cannot be unloaded because it is not present on the port.
DMUS_E_NOT_FOUND
The requested item is not contained by the object.
DMUS_E_NOT_INIT
A required object is not initialized or failed to initialize.
DMUS_E_NOTADLSCOL
The object being loaded is not a valid DLS collection.
DMUS_E_NOTMONO
The wave chunk has more than one interleaved channel. DLS format requires mono.
DMUS_E_NOTPCM
Wave data is not in PCM format.
DMUS_E_OUT_OF_RANGE
The requested time is outside the range of the segment.
DMUS_E_PORT_NOT_CAPTURE
Not a capture port.
DMUS_E_PORT_NOT_RENDER
Not an output port.
DMUS_E_PORTS_OPEN
The requested operation cannot be performed while there are instantiated ports in any process in the system.
DMUS_E_SEGMENT_INIT_FAILED
Segment initialization failed, probably because of a critical memory situation.
DMUS_E_SET_UNSUPPORTED
Setting the parameter is not supported.
DMUS_E_SYNTHACTIVE
The synthesizer has been activated, and the parameter cannot be changed.
DMUS_E_SYNTHINACTIVE
The synthesizer has not been activated and cannot process data.
DMUS_E_SYNTHNOTCONFIGURED
The synthesizer is not properly configured or opened.
DMUS_E_TIME_PAST
The time requested is in the past.
DMUS_E_TOOL_HDR_NOT_FIRST_CK
The IStream object's data does not have a tool header as the first chunk and, therefore, cannot be read by the graph object.
DMUS_E_TRACK_HDR_NOT_FIRST_CK
The IStream object's data does not have a track header as the first chunk and, therefore, cannot be read by the segment object.
DMUS_E_TRACK_NOT_FOUND
There is no track of the requested type.
DMUS_E_TYPE_DISABLED
A track parameter is unavailable because it has been disabled.
DMUS_E_TYPE_UNSUPPORTED
Parameter is unsupported on this track.
DMUS_E_UNKNOWNDOWNLOAD
The synthesizer does not support this type of download.
DMUS_E_UNKNOWN_PROPERTY
The property set or item is not implemented by this port.
DMUS_E_UNSUPPORTED_STREAM
The IStream object does not contain data supported by the loading object.
DMUS_E_WAVEFORMATNOTSUPPORTED
Invalid buffer format was handed to the synthesizer sink.
DMUS_S_DOWN_OCTAVE
The note has been lowered by one or more octaves to fit within the range of MIDI values.
DMUS_S_END
The operation succeeded and reached the end of the data.
DMUS_S_FREE
The allocated memory should be freed.
DMUS_S_LAST_TOOL
There are no more tools in the graph.
DMUS_S_NOBUFFERCONTROL
Although the audio output from the port is routed to the same device as the given DirectSound buffer, buffer controls such as pan and volume do not affect the output.
DMUS_S_OVER_CHORD
No MIDI values have been calculated because the music value has the note at a position higher than the top note of the chord.
DMUS_S_PARTIALDOWNLOAD
Some instruments could not be downloaded to the port.
DMUS_S_PARTIALLOAD
The object could only load partially. This can happen if some components, such as embedded tracks and tools, are not registered properly.
DMUS_S_REQUEUE
The message should be passed to the next tool.
DMUS_S_STRING_TRUNCATED
The method succeeded, but the returned string had to be truncated.
DMUS_S_UP_OCTAVE
The note has been raised by one or more octaves to fit within the range of MIDI values.
E_FAIL
The method did not succeed.
E_INVALIDARG
Invalid argument. Often, this error results from failing to initialize the dwSize member of a structure before passing it to the method.
E_NOAGGREGATION
Aggregation is not supported. The LPUNKNOWN parameter should be set to NULL.
E_NOINTERFACE
No object interface is available.
E_NOTIMPL
The method is not implemented. This value might be returned if a driver does not support a feature necessary for the operation.
E_OUTOFMEMORY
Insufficient memory to complete the task.
E_POINTER
An invalid pointer (usually NULL) was passed as a parameter.
REGDB_E_CLASSNOTREG
The object class is not registered.
S_FALSE
The method succeeded, but there was nothing to do.
S_OK
The operation was completed successfully.


DirectMusic Visual Basic Reference

This section contains reference information for the API elements of Microsoft® DirectMusic® for Microsoft® Visual Basic®. Reference material is divided into the following categories:

  • Classes
  • Types
  • Enumerations
  • Error Codes


Classes

This section contains references for methods of the following DirectMusic classes:

  • DirectMusicBand
  • DirectMusicChordMap
  • DirectMusicCollection
  • DirectMusicComposer
  • DirectMusicLoader
  • DirectMusicPerformance
  • DirectMusicSegment
  • DirectMusicSegmentState
  • DirectMusicStyle


DirectMusicBand

An object of the DirectMusicBand class represents a band, which is used to set the instrument choices and mixer settings for a set of performance channels.

Bands can be stored directly in their own files or embedded in a style. The DirectMusicBand object is obtained by using one of the following methods:

  • DirectMusicLoader.LoadBand
  • DirectMusicLoader.LoadBandFromResource
  • DirectMusicStyle.GetDefaultBand
  • DirectMusicStyle.GetBand

The DirectMusicBand class has the following methods:

Segment creation | CreateSegment
Instrument data | Download
 | Unload


DirectMusicBand.CreateSegment

The DirectMusicBand.CreateSegment method creates a DirectMusicSegment object that can be used to perform the volume, pan, transposition, and patch change commands in the band dynamically, using the DirectMusicPerformance.PlaySegment method.

object.CreateSegment() As DirectMusicSegment

Parameters

object
Object expression that resolves to a DirectMusicBand object.

Return Values

If the method succeeds, it returns a DirectMusicSegment object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_FAIL
DMUS_E_OUTOFMEMORY


DirectMusicBand.Download

The DirectMusicBandDirectDownload method downloads the DLS data for instruments in the band to a performance object. Once a band has been downloaded, the instruments in the band can be selected, either individually with program change MIDI messages, or all at once by playing a band segment created through a call to the DirectMusicBand.CreateSegment method.

object.Download(performance As DirectMusicPerformance)

Parameters

object
Object expression that resolves to a DirectMusicBand object.
performance
Performance in which the band is to perform. The performance manages the mapping of channels to DirectMusic ports.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_NOT_INIT
DMUS_E_OUTOFMEMORY

Remarks

Because a downloaded band uses synthesizer resources, it should be unloaded when no longer needed by using the DirectMusicBand.Unload method.

In the current version of DirectMusic, this method may succeed even though the port does not support DLS.

If DMUS_E_NOT_INIT is raised, it usually means that the performance was not properly connected up to an initialized port. Since this is a complete failure, there is no need to call DirectMusicBand.Unload later.

If the download only partially succeeds, no error is raised but some instruments might not play. The following are some common causes of a partial download:

  • The band has instruments on PChannels that are on channel groups not allocated on the port.
  • The band has instruments in a DLS format incompatible with the synthesizer they are being downloaded to.


DirectMusicBand.Unload

The DirectMusicBand.Unload method unloads the DLS data for instruments in the band previously downloaded by DirectMusicBand.Download.

object.Unload(performance As DirectMusicPerformance)

Parameters

object
Object expression that resolves to a DirectMusicBand object.
performance
Performance from which to unload instruments.

Error Codes

If the method fails, it raises an error, and Err.Number is set.


DirectMusicChordMap

An object of the DirectMusicChordMap class represents a chord map. Chord maps provide the composer (represented by the DirectMusicComposer object) with the information that it needs to create chord progressions for segments that it composes. A chord map can also be applied to an existing segment to change the chords.

The class has no public methods. An instance of it is obtained by using the DirectMusicPerformance.GetChordmap method.

See Also

DirectMusicComposer.AutoTransition, DirectMusicComposer.ChangeChordMap, DirectMusicComposer.ComposeSegmentFromShape, DirectMusicComposer.ComposeSegmentFromTemplate, DirectMusicComposer.ComposeTransition, DirectMusicPerformance.GetChordmap


DirectMusicCollection

An object of the DirectMusicCollection class manages an instance of a DLS file.

The class has no public methods. An instance of it is obtained by using the DirectMusicLoader.LoadCollection or the DirectMusicLoader.LoadCollectionFromResource method, and is associated with a segment by a call to DirectMusicSegment.ConnectToCollection.


DirectMusicComposer

Applications use the methods of the DirectMusicComposer class to compose segments and transitions from compositional elements, and to change the chord map of an existing segment.

A DirectMusicComposer object is obtained by using the DirectX7.DirectMusicComposerCreate method.

The methods of the DirectMusicComposer class can be organized into the following groups.

Changing chord maps | ChangeChordMap
Composing ordinary segments | ComposeSegmentFromShape
 | ComposeSegmentFromTemplate
Composing template segments | ComposeTemplateFromShape
Composing transition segments | AutoTransition
 | ComposeTransition


DirectMusicComposer.AutoTransition

The DirectMusicComposer.AutoTransition method composes a transition from inside a performance's primary segment (or from silence) to another segment, and then cues the transition and the second segment to play.

object.AutoTransition( _
    performance As DirectMusicPerformance, _
    toSeg As DirectMusicSegment, _
    lCommand As Long, _
    lFlags As Long, _
    chordmap As DirectMusicChordMap) _
    As DirectMusicSegment

Parameters

object
Object expression that resolves to a DirectMusicComposer object.
performance
Performance in which to do the transition.
toSeg
Segment to which the transition should smoothly flow. See Remarks.
lCommand
Embellishment to use when composing the transition. See CONST_DMUS_COMMANDT_TYPES. If this value is DMUS_COMMANDT_ENDANDINTRO, the method composes a segment containing both an ending to the primary segment and an introduction to toSeg.
lFlags
Composition options. See CONST_DMUS_COMPOSEF_FLAGS.
chordmap
DirectMusicChordmap to be used when composing the transition.

Return Values

If the method succeeds, it returns a DirectMusicSegment object, unless no style is available for the composition of the transitional segment. See Remarks.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

The value in toSeg can be Nothing, as long as lFlags does not include DMUS_COMPOSEF_MODULATE. If toSeg is Nothing or a segment that contain no style track, intro embellishments are not valid. If there is no currently playing segment or it contain no style track, then fill, break, end, and groove embellishments are not valid.

It is possible for both the currently playing segment and toSeg to be Nothing or segments that contain no style tracks (such as segments based on MIDI files). If so, all embellishments are invalid, and no transition occurs between the currently playing segment and toSeg. The method returns Nothing, but it succeeds and cues the segment represented by toSeg.

The value in chordmap can be Nothing. If so, an attempt is made to obtain a chord map from a chord-map track, first from toSeg, and then from the performance's primary segment. If neither of these segments contains a chord-map track, the chord occurring at the current time in the primary segment is used as the chord in the transition.


DirectMusicComposer.ChangeChordMap

The DirectMusicComposer.ChangeChordMap method modifies the chords and scale pattern of an existing segment to reflect a new chord map.

object.ChangeChordMap(segment As DirectMusicSegment, _
    trackScale As Boolean, _
    chordmap As DirectMusicChordMap)

Parameters

object
Object expression that resolves to a DirectMusicComposer object.
segment
Segment in which to change the chord map.
trackScale
If True, the method transposes all the chords to be relative to the root of the new chord map's scale, rather than leaving their roots as they were.
chordmap
New chord map for the segment.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

The method can be called while the segment is playing.


DirectMusicComposer.ComposeSegmentFromShape

The DirectMusicComposer.ComposeSegmentFromShape method creates an original segment from a style and a chord map, based on a predefined shape. The shape represents the way chords and embellishments occur over time across the segment.

object.ComposeSegmentFromShape(style As DirectMusicStyle, _
    numberOfMeasures As Integer, _
    shape As Integer, _
    activity As Integer, _
    bIntro As Boolean, _
    bEnd As Boolean, _
    chordmap As DirectMusicChordMap) As DirectMusicSegment

Parameters

object
Object expression that resolves to a DirectMusicComposer object.
style
Style from which to compose the segment.
numberOfMeasures
Length, in measures, of the segment to be composed.
shape
Shape of the segment to be composed, based on changes in the groove level. Possible values are of the CONST_DMUS_SHAPET_TYPES enumeration.
activity
Rate of harmonic motion. Valid values are from 0 through 3. Lower values mean more chord changes.
bIntro
True if an introduction is to be composed for the segment, False otherwise.
bEnd
True if an ending is to be composed for the segment, False otherwise.
chordmap
DirectMusicChordmap from which to create the segment.

Return Values

If the method succeeds, it returns a DirectMusicSegment object.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

DirectMusicComposer.ComposeSegmentFromTemplate, DirectMusicComposer.ComposeTemplateFromShape


DirectMusicComposer.ComposeSegmentFromTemplate

The DirectMusicComposer.ComposeSegmentFromTemplate method creates an original segment from a style, a chord map, and a template.

object.ComposeSegmentFromTemplate( _
    style As DirectMusicStyle, _
    templateSeg As DirectMusicSegment, _
    activity As Integer, _
    chordmap As DirectMusicChordMap)
    As DirectMusicSegment

Parameters

object
Object expression that resolves to a DirectMusicComposer object.
style
DirectMusicStyle object from which to create the segment.
templateSeg
DirectMusicSegment object representing the template from which to create the segment.
activity
Rate of harmonic motion. Valid values are from 0 through 3. Lower values mean more chord changes.
chordmap
DirectMusicChordmap object representing the chord map from which to create the segment.

Return Values

If the method succeeds, it returns a DirectMusicSegment object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_INVALIDARG

Remarks

If style is not Nothing, it is used in composing the segment; if it is Nothing, a style is retrieved from the template specified in templateSeg. Similarly, if chordmap is not Nothing, it is used in composing the segment; if it is Nothing, a chord map is retrieved from the template.

If style is Nothing and there is no style track in the template, or chordmap is Nothing and there is no chord-map track, the method returns DMUS_E_INVALIDARG.

The length of the segment is equal to the length of the template passed in.

See Also

DirectMusicComposer.ComposeSegmentFromShape, DirectMusicComposer.ComposeTemplateFromShape


DirectMusicComposer.ComposeTemplateFromShape

The DirectMusicComposer.ComposeTemplateFromShape method creates a new template segment, based on a predefined shape.

object.ComposeTemplateFromShape(numMeasures As Integer, _
    shape As Integer, _
    bIntro As Boolean, _
    bEnd As Boolean, _
    endLength As Integer) As DirectMusicSegment

Parameters

object
Object expression that resolves to a DirectMusicComposer object.
numMeasures
Length, in measures, of the segment to be composed. This value must be greater than 0.
shape
Shape of the segment to be composed, based on groove levels. Possible values are of the CONST_DMUS_SHAPET_TYPES enumeration.
bIntro
True if an introduction is to be composed for the segment, False otherwise.
bEnd
True if an ending is to be composed for the segment, False otherwise.
endLength
Length in measures of the ending, if one is to be composed. If bEnd is True, this value must be greater than 0 and equal to or less than the number of measures available (that is, not used in the introduction). See also Remarks.

Return Values

If the method succeeds, it returns a DirectMusicSegment object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_INVALIDARG
DMUS_E_OUTOFMEMORY

Remarks

The value of endLength should not be greater than the length of the longest ending available in any style likely to be associated with this template through the DirectMusicComposer.ComposeSegmentFromTemplate method. The ending starts playing at endLength measures before the end of the segment. If the ending is less than endLength measures long, the music then reverts to the regular groove.

See Also

DirectMusicComposer.ComposeSegmentFromShape, DirectMusicComposer.ComposeSegmentFromTemplate


DirectMusicComposer.ComposeTransition

The DirectMusicComposer.ComposeTransition method composes a transition from a measure inside one segment to another.

object.ComposeTransition(fromSeg As DirectMusicSegment, _
    toSeg As DirectMusicSegment, _
    mtTime As Long, _
    lCommand As Long, _
    lFlags As Long, _
    chordmap As DirectMusicChordMap) _
    As DirectMusicSegment

Parameters

object
Object expression that resolves to a DirectMusicComposer object.
fromSeg
DirectMusicSegment object representing the segment from which to compose the transition.
toSeg
Segment to which the transition should smoothly flow. Can be Nothing if lFlags does not include DMUS_COMPOSEF_MODULATE.
mtTime
Time in fromSeg from which to compose the transition.
lCommand
Embellishment to use when composing the transition. See CONST_DMUS_COMMANDT_TYPES. If this value is DMUS_COMMANDT_ENDANDINTRO, the method composes a segment containing both an ending to fromSeg and an introduction to toSeg.
lFlags
Composition options. This parameter can contain one or more of the CONST_DMUS_COMPOSEF_FLAGS enumeration.
chordmap
DirectMusicChordmap object representing the chord map to be used when composing the transition. See Remarks.

Return Values

If the method succeeds, it returns a DirectMusicSegment object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_INVALIDARG
DMUS_E_OUTOFMEMORY

Remarks

The value in chordmap can be Nothing. If so, an attempt is made to obtain a chord map from a chord-map track, first from toSeg, and then from fromSeg. If neither of these segments contains a chord-map track, the chord occurring at mtTime in fromSeg is used as the chord in the transition.

The composer looks for a tempo, first in fromSeg, and then in toSeg. If neither of those segments contains a tempo track, the tempo for the transition segment is taken from the style.

See Also

DirectMusicComposer.AutoTransition


DirectMusicLoader

The DirectMusicLoader object is used for finding and loading objects that represent musical and instrument data.

The object is obtained by using the DirectX7.DirectMusicLoaderCreate method.

Objects referred to by other objects are loaded automatically. For example, a style may contain references to bands and collections in other files, and these are loaded, if possible, when the DirectMusicLoader.LoadStyle method is called.

The methods of DirectMusicLoader can be organized into the following groups:

Loading | LoadBand
 | LoadBandFromResource
 | LoadChordMap
 | LoadChordMapFromResource
 | LoadCollection
 | LoadCollectionFromResource
 | LoadSegment
 | LoadSegmentFromResource
 | LoadStyle
 | LoadStyleFromResource
Searching | SetSearchDirectory


DirectMusicLoader.LoadBand

The DirectMusicLoader.LoadBand method loads a band from a file.

object.LoadBand(filename As String) As DirectMusicBand

Parameters

object
Object expression that resolves to a DirectMusicLoader object.
filename
Name of the file containing the band. If the file is not in the current directory or in the directory set by DirectMusicLoader.SetSearchDirectory, the full path must be given.

Return Values

If the method succeeds, it returns a DirectMusicBand object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_FAIL
DMUS_E_INVALIDARG
DMUS_E_OUTOFMEMORY
DMUS_E_INVALID_BAND
DMUS_E_LOADER_FAILEDOPEN
DMUS_E_LOADER_FAILEDCREATE
DMUS_E_LOADER_FORMATNOTSUPPORTED

See Also

DirectMusicLoader.LoadBandFromResource


DirectMusicLoader.LoadBandFromResource

The DirectMusicLoader.LoadBandFromResource method loads a band from a resource.

object.LoadBandFromResource(moduleName As String, _
    resourceName As String) As DirectMusicBand

Parameters

object
Object expression that resolves to a DirectMusicLoader object.
moduleName
Name of the module containing the resource.
resourceName
Identifier of the resource containing the band. The resource must be of type "DMBAND".

Return Values

If the method succeeds, it returns a DirectMusicBand object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_FAIL
DMUS_E_INVALIDARG
DMUS_E_OUTOFMEMORY
DMUS_E_INVALID_BAND
DMUS_E_LOADER_FAILEDCREATE
DMUS_E_LOADER_FORMATNOTSUPPORTED

See Also

DirectMusicLoader.LoadBand


DirectMusicLoader.LoadChordMap

The DirectMusicLoader.LoadChordMap method loads a chord map from a file.

object.LoadChordMap(filename As String) _
    As DirectMusicChordMap

Parameters

object
Object expression that resolves to a DirectMusicLoader object.
filename
Name of the file containing the chord map. If the file is not in the current directory or in the directory set by DirectMusicLoader.SetSearchDirectory, the full path must be given.

Return Values

If the method succeeds, it returns a DirectMusicChordMap object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_FAIL
DMUS_E_INVALIDARG
DMUS_E_OUTOFMEMORY
DMUS_E_LOADER_FAILEDOPEN
DMUS_E_LOADER_FAILEDCREATE
DMUS_E_LOADER_FORMATNOTSUPPORTED

See Also

DirectMusicLoader.LoadChordMapFromResource


DirectMusicLoader.LoadChordMapFromResource

The DirectMusicLoader.LoadChordMapFromResource method loads a chord map from a resource.

object.LoadChordMapFromResource( _
    moduleName As String, _
    resourceName As String) As DirectMusicChordMap

Parameters

object
Object expression that resolves to a DirectMusicLoader object.
moduleName
Name of the module containing the resource.
resourceName
Identifier of the resource containing the chord map. The resource must be of type "DMCHORD".

Return Values

If the method succeeds, it returns a DirectMusicChordMap object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_FAIL
DMUS_E_INVALIDARG
DMUS_E_OUTOFMEMORY
DMUS_E_LOADER_FAILEDOPEN
DMUS_E_LOADER_FAILEDCREATE
DMUS_E_LOADER_FORMATNOTSUPPORTED

See Also

DirectMusicLoader.LoadChordMap


DirectMusicLoader.LoadCollection

The DirectMusicLoader.LoadCollection method loads a DLS collection from a file.

object.LoadCollection(filename As String) _
    As DirectMusicCollection

Parameters

object
Object expression that resolves to a DirectMusicLoader object.
filename
Name of the file containing the DLS collection. If the file is not in the current directory or in the directory set by DirectMusicLoader.SetSearchDirectory, the full path must be given.

Return Values

If the method succeeds, it returns a DirectMusicCollection object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_FAIL
DMUS_E_INVALIDARG
DMUS_E_OUTOFMEMORY
DMUS_E_LOADER_FAILEDOPEN
DMUS_E_LOADER_FAILEDCREATE
DMUS_E_LOADER_FORMATNOTSUPPORTED
DMUS_E_NOTADLSCOL

See Also

DirectMusicLoader.LoadCollectionFromResource


DirectMusicLoader.LoadCollectionFromResource

The DirectMusicLoader.LoadCollectionFromResource method loads a DLS collection from a resource.

object.LoadCollectionFromResource( _
    moduleName As String, _
    resourceName As String) As DirectMusicCollection

Parameters

object
Object expression that resolves to a DirectMusicLoader object.
moduleName
Name of the module containing the resource.
resourceName
Identifier of the resource containing the collection. The resource must be of type "DMCOLL".

Return Values

If the method succeeds, it returns a DirectMusicCollection object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_FAIL
DMUS_E_INVALIDARG
DMUS_E_OUTOFMEMORY
DMUS_E_LOADER_FAILEDOPEN
DMUS_E_LOADER_FAILEDCREATE
DMUS_E_LOADER_FORMATNOTSUPPORTED
DMUS_E_NOTADLSCOL

See Also

DirectMusicLoader.LoadCollection


DirectMusicLoader.LoadSegment

The DirectMusicLoader.LoadSegment method loads a segment from a file.

object.LoadSegment(filename As String) As DirectMusicSegment

Parameters

object
Object expression that resolves to a DirectMusicLoader object.
filename
Name of the file containing the segment. If the file is not in the current directory or in the directory set by DirectMusicLoader.SetSearchDirectory, the full path must be given.

Return Values

If the method succeeds, it returns a DirectMusicSegment object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_FAIL
DMUS_E_INVALIDARG
DMUS_E_OUTOFMEMORY
DMUS_E_LOADER_FAILEDOPEN
DMUS_E_LOADER_FAILEDCREATE
DMUS_E_LOADER_FORMATNOTSUPPORTED

See Also

DirectMusicLoader.LoadSegmentFromResource


DirectMusicLoader.LoadSegmentFromResource

The DirectMusicLoader.LoadSegmentFromResource method loads a segment from a resource.

object.LoadSegmentFromResource( _
    moduleName As String, _
    resourceName As String) As DirectMusicSegment

Parameters

object
Object expression that resolves to a DirectMusicLoader object.
moduleName
Name of the module containing the resource. The resource must be of type "DMSEG".
resourceName
Identifier of the resource containing the segment.

Return Values

If the method succeeds, it returns a DirectMusicSegment object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_FAIL
DMUS_E_INVALIDARG
DMUS_E_OUTOFMEMORY
DMUS_E_LOADER_FAILEDOPEN
DMUS_E_LOADER_FAILEDCREATE
DMUS_E_LOADER_FORMATNOTSUPPORTED
DMUS_E_UNSUPPORTED_STREAM

See Also

DirectMusicLoader.LoadSegment


DirectMusicLoader.LoadStyle

The DirectMusicLoader.LoadStyle method loads a style object from a file.

object.LoadStyle(filename As String) As DirectMusicStyle

Parameters

object
Object expression that resolves to a DirectMusicLoader object.
filename
Name of the file containing the style object. If the file is not in the current directory or in the directory set by DirectMusicLoader.SetSearchDirectory, the full path must be given.

Return Values

If the method succeeds, it returns a DirectMusicStyle object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_FAIL
DMUS_E_INVALIDARG
DMUS_E_OUTOFMEMORY
DMUS_E_LOADER_FAILEDOPEN
DMUS_E_LOADER_FAILEDCREATE
DMUS_E_LOADER_FORMATNOTSUPPORTED

See Also

DirectMusicLoader.LoadStyleFromResource


DirectMusicLoader.LoadStyleFromResource

The DirectMusicLoader.LoadStyleFromResource method loads a style object from a resource.

object.LoadStyleFromResource( _
    moduleName As String, _
    resourceName As String) As DirectMusicStyle

Parameters

object
Object expression that resolves to a DirectMusicLoader object.
moduleName
Name of the module containing the resource.
resourceName
Identifier of the resource containing the style object. The resource must be of type "DMSTYLE".

Return Values

If the method succeeds, it returns a DirectMusicStyle object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_FAIL
DMUS_E_INVALIDARG
DMUS_E_OUTOFMEMORY
DMUS_E_LOADER_FAILEDOPEN
DMUS_E_LOADER_FAILEDCREATE
DMUS_E_LOADER_FORMATNOTSUPPORTED

See Also

DirectMusicLoader.LoadStyle


DirectMusicLoader.SetSearchDirectory

The DirectMusicLoader.SetSearchDirectory method sets the directory to be searched by the DirectMusicLoader.LoadBand, DirectMusicLoader.LoadChordmap, DirectMusicLoader.LoadCollection, DirectMusicLoader.LoadSegment, and DirectMusicLoader.LoadStyle methods when a fully qualified path is not supplied.

object.SetSearchDirectory(dir As String)

Parameters

object
Object expression that resolves to a DirectMusicLoader object.
dir
Directory to search.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_OUTOFMEMORY
DMUS_E_LOADER_BADPATH

Remarks

Once a search path is set, the loader does not need a full path every time it is given an object to load by file name. This allows objects that refer to other objects to find them by file name without knowing the full path.


DirectMusicPerformance

An object of the DirectMusicPerformance class is the overall manager of music playback. It maps performance channels to a port, plays segments, dispatches messages, requests and receives event notifications, and sets and retrieves music parameters. It also has several methods for getting information about timing and for converting time and music values from one system to another.

If an application wants to have two or more complete sets of music playing at the same time, it can do so by creating more than one performance object. Separate performances obey separate tempo maps and play completely asynchronously, whereas all segments within one performance play in lock step.

The DirectMusicPerformance object is obtained by using the DirectX7.DirectMusicPerformanceCreate method.

The methods of the DirectMusicPerformance class can be organized into the following groups:

Messages | SendCurvePMSG
 | SendMIDIPMSG
 | SendNotePMSG
 | SendPatchPMSG
 | SendTempoPMSG
 | SendTimeSigPMSG
 | SendTransposePMSG
Notification | AddNotificationType
 | GetNotificationPMSG
 | RemoveNotificationType
 | SetNotificationHandle
Parameters | GetChordmap
 | GetCommand
 | GetGrooveLevel
 | GetMasterAutoDownload
 | GetMasterGrooveLevel
 | GetMasterTempo
 | GetMasterVolume
 | GetStyle
 | GetTempo
 | GetTimeSig
 | Reset
 | SetMasterAutoDownload
 | SetMasterGrooveLevel
 | SetMasterTempo
 | SetMasterVolume
Ports | GetPortCaps
 | GetPortCount
 | GetPortName
 | SetPort
Segments | GetSegmentState
 | IsPlaying
 | PlaySegment
 | Stop
Timing | AdjustTime
 | ClockToMusicTime
 | GetBumperLength
 | GetClockTime
 | GetLatencyTime
 | GetMusicTime
 | GetPrepareTime
 | GetQueueTime
 | GetResolvedTime
 | MusicToClockTime
 | SetBumperLength
 | SetPrepareTime
Miscellaneous | CloseDown
 | Init
 | Invalidate


DirectMusicPerformance.AddNotificationType

The DirectMusicPerformance.AddNotificationType method causes the performance to generate notification messages whenever events of the requested type occur.

object.AddNotificationType( _
    type As CONST_DMUS_NOTIFICATION_TYPE)

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
type
Type of event for which notification messages are to be sent. For possible values, see CONST_DMUS_NOTIFICATION_TYPE.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_INVALIDARG
DMUS_E_OUTOFMEMORY

See Also

DirectMusicPerformance.RemoveNotificationType


DirectMusicPerformance.AdjustTime

The DirectMusicPerformance.AdjustTime method adjusts the internal performance time forward or backward. This is mostly used to compensate for drift when synchronizing to another source.

object.AdjustTime(rtAmount As Long)

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
rtAmount
Amount of time, in clock time units, to add or subtract. This can be a number in the range from –1000 through 1000 (–1 second through +1 second).

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DMUS_E_INVALIDARG.

Remarks

The adjusted time is used internally by DirectMusic. It is not reflected in the time retrieved by the DirectMusicPerformance.GetClockTime method.


DirectMusicPerformance.ClockToMusicTime

The DirectMusicPerformance.ClockToMusicTime method converts clock time to music time. Clock time is an absolute time. Music time is relative to the tempo of the performance.

object.ClockToMusicTime(ctTime As Long) As Long

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
ctTime
Time to convert, in clock time units.

Return Values

If the method succeeds, it returns the equivalent music time.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DMUS_E_NO_MASTER_CLOCK.

Remarks

If a master tempo has been set for the performance, it is taken into account when converting to music time.

Because music time is less precise than clock time, rounding off occurs.

See Also

DirectMusicPerformance.MusicToClockTime, Clock Time vs. Music Time


DirectMusicPerformance.CloseDown

The DirectMusicPerformance.CloseDown method closes down the performance. An application that created the performance object and called DirectMusicPerformance.Init on it must call CloseDown before the performance object is released.

object.CloseDown()

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

Failure to call CloseDown can cause memory leaks or application failures.

CloseDown releases any downloaded instruments that have not been unloaded.


DirectMusicPerformance.GetBumperLength

The DirectMusicPerformance.GetBumperLength method retrieves the amount of time between the time at which messages are placed in the port buffer and the time at which they begin to be processed by the port.

object.GetBumperLength() As Long

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.

Return Values

If the method succeeds, it returns the bumper length, in milliseconds.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

The default value is 50 milliseconds.

See Also

DirectMusicPerformance.SetBumperLength


DirectMusicPerformance.GetChordmap

The DirectMusicPerformance.GetChordmap method retrieves the chord map from the performance's control segment.

object.GetChordMap(mtTime As Long, _
    mtUntil As Long) As DirectMusicChordMap

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
mtTime
Time for which the chord map is to be retrieved, in music time.
mtUntil
Variable to receive the music time (relative to mtTime) until which the chordmap is valid. If this returns a value of 0, either the chord map is always valid, or it is unknown when it might become invalid. See Remarks.

Return Values

If the method succeeds, it returns a DirectMusicChordmap object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_NO_MASTER_CLOCK
DMUS_E_GET_UNSUPPORTED
DMUS_E_NOT_FOUND
DMUS_E_TRACK_NOT_FOUND

Remarks

Normally, the primary segment is the control segment. However, a secondary segment can be designated as a control segment when it is played. The object returned by the method can become invalid before the time returned in mtUntil if another control segment is cued.

See Also

CONST_DMUS_SEGF_FLAGS


DirectMusicPerformance.GetClockTime

The DirectMusicPerformance.GetClockTime method retrieves the current time.

object.GetClockTime() As Long

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.

Return Values

If the method succeeds, it returns the time, in units of approximately 1 millisecond, relative to an arbitrary start time.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DMUS_E_NO_MASTER_CLOCK.

See Also

DirectMusicPerformance.GetMusicTime, Clock Time vs. Music Time


DirectMusicPerformance.GetCommand

The DirectMusicPerformance.GetCommand method retrieves a command from the performance's control segment. The command indicates what type of pattern is being played at the specified time.

object.GetCommand(mtTime As Long, mtUntil As Long) As Byte

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
mtTime
Time for which the command is to be retrieved, in music time.
mtUntil
Variable to receive the music time (relative to mtTime) until which the command is valid. If this returns a value of 0, either the command is always valid, or it is unknown when it might become invalid. See Remarks.

Return Values

If the method succeeds, it returns a command type. See CONST_DMUS_COMMANDT_TYPES.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following error codes:

DMUS_E_NO_MASTER_CLOCK
DMUS_E_GET_UNSUPPORTED
DMUS_E_NOT_FOUND
DMUS_E_TRACK_NOT_FOUND

Remarks

Normally, the primary segment is the control segment. However, a secondary segment can be designated as a control segment when it is played. The object returned by the method can become invalid before the time returned in mtUntil if another control segment is cued.

See Also

CONST_DMUS_SEGF_FLAGS


DirectMusicPerformance.GetGrooveLevel

The DirectMusicPerformance.GetGrooveLevel method retrieves the groove level from the performance's control segment. The groove level determines which patterns can be played at the specified time.

object.GetGrooveLevel(mtTime As Long, _
    mtUntil As Long) As Byte

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
mtTime
Time for which the groove level is to be retrieved, in music time.
mtUntil
Variable to receive the music time (relative to mtTime) until which the groove level is valid. If this returns a value of 0, either the groove level is always valid, or it is unknown when it might become invalid. See Remarks.

Return Values

If the method succeeds, it returns a value in the range from 1 through 100.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following error codes:

DMUS_E_NO_MASTER_CLOCK
DMUS_E_GET_UNSUPPORTED
DMUS_E_NOT_FOUND
DMUS_E_TRACK_NOT_FOUND

Remarks

Normally, the primary segment is the control segment. However, a secondary segment can be designated as a control segment when it is played. The object returned by the method can become invalid before the time returned in mtUntil if another control segment is cued.

See Also

CONST_DMUS_SEGF_FLAGS


DirectMusicPerformance.GetLatencyTime

The DirectMusicPerformance.GetLatencyTime method retrieves the current latency time. Latency time is the time at which messages are sent to the port to be rendered.

object.GetLatencyTime() As Long

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.

Return Values

If the method succeeds, it returns the latency time, in clock time units.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DMUS_E_NO_MASTER_CLOCK


DirectMusicPerformance.GetMasterAutoDownload

The DirectMusicPerformance.GetMasterAutoDownload method retrieves the current setting for automatic downloading of instruments.

object.GetMasterAutoDownload() As Boolean

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.

Return Values

If the method succeeds, it returns True if autodownloading is on, and False otherwise. The default value is False.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

DirectMusicPerformance.SetMasterAutoDownload, DirectMusicSegment.SetAutoDownloadEnable


DirectMusicPerformance.GetMasterGrooveLevel

The DirectMusicPerformance.GetMasterGrooveLevel method retrieves the current master groove level, which is a value added to all groove levels in the performance. The resulting value is adjusted, if necessary, to fall within the range from 1 through 100.

object.GetMasterGrooveLevel() As Integer

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.

Return Values

If the method succeeds, it returns the master groove level.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

DirectMusicPerformance.SetMasterGrooveLevel


DirectMusicPerformance.GetMasterTempo

The DirectMusicPerformance.GetMasterTempo method retrieves the current master tempo.

object.GetMasterTempo() As Single

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.

Return Values

If the method succeeds, it returns a value in the range from 0.25 through 2.0.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

The master tempo is a scaling factor that is applied to the tempo by the final output tool. By default it is 1. A value of 0.5 would halve the tempo, and a value of 2.0 would double it.

See Also

DirectMusicPerformance.SetMasterTempo


DirectMusicPerformance.GetMasterVolume

The DirectMusicPerformance.GetMasterVolume method retrieves the current master volume.

object.GetMasterVolume() As Long

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.

Return Values

If the method succeeds, it returns the current master volume, in hundredths of a decibel.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

The master volume is an amplification or attenuation factor applied to the default volume of the entire performance. The range of permitted values is determined by the port.

See Also

DirectMusicPerformance.SetMasterVolume


DirectMusicPerformance.GetMusicTime

The DirectMusicPerformance.GetMusicTime method returns the current time of the performance, in music time.

object.GetMusicTime() As Long

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.

Return Values

If the method succeeds, it returns the current time, in music time units.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DMUS_E_NO_MASTER_CLOCK.

See Also

DirectMusicPerformance.GetClockTime, Clock Time vs. Music Time


DirectMusicPerformance.GetNotificationPMsg

The DirectMusicPerformance.GetNotificationPMsg method retrieves a pending notification message.

object.GetNotificationPMSG( _
    message As DMUS_NOTIFICATION_PMSG) As Boolean

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
message
DMUS_NOTIFICATION_PMSG type to receive the message.

Return Values

If the method succeeds, it returns True if a message was received, and False if there was no message pending.

Error Codes

If the method fails, it raises an error, and Err.Number is set.


DirectMusicPerformance.GetPortCaps

The DirectMusicPerformance.GetPortCaps method retrieves information about the capabilities of a port.

object.GetPortCaps(index As Long, caps As DMUS_PORTCAPS)

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
index
Index of the port, in the range from 1 through DirectMusicPerformance.GetPortCount.
caps
DMUS_PORTCAPS type to receive information about the port.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DMUS_E_INVALIDARG.


DirectMusicPerformance.GetPortCount

The DirectMusicPerformance.GetPortCount method returns the number of DirectMusic ports available on the system.

object.GetPortCount() As Long

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.

Return Values

If the method succeeds, it returns the number of available ports.

Error Codes

If the method fails, it raises an error, and Err.Number is set.


DirectMusicPerformance.GetPortName

The DirectMusicPerformance.GetPortName returns the name of a port.

object.GetPortName(index As Long) As String

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
index
Index of the port. Must be in the range from 1 through the value returned by DirectMusicPerformance.GetPortCount.

Return Values

If the method succeeds, it returns the name of the port — for example, Microsoft Synthesizer.

Error Codes

If the method fails, it raises an error, and Err.Number is set.


DirectMusicPerformance.GetPrepareTime

The DirectMusicPerformance.GetPrepareTime method retrieves the approximate interval between the time at which messages are prepared and the time at which they are processed and heard.

object.GetPrepareTime() As Long

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.

Return Values

If the method succeeds, it returns the prepare time, in milliseconds.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

The default value is 1000 milliseconds.

See Also

DirectMusicPerformance.SetPrepareTime


DirectMusicPerformance.GetQueueTime

The DirectMusicPerformance.GetQueueTime method retrieves the current queue (or flush) time. Messages that have time stamps earlier than this time have already been queued to the port and cannot be invalidated.

object.GetQueueTime() As Long

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.

Return Values

If the method succeeds, it returns the queue time, in clock time units.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DMUS_E_NO_MASTER_CLOCK.

Remarks

Queue time is equal to the value returned by DirectMusicPerformance.GetLatencyTime plus the value returned by DirectMusicPerformance.GetBumperLength.

When a segment is stopped immediately, all messages that have been sent but not queued to the port buffer are flushed. If you want to resume playing the segment again at the last point heard, set the new start point to the offset of queue time within the segment when the segment was stopped.

See Also

DirectMusicPerformance.Invalidate


DirectMusicPerformance.GetResolvedTime

The DirectMusicPerformance.GetResolvedTime method adjusts a given time to a given boundary.

object.GetResolvedTime(ctTime As Long, _
    flags As Long) As Long

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
ctTime
Time to resolve, in clock time units. If this is less than the current time, the current time is used.
flags
One or more of the following CONST_DMUS_SEGF_FLAGS describing the resolution desired:
DMUS_SEGF_AFTERPREPARETIME
Resolve to a time after the prepare time.
DMUS_SEGF_GRID
Resolve to a time on a grid boundary.
DMUS_SEGF_BEAT
Resolve to a time on a beat boundary.
DMUS_SEGF_MEASURE
Resolve to a time on a measure boundary.

Return Values

If the method succeeds, it returns the resolved time.

Error Codes

If the method fails, it raises an error, and Err.Number is set.


DirectMusicPerformance.GetSegmentState

The DirectMusicPerformance.GetSegmentState method retrieves the DirectMusicSegmentState object representing the primary segment playing at a given time.

object.GetSegmentState(mtTime As Long) _
    As DirectMusicSegmentState

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
mtTime
Time for which the segment state is to be retrieved, in music time.

Return Values

If the method succeeds, it returns a DirectMusicSegmentState object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DMUS_E_NOT_FOUND.

Remarks

To get the currently playing segment state, pass the time retrieved by the DirectMusicPerformance.GetMusicTime method. Currently playing in this context means that it is being called into to perform messages. Because of latency, the currently playing segment state is not necessarily the one actually being heard.

Because of latency, it is also a good idea to add 150 to mtTime if retrieving a segment state immediately after calling DirectMusicPerformance.PlaySegment.


DirectMusicPerformance.GetStyle

The DirectMusicPerformance.GetStyle method retrieves the style underlying the control segment at a given time.

object.GetStyle(mtTime As Long, mtUntil As Long) _
    As DirectMusicStyle

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
mtTime
Time for which the style is to be retrieved, in music time.
mtUntil
Variable to receive the music time (relative to mtTime) until which the style is valid. If this returns a value of 0, either the style is always valid, or it is unknown when it might become invalid. See Remarks.

Return Values

If the method succeeds, it returns a DirectMusicStyle object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_NO_MASTER_CLOCK
DMUS_E_GET_UNSUPPORTED
DMUS_E_NOT_FOUND
DMUS_E_TRACK_NOT_FOUND

Remarks

Normally, the primary segment is the control segment. However, a secondary segment can be designated as a control segment when it is played. The object returned by the method can become invalid before the time returned in mtUntil if another control segment is cued.


DirectMusicPerformance.GetTempo

The DirectMusicPerformance.GetTempo method retrieves the tempo at a given time.

object.GetTempo(mtTime As Long, mtUntil As Long) As Double

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
mtTime
Time for which to retrieve the tempo, in music time. The last tempo change before or at this time is used to determine the tempo.
mtUntil
Variable to receive the music time (relative to mtTime) until which the tempo is valid. If this returns a value of 0, either the tempo is always valid, or it is unknown when it might become invalid.

Return Values

If the method succeeds, it returns the tempo, in beats per minute. This value is in the range from DMUS_TEMPO_MIN through DMUS_TEMPO_MAX (see CONST_DMUS).

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_NO_MASTER_CLOCK
DMUS_E_GET_UNSUPPORTED
DMUS_E_NOT_FOUND
DMUS_E_TRACK_NOT_FOUND


DirectMusicPerformance.GetTimeSig

The DirectMusicPerformance.GetTimeSig method retrieves the time signature at a given time.

object.GetTimeSig(mtTime As Long, _
    mtUntil As Long, _
    timeSig As DMUS_TIMESIGNATURE)

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
mtTime
Time for which to retrieve the time signature, in music time. The last time signature change before or at this time is used to determine the time signature.
mtUntil
Variable to receive the music time (relative to mtTime) until which the time signature is valid. If this returns a value of 0, either the time signature is always valid, or it is unknown when it might become invalid. See Remarks.
timeSig
DMUS_TIMESIGNATURE type to receive information about the time signature. The mtTime member receives the offset of the last time signature change from the requested time, and is always 0 or less.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_NO_MASTER_CLOCK
DMUS_E_GET_UNSUPPORTED
DMUS_E_NOT_FOUND
DMUS_E_TRACK_NOT_FOUND


DirectMusicPerformance.Init

The DirectMusicPerformance.Init method initializes the performance and associates it with a DirectSound object. This method should be called only once, before any other methods are called on the performance.

object.Init(DirectSound As DirectSound, hwnd As Long)

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
DirectSound
Existing DirectSound object, or Nothing if you want DirectMusic to create the object.
hwnd
Window handle to be used for the creation of DirectSound. This parameter can be 0, in which case the foreground window is used. See Remarks.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_ALREADY_INITED
DMUS_E_OUTOFMEMORY

Remarks

There should be only one DirectSound object per process. If your application uses a DirectSound object for playing waves, it must pass in that object here.

The hwnd parameter is significant only if DirectSound is Nothing. If a DirectSound object is created separately by the application and passed to this method, the application is responsible for setting the window handle in a call to DirectSound.SetCooperativeLevel.

Do not 0 pass as hwnd because the application window might not be in the foreground when the method is called. In general, the top-level application window handle should be passed to DirectMusicPerformance.Init, DirectSound.SetCooperativeLevel, and DirectDraw7.SetCooperativeLevel.

The performance must be terminated by using the DirectMusicPerformance.CloseDown method before being released.


DirectMusicPerformance.Invalidate

The DirectMusicPerformance.Invalidate method flushes all queued messages whose time stamps are later than the supplied time and causes all tracks of all segments to resend their data from the given time forward.

object.Invalidate(mtTime As Long, flags As Long)

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
mtTime
Time from which to invalidate, adjusted by flags. Setting this value to 0 causes immediate invalidation.
flags
Adjusts mtTime to align to measures, beats, or grids. This value can be 0 or one of the following members of CONST_DMUS_SEGF_FLAGS:

DMUS_SEGF_MEASURE
DMUS_SEGF_BEAT
DMUS_SEGF_GRID

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DMUS_E_NO_MASTER_CLOCK.

Remarks

If mtTime is so long ago that it is impossible to invalidate that time, the earliest possible time is used.

See Also

DirectMusicPerformance.GetQueueTime


DirectMusicPerformance.IsPlaying

The DirectMusicPerformance.IsPlaying method determines whether a particular segment or segment state is currently playing at the speakers.

object.IsPlaying(segment As DirectMusicSegment, _
    segmentState As DirectMusicSegmentState) As Boolean

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
segment
DirectMusicSegment to check. If Nothing, check only segmentState.
segmentState
DirectMusicSegmentState state to check. If Nothing, check only segment.

Return Values

If the method succeeds and the requested segment or segment state is playing, the return value is True. If neither is playing, or only one was requested and it is not playing, the return value is False.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_NO_MASTER_CLOCK


DirectMusicPerformance.MusicToClockTime

The DirectMusicPerformance.MusicToClockTime method converts time in music time format to time in clock time format.

object.MusicToClockTime(mtTime As Long) As Long

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
mtTime
Time in music time format to convert.

Return Values

If the method succeeds, it returns the time, in clock time units.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DMUS_E_NO_MASTER_CLOCK.

Remarks

Because clock time has a greater precision than music time, a time that has been converted from clock time to music time, and then back again, will probably not have its original value.

See Also

DirectMusicPerformance.ClockToMusicTime, Clock Time vs. Music Time


DirectMusicPerformance.PlaySegment

The DirectMusicPerformance.PlaySegment method begins playback of a segment.

object.PlaySegment(segment As DirectMusicSegment, _
    lFlags As Long, _
    startTime As Long) As DirectMusicSegmentState

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
segment
DirectMusicSegment to play.
lFlags
Flags that modify the method's behavior. See CONST_DMUS_SEGF_FLAGS.
startTime
Time at which to begin playing the segment, adjusted to any resolution boundary specified in lFlags. The time is in music time unless the DMUS_SEGF_REFTIME flag is set. A value of 0 causes the segment to start playing as soon as possible.

Return Values

If the method succeeds, it returns a DirectMusicSegmentState object representing the playing segment.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_OUTOFMEMORY
DMUS_E_NO_MASTER_CLOCK
DMUS_E_SEGMENT_INIT_FAILED
DMUS_E_TIME_PAST

Remarks

Segments should be greater than 250 milliseconds in length.

The boundary resolutions in lFlags are relative to the currently playing primary segment.

If a primary segment is scheduled to play while another primary segment is playing, the first one stops unless you set the DMUS_SEGF_QUEUE flag for the second segment. In this case, it plays as soon as the first one reaches its end.

See Also

DirectMusicPerformance.IsPlaying


DirectMusicPerformance.RemoveNotificationType

The DirectMusicPerformance.RemoveNotificationType method removes a previously added notification type from the performance so that notification messages of that type are no longer sent.

object.RemoveNotificationType( _
    type As CONST_DMUS_NOTIFICATION_TYPE)

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
type
Type of event for which notification messages are no longer to be sent. For possible values, see CONST_DMUS_NOTIFICATION_TYPE.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DMUS_E_INVALIDARG

See Also

DirectMusicPerformance.AddNotificationType


DirectMusicPerformance.Reset

The DirectMusicPerformance.Reset method resets the port.

object.Reset(resetflags As Long)

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
resetflags
Flags. By default (resetflags = 0), the method performs a GMReset. If this value is 1, the port is reset by being closed and reopened.

Error Codes

If the method fails, it raises an error, and Err.Number is set.


DirectMusicPerformance.SendCurvePMSG

The DirectMusicPerformance.SendCurvePMSG method sends a performance message containing information about a MIDI curve.

object.SendCurvePMSG(lTime As Long, _
    flags As Long, _
    channel As Long, _
    msg As DMUS_CURVE_PMSG)

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
lTime
Time at which the message is to play. This is in music time unless DMUS_PMSGF_REFTIME is in flags.
flags
Flags modifying how and when the message is processed. See CONST_DMUS_PMSGF_FLAGS.
channel
Performance channel that is the destination for the message.
msg
DMUS_CURVE_PMSG type containing information about the curve.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_NO_MASTER_CLOCK
DMUS_E_ALREADY_SENT
DMUS_E_INVALIDARG

Remarks

If the time of the message is set to 0 and the flags parameter contains DMUS_PMSGF_REFTIME, it is assumed that this message is cued to go out immediately.


DirectMusicPerformance.SendMIDIPMSG

The DirectMusicPerformance.SendMIDIPMSG method sends a performance message containing information about a MIDI channel message not covered by other methods.

object.SendMIDIPMSG(lTime As Long, _
    flags As Long, _
    channel As Long, _
    status As Byte, _
    byte1 As Byte, _
    byte2 As Byte)

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
lTime
Time at which the message is to play. This is in music time unless DMUS_PMSGF_REFTIME is in flags.
flags
Flags modifying how and when the message is processed. See CONST_DMUS_PMSGF_FLAGS.
channel
Performance channel that is the destination for the message.
status
Standard MIDI status byte. See Remarks.
byte1
First data byte. Ignored for MIDI messages that do not require it.
byte2
Second data byte. Ignored for MIDI messages that do not require it.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_NO_MASTER_CLOCK
DMUS_E_ALREADY_SENT
DMUS_E_INVALIDARG

Remarks

If the time of the message is set to 0 and the flags parameter contains DMUS_PMSGF_REFTIME, it is assumed that this message is cued to go out immediately.

Because the channel is specified in another parameter, status does not contain the channel number in the 4 lower bits, as it would in a standard MIDI message. Thus status is &H80 for a note-off, &H90 for a note-on, and so on. See the MIDI specification for other status bytes.


DirectMusicPerformance.SendNotePMSG

The DirectMusicPerformance.SendNotePMSG method sends a performance message containing information about a note.

object.SendNotePMSG(lTime As Long, _
    flags As Long, _
    channel As Long, _
    msg As DMUS_NOTE_PMSG)

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
lTime
Time at which the message is to play. This is in music time unless DMUS_PMSGF_REFTIME is in flags.
flags
Flags modifying how and when the message is processed. See CONST_DMUS_PMSGF_FLAGS.
channel
Performance channel that is the destination for the message.
msg
DMUS_NOTE_PMSG type containing information about the note.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_NO_MASTER_CLOCK
DMUS_E_ALREADY_SENT
DMUS_E_INVALIDARG

Remarks

If the time of the message is set to 0 and the flags parameter contains DMUS_PMSGF_REFTIME, it is assumed that this message is cued to go out immediately.

See Also

Music Values and MIDI Notes


DirectMusicPerformance.SendPatchPMSG

The DirectMusicPerformance.SendPatchPMSG method sends a performance message containing information about a MIDI patch change.

object.SendPatchPMSG(lTime As Long, _
    flags As Long, _
    channel As Long, _
    instrument As Byte, _
    byte1 As Byte, _
    byte2 As Byte)

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
lTime
Time at which the message is to play. This is in music time unless DMUS_PMSGF_REFTIME is in flags.
flags
Flags modifying how and when the message is processed. See CONST_DMUS_PMSGF_FLAGS.
channel
Performance channel that is the destination for the message.
instrument
Patch number to assign to the channel.
byte1
Most significant byte of bank select.
byte2
Least significant byte of bank select.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_NO_MASTER_CLOCK
DMUS_E_ALREADY_SENT
DMUS_E_INVALIDARG

Remarks

If the time of the message is set to 0 and the flags parameter contains DMUS_PMSGF_REFTIME, it is assumed that this message is cued to go out immediately.


DirectMusicPerformance.SendTempoPMSG

The DirectMusicPerformance.SendTempoPMSG method sends a performance message containing information about a tempo change.

object.SendTempoPMSG(lTime As Long, _
    flags As Long, _
    tempo As Double)

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
lTime
Time at which the message is to play. This is in music time unless DMUS_PMSGF_REFTIME is in flags.
flags
Flags modifying how and when the message is processed. See CONST_DMUS_PMSGF_FLAGS.
tempo
New tempo, in beats per minute.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_NO_MASTER_CLOCK
DMUS_E_ALREADY_SENT
DMUS_E_INVALIDARG

Remarks

If the time of the message is set to 0 and the flags parameter contains DMUS_PMSGF_REFTIME, it is assumed that this message is cued to go out immediately.


DirectMusicPerformance.SendTimeSigPMSG

The DirectMusicPerformance.SendCurvePMSG method sends a performance message containing information about a MIDI curve.

object.SendTimeSigPMSG(lTime As Long, _
    flags As Long, _
    timeSig As DMUS_TIMESIGNATURE)

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
lTime
Time at which the message is to play. This is in music time unless DMUS_PMSGF_REFTIME is in flags.
flags
Flags modifying how and when the message is processed. See CONST_DMUS_PMSGF_FLAGS.
timeSig
DMUS_TIMESIGNATURE type containing information about the time signature.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_NO_MASTER_CLOCK
DMUS_E_ALREADY_SENT
DMUS_E_INVALIDARG

Remarks

If the time of the message is set to 0 and the flags parameter contains DMUS_PMSGF_REFTIME, it is assumed that this message is cued to go out immediately.


DirectMusicPerformance.SendTransposePMSG

The DirectMusicPerformance.SendTransposePMSG method sends a performance message causing a transposition to begin.

object.SendTransposePMSG(lTime As Long, _
    flags As Long, _
    channel As Long, _
    transpose As Integer)

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
lTime
Time at which the message is to play. This is in music time unless DMUS_PMSGF_REFTIME is in flags.
flags
Flags modifying how and when the message is processed. See CONST_DMUS_PMSGF_FLAGS.
channel
Pchannel on which the transposition is to take place.
transpose
Number of semitones by which to transpose notes. This can be a negative value. If the transposition of a note puts it outside the standard MIDI range from 0 through 127, it does not play.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_NO_MASTER_CLOCK
DMUS_E_ALREADY_SENT
DMUS_E_INVALIDARG

Remarks

If the time of the message is set to 0 and the flags parameter contains DMUS_PMSGF_REFTIME, it is assumed that this message is cued to go out immediately.


DirectMusicPerformance.SetBumperLength

The DirectMusicPerformance.SetBumperLength method sets the amount of time between the time at which messages are placed in the port buffer and the at which they begin to be processed by the port.

object.SetBumperLength(lMilliSeconds As Long)

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
lMilliSeconds
Desired bumper length, in milliseconds. The default value is 50.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

DirectMusicPerformance.GetBumperLength, DirectMusicPerformance.SetPrepareTime


DirectMusicPerformance.SetMasterAutoDownload

The DirectMusicPerformance.SetMasterAutoDownload method turns automatic downloading of instruments on or off.

object.SetMasterAutoDownload(b As Boolean)

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
b
True to turn autodownloading on, False to turn it off. The default value is False.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

DirectMusicPerformance.GetMasterAutoDownload, DirectMusicSegment.SetAutoDownloadEnable


DirectMusicPerformance.SetMasterGrooveLevel

The DirectMusicPerformance.SetMasterGrooveLevel method sets a value to be added to all groove levels in the performance.

object.SetMasterGrooveLevel(level As Integer)

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
level
Value to add to the groove level, in the range from –99 through 99.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_FAIL
DMUS_E_OUTOFMEMORY

See Also

DirectMusicPerformance.GetMasterGrooveLevel

Remarks

The adjusted groove level is always in the range from 1 through 100.


DirectMusicPerformance.SetMasterTempo

The DirectMusicPerformance.SetMasterTempo method sets a scaling factor that is applied to the tempo.

object.SetMasterTempo(tempo As Single)

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
tempo
Desired master tempo, in the range from 0.25 through 2.0.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

By default, the master tempo is 1. A value of 0.5 would halve the tempo, and a value of 2.0 would double it.

See Also

DirectMusicPerformance.GetMasterTempo


DirectMusicPerformance.SetMasterVolume

The DirectMusicPerformance.SetMasterVolume method adjusts the master volume of the performance.

object.SetMasterVolume(vol As Long)

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
vol
Master volume adjustment, in hundredths of a decibel.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

The master volume is an amplification or attenuation factor applied to the default volume of the entire performance. The range of permitted values is determined by the port.

See Also

DirectMusicPerformance.GetMasterVolume


DirectMusicPerformance.SetNotificationHandle

The DirectMusicPerformance.SetNotificationHandle method sets the event handle for notifications. When signaled, the application should call the DirectMusicPerformance.GetNotificationPMsg method to retrieve the notification event.

object.SetNotificationHandle(hnd As Long)

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
hnd
Event handle, or 0 to clear an existing handle.

See Also

DirectXEvent


DirectMusicPerformance.SetPort

The DirectMusicPerformance.SetPort method sets the active port for the performance. This method must be called after the performance is initialized and before any instruments are downloaded or any segment is played.

object.SetPort(index As Long, numGroups As Long)

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
index
Index of the port. Must be in the range from 1 through the value returned by DirectMusicPerformance.GetPortCount, or –1 for the default port.
numGroups
Number of channel groups on the port. Must be less than or equal to the number of channel groups reported in the lMaxChannelGroups member of the DMUS_PORTCAPS type returned by the DirectMusicPerformance.GetPortCaps method.

Remarks

Each channel group consists of 16 channels. Allocate enough channel groups to accommodate all performance channels in the segments that you intend to play. For MIDI files, one channel group is sufficient. The Microsoft Software Synthesizer supports up to 1000 channel groups.


DirectMusicPerformance.SetPrepareTime

The DirectMusicPerformance.SetPrepareTime method sets the approximate interval between the time at which messages are prepared and the time at which they are processed and heard.

object.SetPrepareTime(lMilliSeconds As Long)

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
lMilliSeconds
Prepare time, in milliseconds. The default value is 1000.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

DirectMusicPerformance.GetPrepareTime, DirectMusicPerformance.SetBumperLength


DirectMusicPerformance.Stop

The DirectMusicPerformance.Stop method stops playback of one or more segments.

object.Stop(segment As DirectMusicSegment, _
    segmentState As DirectMusicSegmentState, _
    mtTime As Long, _
    lFlags As Long)

Parameters

object
Object expression that resolves to a DirectMusicPerformance object.
segment
DirectMusicSegment to stop playing. All segment states based on this segment are stopped at mtTime. See Remarks.
segmentState
DirectMusicSegmentState object representing the instance of the segment to stop playing. See Remarks.
mtTime
Music time at which to stop the segment, segment state, or both. If the time is in the past or this value is 0, the requested segments and segment states stop playing immediately.
lFlags
Flag that indicates when the stop should occur. Boundaries are in relation to the current primary segment. Must be one of the following values:
0
Stop immediately.
DMUS_SEGF_GRID
Stop on the next grid boundary at or after mtTime.
DMUS_SEGF_MEASURE
Stop on the next measure boundary at or after mtTime.
DMUS_SEGF_BEAT
Stop on the next beat boundary at or after mtTime.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

If segment and segmentState are both Nothing, all music stops, and all currently cued segments are released. If either segment or segmentState is not Nothing, only the requested segment states are removed from the performance.

If you set all parameters to Nothing or 0, everything stops immediately, and controller reset messages and note-off messages are sent to all mapped performance channels.

See Also

DirectMusicPerformance.PlaySegment, CONST_DMUS_SEGF_FLAGS


DirectMusicSegment

An object of the DirectMusicSegment class represents a single piece of music or a template.

Segments are usually loaded by calling DirectMusicLoader.LoadSegment and DirectMusicLoader.LoadSegmentFromResource. They can also be composed from musical elements by using methods of the DirectMusicComposer object, or created from existing segments by using the DirectMusicSegment.Clone method.

The methods of the DirectMusicSegment object can be grouped as follows:

Timing and looping | GetLength
 | GetLoopPointStart
 | GetLoopPointEnd
 | GetRepeats
 | GetStartPoint
 | SetLength
 | SetLoopPoints
 | SetRepeats
 | SetStartPoint
Duplication | Clone
Instruments | ConnectToCollection
 | Download
 | Unload
Parameters | SetAutoDownloadEnable
 | SetStandardMidiFile
 | SetTempoEnable
 | SetTimeSigEnable


DirectMusicSegment.Clone

The DirectMusicSegment.Clone method creates a copy of all or part of the segment.

object.Clone(mtStart As Long, _
    mtEnd As Long) As DirectMusicSegment

Parameters

object
Object expression that resolves to a DirectMusicSegment object.
mtStart
Start of the part to clone, in music time. If less than 0 or greater than the length of the segment, 0 is used.
mtEnd
End of the part to clone, in music time. If this value is past the end of the segment, the segment is cloned to the end. A value of 0 or anything less than mtStart also clones to the end.

Return Values

If the method succeeds, it returns a DirectMusicSegment object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DMUS_E_OUTOFMEMORY.

Remarks

The start point and loop points set by the DirectMusicSegment.SetStartPoint and DirectMusicSegment.SetLoopPoints methods are set to their default values (0, and 0 to the end of the segment respectively) inside the clone. The number of repeats is also reset to 0.

For style-based segments, if mtStart is greater than 0, it should be on a measure boundary.


DirectMusicSegment.ConnectToCollection

The DirectMusicSegment.ConnectToCollection method associates a segment with a DLS instrument collection. This is the collection that is downloaded when the DirectMusicSegment.Download method is called.

object.ConnectToCollection(c As DirectMusicCollection)

Parameters

object
Object expression that resolves to a DirectMusicSegment object.
c
DirectMusicCollection object representing instruments to be used in playing the segment.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_SET_UNSUPPORTED
DMUS_E_TRACK_NOT_FOUND

Remarks

By default, the General MIDI collection in the Gm.dls file is used. This method needs to be called only if the segment is to be played with custom instruments.


DirectMusicSegment.Download

The DirectMusicSegment.Download method downloads the collection associated with the segment so that the port can play the instruments.

object.Download(performance As DirectMusicPerformance)

Parameters

object
Object expression that resolves to a DirectMusicSegment object.
performance
DirectMusicPerformance object to whose port the instruments are being downloaded.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

DirectMusicSegment.ConnectToCollection, DirectMusicSegment.Unload, DirectMusicSegment.SetAutoDownloadEnable


DirectMusicSegment.GetLength

The DirectMusicSegment.GetLength method retrieves the length of the segment.

object.GetLength() As Long

Parameters

object
Object expression that resolves to a DirectMusicSegment object.

Return Values

If the method succeeds, it returns the length of the segment, in music time.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

If for some reason the segment's length was never set, the method returns 0.

See Also

DirectMusicSegment.SetLength


DirectMusicSegment.GetLoopPointEnd

The DirectMusicSegment.GetLoopPointEnd method retrieves the point in the segment at which a repeating section is to end.

object.GetLoopPointEnd() As Long

Parameters

object
Object expression that resolves to a DirectMusicSegment object.

Return Values

If the method succeeds, it returns the end point of the loop, in music time. If this value is 0, the entire segment loops.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

The section does not repeat unless the number of repetitions has been set to 1 or more by using the DirectMusicSegment.SetRepeats method. By default, the entire segment repeats.

See Also

DirectMusicSegment.GetLoopPointStart, DirectMusicSegment.SetLoopPoints, DirectMusicSegment.GetRepeats


DirectMusicSegment.GetLoopPointStart

The DirectMusicSegment.GetLoopPointStart method retrieves the point in the segment at which a repeating section is to start.

object.GetLoopPointStart() As Long

Parameters

object
Object expression that resolves to a DirectMusicSegment object.

Return Values

If the method succeeds, it returns the start point of the loop, in music time.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

The section does not repeat unless the number of repetitions has been set to 1 or more by using the DirectMusicSegment.SetRepeats method. By default, the entire segment repeats.

See Also

DirectMusicSegment.GetLoopPointEnd, DirectMusicSegment.SetLoopPoints, DirectMusicSegment.GetRepeats


DirectMusicSegment.GetRepeats

The DirectMusicSegment.GetRepeats method retrieves the number of times that the looping portion of a segment is set to repeat.

object.GetRepeats() As Long

Parameters

object
Object expression that resolves to a DirectMusicSegment object.

Return Values

If the method succeeds, it returns the number of times that the looping portion repeats.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

DirectMusicSegment.SetRepeats, DirectMusicSegment.SetLoopPoints, DirectMusicSegment.GetLoopPointStart, DirectMusicSegment.GetLoopPointEnd, DirectMusicSegmentState.GetRepeats


DirectMusicSegment.GetStartPoint

The DirectMusicSegment.GetStartPoint method retrieves the point at which the segment starts playing in response to the DirectMusicPerformance.PlaySegment method.

object.GetStartPoint() As Long

Parameters

object
Object expression that resolves to a DirectMusicSegment object.

Return Values

If the method succeeds, it returns the start point of the segment, in music time.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

DirectMusicSegment.SetStartPoint


DirectMusicSegment.SetAutoDownloadEnable

The DirectMusicSegment.SetAutoDownloadEnable method enables or disables automatic downloading and unloading of instruments in the collection associated with the segment.

object.SetAutoDownloadEnable(b As Boolean)

Parameters

object
Object expression that resolves to a DirectMusicSegment object.
b
True to enable autodownloading, or False to disable it.

Remarks

Automatic downloading is disabled by default. When it is enabled, instruments are automatically downloaded when the segment is played, and unloaded when it is stopped.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_SET_UNSUPPORTED
DMUS_E_TRACK_NOT_FOUND

See Also

DirectMusicSegment.Download


DirectMusicSegment.SetLength

The DirectMusicSegment.SetLength method sets the length of the segment.

object.SetLength(mtLength As Long)

Parameters

object
Object expression that resolves to a DirectMusicSegment object.
mtLength
Desired length, in music time. Must be greater than 0.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DMUS_E_OUT_OF_RANGE.

Remarks

In most cases, applications do not need to set the length, which is automatically set when the segment is loaded. However, this method can be used to shorten a segment.

See Also

DirectMusicSegment.GetLength


DirectMusicSegment.SetLoopPoints

The DirectMusicSegment.SetLoopPoints method sets the start and end points inside the segment to repeat the number of times set by the DirectMusicSegment.SetRepeats method.

object.SetLoopPoints(mtStart As Long, mtEnd As Long)

Parameters

object
Object expression that resolves to a DirectMusicSegment object.
mtStart
Point at which to begin the loop, in music time.
mtEnd
Point at which to end the loop, in music time. A value of 0 loops the entire segment.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DMUS_E_OUT_OF_RANGE.

Remarks

When the segment is played, it plays from the segment start time until mtEnd, then loops to mtStart, plays the looped portion the number of times set by DirectMusicSegment.SetRepeats, then plays to the end.

The default values are set to loop the entire segment from beginning to end.

The method fails if mtStart is greater than or equal to the length of the segment, or if mtEnd is greater than the length of the segment. If mtEnd is 0, mtStart must be 0 as well.

This method does not affect any currently playing segment states created from this segment.

A segment that is reused might be loaded from an internal cache, in which case it has the same loop points that it had the last time these values were set. It is a good idea to reset the loop points to 0 before releasing or resetting the object.

See Also

DirectMusicSegment.GetLoopPointStart, DirectMusicSegment.GetLoopPointEnd, DirectMusicSegment.SetRepeats


DirectMusicSegment.SetRepeats

The DirectMusicSegment.SetRepeats method sets the number of times that the looping portion of the segment is to repeat.

object.SetRepeats(lRepeats As Long)

Parameters

object
Object expression that resolves to a DirectMusicSegment object.
lRepeats
Number of repetitions.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

DirectMusicSegment.GetRepeats, DirectMusicSegment.SetLoopPoints


DirectMusicSegment.SetStandardMidiFile

The DirectMusicSegment.SetStandardMidiFile method informs DirectMusic that the segment is based on a standard MIDI file, not one authored specifically for DirectMusic. Calling this method ensures that certain events are handled properly when the segment is played.

object.SetStandardMidiFile()

Parameters

object
Object expression that resolves to a DirectMusicSegment object.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

The method should be called before instruments are downloaded.


DirectMusicSegment.SetStartPoint

The DirectMusicSegment.SetStartPoint method sets the point at which the segment starts playing in response to a call to the DirectMusicPerformance.PlaySegment method.

object.SetStartPoint(mtStart As Long)

Parameters

object
Object expression that resolves to a DirectMusicSegment object.
mtStart
Point within the segment at which it is to start playing, in music time. If this value is less than 0 or greater than the length of the segment, the start point is set to 0.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DMUS_E_OUT_OF_RANGE.

Remarks

By default, the start point is 0, meaning that the segment starts from the beginning.

The call fails if mtStart is greater than or equal to the length of the segment.

The method does not affect any currently playing segment states created from this segment.

A segment that is reused might be loaded from an internal cache, in which case it has the same start point that it had the last time that this value was set. It is a good idea to set the start point to 0 before the object is released or reset.

See Also

DirectMusicSegment.GetStartPoint, DirectMusicSegmentState.GetStartPoint, DirectMusicSegment.SetLoopPoints


DirectMusicSegment.SetTempoEnable

The DirectMusicSegment.SetTempoEnable method enables or disables tempo messages for the segment.

object.SetTempoEnable(b As Boolean)

Parameters

object
Object expression that resolves to a DirectMusicSegment object.
b
True to enable tempo messages, or False to disable them.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_SET_UNSUPPORTED
DMUS_E_TRACK_NOT_FOUND


DirectMusicSegment.SetTimeSigEnable

The DirectMusicSegment.SetTimeSigEnable method enables or disables time signature messages for the segment.

object.SetTempoEnable(b As Boolean)

Parameters

object
Object expression that resolves to a DirectMusicSegment object.
b
True to enable time signature messages, or False to disable them.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to one of the following values:

DMUS_E_SET_UNSUPPORTED
DMUS_E_TRACK_NOT_FOUND


DirectMusicSegment.Unload

The DirectMusicSegment.Unload method unloads instruments that were downloaded to the port by the DirectMusicSegment.Download method.

object.Unload(performance As DirectMusicPerformance)

Parameters

object
Object expression that resolves to a DirectMusicSegment object.
performance
DirectMusicPerformance object from whose port the instruments are being unloaded.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

DirectMusicSegment.SetAutoDownloadEnable


DirectMusicSegmentState

The DirectMusicSegmentState class is used to get information about a segment instance. When the DirectMusicPerformance.PlaySegment method is called, it creates a DirectMusicSegmentState object that represents that instance of the segment and enables the application to retrieve information about it. The object can also be passed to methods of DirectMusicPerformance to determine whether a segment instance is still playing, or to stop it.

The class has the following methods:

Information | GetRepeats
 | GetSeek
 | GetSegment
 | GetStartPoint
 | GetStartTime

See Also

DirectMusicPerformance.GetSegmentState, DirectMusicPerformance.IsPlaying, DirectMusicPerformance.Stop


DirectMusicSegmentState.GetRepeats

The DirectMusicSegmentState.GetRepeats method returns the number of times that the looping portion of the segment is set to repeat.

object.GetRepeats() As Long

Parameters

object
Object expression that resolves to a DirectMusicSegmentState object.

Return Values

If the method succeeds, it returns the repeat count. A value of 0 indicates that the segment is to play through only once, with no portion repeated.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

DirectMusicSegment.SetRepeats


DirectMusicSegmentState.GetSeek

The DirectMusicSegmentState.GetSeek method retrieves the current seek pointer in the segment state. This is immediately after the last point in the segment for which messages have been generated.

object.GetSeek() As Long

Parameters

object
Object expression that resolves to a DirectMusicSegmentState object.

Return Values

If the method succeeds, it returns the current seek pointer, in music time.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

Remarks

When a segment is stopped, messages that have been sent but not yet queued to the port buffer are flushed. Therefore, if you stop a segment and then restart it at the last seek pointer, some notes are lost.


DirectMusicSegmentState.GetSegment

The DirectMusicSegmentState.GetSegment method returns an object representing the segment that owns this segment state.

object.GetSegment() As DirectMusicSegment

Parameters

object
Object expression that resolves to a DirectMusicSegmentState object.

Return Values

If the method succeeds, it returns a DirectMusicSegment object.

Error Codes

If the method fails, it raises an error, and Err.Number is set.


DirectMusicSegmentState.GetStartPoint

The DirectMusicSegmentState.GetStartPoint method returns the offset into the segment at which play began or will begin.

object.GetStartPoint() As Long

Parameters

object
Object expression that resolves to a DirectMusicSegmentState object.

Return Values

If the method succeeds, it returns the start point for this segment state, in music time. This might not be same value as is returned by DirectMusicSegment.GetStartPoint if the start point of the segment has been changed since this segment state was created. Different instances of a playing segment can have different start points.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

DirectMusicSegment.SetStartPoint, DirectMusicSegmentState.GetStartTime


DirectMusicSegmentState.GetStartTime

The DirectMusicSegmentState.GetStartTime method gets the performance time at which the segment started or will start playing.

object.GetStartTime() As Long

Parameters

object
Object expression that resolves to a DirectMusicSegmentState object.

Return Values

If the method succeeds, it returns the start time, in music time, of this instance of the segment.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DMUS_E_BUFFER_EMPTY.

Remarks

If the segment was started from some point other than the beginning, you can retrieve the time at which the beginning of the segment would have fallen by subtracting the time returned by DirectMusicSegmentState.GetStartPoint from the value returned by this method.

See Also

DirectMusicSegment.SetStartPoint, DirectMusicSegment.GetStartPoint, DirectMusicSegmentState.GetStartPoint


DirectMusicStyle

An object of the DirectMusicStyle class provides the performance with the information that it needs to play musical patterns. Styles usually include bands and motifs, and can include chord maps, so the DirectMusicStyle object also provides methods for accessing these objects.

The object is generally obtained by using the DirectMusicLoader.LoadStyle or the DirectMusicLoader.LoadStyleFromResource method. It can also be obtained from the performance by using the DirectMusicPerformance.GetStyle method, provided the current control segment is based on a style.

The methods of the DirectMusicStyle class can be organized in the following groups:

Bands | GetBand
 | GetBandCount
 | GetBandName
 | GetDefaultBand
Motifs | GetMotif
 | GetMotifCount
 | GetMotifName
Time | GetTempo
 | GetTimeSignature


DirectMusicStyle.GetBand

The DirectMusicStyle.GetBand method gets a band object by name.

object.GetBand(name As String) As DirectMusicBand

Parameters

object
Object expression that resolves to a DirectMusicStyle object.
name
Name assigned to the band by the author of the style.

Return Values

If the method succeeds, it returns a DirectMusicBand object.

Error Codes

If the method fails, it raises an error, and Err.Number can be set to DMUS_E_FAIL.

See Also

DirectMusicStyle.GetBandName, DirectMusicStyle.GetDefaultBand


DirectMusicStyle.GetBandCount

The DirectMusicStyle.GetBandCount method gets the number of bands available in the style.

object.GetBandCount() As Long

Parameters

object
Object expression that resolves to a DirectMusicStyle object.

Return Values

If the method succeeds, it returns the number of bands in the style.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

DirectMusicStyle.GetBand, DirectMusicStyle.GetBandName


DirectMusicStyle.GetBandName

The DirectMusicStyle.GetBandName method gets the name of a band in the style.

object.GetBandName(index As Long) As String

Parameters

object
Object expression that resolves to a DirectMusicStyle object.
index
Index of the band in the style, in the range from 1 through DirectMusicStyle.GetBandCount.

Return Values

If the method succeeds, it returns the name assigned to the band by the author of the style.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

DirectMusicStyle.GetBand


DirectMusicStyle.GetDefaultBand

The DirectMusicStyle.GetDefaultBand method gets the default band for the style .

object.GetDefaultBand() As DirectMusicBand

Parameters

object
Object expression that resolves to a DirectMusicStyle object.
name
Name assigned to the band by the author of the style.

Return Values

If the method succeeds, it returns a DirectMusicBand object.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

DirectMusicStyle.GetBand


DirectMusicStyle.GetMotif

The DirectMusicStyle.GetMotif method creates a segment containing the named motif.

object.GetMotif(name As String) As DirectMusicSegment

Parameters

object
Object expression that resolves to a DirectMusicStyle object.
name
Name assigned to the motif by the author of the style

Return Values

If the method succeeds, it returns a DirectMusicSegment object representing the motif.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

DirectMusicStyle.GetMotifCount, DirectMusicStyle.GetMotifName


DirectMusicStyle.GetMotifCount

The DirectMusicStyle.GetMotifCount method gets the number of motifs available in the style.

object.GetMotifCount() As Long

Parameters

object
Object expression that resolves to a DirectMusicStyle object.

Return Values

If the method succeeds, it returns the number of motifs in the style.

Error Codes

If the method fails, it raises an error, and Err.Number is set.


DirectMusicStyle.GetMotifName

The DirectMusicStyle.GetMotifName method gets the name of a motif in the style.

object.GetMotifName(index As Long) As String

Parameters

object
Object expression that resolves to a DirectMusicStyle object.
index
Index of the motif in the style, in the range from 1 through DirectMusicStyle.GetMotifCount.

Return Values

If the method succeeds, it returns the name assigned to the motif by the author of the style.

Error Codes

If the method fails, it raises an error, and Err.Number is set.

See Also

DirectMusicStyle.GetMotif


DirectMusicStyle.GetTempo

The DirectMusicStyle.GetTempo method retrieves the recommended tempo of the style.

object.GetTempo() As Double

Parameters

object
Object expression that resolves to a DirectMusicStyle object.

Return Values

If the method succeeds, it returns the recommended tempo, in beats per minute.

Error Codes

If the method fails, it raises an error, and Err.Number is set.


DirectMusicStyle.GetTimeSignature

The DirectMusicStyle.GetTimeSignature method retrieves the style's time signature.

object.GetTimeSignature(pTimeSig As DMUS_TIMESIGNATURE)

Parameters

object
Object expression that resolves to a DirectMusicStyle object.
pTimeSig
DMUS_TIMESIGNATURE type to receive information about the time signature.

Error Codes

If the method fails, it raises an error, and Err.Number is set.


Types

This section contains information on the following types used in DirectMusic for Visual Basic:

  • DMUS_CURVE_PMSG
  • DMUS_NOTE_PMSG
  • DMUS_NOTIFICATION_PMSG
  • DMUS_PORTCAPS
  • DMUS_TIMESIGNATURE


DMUS_CURVE_PMSG

The DMUS_CURVE_PMSG type contains information about a MIDI curve message.

Type DMUS_CURVE_PMSG
    beat As Byte
    ccData As Byte
    curveShape As Byte
    endValue As Integer
    flags As Byte
    grid As Byte
    measure As Integer
    mtDuration As Long
    mtOriginalStart As Long
    mtResetDuration As Long
    offset As Integer
    resetValue As Integer
    startValue As Integer
    type As Byte
End Type

Members

beat
Beat count (within a measure) at which this curve occurs.
ccData
CC number if this is a control change type.
curveShape
Shape of the curve. This can be one of the values from the CONST_DMUS_CURVES enumeration.
endValue
End value of the curve.
flags
Set to DMUS_CURVE_RESET if the resetValue must be set when the time is reached or an invalidation occurs because of a transition. If 0, the curve stays permanently at the new value.
grid
Grid offset from a beat at which this curve occurs.
measure
Measure in which this curve occurs.
mtDuration
How long the curve lasts.
mtOriginalStart
Original start time, in music time. Must be set to either 0 when this message is created, or to the original time of the curve.
mtResetDuration
How long after the curve is finished until the reset value is set, in music time.
offset
Offset from a grid at which this curve occurs, in music time.
resetValue
Reset value of the curve, set after mtResetDuration or upon a flush or invalidation.
startValue
Start value of the curve.
type
Type of curve. This can be one of the values from the CONST_DMUS_CURVET enumeration.

See Also

DirectMusicPerformance.SendCurvePMSG


DMUS_NOTE_PMSG

The DMUS_NOTE_PMSG type contains data for a music note event.

Type DMUS_NOTE_PMSG
    beat as Byte
    durRange As Byte
    flags As Byte
    grid As Byte
    measure As Integer
    midiValue As Byte
    mtDuration As Long
    musicValue As Integer
    offset As Integer
    playModeFlags As Byte
    subChordLevel As Byte
    timeRange As Byte
    velocity As Byte
    velRange As Byte
End Type

Members

beat
Beat count (within a measure) at which this note occurs.
durRange
Range to randomize duration.
flags
Should be set to DMUS_NOTEF_NOTEON. See Remarks.
grid
Grid offset from a beat at which this note occurs.
measure
Measure in which this note occurs.
midiValue
MIDI note value, converted from musicValue.
mtDuration
Duration of the note.
musicValue
Description of the note. In most play modes, this is a packed array of four-bit values, as follows:

Octave, in the range from –2 through 14. The note is transposed up or down by the octave times 12.

Chord position, in the range from 0 through 15, though it should never be above 3. The first position in the chord is 0.

Scale position, in the range from 0 through 15. Typically, it is from 0 through 2, but it is possible to have a one-note chord and have everything above the chord be interpreted as a scale position.

Accidental, in the range from –8 through 7, but typically in the range from –2 through 2. This represents an offset that takes the note out of the scale.

In the fixed play modes, the music value is a MIDI note value in the range from 0 through 127.

offset
Offset from a grid at which this note occurs, in music time.
playModeFlags
Play mode determining how the music value is related to the chord and subchord. For a list of values, see CONST_DMUS_PLAYMODE_FLAGS.
subChordLevel
Subchord level that the note uses.
timeRange
Range by which to randomize time.
velocity
Note velocity.
velRange
Range by which to randomize velocity.

Remarks

Applications sending note messages must provide values only in the flags, midiValue, mtDuration, and velocity members. The other members are of interest only to tools, which are not supported in DirectX for Visual Basic.

Normally, the application sets flags to DMUS_NOTEF_NOTEON. The application is not responsible for sending note-off messages. When the DirectMusic output tool receives a DMUS_NOTE_PMSG and sees that DMUS_NOTEF_NOTEON is set, it clears the flag, adds mtDuration to the time stamp, and requeues the message so that the note is turned off at the appropriate time.

It is possible, however, for the application to stop a note prematurely by sending the same note on the same channel with flags set to 0.

See Also

DirectMusicPerformance.SendNotePMSG, Music Values and MIDI Notes


DMUS_NOTIFICATION_PMSG

The DMUS_NOTIFICATION_PMSG type contains information about a notification message sent by the performance.

Type DMUS_NOTIFICATION_PMSG
    ctTime As Long
    lField1 As Long
    lField2 As Long
    lNotificationOption As Long
    lNotificationType As Long
    mtTime As Long
End Type

Members

ctTime
Time stamp of the message, in clock time.
lField1
Extra data specific to the type of notification. For DMUS_NOTIFY_ON_MEASUREANDBEAT notifications, this member returns the beat number within the measure.
lField2
Extra data specific to the type of notification. Reserved for future or application-defined use.
lNotificationOption
Identifier of the notification subtype, from the CONST_DMUS_NOTIFICATION_SUBTYPE enumeration.

If the notification type is DMUS_NOTIFY_ON_SEGMENT, this member can contain one of the following values:

DMUS_NOTIFICATION_SEGABORT
The segment was stopped by DirectMusicPerformance.Stop.
DMUS_NOTIFICATION_SEGALMOSTEND
The segment has reached the end minus the prepare time.
DMUS_NOTIFICATION_SEGEND
The segment has ended.
DMUS_NOTIFICATION_SEGLOOP
The segment has looped.
DMUS_NOTIFICATION_SEGSTART
The segment has started.

If the notification type is DMUS_NOTIFY_ON_COMMAND, this member can contain one of the following values:

DMUS_NOTIFICATION_GROOVE
Groove change.
DMUS_NOTIFICATION_EMBELLISHMENT
Embellishment command (intro, fill, break, or end).

If the notification type is DMUS_NOTIFY_ON_PERFORMANCE, this member can contain one of the following values:

DMUS_NOTIFICATION_MUSICSTARTED
Playback has started.
DMUS_NOTIFICATION_MUSICSTOPPED
Playback has stopped.

If the notification type is DMUS_NOTIFY_ON_MEASUREANDBEAT, this member contains DMUS_NOTIFICATION_MEASUREBEAT. No other subtypes are defined.

If the notification type is DMUS_NOTIFY_ON_CHORD, this member contains DMUS_NOTIFICATION_CHORD. No other subtypes are defined.

lNotificationType
Identifier of the notification type, from the CONST_DMUS_NOTIFICATION_TYPE enumeration.
mtTime
Time stamp of the message, in music time.

See Also

DirectMusicPerformance.AddNotificationType, DirectMusicPerformance.GetNotificationPMSG


DMUS_PORTCAPS

The DMUS_PORTCAPS type returns information about the capabilities of a port. It is passed to the DirectMusicPerformance.GetPortCaps method.

Type DMUS_PORTCAPS
    lClass as Long
    lEffectFlags As Long
    lFlags As Long
    lMaxAudioChannels As Long
    lMaxChannelGroups As Long
    lMaxVoices As Long
    lMemorySize As Long
    lType As Long
End Type

Members

lClass
Class of this port. One of the members of the CONST_DMUS_PC_CLASS enumeration.
lEffectFlags
Flags from the CONST_DMUS_EFFECT_FLAGS enumeration indicating what audio effects are available on the port.
lFlags
Flags describing various capabilities of the port. See CONST_DMUS_PC_FLAGS.
lMaxAudioChannels
Maximum number of audio channels that can be rendered by the port. The value can be –1 if the driver does not support returning this parameter.
lMaxChannelGroups
Maximum number of channel groups supported by this port. A channel group is a set of 16 MIDI channels.
lMaxVoices
Maximum number of voices that can be allocated when this port is opened. The value can be –1 if the driver does not support returning this parameter.
lMemorySize
Amount of memory available to store DLS instruments. If the port is using system memory and the amount is therefore limited only by the available system memory, this field contains DMUS_PC_SYSTEMMEMORY.
lType
Type of this port. See CONST_DMUS_PORT_TYPE.


DMUS_TIMESIGNATURE

The DMUS_TIMESIGNATURE type contains information about a time signature. It is passed to the DirectMusicPerformance.GetTimeSig and DirectMusicStyle.GetTimeSignature methods, and is also used in messages sent by the DirectMusicPerformance.SendTimeSigPMSG method.

Type DMUS_TIMESIGNATURE
    beat As Byte
    beatsPerMeasure As Byte
    gridsPerBeat As Integer
    mtTime As Long
End Type

Members

beat
Bottom of time signature.
beatsPerMeasure
Top of time signature.
gridsPerBeat
Grids (subdivisions) per beat. This value determines the timing resolution for certain music events—for example, segments cued with the DMUS_SEGF_GRID flag (see CONST_DMUS_SEGF_FLAGS.).
mtTime
Music time at which this time signature occurs.


Enumerations

DirectMusic for Visual Basic uses enumerations to group constants to take advantage of the statement completion feature of the Microsoft® Visual Studio® development environment.

This section contains reference information for the following enumerations:

  • CONST_DMUS
  • CONST_DMUS_COMMANDT_TYPES
  • CONST_DMUS_COMPOSEF_FLAGS
  • CONST_DMUS_CURVE_FLAGS
  • CONST_DMUS_CURVES
  • CONST_DMUS_CURVET
  • CONST_DMUS_EFFECT_FLAGS
  • CONST_DMUS_NOTEF_FLAGS
  • CONST_DMUS_NOTIFICATION_SUBTYPE
  • CONST_DMUS_NOTIFICATION_TYPE
  • CONST_DMUS_PC_CLASS
  • CONST_DMUS_PC_FLAGS
  • CONST_DMUS_PLAYMODE_FLAGS
  • CONST_DMUS_PMSGF_FLAGS
  • CONST_DMUS_PORT_TYPE
  • CONST_DMUS_SEGF_FLAGS
  • CONST_DMUS_SHAPET_TYPES
  • CONST_DMUSERR


CONST_DMUS

The CONST_DMUS enumeration contains miscellaneous constants used in DirectMusic.

Enum CONST_DMUS
    DMUS_MAXSUBCHORD = 8
    DMUS_TEMPO_MAX = 350 (&H15E)
    DMUS_TEMPO_MIN =  10
End Enum
DMUS_MAXSUBCHORD
Maximum number of subchords allowed in a chord.
DMUS_TEMPO_MAX
Maximum tempo, in beats per minute.
DMUS_TEMPO_MIN
Minimum tempo, in beats per minute.


CONST_DMUS_COMMANDT_TYPES

The members of the CONST_DMUS_COMMANDT_TYPES enumeration represent commands that establish musical patterns. They are used in the lCommand parameter of the DirectMusicComposer.AutoTransition and DirectMusicComposer.ComposeTransition methods and are returned by the DirectMusicPerformance.GetCommand method.

Type CONST_DMUS_COMMANDT_TYPES
    DMUS_COMMANDT_BREAK       = 3
    DMUS_COMMANDT_END         = 4
    DMUS_COMMANDT_ENDANDINTRO = 5
    DMUS_COMMANDT_FILL        = 1
    DMUS_COMMANDT_GROOVE      = 0
    DMUS_COMMANDT_INTRO       = 2
End Enum
DMUS_COMMANDT_BREAK
The command is a break.
DMUS_COMMANDT_END
The command is an ending.
DMUS_COMMANDT_ENDANDINTRO
The command is an ending and an intro.
DMUS_COMMANDT_FILL
The command is a fill.
DMUS_COMMANDT_GROOVE
The command is a groove command.
DMUS_COMMANDT_INTRO
The command is an intro.


CONST_DMUS_COMPOSEF_FLAGS

The members of the CONST_DMUS_COMPOSEF_FLAGS enumeration are used in the lFlags parameter of the DirectMusicComposer.AutoTransition and DirectMusicComposer.ComposeTransition methods.

Enum CONST_DMUS_COMPOSEF_FLAGS
    DMUS_COMPOSEF_AFTERPREPARETIME = 64 (&H40)
    DMUS_COMPOSEF_ALIGN             = 1
    DMUS_COMPOSEF_BEAT             = 16 (&H10)
    DMUS_COMPOSEF_GRID              = 8
    DMUS_COMPOSEF_IMMEDIATE         = 4
    DMUS_COMPOSEF_LONG           = 8192 (&H2000)
    DMUS_COMPOSEF_MEASURE          = 32 (&H20)
    DMUS_COMPOSEF_MODULATE       = 4096 (&H1000)
    DMUS_COMPOSEF_NONE              = 0
    DMUS_COMPOSEF_OVERLAP           = 2
End Enum
DMUS_COMPOSEF_AFTERPREPARETIME
AutoTransition only. Use the DMUS_SEGF_AFTERPREPARETIME flag (see CONST_DMUS_SEGF_FLAGS) when cuing the transition.
DMUS_COMPOSEF_ALIGN
Align transition to the time signature of the currently playing segment. Not currently implemented.
DMUS_COMPOSEF_BEAT
AutoTransition only. Start transition on a beat boundary.
DMUS_COMPOSEF_GRID
AutoTransition only. Start transition on a grid boundary.
DMUS_COMPOSEF_IMMEDIATE
AutoTransition only. Start transition on a music or clock time boundary.
DMUS_COMPOSEF_MEASURE
AutoTransition only. Start transition on a measure boundary.
DMUS_COMPOSEF_LONG
Composes a long transition. If this flag is not set, the length of the transition is at most one measure unless the lCommand parameter of ComposeTransition or AutoTransition specifies an ending and the style contains an ending of greater than one measure. If this flag is set, the length of the transition increases by one measure.
DMUS_COMPOSEF_MODULATE
Compose a transition that modulates smoothly from fromSeg to toSeg, using the chord of toSeg.
DMUS_COMPOSEF_NONE
No flags. By default, the transition starts on a measure boundary.
DMUS_COMPOSEF_OVERLAP
Overlap the transition into toSeg. Not currently implemented.


CONST_DMUS_CURVE_FLAGS

The CONST_DMUS_CURVE_FLAGS enumeration contains a single constant used in the DMUS_CURVE_PMSG type.

Enum CONST_DMUS_CURVE_FLAGS
    DMUS_CURVE_RESET = 1
End Enum
DMUS_CURVE_RESET
The reset value must be set when the time is reached or an invalidation occurs because of a transition.


CONST_DMUS_CURVES

Members of the CONST_DMUS_CURVES enumeration are used to define the shape of a curve in the DMUS_CURVE_PMSG type.

Enum CONST_DMUS_CURVES
    DMUS_CURVES_EXP =     2
    DMUS_CURVES_INSTANT = 1
    DMUS_CURVES_LINEAR =  0
    DMUS_CURVES_LOG =     3
    DMUS_CURVES_SINE =    4
End Enum
DMUS_CURVES_EXP
Exponential curve shape.
DMUS_CURVES_INSTANT
Instant curve shape (beginning and end of curve happen at essentially the same time).
DMUS_CURVES_LINEAR
Linear curve shape.
DMUS_CURVES_LOG
Logarithmic curve shape.
DMUS_CURVES_SINE
Sine curve shape.


CONST_DMUS_CURVET

Members of the CONST_DMUS_CURVET enumeration are used to describe the type of curve in the DMUS_CURVE_PMSG type.

Enum CONST_DMUS_CURVET
    DMUS_CURVET_CCCURVE =  4
    DMUS_CURVET_MATCURVE = 5
    DMUS_CURVET_PATCURVE = 6
    DMUS_CURVET_PBCURVE =  3
End Enum
DMUS_CURVET_CCCURVE
Continuous controller curve (MIDI Control Change channel voice message; status byte &HBn, where n is the channel number).
DMUS_CURVET_MATCURVE
Monophonic aftertouch curve (MIDI Channel Pressure channel voice message; status byte &HDn).
DMUS_CURVET_PATCURVE
Polyphonic aftertouch curve (MIDI Poly Key Pressure channel voice message, status byte &HDn).
DMUS_CURVET_PBCURVE
Pitch-bend curve (MIDI Pitch Bend channel voice message; status byte &HEn).


CONST_DMUS_EFFECT_FLAGS

Members of the CONST_DMUS_EFFECT_FLAGS enumeration are used in the DMUS_PORTCAPS type to specify which effects are supported by a port.

Enum CONST_DMUS_EFFECT_FLAGS
    DMUS_EFFECT_CHORUS = 2
    DMUS_EFFECT_NONE   = 0
    DMUS_EFFECT_REVERB = 1
End Enum
DMUS_EFFECT_CHORUS
The port supports chorus.
DMUS_EFFECT_NONE
The port does not support any effects.
DMUS_EFFECT_REVERB
The port supports reverb.


CONST_DMUS_NOTEF_FLAGS

The CONST_DMUS_NOTEF_FLAGS enumeration contains a single constant used in note messages.

Enum CONST_DMUS_NOTEF_FLAGS
    DMUS_NOTEF_NOTEON = 1
End Enum
DMUS_NOTEF_NOTEON
See the Remarks for DMUS_NOTE_PMSG.


CONST_DMUS_NOTIFICATION_SUBTYPE

The members of the CONST_DMUS_NOTIFICATION_SUBTYPE enumeration provide information about the musical events reported in notification messages.

Enum CONST_DMUS_NOTIFICATION_SUBTYPE
    DMUS_NOTIFICATION_CHORD =         0
    DMUS_NOTIFICATION_EMBELLISHMENT = 1
    DMUS_NOTIFICATION_GROOVE =        0
    DMUS_NOTIFICATION_MEASUREBEAT =   0
    DMUS_NOTIFICATION_MUSICSTARTED =  0
    DMUS_NOTIFICATION_MUSICSTOPPED =  1
    DMUS_NOTIFICATION_SEGABORT =      4
    DMUS_NOTIFICATION_SEGALMOSTEND =  2
    DMUS_NOTIFICATION_SEGEND =        1
    DMUS_NOTIFICATION_SEGLOOP =       3
    DMUS_NOTIFICATION_SEGSTART =      0
End Enum

For an explanation of the values, see DMUS_NOTIFICATION_PMSG.


CONST_DMUS_NOTIFICATION_TYPE

The members of the CONST_DMUS_NOTIFICATION_TYPE enumeration identify a notification type. They are passed to the DirectMusicPerformance.AddNotificationType and DirectMusicPerformance.RemoveNotificationType methods and identify the notification type in messages retrieved by DirectMusicPerformance.GetNotificationPMSG.

Enum CONST_DMUS_NOTIFICATION_TYPE
    DMUS_NOTIFY_ON_CHORD          = 1
    DMUS_NOTIFY_ON_COMMAND        = 2
    DMUS_NOTIFY_ON_MEASUREANDBEAT = 3
    DMUS_NOTIFY_ON_PERFORMANCE    = 4
    DMUS_NOTIFY_ON_SEGMENT        = 5
End Enum
DMUS_NOTIFY_ON_CHORD
Chord change.
DMUS_NOTIFY_ON_COMMAND
Command event.
DMUS_NOTIFY_ON_MEASUREANDBEAT
Measure and beat event.
DMUS_NOTIFY_ON_PERFORMANCE
Performance event. When this value is found in the lNotificationType member of a DMUS_NOTIFICATION_PMSG type, the event is further defined in the lNotificationOption member.
DMUS_NOTIFY_ON_SEGMENT
Segment event. When this value is found in the lNotificationType of a DMUS_NOTIFICATION_PMSG type, the event is further defined in the lNotificationOption member.

See Also

DMUS_NOTIFICATION_PMSG


CONST_DMUS_PC_CLASS

Members of the CONST_DMUS_PC_CLASS enumeration are used in the DMUS_PORTCAPS type to specify the class of the port.

Enum CONST_DMUS_PC_CLASS
    DMUS_PC_INPUTCLASS =  0
    DMUS_PC_OUTPUTCLASS = 1
End Enum
DMUS_PC_INPUTCLASS
Input port.
DMUS_PC_OUTPUTCLASS
Output port.


CONST_DMUS_PC_FLAGS

Members of the CONST_DMUS_PC_FLAGS enumeration are used in the DMUS_PORTCAPS type to describe miscellaneous capabilities of the port.

Enum CONST_DMUS_PC_FLAGS
    DMUS_PC_DIRECTSOUND =         128 (&H80)
    DMUS_PC_DLS =                   1
    DMUS_PC_EXTERNAL =              2
    DMUS_PC_GMINHARDWARE =         16 (&H10)
    DMUS_PC_GSINHARDWARE =         32 (&H20)
    DMUS_PC_MEMORYSIZEFIXED =       8
    DMUS_PC_SHAREABLE =           256 (&H100)
    DMUS_PC_SOFTWARESYNTH =         4
    DMUS_PC_SYSTEMMEMORY = 2147483647 (&H7FFFFFFF)
    DMUS_PC_XGINHARDWARE =         64 (&H40)
End Enum
DMUS_PC_DIRECTSOUND
The port supports streaming wave data to DirectSound.
DMUS_PC_DLS
The port supports DLS Level 1 sample collections.
DMUS_PC_EXTERNAL
This port connects to devices outside of the host—for example, devices connected over an external MIDI port such as the MPU-401.
DMUS_PC_GMINHARDWARE
The synthesizer has its own GM instrument set, so GM instruments do not need to be downloaded.
DMUS_PC_GSINHARDWARE
This port contains the Roland GS sound set in hardware.
DMUS_PC_MEMORYSIZEFIXED
Memory available for DLS instruments cannot be adjusted.
DMUS_PC_SHAREABLE
More than one port can be created that uses the same range of channel groups on the device. Unless this bit is set, the port can be opened only in exclusive mode. In exclusive mode, an attempt to create a port fails unless free channel groups are available to assign to the create request.
DMUS_PC_SOFTWARESYNTH
The port is a software synthesizer.
DMUS_PC_SYSTEMMEMORY
The port is using system memory, and the amount is therefore limited only by the available system memory. This constant is used in DMUS_PORTCAPS.lMemorysize, not lFlags.
DMUS_PC_XGINHARDWARE
The port contains the Yamaha XG extensions in hardware.


CONST_DMUS_PLAYMODE_FLAGS

The members of the CONST_DMUS_PLAYMODE_FLAGS enumeration are used to set the play mode in a DMUS_NOTE_PMSG message type. The play mode determines how the note is transposed to the current chord before it is converted to a MIDI note.

Enum CONST_DMUS_PLAYMODE_FLAGS
    DMUS_PLAYMODE_ALWAYSPLAY     = 14
    DMUS_PLAYMODE_CHORD_INTERVALS = 8
    DMUS_PLAYMODE_CHORD_ROOT      = 2
    DMUS_PLAYMODE_FIXED           = 0
    DMUS_PLAYMODE_FIXEDTOCHORD    = 2
    DMUS_PLAYMODE_FIXEDTOKEY      = 1
    DMUS_PLAYMODE_KEY_ROOT        = 1
    DMUS_PLAYMODE_MELODIC         = 6
    DMUS_PLAYMODE_NONE           = 16 (&H10)
    DMUS_PLAYMODE_NORMALCHORD    = 10
    DMUS_PLAYMODE_PEDALPOINT      = 5
    DMUS_PLAYMODE_SCALE_INTERVALS = 4
End Enum

The following members are the basic flags:

DMUS_PLAYMODE_CHORD_INTERVALS
Use chord intervals from chord pattern.
DMUS_PLAYMODE_CHORD_ROOT
Transpose over the chord root.
DMUS_PLAYMODE_KEY_ROOT
Transpose over the key root.
DMUS_PLAYMODE_NONE
No mode. Indicates that the parent part's mode should be used.
DMUS_PLAYMODE_SCALE_INTERVALS
Use scale intervals from scale pattern.
The following members represent combinations of the basic flags:
DMUS_PLAYMODE_ALWAYSPLAY
Combination of DMUS_PLAYMODE_SCALE_INTERVALS, DMUS_PLAYMODE_CHORD_INTERVALS, and DMUS_PLAYMODE_CHORD_ROOT. If it is desirable to play a note that is above the top of the chord, this mode finds a position for the note by using intervals from the scale. Essentially, this mode is a combination of the normal and melodic playback modes, in which a failure in normal mode causes a second try in melodic mode.
DMUS_PLAYMODE_FIXED
Interpret the music value as a MIDI value. This is defined as 0 and signifies the absence of other flags. This flag is used for drums, sound effects, and sequenced notes that should not be transposed by the chord or scale.
DMUS_PLAYMODE_FIXEDTOCHORD
Same as DMUS_PLAYMODE_CHORD_ROOT. The music value is a fixed MIDI value, but it is transposed over the chord root.
DMUS_PLAYMODE_FIXEDTOKEY
Same as DMUS_PLAYMODE_KEY_ROOT. The music value is a fixed MIDI value, but it is transposed over the key root.
DMUS_PLAYMODE_MELODIC
Combination of DMUS_PLAYMODE_CHORD_ROOT and DMUS_PLAYMODE_SCALE_INTERVALS. The chord root is used, but the notes track only the intervals in the scale. The key root and chord intervals are ignored. This is useful for melodic lines that play relative to the chord root.
DMUS_PLAYMODE_NORMALCHORD
Combination of DMUS_PLAYMODE_CHORD_ROOT and DMUS_PLAYMODE_CHORD_INTERVALS. This is the prevalent playback mode. The notes track the intervals in the chord, which is based on the chord root. If there is a scale component to the music value, the additional intervals are pulled from the scale and added. If the chord does not have an interval to match the chord component of the music value, the note is silent.
DMUS_PLAYMODE_PEDALPOINT
Combination of DMUS_PLAYMODE_KEY_ROOT and DMUS_PLAYMODE_SCALE_INTERVALS. The key root is used, and the notes track only the intervals in the scale. The chord root and intervals are ignored. This is useful for melodic lines that play relative to the key root.


CONST_DMUS_PMSGF_FLAGS

The members of the CONST_DMUS_PMSGF_FLAGS enumeration are used in the various message-sending methods of DirectMusicPerformance to specify when a message should be delivered to tools.

Enum CONST_DMUS_PMSGF_FLAGS
    DMUS_PMSGF_MUSICTIME      = 2
    DMUS_PMSGF_REFTIME        = 1
    DMUS_PMSGF_TOOL_ATTIME   = 16 (&H10)
    DMUS_PMSGF_TOOL_FLUSH    = 32 (&H20)
    DMUS_PMSGF_TOOL_IMMEDIATE = 4
    DMUS_PMSGF_TOOL_QUEUE     = 8
End Enum
DMUS_PMSGF_REFTIME
The time stamp is in clock time.
DMUS_PMSGF_MUSICTIME
The time stamp is in music time.
DMUS_PMSGF_TOOL_IMMEDIATE
DMUS_PMSGF_TOOL_QUEUE
DMUS_PMSGF_TOOL_ATTIME
DMUS_PMSGF_TOOL_FLUSH
See Remarks.

Remarks

Because DirectX for Visual Basic does not support DirectMusic tools, only DMUS_PMSGF_REFTIME and DMUS_PMSGF_MUSICTIME are currently valid. The time of messages is in music time by default, so DMUS_PMSGF_REFTIME is the only flag that applications normally use.


CONST_DMUS_PORT_TYPE

The CONST_DMUS_PORT_TYPE enumeration is used in the DMUS_PORTCAPS type to specify the driver model of the port.

Enum CONST_DMUS_PORT_TYPE
    DMUS_PORT_KERNEL_MODE =     2
    DMUS_PORT_USER_MODE_SYNTH = 1
    DMUS_PORT_WINMM_DRIVER =    0
End Enum
DMUS_PORT_WINMM_DRIVER
Windows multimedia driver.
DMUS_PORT_USER_MODE_SYNTH
User-mode synthesizer.
DMUS_PORT_KERNEL_MODE
Windows Driver Model (WDM) driver.


CONST_DMUS_SEGF_FLAGS

The members of the CONST_DMUS_SEGF_FLAGS enumeration are used in various methods of the DirectMusicPerformance object to control the timing and other aspects of actions on a segment.

Enum CONST_DMUS_SEGF_FLAGS
    DMUS_SEGF_AFTERPREPARETIME = 1024 (&H400)
    DMUS_SEGF_BEAT             = 4096 (&H1000)
    DMUS_SEGF_CONTROL           = 512 (&H200)
    DMUS_SEGF_DEFAULT         = 16384 (&H4000)
    DMUS_SEGF_GRID             = 2048 (&H800)
    DMUS_SEGF_MEASURE          = 8192 (&H2000)
    DMUS_SEGF_NOINVALIDATE    = 32768 (&H8000)
    DMUS_SEGF_QUEUE             = 256 (&H100)
    DMUS_SEGF_REFTIME            = 64 (&H40)
    DMUS_SEGF_SECONDARY         = 128 (&H80)
End Enum
DMUS_SEGF_AFTERPREPARETIME
Play after the prepare time. (See DirectMusicPerformance.GetPrepareTime.)
DMUS_SEGF_BEAT
Play on a beat boundary.
DMUS_SEGF_CONTROL
Play as a control segment (secondary segments only). See Remarks.
DMUS_SEGF_DEFAULT
Use segment's default boundary.
DMUS_SEGF_GRID
Play on a grid boundary.
DMUS_SEGF_MEASURE
Play on a measure boundary.
DMUS_SEGF_NOINVALIDATE
Setting this flag in DirectMusicPerformance.PlaySegment for a primary or control segment causes the new segment not to cause an invalidation. Without this flag, an invalidation occurs, cutting off and resetting any currently playing curve or note. This flag should be combined with DMUS_SEGF_AFTERPREPARETIME so that notes in the new segment do not play over notes played by the old segment.
DMUS_SEGF_QUEUE
Put at the end of the primary segment queue (primary segment only).
DMUS_SEGF_REFTIME
Time parameter is in clock time.
DMUS_SEGF_SECONDARY
Secondary segment.

Remarks

Normally, the primary segment is the control segment. The DMUS_SEGF_CONTROL flag can be used to make a secondary segment the control segment. There should be only one control segment at a time. (It is possible to create multiple control segments, but there is no guarantee of which one will actually be used by DirectMusic as the control segment.) By default, only the control segment sends tempo messages.

If the DMUS_SEGF_CONTROL flag is set, DMUS_SEGF_SECONDARY is assumed.

See Also

DirectMusicPerformance.GetResolvedTime, DirectMusicPerformance.Invalidate, DirectMusicPerformance.PlaySegment, DirectMusicPerformance.Stop


CONST_DMUS_SHAPET_TYPES

The members of the CONST_DMUS_SHAPET_TYPES enumeration are used in the wShape parameter of the DirectMusicComposer.ComposeSegmentFromShape and DirectMusicComposer.ComposeTemplateFromShape methods to specify the desired pattern of the groove level.

Enum CONST_DMUS_SHAPET_TYPES
    DMUS_SHAPET_FALLING  = 0
    DMUS_SHAPET_LEVEL    = 1
    DMUS_SHAPET_LOOPABLE = 2
    DMUS_SHAPET_LOUD     = 3
    DMUS_SHAPET_PEAKING  = 5
    DMUS_SHAPET_QUIET    = 4
    DMUS_SHAPET_RANDOM   = 6
    DMUS_SHAPET_RISING   = 7
    DMUS_SHAPET_SONG     = 8
End Enum
DMUS_SHAPET_FALLING
The groove level falls.
DMUS_SHAPET_LEVEL
The groove level remains even.
DMUS_SHAPET_LOOPABLE
The segment is arranged to loop back to the beginning.
DMUS_SHAPET_LOUD
The groove level is high.
DMUS_SHAPET_PEAKING
The groove level rises to a peak, then falls.
DMUS_SHAPET_QUIET
The groove level is low.
DMUS_SHAPET_RANDOM
The groove level is random.
DMUS_SHAPET_RISING
The groove level rises.
DMUS_SHAPET_SONG
The segment is in a song form. Several phrases of 6 to 8 bars are composed and put together to give a verse-chorus effect, with variations in groove level.


CONST_DMUSERR

The CONST_DMUSERR enumeration represents DirectMusic error codes.


Error Codes

This section provides a brief explanation of the various error codes that can be returned by DirectMusic methods. For a list of the specific codes that each method can return, see the individual method descriptions. These lists are not necessarily comprehensive.

DMUS_E_ALL_TRACKS_FAILED
The segment object was unable to load all tracks from the IStream object data, perhaps because of errors in the stream or because the tracks are incorrectly registered on the client.
DMUS_E_ALREADY_ACTIVATED
The port has been activated, and the parameter cannot be changed.
DMUS_E_ALREADY_DOWNLOADED
Buffer has already been downloaded.
DMUS_E_ALREADY_EXISTS
The tool is already contained in the graph. You must create a new instance.
DMUS_E_ALREADY_INITED
The object has already been initialized.
DMUS_E_ALREADY_LOADED
The DLS collection is already open.
DMUS_E_ALREADY_SENT
The message has already been sent.
DMUS_E_ALREADYCLOSED
The port is not open.
DMUS_E_ALREADYOPEN
The port was already opened.
DMUS_E_BADARTICULATION
Invalid articulation chunk in DLS collection.
DMUS_E_BADINSTRUMENT
Invalid instrument chunk in DLS collection.
DMUS_E_BADOFFSETTABLE
Offset table has errors.
DMUS_E_BADWAVE
Corrupt wave header.
DMUS_E_BADWAVELINK
Wave-link chunk in DLS collection points to an invalid wave.
DMUS_E_BUFFER_EMPTY
There is no data in the buffer.
DMUS_E_BUFFER_FULL
The specified number of bytes exceeds the maximum buffer size.
DMUS_E_BUFFERNOTAVAILABLE
The buffer is not available for download.
DMUS_E_BUFFERNOTSET
No buffer was prepared for the data.
DMUS_E_CANNOT_OPEN_PORT
The default system port could not be opened.
DMUS_E_DEVICE_IN_USE
Device is already in use (possibly by a non-DirectMusic client) and cannot be opened again.
DMUS_E_DMUSIC_RELEASED
Operation cannot be performed because the final instance of the DirectMusic object was released. Ports cannot be used after final release of the DirectMusic object.
DMUS_E_DRIVER_FAILED
An unexpected error was returned from a device driver, indicating possible failure of the driver or hardware.
DMUS_E_DSOUND_ALREADY_SET
A DirectSound object has already been set.
DMUS_E_DSOUND_NOT_SET
Port could not be created because no DirectSound object has been specified.
DMUS_E_FAIL
The method did not succeed.
DMUS_E_GET_UNSUPPORTED
Getting the parameter is not supported.
DMUS_E_INSUFFICIENTBUFFER
Buffer is not large enough for the requested operation.
DMUS_E_INVALIDARG
Invalid argument.
DMUS_E_INVALID_BAND
File does not contain a valid band.
DMUS_E_INVALID_DOWNLOADID
Invalid download identifier was used in the process of creating a download buffer.
DMUS_E_INVALID_EVENT
The event either is not a valid MIDI message or makes use of running status, and cannot be packed into the buffer.
DMUS_E_INVALIDBUFFER
Invalid DirectSound buffer was handed to port.
DMUS_E_INVALIDFILE
Not a valid file.
DMUS_E_INVALIDPATCH
No instrument in the collection matches the patch number.
DMUS_E_INVALIDPOS
Error reading wave data from a DLS collection. Indicates a bad file.
DMUS_E_LOADER_BADPATH
The file path is invalid.
DMUS_E_LOADER_FAILEDCREATE
Object could not be found or created.
DMUS_E_LOADER_FAILEDOPEN
File open failed because the file does not exist or is locked.
DMUS_E_LOADER_FORMATNOTSUPPORTED
The object cannot be loaded because the data format is not supported.
DMUS_E_LOADER_OBJECTNOTFOUND
The object was not found.
DMUS_E_NO_MASTER_CLOCK
There is no master clock in the performance. Be sure to call the DirectMusicPerformance.Init method.
DMUS_E_NOINTERFACE
No object interface is available.
DMUS_E_NOT_DOWNLOADED_TO_PORT
The object cannot be unloaded because it is not present on the port.
DMUS_E_NOT_FOUND
The requested item is not contained by the object.
DMUS_E_NOT_INIT
A required object is not initialized or failed to initialize.
DMUS_E_NOTADLSCOL
The object being loaded is not a valid DLS collection.
DMUS_E_NOTIMPL
The method is not implemented. This value can be returned if a driver does not support a feature necessary for the operation.
DMUS_E_OUT_OF_RANGE
The requested time is outside the range of the segment.
DMUS_E_OUTOFMEMORY
Insufficient memory to complete task.
DMUS_E_PORT_NOT_RENDER
Not an output port.
DMUS_E_PORTS_OPEN
The requested operation cannot be performed while there are instantiated ports in any process in the system.
DMUS_E_SEGMENT_INIT_FAILED
Segment initialization failed, probably because of a critical memory situation.
DMUS_E_SET_UNSUPPORTED
Setting the parameter is not supported.
DMUS_E_TIME_PAST
The time requested is in the past.
DMUS_E_TRACK_NOT_FOUND
There is no track of the requested type.
DMUS_E_TYPE_DISABLED
Parameter is unavailable because it has been disabled.
DMUS_E_TYPE_UNSUPPORTED
Parameter is unsupported on this track.
DMUS_E_UNKNOWN_PROPERTY
The property set or item is not implemented by this port.
DMUS_E_UNSUPPORTED_STREAM
The stream does not contain data supported by the loading object.


DirectMusic Samples

This section describes sample applications included with the DirectX SDK that demonstrate the use of DirectMusic. Descriptions are organized as follows:

  • DirectMusic C/C++ Samples
  • DirectMusic Visual Basic Samples


DirectMusic C/C++ Samples

[Visual Basic]

This section pertains only to application development in C and C++. See DirectMusic Visual Basic Samples.

[C++]

The following sample applications demonstrate the use and capabilities of the DirectMusic® application programming interface:

  • 3DMusic Sample
  • DMBoids Sample
  • DMDonuts Sample
  • DirectMusic MIDI Sample
  • DirectMusic Shell Sample
  • EchoTool Sample
  • MusicLines Sample
  • PlayMotif Sample
  • PlayPrimary Sample

Although DirectX® samples include Microsoft® Visual C++® project workspace files, you might need to verify other settings in your development environment to ensure that the samples compile properly. For more information, see Compiling DirectX Samples and Other DirectX Applications.


3DMusic Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectMusic Visual Basic Samples.

[C++]

Description

The 3DMusic sample shows how to play a MIDI file into a custom DirectSound 3-D buffer.

Path

Source: (SDK root)\Samples\Multimedia\Dmusic\Src\3DMusic

Executable: (SDK root)\Samples\Multimedia\DMusic\Bin\3DMusic.exe

User's Guide

The icons represents a listener and a sound source in a 3-D environment, although movement and orientation are possible in only two dimensions.

Use the arrow keys to move the sound source. Use the numeric keypad to change the orientation of the listener.

Choosing Play Stereo Drip from the File menu causes a dripping sound to play at random pan and volume, illustrating how pseudo–3-D effects can be achieved with a 2-D buffer.

Programming Notes

The program uses the registry key set up by the DirectX SDK setup to find the media file path.

Helper.cpp contains useful functions that set up DirectMusic. These functions are called from Sound.cpp.


DMBoids Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectMusic Visual Basic Samples.

[C++]

Description

DMBoids is a version of Boids that adds DirectMusic support. As objects fly over a simple landscape, the music responds to user input and events on the screen.

Path

Source: (SDK root)\Samples\Multimedia\Dmusic\Src\DMBoids

Executable: (SDK root)\Samples\Multimedia\DMusic\Bin\Dmboids.exe

User's Guide

Press F10 to access the main menu. The Drivers menu allows you to change the driver, device, and video mode. The application runs only in full-screen modes.

The A (alignment), C (cohesion) and O (obstacle) keys alter behavior of the boids in various ways as long as they are held down.

Hold down the S key or the spacebar and the birds flock in closer. Release the key and they spread apart. Note the use of motifs to track this behavior.

Hold down the M key and the birds wander off their path. Notice that the music completely changes. Release and the birds will eventually get back on the path.

Press the ESC key to quit.

Programming Notes

DirectMusic features illustrated include the following:

  • Software synthesis with DLS. In addition to the musical instruments from the GS sound set, the application uses custom downloadable sounds such as the voices that appear to come from the planets.
  • Composing and performing style-based segments.
  • Musical transitions using style-based motifs and segment cues.
  • Echo/articulation tool coded that uses the proximity of the birds to adjust the echoes and note durations of the music as it plays.


DMDonuts Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectMusic Visual Basic Samples.

[C++]

Description

DM Donuts is a variation of the Space Donuts sample with the addition of music that responds to game events.

Path

Source: (SDK root)\Samples\Multimedia\Dmusic\Src\DMDonuts

Executable: (SDK root)\Samples\Multimedia\DMusic\Bin\Dmdonuts.exe

User's Guide

While the donut floats in space, notice that the music is subtle and spacey. Press the arrow keys to move the ship. Bounce around and see how the music and rhythm respond.

Shoot the donut by firing with the space bar. Immediately there is an explosion of music and the background music grows in intensity.

Press the 7 key on the numeric keypad. This turns on the shields. Notice how the music becomes muted as if you were listening from inside the shield.

When all the donut fragments are destroyed, notice that the music immediately transitions into an ending, then starts the next level on the start of the next musical theme.

Notice that the music is never the same.

You can control the ship with the joystick if you prefer, by changing the input device under the Game menu.

The following is a complete list of game commands. All numbers must be entered from the numeric keypad. "Joy" refers to a joystick button.

Key | Command
ESC, F12 | Quit
4 | Turn left
6 | Turn right
5 (Joy 3) | Stop
8 | Accelerate forward
2 | Accelerate backward
7 (Joy 2) | Shields
SPACEBAR (Joy 1) | Fire
ENTER | Start game
F1 | Toggle trailing afterimage effect on/off
F5 | Toggle frame rate display on/off
F7 | Turn music on/off
F10 | Main menu

The display defaults to 640x480 at 256 colors. You can specify a different resolution and pixel depth on the command line.

The game uses the following command line switches, which are case-sensitive:

e | Use software emulation, not hardware acceleration
t | Test mode, no input required
x | Stress mode. Never halt if you can help it

These switches may be followed by three option numbers representing x-resolution, y-resolution, and bits per pixel. For example:

donuts -t 800 600 16

Programming Notes

Techniques illustrated include the following:

  • Composing and performing style-based segments.
  • Autotransitions on game state changes.
  • Motifs (short musical clips) to highlight actions. Because the motifs track the rhythm and harmony of the underlying music, they add to the music while providing sonic reinforcement.
  • Dynamic bands that change the orchestration in response to real-time events.

By default, this sample runs on the software synthesizer. On versions of the operating system that support DLS synthesis in hardware, undefine the _SOFTWARE_SYNTH_ compile flag and recompile the sample.


DirectMusic MIDI Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectMusic Visual Basic Samples.

[C++]

Description

The DirectMusic MIDI sample is a simple MIDI file player.

Path

Source: (SDK root)\Samples\Multimedia\Dmusic\Src\DMusMIDI

Executable: (SDK root)\Samples\Multimedia\DMusic\Bin\Dmusmidi.exe

User's Guide

Load a MIDI file by choosing Open from the File menu. (There is a sample file in the \Samples\Multimedia\DMusic\Media folder.) You can also load a file by drag-and-drop. If Autoplay Dropped Files is selected on the Options menu, a dropped file automatically starts playing.

Once a file is loaded, you can play, pause, or stop it by choosing from the File menu or the toolbar.

The Options menu provides a choice for adding reverberation to the music, and several choices for the interface. The time can be displayed in hours, minutes, and seconds from the start of play, or in music time ticks.

When no music is playing, you can select a port from the Device menu. Note that to hear music from the "MIDI Out" port, you must have an external synthesizer attached.

Programming Notes

The application demonstrates how to load a MIDI file as a segment, play it, stop it, and restart it either at the beginning or at the point where it was stopped. It also shows how to set the reverb property.

The code is written in pure C, so methods are called through pointers to vtables. For more information, see Accessing COM Objects by Using C.


DirectMusic Shell Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectMusic Visual Basic Samples.

[C++]

Description

The DirectMusic Shell sample demonstrates interactive music that responds to Windows system events.

Path

Source: (SDK root)\Samples\Multimedia\Dmusic\Src\DMShell

Executable: (SDK root)\Samples\Multimedia\DMusic\Bin\Dmshell.exe

User's Guide

When you run the program, its icon appears in the tray on the taskbar. Click on the icon to see a menu that allows you to change music schemes, select the output device, start and stop the music, and close the program.

Listen to the music and note how it changes and how motifs are introduced in response to system events such as minimizing, restoring, or closing a window, opening an application menu or the Start menu, and pressing a key (there are special sounds for a few keys).

Programming Notes

The Windows system messages are obtained in Dmhook.dll, the source code for which is found in the (SDK root)\Samples\Multimedia\Dmusic\Src\DMHook folder. (Dmhook.dll must be compiled with a Microsoft compiler.)


EchoTool Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectMusic Visual Basic Samples.

[C++]

Description

The EchoTool sample shows how to implement a tool in DirectMusic.

Path

Source: (SDK root)\Samples\Multimedia\Dmusic\Src\EchoTool

Executable: (SDK root)\Samples\Multimedia\DMusic\Bin

User's Guide

Select an option button to change the delay of the echoes. Click the Close button to exit the application.

Programming Notes

The tool creates up to four delayed echoes of the music playing through it.

Helper.cpp contains useful functions that set up DirectMusic. These functions are called from Main.cpp. Echotool.cpp contains the tool code.

For more information, see Tutorial 2: Using Tools.


MusicLines Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectMusic Visual Basic Samples.

[C++]

Description

The MusicLines sample demonstrates interactive music elements in a simple game, and in particular how game elements can be driven by the music.

Path

Source: (SDK root)\Samples\Multimedia\Dmusic\Src\MusicLines

Executable: (SDK root)\Samples\Multimedia\DMusic\Bin

User's Guide

In the opening dialog box, choose windowed or full-screen mode and a difficulty level, and set the players to human or computer. If two humans are playing, one can use the arrow keys while the other uses the keys AZSW. Start moving by pressing an arrow key.

The object of the game is to force the other player to collide with an existing line.

Change the direction of your line by pressing the arrow keys or the equivalent letter keys. Observe how the main music changes to reflect the current state of play, how motifs are used to signal events such as collisions, and how the speed of the lines is actually controlled by the music.

If you win against the computer, you can continue extending your line or bring the game to an end by deliberately colliding. Play again by pressing the space bar. Quit by pressing ALT+F4.

Programming Notes

The music logic is in Mlmusic.cpp and is amply commented.


PlayMotif Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectMusic Visual Basic Samples.

[C++]

Description

This sample application shows how motifs can be played over a primary segment.

Path

Source: (SDK root)\Samples\Multimedia\Dmusic\Src\PlayMotf

Executable: (SDK root)\Samples\Multimedia\DMusic\Bin

User's Guide

Click the buttons to play the various secondary segments (motifs) on top of the main playing primary segment. Click Close to exit the application.

Programming Notes

The program uses the registry key set up by the DirectX SDK setup to find the media file path.


PlayPrimary Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectMusic Visual Basic Samples.

[C++]

Description

The PlayPrimary sample shows how to play a primary segment based on an authored music section.

Path

Source: (SDK root)\Samples\Multimedia\Dmusic\Src\PlayPri

Executable: (SDK root)\Samples\Multimedia\DMusic\Bin

User's Guide

Click Close to quit the program.

Programming Notes

The program uses the registry key set up by the DirectX SDK setup to find the media file path.


DirectMusic Visual Basic Samples

[C++]

This section pertains only to application development in Visual Basic. See DirectMusic C/C++ Samples.

[Visual Basic]

The following sample applications demonstrate the use and capabilities of the DirectMusic® application programming interface:

  • ClubMet Sample
  • DLSEffects Sample
  • DMDrums Sample
  • PlayDMusic Sample


ClubMet Sample

[C++]

This topic pertains only to application development in Visual Basic. See DirectMusic C/C++ Samples.

[Visual Basic]

Description

The ClubMet sample application demonstrates how DirectMusic can respond to input events.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\Dmusic\Src\ClubMet

Executable: (SDK root)\Samples\Multimedia\VBSamples\DMusic\Bin\ClubMet.exe

User's Guide

Click on the days of the week and the buttons. Note how the style changes according to the day selected, and how motifs are played in response to button clicks.

Programming Notes

The sample shows how segments and transitions can be created from styles by DirectMusicComposer.


DLSEffects Sample

[C++]

This topic pertains only to application development in Visual Basic. See DirectMusic C/C++ Samples.

[Visual Basic]

Description

The DLSEffects sample application shows how an application can use DirectMusic and DLS files for sound effects other than music.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\Dmusic\Src\DLSEffects

Executable: (SDK root)\Samples\Multimedia\VBSamples\DMusic\Bin\DLSEffects.exe

User's Guide

Click the buttons labeled C3 to C10 to play a vocal effect. Click On to play the heartbeat effect continuously, and vary the pitch by using the Note and Pitch Bend sliders. Set the velocity (volume) of notes by using the slider on the right. Changes in velocity apply only to effects started after the change is made.

Programming Notes

This application demonstrates the use of downloadable sounds for sound effects, and how to send MIDI notes.

The DLS instruments are taken from Boids.dls. That collection actually contains only a single instrument, called Vocals. However, the instrument is based on different wave samples for different "regions" or ranges of notes. For example, the first speech sound is used when any note between C3 and B3 is sent. The speech sounds are played at the correct pitch only when the note is the lowest one in the region.

One of the samples, called Heartbeat, is valid for the range B7-B8. Because this is not a vocal sample, the pitch can reasonably be varied. This is done by playing various notes within the range, as determined by the slider setting.

Heartbeat is also the only sample in the DLS collection that is based on a looped wave. Hence it can be played continuously for up to the maximum duration of a note. The other samples will play only once regardless of the duration of the note sent.


DMDrums Sample

[C++]

This topic pertains only to application development in Visual Basic. See DirectMusic C/C++ Samples.

[Visual Basic]

Description

The DMDrums sample application shows how an application can vary music by changing the master groove level, band, volume, and tempo. It also shows how to play motifs in response to user input.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\Dmusic\Src\DMDrums

Executable: (SDK root)\Samples\Multimedia\VBSamples\DMusic\Bin\Dmdrums.exe

User's Guide

Start and stop the music by clicking the green and red buttons. Select different types of music from the top list box and different bands from the bottom one. Adjust tempo and volume with the up and down controls. Play drum motifs by clicking on any of the drum buttons.

Programming Notes

The "style" of music is actually determined by the master groove level, which causes different patterns to be selected from the style object associated with the segment.

Every drum button plays a different motif. The instrument associated with the button is assigned in the motif.


PlayDMusic Sample

[C++]

This topic pertains only to application development in Visual Basic. See DirectMusic C/C++ Samples.

[Visual Basic]

Description

The PlayDMusic sample shows how to load and play authored segments and standard MIDI files.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\Dmusic\Src\Play

Executable: (SDK root)\Samples\Multimedia\VBSamples\DMusic\Bin\Playdmusic.exe

User's Guide

Load a segment or MIDI file by choosing Open from the File menu or by clicking the open file icon. Play, pause, and stop the segment by using the buttons. Adjust the volume by clicking the arrows.

Choose Show from the Options menu to display the time either in seconds or in music time ticks.

You can connect the band to a different DLS collection, and issue a GMReset command, by selecting those commands from the File menu.

Programming Notes

The program uses a second performance in order to retrieve information about the segment before it is played.


DirectPlay

The DirectPlay® application programming interface (API) is the component of DirectX® that allows you to write network applications such as multiplayer games.

Information on DirectPlay is presented in the following topics:

  • About DirectPlay
  • Why Use DirectPlay?
  • DirectPlay Architecture
  • DirectPlay Essentials
  • DirectPlay Tutorials
  • DirectPlay Reference
  • DirectPlay Tools and Samples


About DirectPlay

The Microsoft® DirectPlay® application programming interface (API) for Microsoft Windows® lets developers create multiplayer games, game servers, chat clients, and other network applications without writing code for individual transports, protocols, or online services.

DirectPlay provides services for:

  • Establishing a connection between computers through a network, over the Internet, or by a modem.
  • Communicating through a lobby where participants can meet one another and organize sessions.
  • Creating and joining sessions.
  • Managing players and groups within a session.
  • Harmonizing the session state on different computers through the exchange of messages.


Why Use DirectPlay?

Instead of forcing the developer to deal with the differences that each connectivity solution represents, DirectPlay provides well-defined, generalized communication capabilities. DirectPlay shields developers from the underlying complexities of diverse connectivity implementations, freeing them to concentrate on producing great applications.

The DirectPlay application programming interface (API) is a network abstraction and distributed object system. The API defines the functionality of the abstract DirectPlay network, and all the functionality is available to your application regardless of whether the actual underlying network supports it. In cases where the underlying network does not support functionality, DirectPlay emulates it. Examples include group messaging and guaranteed messaging.

DirectPlay also supports lobbies, places where users of various applications can meet, exchange messages, organize game sessions, and launch applications. For end users, the main benefit of lobbies is the ease of establishing a session with other players. Not only does the lobby provide a place for the player to find opponents, but when the application starts there is no need for the user to do the following:

  • Select a service provider. The lobby specifies which service provider to use.
  • Enter a network address or configure the network. The lobby supplies this information if it is needed.
  • Enter the name of the player. The lobby passes in the same name that the player entered to connected to the lobby.

Other benefits of the lobby are:

  • Keeping track of sessions in progress and enabling users to join them.
  • Receiving status messages from the session and displaying the progress to other users on a scoreboard.
  • Obtaining final scores and maintaining player rankings for tournament play.


DirectPlay Architecture

The service provider architecture of DirectPlay insulates the application from the underlying network it is running on. The application can query DirectPlay for specific capabilities of the underlying network, such as latency and bandwidth, and adjust its communications accordingly.

The following diagram illustrates the DirectPlay service provider architecture.

The first step in using DirectPlay is to select which service provider to use. The service provider determines what type of network or protocol will be used for communications. The protocol can range from TCP/IP over the Internet, to an IPX local area network, to a serial cable connection between two computers.

The applications uses the service provider to make a connection to a point on the network. The user may need to provide additional information to make a connection, or the application can specify the connection parameters.

Further information on the architecture of DirectPlay is given in the following topics:

  • Communication Models
  • Lobbies
  • Service Providers
  • Security
  • Overview of DirectPlay Interfaces [C++]
  • Overview of DirectPlay Classes [Visual Basic]


Communication Models

This section discusses general principles of communication and maintaining a common state in a network game or similar application. Using DirectPlay, an application can manage its own data using either of the models discussed.

The fundamental concern when writing a networked, multiplayer application is how to propagate state information to all the computers in the session. The state of the session defines what users see on their computers and what actions they can perform. Generally, two things make up the session state: the environment and the individual users or players.

Note While "user" and "player" are often synonymous in a general sense, it is important to remember that a player is also a logical entity in a DirectPlay application. An application might allow a user to be represented by more than one player.

The environment consists of the objects that the players can interact with or manipulate—for example, a dungeon, a racecourse, or a sequence of chat messages. The environment can also include computer-controlled players.

Within the environment, each player also has a state indicating the player's current properties. These might include position, velocity, energy, armor, and so on.

When a player first joins the session, the session's current state must be downloaded, including the environment and the state of the other players.

Actions performed by users or the natural progression of a game change the state of the session. When this happens, the change must be propagated to the other computers in the session through messages. There are many techniques for updating the session state, but they all depend on sending messages between computers.

Two fundamental ways are available for maintaining state data in a session. The first way is called peer-to-peer. In peer-to-peer sessions, all the computers in the session have the complete state of the environment and of all the players. Any change in state that happens on one computer must be propagated to all the other computers in the session. No one computer is really in charge.

The second way to maintain the session state is called client/server. In client/server sessions, one computer is designated the server, and it maintains the complete state of the game and performs conflict resolution. All the other computers in the session are clients. Each client has only the information that is relevant to that computer and receives that information from the server. When one computer changes something, it propagates the change to the server. The server then determines which clients it must inform of the change.

Using DirectPlay, you can create and manage both peer-to-peer and client/server applications. DirectPlay provides all the tools needed to write a networked, multiplayer application by providing the services to manage players, send messages between players, and automatically propagate the state among all the computers.

The following sections discuss the two modes of communications within DirectPlay sessions:

  • Peer-to-Peer Session
  • Client/Server Session


Peer-to-Peer Session

In a peer-to-peer session, one computer is designated the name server. This computer responds to enumeration requests, regulates computers trying to join the session, downloads the session's state to new computers that have joined, and generates ID numbers as players and groups are created. Beyond that, the name server is just another peer in the session and runs the same application as all the other peers. Messages are not routed through the name server, and the name server does not generate all the system messages.

DirectPlay automatically performs the name server functions, which are not exposed to the application in any way. An instance of the DirectPlay application running on the name server is also the session's host. Only the host instance can change the session description data. Each peer application in the session has access to the complete list of players and groups in the session and can send and receive messages to and from any other player in the session or send a message to any group in the session. For more details, see Session Management.

The session's network address corresponds to the name server's network address. When a computer needs to join the session, it sends the join request to the name server. In response, the name server downloads the session's state to the new computer. If the name server leaves the session, a new computer is elected name server. When the name server migrates, the session's network address also changes.

The following diagram illustrates joining a session. To join a session, a machine sends the join request to the name server of the session.

In peer-to-peer sessions, every change in state on every computer (such as player movements) must be broadcast to all the other computers in the session. Because of the limit on the amount of data a computer can receive (especially if connected through a phone line), the application should impose a limit on how many computers can participate. Minimizing the quantity and frequency of data exchanged can help increase the number of computers that can be in a session before performance degrades.

Computers in a peer-to-peer DirectPlay session communicate directly with each other—that is, messages are not sent through an intermediate computer to reach their destination (although they can go through a router). When DirectPlay needs to send the same message to a set of computers, it attempts to use any multicast capabilities in the service provider. If multicast is not supported, then individual unicast messages are sent to each destination computer.

The following diagram illustrates group messaging without multicast. To broadcast a message, individual messages are sent to each machine.

Group messaging can be a source of inefficiency in sessions with more than four players. Adding a multicast server to the session can alleviate this inefficiency. A multicast server is a computer that will forward a single message to multiple destinations. A computer needing to broadcast a message to all the other computers in the session can send one message to the multicast server, which in turn sends individual messages to all the other computers. This is more efficient if the server has a high-speed link to the network (such as a T1 line), while the other computers have slow-speed links (such as phone lines).

The following diagram illustrates group messaging using a multicast server. Player-to-player messages are sent directly to the destination machine. Group messages are sent to the multicast server, which forwards them to all the destination machines.

DirectPlay supports the creation of a multicast server in a session. If the name server is on a sufficiently high-speed link, it can choose to be a multicast server for the session as well. Adding a multicast server to a session only changes how group messages (including broadcast) are routed—the application's behavior does not change. Unicast player-to-player messages are still sent directly to the destination computers.


Client/Server Session

In a DirectPlay client/server session, one computer is designated the server. Like the peer-to-peer name server, this computer responds to enumeration requests, regulates computers trying to join the session, downloads the session's state to new computers that have joined, and generates ID numbers as players and groups are created. The client/server model differs from the peer-to-peer model in that all messages in the session are routed through the server.

The server computer runs a special version of the application (the application server) that can maintain the master state of the game, updating that state according to actions that the client computers take, and notifying individual clients of relevant events. The application server creates a special player called the server player. Any client computer can send a message directly to the server player or receive a message from the server player. When the server player receives a message, it can send messages to other client players to inform them of a change in state.

The following diagram illustrates client/server communications. Each machine communicates directly with the server only. The server can forward messages to other clients.

The client computers run client versions of the application that can maintain the local state, updating the state in response to messages from the server, and sending messages to the server when local action occurs.

You can implement a client/server application in two ways. One mode is a hybrid peer-to-peer and client/server session, where every client application has the complete player and group list available to it (including the server player). Any client player can send a message directly to any player in the session, and each player or group can have data associated with it (such as name or remote data) that will be updated on all the computers whenever it changes. All the benefits of peer-to-peer state propagation are available, and, in addition, a server player is available. However, you cannot control the propagation of the player-to-player data. Depending on the frequency with which players and groups are created and destroyed or their data changes, client computers could be overloaded with incoming messages. This type of session is not scalable beyond about 16 players. It is not very different from a peer-to-peer session, except that it has a server player, all messages are routed through the server, and the server player will receive a copy of all the messages that pass through the server.

The second mode is pure client/server. Each client application sees only the server player and its own local players in the session. A client player can send messages only to the server player and receive messages from only the server player. The application server can see all the players on all clients. When the server receives a message from a client, it can intelligently decide how to update the master application state and inform the clients that need to be notified of this update. In this mode, the client application must manage the player list and the data associated with each player.

The following diagram shows a logical representation of the contents of a DirectPlay client/server session.

As in a peer-to-peer session, the session's network address corresponds to the server's network address. When a computer needs to join the session, it sends the join request to the server. In response, the server downloads the session's state to the new computers. If the server leaves the session, the session is terminated.

Because all messages are routed through the server, it automatically behaves as a multicast server.


Lobbies

A DirectPlay lobby server is a common place on a network that (at a minimum) tracks DirectPlay application sessions in progress and connected users. Users can navigate around the lobby server to find areas of interest, chat with other users, join a session, or gather a group of players to start a new session.

A lobby server's main advantage is that it acts as a central, well-known location where users can go to find sessions and other people to interact with. The lobby server manages all the network addresses of the various players and sessions and can automatically launch applications on the users' machines and connect them to the correct address without user intervention. The management of sessions, players, and their network addresses is especially useful on the Internet.

Lobby servers can be enhanced to provide many more services to the user, such as tournaments, individual score tracking, high-score lists, personal profiles, avatars (graphical representations of users), message boards, news, authenticated membership, software updates, and so on.

A lobby-aware application is one that has been specifically developed to operate with lobby servers. There are two types of lobbies that a user can experience: external and internal.

An external lobby is a client application whose sole purpose is to interact with a lobby server and the other users connected to it. When the time comes to start or join an application session, the lobby client launches the application in a separate process and gives it all the information necessary to establish a connection to the session. Adding support for external lobby launching to a DirectPlay application is quite straightforward and explained further in Supporting External Lobby Launching.

An internal lobby is a lobby user interface that is integrated into the application itself. This is more difficult to implement because the application must implement the user interface for the lobby as well as that for the game. However, it has the advantage that you can customize the lobby experience to match the application's theme.

The DirectPlay lobby architecture consists of a client API that all applications, whether they are external lobby clients or applications that have a lobby client built in, use to connect to any DirectPlay-compliant lobby server. This is done through a lobby provider interface that, like a service provider, abstracts the interaction with the lobby server. The author of the lobby server application must write the lobby provider that resides on the client computer. The application calls the standard DirectPlay methods, and the lobby provider's dynamic-link library (DLL) services these methods by communicating with the lobby server software.

The following diagram illustrates the DirectPlay lobby architecture. Different lobby client applications can connect to the same lobby server through the DirectPlay API.

At the very least, the lobby server must be able to track all the users currently connected to it, organize them by grouping them, and synchronize the launch of an application session.

The DirectPlay API defines a common level of functionality for all lobby servers. Any generic lobby client application can connect to any generic lobby server and, through the DirectPlay API and the lobby provider architecture, they can work together. An application can extend the basic functionality by defining properties that can be altered in response to messages. A lobby client designed to work with a specific lobby server can implement extended functionality that is not defined by the DirectPlay API.


Service Providers

The DirectPlay object is a common interface to the application for session, player, and group management, data management and propagation, and lobby services for locating other players on a network.

Service providers furnish network-specific communications services as requested by DirectPlay. A service provider can simply be a layer between DirectPlay and an existing transport like Windows Sockets, or it can use specialized resources on an online service such as multicast servers, enhanced quality of service, or billing services.

Microsoft includes four generic service providers with DirectPlay: head-to-head modem (TAPI), serial connection, Internet TCP/IP (using Windows Sockets), and IPX (also using Windows Sockets). Online services and network operators can supply other service providers.

DirectPlay hides the complexities and unique tasks required to establish a communications link inside the service provider implementation. An application using DirectPlay need only concern itself with the performance and capabilities of the virtual network presented by DirectPlay. It need not know whether a modem, network card, or online service is providing the medium.

DirectPlay will dynamically bind to any DirectPlay provider installed on the user's system. The application interacts with the DirectPlay object. The DirectPlay object interacts with one of the available DirectPlay service providers, and the selected service provider interacts with the transport, protocol, and other network resources.


Security

Using DirectPlay security features, an application running on a server can create secure sessions. DirectPlay implements security through the Security Support Provider Interface (SSPI) on Windows. Key features supported by DirectPlay in a secure session are:

  • Authentication to verify the identity of the user. Once a user has been authenticated, communications between the client and server can be done securely either by digitally signing or by encrypting the messages.
  • Digitally signed system messages to verify the identity of the sender.
  • Encryption of sensitive system messages.

The following diagram shows DirectPlay security architecture.

Legend

SSPI
Security Support Provider Interface
CAPI
CryptoAPI
MS RSA Base CP
Microsoft RSA Base Cryptographic Provider

DirectPlay provides message encryption support through the Windows Cryptography Application Programming Interface (CAPI). This is a standard interface similar to SSPI that gives software access to various cryptographic packages under the Windows operating system. This architecture allows DirectPlay applications to plug in cryptographic packages that provide the desired level of encryption (40 bit, 128 bit, and so on) legally allowed in the locale of use.

The default CryptoAPI (CAPI) provider for DirectPlay cryptography services is the Microsoft RSA Base Cryptographic Provider version 1.0. The default CAPI provider type is PROV_RSA_FULL. The default encryption algorithm is the CALG_RC4 stream cipher. This provider is supplied with the Microsoft Windows 32-bit operating systems.

DirectPlay provides user and message authentication (digital signing) support through the Windows Security Support Provider Interface (SSPI). This is a standard interface that gives software access to various security packages under the Windows operating system. A security package is an implementation of a protocol between a client and server that establishes the identity of the client and provides other security services, such as digital signing. The default security package that DirectPlay uses is called NTLM Security Support Provider (NTLMSSP).

This security package is based on the NTLM authentication protocol. NTLM is a shared-secret, user challenge-response authentication protocol that supports pass-through authentication to a domain controller in the server's domain or in a domain trusted by the current domain's domain controller. This protocol provides a high level of security because passwords are never sent out on the network. NTLMSSP ships with the Windows operating systems.

For more information, including how to start a secure session and specify security packages, and how to implement support for firewalls, see Security and Authentication.


Overview of DirectPlay Interfaces

[Visual Basic]

This topic applies only to applications written in C++.

[C++]

DirectPlay is composed of objects and interfaces based on the component object model (COM). For an overview, see The Component Object Model.

This section contains general information about the DirectPlay COM interfaces under the following headings:

  • Unicode vs. ANSI Interfaces
  • IDirectPlay4 Interface
  • IDirectPlayLobby3 Interface


Unicode vs. ANSI Interfaces

[Visual Basic]

This topic applies only to applications written in C++.

[C++]

DirectPlay supports both Unicode and ANSI strings by defining string pointers in a structure as the union of a Unicode string pointer (LPWSTR) and an ANSI string pointer (LPSTR). The two string pointers have different names. Typically, the ANSI member ends with the letter "A". Depending on which DirectPlay interface is chosen (IDirectPlay4 for Unicode or IDirectPlay4A for ANSI), or which DirectPlayLobby interface is chosen (IDirectPlayLobby3 for Unicode or IDirectPlayLobby3A for ANSI), the application should read and write the strings from the appropriate structure and ignore the other one.


IDirectPlay4 Interface

[Visual Basic]

This topic applies only to applications written in C++.

[C++]

The IDirectPlay4 interface is the only interface you need for creating network applications that do not provide or require lobby services.

Dplay.h includes previous versions of this interface. These are included for compatibility with applications written for previous versions of DirectX.

  • IDirectPlay contains the methods required to run applications that were written for the DirectX SDK versions 1 and 2. In addition, Dplay.h contains many defines and structures used only with the original IDirectPlay interface methods. Define IDIRECTPLAY2_OR_GREATER in your code or compiler in order to ignore these obsolete elements.
  • IDirectPlay2 contains the methods required to run applications that were written for DirectX version 3.
  • IDirectPlay3 contains the methods required to run applications written for DirectX version 5.0.

Although you could use any of these obsolete interfaces to create new applications, it is recommended that you use the newer IDirectPlay4 interface to take advantage of its increased functionality. It directly inherits from IDirectPlay3, so any code written for IDirectPlay3 will work with IDirectPlay4 with no modification. For more information, see Migrating from Previous Versions of DirectX.


IDirectPlayLobby3 Interface

[Visual Basic]

This topic applies only to applications written in C++.

[C++]

The IDirectPlayLobby3 interface lets game developers launch external applications, enable communication between an application and a lobby client, and manipulate DirectPlay addresses. For an overview of lobby sessions, see Lobbies. For practical information about detecting a launch by an external lobby and registering lobby-aware applications, see Building Lobby-Aware Applications.

The include file Dplobby.h also declares the IDirectPlayLobby and IDirectPlayLobby2 COM interfaces. IDirectPlayLobby contains the methods required to run applications written for DirectX versions 1, 2, and 3. IDirectPlayLobby2 contains the methods required to run applications written for DirectX version 5.0. Although you could use these interfaces to create new applications, it is recommended that you use IDirectPlayLobby3 in order to take advantage of its increased functionality. For more information, see Migrating from Previous Versions of DirectX.


Overview of DirectPlay Classes

[C++]

This topic applies only to applications written in Visual Basic.

[Visual Basic]

The central object of any DirectPlay application is an instance of the DirectPlay4 class. The methods of this object are used for managing connections, sessions, players, and groups.

The DirectPlaySessionData class represents data about a session. Objects of this class are used in enumerating, creating, and joining sessions.

The DirectPlayLobby3 class enables applications to communicate through a lobby and be launched by a lobby server. If your application doesn't need to work with lobbies, it probably doesn't need to create a DirectPlayLobby3 object. However, this class does have methods for enumerating modems and creating DirectPlay addresses that might be used by a non-lobbied application.

The DirectPlayLobbyConnection class represents connection data passed to an application when it is launched from a lobby.

Collections of various kinds, called enumerations, are managed by objects of the following classes:

  • DirectPlayEnumConnections
  • DirectPlayEnumLocalApplications
  • DirectPlayEnumPlayers
  • DirectPlayEnumSessions

For example, in order to obtain information about the available connections, the application creates a DirectPlayEnumConnections object. Methods of this object can be used to retrieve data about any individual connection.

Objects of the DirectPlayMessage class represent messages sent to or from an application or a lobby.

The DirectPlayAddress class encapsulates predetermined connection data that is to be used by an application, such as an IP address or telephone number. Most applications don't need to use this class.

Finally, an object of the DirectPlaySessionData class contains information about an existing session or one that is to be created.


DirectPlay Essentials

This section is a practical guide to implementing the DirectPlay® API. The following topics are discussed:

  • Basic Steps in Writing a DirectPlay Application
  • Using DirectPlay Providers
  • Lobby Providers
  • Session Management
  • Player Management
  • Group Management
  • Lobby Sessions
  • Building Lobby-Aware Applications
  • DirectPlay Messages
  • DirectPlay Address
  • DirectPlay Protocol
  • Asynchronous Networking with the DirectPlay Protocol
  • Security and Authentication
  • Migrating from Previous Versions of DirectX


Basic Steps in Writing a DirectPlay Application

This section is an overview of the basic steps a typical application would take in order to participate in a non-lobbied multiplayer game or other networked application.

[C++]

To see these steps implemented in code, see the source for the Duel sample. See also Tutorial 2: Connecting by Using a Dialog Box.

1. Initialize DirectPlay

The application must first create a DirectPlay object by creating an instance of the IDirectPlay4 interface. The methods of this interface are used to manage all aspects of communication, other than within a lobby.

2. Enumerate the service providers

The application enumerates the service providers available on the system by using the IDirectPlay4::EnumConnections method. Typically, the available connections are presented to the user in a list box, and the user is asked to select one.

3. Initialize the connection

When the user has selected a connection, the application calls IDirectPlay4::InitializeConnection. At this point the service provider may ask the user to supply further information, such as a preferred modem and telephone number. If the user cancels out of any service provider dialogs, he or she can still create a session but cannot join an existing one.

4. Create or join a session

The application typically gives the user the choice of creating a new session or joining an existing one. To get a list of existing sessions, it calls IDirectPlay4::EnumSessions. The IDirectPlay4::Open or IDirectPlay4::SecureOpen method is used to create or join a session. An application that creates a session automatically joins it as well, and normally becomes the host.

5. Create a player

Once the application is part of a session, it must create at least one player for purposes of identification and message management. This is done by using the IDirectPlay4::CreatePlayer method.

As players are created, they can be enumerated by calling IDirectPlay4::EnumPlayers. The application might do this, for example, to display a list of names of players currently enrolled in the session.

Players can also be organized in groups and subgroups. For more information, see Group Management.

6. Start the Game

The application determines how and when the game (or other kind of session) starts. The host user might be permitted to initiate play at any time after a quorum of players has been reached, or play might start automatically when a certain number of players have joined. The host sends a message to all players announcing that play has started. Players now begin exchanging messages in order to update the state of the game, using the IDirectPlay4::Send, IDirectPlay4::SendEx, and IDirectPlay4::Receive methods.

[Visual Basic]

To see these steps implemented in code, see Tutorial 1: Creating a Simple Network Game.

1. Initialize DirectPlay

The application must first create a DirectPlay4 object by calling DirectX7.DirectPlayCreate. The methods of the DirectPlay4 class are used to manage all aspects of communication, other than with a lobby.

2. Enumerate the service providers

The application enumerates the connections available through the various service providers on the system by using the DirectPlay4.GetDPEnumConnections method. Typically, the available connections are presented to the user in a list box, and the user is asked to select one.

3. Initialize the connection

When the user has selected a connection, the application calls DirectPlay4.InitializeConnection. This step binds DirectPlay to a particular service provider. At this point the service provider may ask the user to supply further information, such as a preferred modem and telephone number. If the user cancels out of any service provider dialogs, he or she can still create a session, postponing the establishment of a physical connection until another player is ready to connect, for instance by dialing in.

4. Create or join a session

The application typically gives the user the choice of creating a new session or, if a physical connection has been established, joining an existing one. To get a list of existing sessions, it calls DirectPlay4.GetDPEnumSessions. The DirectPlay4.Open or DirectPlay4.SecureOpen method is used to create or join a session. An application that creates a session automatically joins it as well, and normally becomes the host.

5. Create a player

Once the application is part of a session, it must create at least one player for purposes of identification and message management. This is done by using the DirectPlay4.CreatePlayer method.

As players are created, they can be enumerated by calling DirectPlay4.GetDPEnumPlayers. The application might do this, for example, to display a list of players currently enrolled in the session.

Players can also be organized in groups and subgroups. For more information, see Group Management.

6. Start the Game

The application determines how and when the game (or other kind of session) starts. The host user might be permitted to initiate play at any time after a quorum of players has been reached, or play might start automatically when a certain number of players have joined. The host sends an application-defined message to all players announcing that play has started. Players now begin exchanging messages in order to update the state of the game, using the DirectPlay4.Send, DirectPlay4.SendEx, and DirectPlay4.Receive methods.


Using DirectPlay Providers

The service provider furnishes network-specific communication services as requested by DirectPlay. For an overview, see Service Providers.

Microsoft includes the following service providers with DirectPlay:

  • TCP/IP
  • IPX
  • Modem-to-Modem
  • Serial Link

This section outlines what to expect from the default service providers. To obtain information about the behavior of third-party service providers, contact the network operator.


TCP/IP

The Transmission Control Protocol/Internet Protocol (TCP/IP) service provider uses Windows Sockets to communicate over the Internet or local area network (LAN) using the TCP/IP protocol. It uses User Datagram Protocol (UDP) packets for nonguaranteed messaging and TCP for guaranteed messaging. A single computer can host multiple DirectPlay sessions using TCP/IP.

When the application enumerates sessions, TCP/IP displays a dialog box asking the user for the session's IP address. If the session is on the Internet, the user must enter the IP address of the computer hosting the session to be joined. If the computer has a name (such as microsoft.com), the name can be used instead of the IP address, and DirectPlay will use Domain Name System (DNS) lookup to find it. The user can also leave the address blank and select OK. In this case, DirectPlay will broadcast a message looking for sessions. This will generally work only on a LAN and only on the same subnet.

[C++]

If you're hosting a session, the application can use IDirectPlay4::GetPlayerAddress to obtain the local IP address.

An application can use the IDirectPlay4::InitializeConnection method, or the IDirectPlayLobby3::SetConnectionSettings method followed by a call to IDirectPlayLobby3::Connect, to supply an IP address to the service provider in a DirectPlay address. The IP address must be a null-terminated ANSI or Unicode string (each has a different data type GUID). If a broadcast enumeration of sessions is desired, the address must be a zero-length string—that is, a string consisting only of the null terminator. For more information, see DirectPlay Address.

The TCP/IP service provider uses port 47624 to send and receive enumeration requests. Communications are sent on the port range 2300-2400. To work through a firewall, all computers must be using DirectX 6.0 or later and port 47624, and the range 2300-2400 must be open for both inbound and outbound TCP and UDP traffic. For more information, see Firewall Support.

Note DirectPlay starts assigning ports at 2300 and works its way up, sequentially. It is possible to open a smaller range starting at 2300.

An application can select a specific port to use. To do so, it must initialize the TCP/IP service provider with a DirectPlay address that includes the data chunk DPAID_INetPort. For more information, see DirectPlay Address and DirectPlay Address Data Types. If an application selects a specific port to use, all communication is sent through that port, and it is only necessary to open that one port (for both inbound and outbound using TCP and UDP).

The TCP/IP service provider GUID is defined as DPSPGUID_TCPIP.

[Visual Basic]

If you're hosting a session, the application can use DirectPlay4.GetPlayerAddress to obtain the local IP address.

An application can create a DirectPlay address for an IP address by using the DirectPlayLobby3.CreateINetAddress method. The address can then be supplied to the service provider by passing the DirectPlayAddress object to DirectPlay4.InitializeConnection method, or by passing it to DirectPlayLobby3.SetConnectionSettings and then calling DirectPlayLobby3.Connect. For more information, see DirectPlay Address.

Adding DirectPlay lobby support can eliminate the need for users to enter an IP address when the game is started. For more information, see Synchronized Launching.


IPX

The IPX service provider uses Windows Sockets to communicate over a local area network (LAN) using the Internet Packet Exchange (IPX) protocol. The service provider supports only nonguaranteed messaging. You can use the DirectPlay protocol for guaranteed messaging on IPX. A single computer can host only one DirectPlay session using IPX.

IPX always uses a broadcast to find sessions on the network, so the service provider never displays a dialog box requesting more information.

IPX will not enumerate sessions on another subnet.

Once a session is established, packets are sent directly between computers (they are not broadcast).

The IPX service provider GUID can be specified as DPSPGUID_IPX.


Modem-to-Modem

A modem-to-modem service provider uses Telephony API (TAPI) to communicate with another modem. The service provider supports only nonguaranteed messaging. You can use the DirectPlay protocol for guaranteed messaging for modem sessions.

Creating a session causes a dialog box to appear, asking the user for a modem selection and configuration, and then letting the user put the modem in autoanswer mode. Enumerating sessions will also trigger a dialog box asking the user what phone number to call and which modem to use. After the information is entered, DirectPlay will dial the modem and try to find sessions hosted by the computer on the other end.

[C++]

To enumerate the modem sessions without any dialog boxes (when, for example, the phone number is known by the application and was given to the service provider when IDirectPlay4::InitializeConnection was called), use IDirectPlay4::EnumSessions in a loop with the DPENUMSESSIONS_RETURNSTATUS flag (see EnumSessions for more details). When DP_OK is returned, the application should then use EnumSessions one more time to obtain the actual list of sessions.

When using EnumSessions in a loop like this, the application must implement a windows message loop as follows:

while (lpDPLAY->EnumSessions(lpsd, 0, lpEnumSessionsCallback,
        lpContext, DPENUMSESSIONS_RETURNSTATUS) == DPERR_CONNECTING)
{
    MSG    msg;

    if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    Sleep(500);
}

If you insert too many delays into the message processing, you can lose packets—for example, if you print a lot of debug information.

The current list of available modems can be obtained from the service provider by initializing it and calling the IDirectPlay4::GetPlayerAddress method with a player ID of zero. The DirectPlay address returned will contain a data chunk with the ANSI modem names (DPAID_Modem) and the Unicode modem names (DPAID_ModemW). The list of modems is a series of null-terminated strings with a zero-length string at the end of the list. For more information, see DirectPlay Address Data Types.

[Visual Basic]

To enumerate the modem sessions without any dialog boxes (when, for example, the phone number is known by the application and was given to the service provider when DirectPlay4.InitializeConnection was called), call DirectPlay4.GetDPEnumSessions repeatedly with the DPENUMSESSIONS_RETURNSTATUS flag until it does not raise the DPERR_CONNECTING error. You should allow events to be processed while executing the loop. The following sample code illustrates one way to do this:

' objDPlay is the DirectPlay4 object
' SessionData is a DirectPlaySessionData object containg valid info.

On Error GoTo DO_AGAIN
Do While DoEvents
    objDPlay.GetDPEnumSessions(SessionData, 0, _
          DPENUMSESSIONS_AVAILABLE Or DPENUMSESSIONS_RETURNSTATUS)
    Exit Do    ' No error, enumeration complete
DO_AGAIN:
    ' If some other error, give up
    if Err.Number <> DPERR_CONNECTING Then
        ' Handle error – can't enumerate sessions
        Exit Do
    End If
    ' Still connecting, so try again
Loop
On Error GoTo 0

The names available modems can be obtained from the service provider by initializing it and calling the DirectPlayLobby3.GetModemName method for index values from 1 to the value returned by DirectPlayLobby3.GetModemCount.

The modem-to-modem service provider GUID can be specified as DPSPGUID_MODEM.


Serial Link

A serial link is used to communicate with another computer through the serial ports. The service provider supports only nonguaranteed messaging. You can use the DirectPlay protocol for guaranteed messaging on serial links.

Creating a session or enumerating sessions causes the provider to display a dialog box asking the user to configure the serial port. The port must be configured the same way on both computers.

The serial link service provider can be specified as DPSPGUID_SERIAL.


Lobby Providers

The lobby provider is a client component dynamic-link library (DLL) supplied by the developer of a lobby server. It implements communications functions with the lobby server as requested by DirectPlay. A lobby client written using the DirectPlay API can interoperate with any lobby server for which a lobby provider DLL is present on the system.

The DirectX SDK installs a lobby provider for use with the test lobby server and client included with the SDK. In order to use it you must register it by double-clicking on Dpldplay.reg in the \Samples\Multimedia\DPlay\Bin folder in your DirectX SDK directory. For more information, see the Bellhop sample.


Session Management

A DirectPlay session is a communications channel between two or more applications or instances of an application.

Note When using some connection types, it is possible for multiple application instances on a single computer to be part of a session. For example, up to four players can play the Memory sample on a single computer using an IPX or TCP/IP connection. Most often, however, a session involves separate computers. For the sake of simplicity, the following discussion refers to each participant in a session as a "computer".

A computer can become part of a session in one of two ways: it can enumerate all the existing sessions on a network and join one of them, or it can create a new session and wait for other computers to join it. Once the application is part of a session, it can create a player and exchange messages with all the other players in the session.

Each session has one computer designated as the host. The host is the owner of the session and is the only computer that can change the session's properties.

The following diagram illustrates the DirectPlay session model:

DirectPlay provides the following session management methods:

[C++]
  • IDirectPlay4::EnumSessions enumerates all the available sessions.
  • IDirectPlay4::Open joins one of the enumerated sessions or creates a new session.
  • IDirectPlay4::SecureOpen performs the same function as IDirectPlay4::Open, but enables the application to alter the default opening behavior.
  • IDirectPlay4::StartSession launches a session from a staging area.
  • IDirectPlay4::Close leaves the currently open session.
  • IDirectPlay4::GetSessionDesc gets the properties of the current session.
  • IDirectPlay4::SetSessionDesc changes the properties of the current session.
  • IDirectPlay4::GetCaps gets the communications capabilities of the underlying network.
[Visual Basic]
  • DirectPlay4.GetDPEnumSessions enumerates all the available sessions.
  • DirectPlay4.Open joins one of the enumerated sessions or creates a new session.
  • DirectPlay4.SecureOpen performs the same function as DirectPlay4.Open, but enables the application to alter the default opening behavior.
  • DirectPlay4.StartSession launches a session from a staging area.
  • DirectPlay4.Close leaves the currently open session.
  • DirectPlay4.CreateSessionData creates a DirectPlaySessionData object that is used to describe a session.
  • DirectPlay4.GetSessionDesc gets the properties of the current session.
  • DirectPlay4.SetSessionDesc changes the properties of the current session.
  • DirectPlay4.GetCaps gets the communications capabilities of the underlying network.


Player Management

A player represents a logical object within the session that can send and receive messages. When a player is created, DirectPlay assigns a unique identity number that will not be reused as long as the session lasts.

Each player is identified as being either a local player (one that exists on your computer) or a remote player (one that exists on another computer). Each computer must have at least one local player before it can start sending and receiving messages. Individual computers can have more than one local player.

When an application sends a message, it is always directed to another player—not another computer. The destination player can be another local player (in which case the message will not go out over the network) or a remote player. Similarly, when an application receives messages, they are always addressed to a specific (local) player and marked as being from some other player (except system messages, which are always marked as being from DPID_SYSMSG).

DirectPlay provides some additional player management methods that an application can use. They enable an application to associate a name with a player and automatically propagate that name to all the computers in the session. Similarly, the application can associate some arbitrary data with a player that will be propagated to all the other computers in the session. The application can also associate private local data with a player that is available only to the local computer.

[C++]

DirectPlay provides the following essential methods for player management:

  • IDirectPlay4::EnumPlayers enumerates all the players in the sessions.
  • IDirectPlay4::CreatePlayer creates a local player.
  • IDirectPlay4::DestroyPlayer destroys a local player.

DirectPlay provides these additional methods to manage player information:

  • IDirectPlay4::GetPlayerAccount gets a player's account information.
  • IDirectPlay4::GetPlayerAddress gets a player's network-specific address.
  • IDirectPlay4::GetPlayerData gets the application-specific data associated with a player.
  • IDirectPlay4::GetPlayerFlags gets additional information about a player.
  • IDirectPlay4::GetPlayerCaps gets information about a player's communications capabilities.
  • IDirectPlay4::GetPlayerName gets a player's friendly and formal names.
  • IDirectPlay4::SetPlayerName changes a player's friendly and formal names.
  • IDirectPlay4::SetPlayerData associates application-specific data with a player.
[Visual Basic]

DirectPlay provides the following essential methods for player management:

  • DirectPlay4.GetDPEnumPlayers enumerates all the players in the sessions.
  • DirectPlay4.CreatePlayer creates a local player.
  • DirectPlay4.DestroyPlayer destroys a local player.

DirectPlay provides these additional methods to manage player information:

  • DirectPlay4.GetPlayerAccountId gets a player's account information.
  • DirectPlay4.GetPlayerAddress gets a player's network-specific address.
  • DirectPlay4.GetPlayerCaps gets a player's communications capabilities.
  • DirectPlay4.GetPlayerData gets the application-specific data associated with a player.
  • DirectPlay4.GetPlayerFlags gets additional information about a player.
  • DirectPlay4.GetPlayerFormalName gets a player's formal or "long" name.
  • DirectPlay4.GetPlayerFriendlyName gets a player's friendly or "short" name.
  • DirectPlay4.SetPlayerName changes a player's formal and friendly names.
  • DirectPlay4.SetPlayerData associates application-specific data with a player.


Group Management

DirectPlay supports groups within a session. A group is a logical collection of players. An application can send a message to a group, and all the players in the group will receive the message. Like players, groups are identified by unique numbers that are not reused in the course of a session.

Groups can be used to organize players in a session—for example, in teams. A player can belong to more than one group. When a group is destroyed, all member players are removed from the group, but the players themselves are not destroyed.

Groups can also contain subgroups and shortcuts to groups. When a group is created by using the CreateGroup method, it is a top-level group (call it A). A shortcut to that group can then be added to another group (call it B) by using the AddGroupToGroup method. When group B is destroyed, the shortcut to A is also destroyed, but A continues to exist as a top-level group. On the other hand, if A is created within B by using the CreateGroupInGroup method, then A is not a top-level group and ceases to exist when B is destroyed.

A message sent to a group is delivered to all players who are part of that group, whether directly or indirectly. Suppose, for example, a player called Quarterback is added to a group called BlueOffense. The BlueOffense group is then added to the BlueTeam group. Quarterback has not been added directly to BlueTeam, but nonetheless receives all messages addressed to BlueTeam as well as those addressed to BlueOffense.

It is a good idea to take advantage of the group management methods of DirectPlay rather than implementing your own system for player groups. DirectPlay is able to take advantage of any multicasting capabilities of the service provider in order to send group messages, thus reducing message traffic. For more information, see Peer-to-Peer Session.

[C++]

DirectPlay provides the following essential methods for administering groups and their membership:

IDirectPlay4::AddPlayerToGroup adds a player to a group.

IDirectPlay4::CreateGroup creates a new top-level group.

IDirectPlay4::DeletePlayerFromGroup removes a player from a group.

IDirectPlay4::DestroyGroup destroys a group.

IDirectPlay4::EnumGroupPlayers enumerates the players in a group.

IDirectPlay4::EnumGroups enumerates all the groups in the session.

DirectPlay provides these additional methods for managing groups and group information:

IDirectPlay4::AddGroupToGroup adds a group shortcut to an already existing group.

IDirectPlay4::CreateGroupInGroup creates a group within an existing group.

IDirectPlay4::DeleteGroupFromGroup removes a group previously added to another group by using AddGroupToGroup, but doesn't destroy the deleted group.

IDirectPlay4::EnumGroupsInGroup enumerates all the groups within another group.

IDirectPlay4::GetGroupConnectionSettings retrieves a group's connection settings.

IDirectPlay4::GetGroupData gets the application-specific data associated with a group.

IDirectPlay4::GetGroupFlags gets additional information about how a group was created.

IDirectPlay4::GetGroupName gets the group's name.

IDirectPlay4::GetGroupOwner gets the owner of a group.

IDirectPlay4::GetGroupParent gets the ID of the parent of a subgroup created by using CreateGroupInGroup.

IDirectPlay4::SetGroupConnectionSettings sets a group's connection settings.

IDirectPlay4::SetGroupData changes the application-specific data associated with a group created by this computer.

IDirectPlay4::SetGroupName changes the name of a group created by this computer.

IDirectPlay4::SetGroupOwner changes the owner of a group.

[Visual Basic]

DirectPlay provides the following essential methods for administering groups and their membership:

DirectPlay4.AddPlayerToGroup adds a player to a group.

DirectPlay4.CreateGroup creates a new top-level group.

DirectPlay4.DeletePlayerFromGroup removes a player from a group.

DirectPlay4.DestroyGroup destroys a group.

DirectPlay4.GetDPEnumGroupPlayers enumerates the players in a group.

DirectPlay4.GetDPEnumGroups enumerates all the groups in the session.

DirectPlay provides these additional methods for managing groups and group information:

DirectPlay4.AddGroupToGroup adds a group shortcut to an existing group.

DirectPlay4.CreateGroupInGroup creates a group within an existing group.

DirectPlay4.DeleteGroupFromGroup removes a group previously added to another group by using AddGroupToGroup, but doesn't destroy the deleted group.

DirectPlay4.GetDPEnumGroupsInGroup enumerates all the groups within another group.

DirectPlay4.GetGroupData gets the application-specific data associated with a group.

DirectPlay4.GetGroupFlags gets additonal information about how a group was created.

DirectPlay4.GetGroupLongName gets the group's long or formal name.

DirectPlay4.GetGroupOwner gets the owner of a group.

DirectPlay4.GetGroupParent gets the ID of the parent of a subgroup created by using CreateGroupInGroup.

DirectPlay4.GetGroupShortName gets the group's short or friendly name.

DirectPlay4.SetGroupConnectionSettings sets a group's connection settings in a lobby session.

DirectPlay4.SetGroupData changes the application-specific data associated with a group created by this computer.

DirectPlay4.SetGroupName changes the long and short name of a group.

DirectPlay4.SetGroupOwner changes the owner of a group.


Lobby Sessions

A lobby session closely resembles a DirectPlay client/server session (see the illustration in Client/Server Session). The term lobby session refers to a connection to a lobby server where clients and the server have not been specifically written to work together. The term application session refers to a traditional DirectPlay session in which all the clients and the server (if any) have been specifically written to work together.

The first step in using DirectPlay to communicate with a lobby server is to select which lobby provider to use and which lobby server to connect to. The available connections are enumerated just like other DirectPlay service providers, and the connection is made in the same way. See Basic Steps in Writing a DirectPlay Application.

The lobby client uses the same methods to locate and join a lobby session as an application client uses to locate and join an application session. (See Session Management.) Joining a lobby session gives the client application access to all the information on the lobby server and enables the user to interact with other users on the lobby server.

As in a DirectPlay application session, the player is the basic entity in a lobby session. Each player represents a user on a client computer connected to the lobby server. There is also the server player representing the lobby server. After a lobby client connects to a lobby server (by joining the lobby session), it must establish the user's presence by creating a player and adding the player to an initial group before the player can start communicating with the server and other players. In fact, other users connected to the session won't even be aware of the new user's presence until this happens.

The same player management methods used by application sessions are used to manage players in a lobby session. See Player Management.

Players in a lobby session cannot send ordinary messages to one another. In the DirectPlay lobby architecture, any application that uses the DirectPlay API can connect to any lobby server. This means that several different lobby client applications might be present in the same lobby session, all of which might use a different set of application-defined messages.

[C++]

Clients can, however, exchange messages with the lobby by using standard lobby messages and the IDirectPlayLobby3::SendLobbyMessage method. In addition, players can send text to one another by using the IDirectPlay4::SendChatMessage method. This method causes the lobby to send a system message to the recipient, containing the contents of the chat message.

[Visual Basic]

Clients can, however, exchange messages with the lobby by using standard lobby messages and the DirectPlayLobby3.SendLobbyMessage method. In addition, players can send text to one another by using the DirectPlay4.SendChatMessage method. This method causes the lobby to send a system message to the recipient, containing the contents of the chat message.

Groups take on more significance in a lobby session, because they are used to define the organization of the entire lobby server and for launching application sessions.

For the purposes of the lobby server, groups are classified as one of two types: rooms and staging areas.

A room is a standard group that can contain players and other groups. A room is primarily used as a meeting place for players to interact with other players in the context of the lobby. The room contains links to other rooms and links to the second type of group—a staging area.

A staging area group typically contains only players. A staging area is used to marshal players together in order to launch a new session. After the session has been launched, the staging area can either be destroyed or remain in existence so that new players can join the session in progress.

Room groups are organized primarily in a hierarchical structure. A few top-level groups are created and other groups are created within existing groups. The lobby client can enumerate all the top-level groups as well as the groups contained within a group. The lobby server can also organize the groups in a web structure. Once a group is created, you can add it to another group, which creates a link between the two groups. When a lobby client enumerates groups within a group, all subgroups and linked groups are returned.

The following diagram illustrates the organization of a lobby session.

Players cannot be seen until they are part of a group. Players can belong to more than one group at once.

In general, the scope of the lobby session visible to a player is limited by the groups the player is part of. This limitation reduces the amount of information that the server must download to the client. Players can navigate through the lobby server space simply by deleting themselves from their current group and adding themselves to a new group.


Synchronized Launching

[C++]

Application sessions are marshaled and launched from a staging area. One player creates a staging area and waits for other players to join it. A player can set the properties of the application session to be created through the IDirectPlay4::SetGroupConnectionSettings method. Other players who are considering joining the group can find out what the application session properties are by calling the IDirectPlay4::GetGroupConnectionSettings method. After enough players have joined the staging area, any player can call the IDirectPlay4::StartSession method to initiate the synchronized launch sequence.

Every player in the staging area now receives a DPMSG_STARTSESSION system message with a DPLCONNECTION structure. If the player is using an external lobby client, the lobby client can now launch the application by passing the connection information to the IDirectPlayLobby3::RunApplication method. If the player is using an internal lobby, the application can establish a connection to the appropriate session by calling IDirectPlayLobby3::ConnectEx. For more information, see Supporting External Lobby Launching.

[Visual Basic]

Application sessions are marshaled and launched from a staging area. (See Lobby Sessions.) One player creates a staging area and waits for other players to join it.

A player can set the properties of the application session to be created by using the DirectPlay4.SetGroupConnectionSettings method. After enough players have joined the staging area, any player can call the DirectPlay4.StartSession method to initiate the synchronized launch sequence.

Every player in the staging area now receives a DPSYS_STARTSESSION system message with information about the connection. If the player is using an external lobby client, the lobby client can then launch the application by using the DirectPlayLobby3.RunApplication method. If the player is using an internal lobby, the application can establish a connection to the appropriate session by calling DirectPlayLobby3.Connect, after retrieving the connection settings by calling DirectPlayMessage.ReadSysMsgConnection and setting them with DirectPlayLobby3.SetConnectionSettings. For more information, see Supporting External Lobby Launching.


Building Lobby-Aware Applications

For a DirectPlay application to be lobby-aware, at a minimum it must support being launched from a lobby. You can add other features to make it integrate better with the lobby. For additional information see the following topics:

  • Registering Lobby-Aware Applications
  • Supporting External Lobby Launching
  • Supporting Ripple Launching
  • Supporting Dynamic Lobby Connection
  • Staying in Touch with the Lobby

The DirectX samples include a test lobby server (Lserver.exe) and a lobby client (Bellhop.exe). Together they can be used to test the lobby-aware functions of your applications.


Registering Lobby-Aware Applications

In order to be recognized and launched by a DirectPlay lobby client, an application needs to be entered as a DirectPlay application in the system registry. Normally you would register the application during setup, which requires creating a DirectPlayLobby3 object in the setup program. The application must also be unregistered when it is uninstalled.

[C++]

You can register your application by filling in the DPAPPLICATIONDESC or DPAPPLICATIONDESC2 structure with the necessary information, then passing it to IDirectPlayLobby3::RegisterApplication. To remove the registry entries, call IDirectPlayLobby3::UnRegisterApplication.

You can also register a lobby-aware application during the DirectX setup process, by calling the DirectXRegisterApplication function. The advantage of this function is that it can be called before the DirectPlay run-time files have been installed.

[Visual Basic]

You can register your application by filling in the DPAPPLICATIONDESC2 type with the necessary information, then passing it to DirectPlayLobby3.RegisterApplication. To remove the registry entries, call DirectPlayLobby3.UnRegisterApplication.


Supporting External Lobby Launching

The basic steps in recognizing a lobby launch and becoming part of an application session are as follows:

[C++]
  1. At startup, create an IDirectPlayLobby3 interface using the CoCreateInstance function.
  2. Call the IDirectPlayLobby3::GetConnectionSettings method. (Normally you would call it twice, once to retrieve the necessary buffer size, and again after the buffer has been allocated.) If the method returns DPERR_NOTLOBBIED, the application was not launched by a lobby but was presumably executed by the user in the normal way. Proceed with the code path that allows the user to connect to or create a non-lobbied session. If GetConnectionSettings succeeds, it returns a DPLCONNECTION structure with the connection settings (including the session description) established by the lobby. You can make changes by using IDirectPlayLobby3::SetConnectionSettings.
  3. Call IDirectPlayLobby3::ConnectEx to create or join the application session. (The application knows whether it is to create or join a session by examining DPLCONNECTION.dwFlags.)
  4. Create a player, using the name information supplied in the DPLCONNECTION structure obtained in step 2.

At this point, the application can continue on the same code path as if the user had manually selected a connection, joined or created a session, and entered the name of the player to create.

The IDirectPlayLobby3 interface can be saved if the game will pass information back to the lobby (see Staying in Touch with the Lobby). Otherwise it can be discarded by using the Release method.

For more information and sample code, see the Duel (Lobby.c) and ChatConnect (Lobby.cpp) samples, and Tutorial 1: Connecting by Using the Lobby.

[Visual Basic]
  1. At startup, create a DirectPlayLobby3 object by using the DirectX7.DirectPlayLobbyCreate method.
  2. Call the DirectPlayLobby3.GetConnectionSettings method. If the method raises a DPERR_NOTLOBBIED error, the application was not launched by a lobby but was presumably executed by the user in the normal way. Proceed with the code path that allows the user to connect to or create a non-lobbied session. If GetConnectionSettings succeeds, it returns a DirectPlayLobbyConnection object representing the connection settings (including the session description) established by the lobby. You can make changes by using DirectPlayLobby3.SetConnectionSettings.
  3. Call DirectPlayLobby3.Connect to create or join the application session. (The application knows whether it is to create or join a session by examining the value returned by DirectPlayLobbyConnection.GetFlags.)
  4. Create a player, using the name information supplied in the DirectPlayLobbyConnection object obtained in step 2.

At this point, the application can continue on the same code path as if the user had manually selected a connection, joined or created a session, and entered the name of the player to create.

The DirectPlayLobby3 object can be saved if the game will pass information back to the lobby (see Staying in Touch with the Lobby).

Many lobbies launch the application and then go into a suspend mode, waiting for the application to terminate. DirectPlay notifies the lobby when the application it launched has terminated. For this reason it is important that the application launched by the lobby not launch another application. (However, a properly registered application can itself be run by a launcher. See Supporting Ripple Launching.)


Supporting Ripple Launching

Ripple launching is the running of an application by another application that has itself been launched from a lobby. In the following discussion, the program run by the lobby is called the launcher, and the program it launches is called the application.

[C++]

In order to support ripple launching in your application, you must register it by passing the DPAPPLICATIONDESC2 structure to IDirectPlayLobby3::RegisterApplication. This structure has a member, lpszAppLauncherName, that contains the name of the launcher. The launcher must reside in the same directory as the application.

When a lobby client runs the application by calling IDirectPlayLobby3::RunApplication, DirectPlay finds the name of the launcher in the registry and runs the launcher rather than the application. It is then the responsibility of the launcher to run the application.

The launcher must pass on to the application any command-line parameters it is provided with. The application should silently ignore any command-line parameters it does not understand.

The application should always call IDirectPlayLobby3::GetConnectionSettings at least once before using IDirectPlayLobby3::WaitForConnectionSettings. (See Supporting Dynamic Lobby Connection.)

The following example shows how to register a ripple-launched application, where lpDPLobby3A points to an IDirectPlayLobby3 interface:

DPAPPLICATIONDESC2  dpad2;

dpad2.dwSize = sizeof (DPAPPLICATIONDESC2);
dpad2.dwFlags = 0;
dpad2.lpszApplicationNameA= "MyApp";
dpad2.guidApplication = {12345678-...};
dpad2.lpszFilenameA= "myapp.exe";
dpad2.lpszCommandLineA= "/lobbied";
dpad2.lpszPathA= "C:\\games";
dpad2.lpszCurrentDirectoryA= "C:\\games";
dpad2.lpszDescriptionA= "My Application";
dpad2.lpszDescriptionW= L"My Application";
dpad2.lpszAppLauncherNameA= "launcher.exe";

HRESULT hr = lpDPLobby3A->RegisterApplication(0, &dpad2);

The following example is a complete console application that launches the Duel sample:

#include <windows.h>
#include "stdio.h"

int main(int argc, char* argv[])
{
  PROCESS_INFORMATION ProcInfo;
  STARTUPINFO StartupInfo;
  BOOL bCreated;

  LPTSTR lpCommandLine;

  printf("Launcher application\n");

  lpCommandLine = GetCommandLineA();

  // Strip EXE name from command line,
  // pass rest to ripple-launched app.

  while(*lpCommandLine && *lpCommandLine!= ' ') lpCommandLine++;

  printf("passing command line: %s\n",lpCommandLine);

  memset(&StartupInfo,0,sizeof(StartupInfo));
  StartupInfo.cb = sizeof(StartupInfo);

  bCreated=CreateProcessA(
    "duel.exe",
    lpCommandLine,
    NULL,
    NULL,
    TRUE,
    0,
    NULL,
    NULL,
    &StartupInfo,
    &ProcInfo);

  if(bCreated){
    printf("Waiting for application to exit\n");
    WaitForSingleObject(ProcInfo.hThread, INFINITE);
  } else {
    printf("Failed to create process\n");
  }

  printf("launcher application has left the building...\n");

  return 0;
}
[Visual Basic]

In order to support ripple launching in your application, you must register it by passing the DPAPPLICATIONDESC2 type to DirectPlayLobby3.RegisterApplication. This type has a member, strAppLauncherName, that contains the name of the launcher. The launcher must reside in the same directory as the application.

When a lobby client runs the application by calling DirectPlayLobby3.RunApplication, DirectPlay finds the name of the launcher in the registry and runs the launcher rather than the application. It is then the responsibility of the launcher to run the application.

The launcher must pass on to the application any command-line parameters it is provided with. The application should silently ignore any command-line parameters it does not understand.

The application should always call DirectPlayLobby3.GetConnectionSettings at least once before using DirectPlayLobby3.WaitForConnectionSettings. (See Supporting Dynamic Lobby Connection.)

The following example shows how to register a ripple-launched application, where DPLobby3 is a DirectPlayLobby3 object:

Dim dpad2 As DPAPPLICATIONDESC2

With dpad2
  .lFlags = 0
  .strAppLauncherName= "launcher.exe"
  .strApplicationName= "MyApp"
  .strCommandLine= "/lobbied"
  .strCurrentDirectory= "C:\games"
  .strDescription= "My Application"
  .strFilename= "myapp.exe"
  .strGuid = "{AC330441-9B71-11D2-9AAB-0020781461AC}"
  .strPath= "C:\games"
End With

Call DPLobby3.RegisterApplication(dpad2)


Supporting Dynamic Lobby Connection

One drawback of external lobby launching is that the lobby server always tells the lobby client to launch a new instance of the application, even if one is already running. You can avoid a redundant launch by supporting dynamic lobby connection.

The instructions in this section assume the application is already running and has a connection to a lobby server that will return connection settings.

[C++]
  1. At startup, create an IDirectPlayLobby3 interface by using the CoCreateInstance function.
  2. Allow the user to select "Wait for lobby connection", or words to that effect, rather than making a manual connection. Take the following steps only if that selection has been made. (See the Duel sample for one implementation.)
  3. Call IDirectPlayLobby3::WaitForConnectionSettings to put your application in wait mode. This does not block execution, it simply tells DirectPlay that the application is active and waiting for a connection, so that the lobby client's call to DirectPlayLobby3::RunApplication will not launch another instance.
  4. Wait for a lobby message to come in by using IDirectPlayLobby3::ReceiveLobbyMessage. The message type to expect is the DPLSYS_NEWCONNECTIONSETTINGS system message. Note that you can call WaitForConnectionSettings again to cancel wait mode in response to a user cancel.
  5. After you receive the system message, examine the connection information that was passed in by the lobby and modify settings as necessary. The IDirectPlayLobby3::GetConnectionSettings method returns a DPLCONNECTION structure with the connection settings. New settings can be set by using IDirectPlayLobby3::SetConnectionSettings.
  6. Call IDirectPlayLobby3::ConnectEx to create or join the application session. (The application knows whether it is to create or join a session by examining DPLCONNECTION.dwFlags.)
  7. Create a player using the name information supplied in the DPLCONNECTION structure obtained in step 5.
[Visual Basic]
  1. At startup, create an DirectPlayLobby3 object by using the DirectX7.DirectPlayLobbyCreate method.
  2. Allow the user to select "Wait for lobby connection", or words to that effect, rather than making a manual connection. Take the following steps only if that selection has been made.
  3. Call DirectPlayLobby3.WaitForConnectionSettings to put your application in wait mode. This does not block execution, it simply tells DirectPlay that the application is active and waiting for a connection, so that the lobby client's call to DirectPlayLobby3.RunApplication will not launch another instance.
  4. Wait for a lobby message to come in by using DirectPlayLobby3.ReceiveLobbyMessage. The message type to expect is the DPLSYS_NEWCONNECTIONSETTINGS system message. Note that you can call WaitForConnectionSettings again to cancel wait mode in response to a user cancel.
  5. After you receive the system message, examine the connection information that was passed in by the lobby and modify settings as necessary. The DirectPlayLobby3.GetConnectionSettings method returns a DirectPlayLobbyConnection object containing the connection settings. New settings can be set by using DirectPlayLobby3.SetConnectionSettings.
  6. Call DirectPlayLobby3.Connect to create or join the application session. (The application knows whether it is to create or join a session by examining the value returned by DirectPlayLobbyConnection.GetFlags.)
  7. Create a player using the name information supplied in the DirectPlayLobbyConnection object obtained in step 5.


Staying in Touch with the Lobby

After being launched by a lobby, or after connecting dynamically, your application might want to continue exchanging information with the lobby. For example, the lobby server might want to keep track of how many players are currently in the game, or their scores, in order to display this information to other users in the lobby. Similarly, the application might want to receive data such as player or game configurations where these were set in the lobby rather than in the application itself.

[C++]

You can exchange messages with the lobby by using the IDirectPlayLobby3::SendLobbyMessage and IDirectPlayLobby3::ReceiveLobbyMessage methods.

Information is sent to the lobby by setting properties. The application must create and fill in a DPLMSG_SETPROPERTY message structure and send it to the lobby by using the SendLobbyMessage method. Each property identifies a distinct type of data. At design time, the application developer assigns GUIDs to each property that can be set. The lobby operator needs to obtain this list of GUIDs from the application developer along with the description and data structure of each property.

An application can request confirmation that the property was set correctly by supplying a nonzero value in DPLMSG_SETPROPERTY.dwRequestID. The lobby then replies by sending a DPLMSG_SETPROPERTYRESPONSE message.

Information is obtained from the lobby in a similar fashion, by requesting properties. The application fills in a DPLMSG_GETPROPERTY structure and sends it to the lobby by using the SendLobbyMessage method. The lobby sends back a DPLMSG_GETPROPERTYRESPONSE structure containing the property data that was requested. As before, the application developer generates the GUIDs for each property and shares these with the lobby developer.

Not all lobbies will be able to support these standard lobby messages. The application can determine whether the lobby that it was launched from supports standard lobby messages by sending a DPLMSG_GETPROPERTY message requesting the DPLPROPERTY_MessagesSupported property.

For more information, see DirectPlay Defined Properties.

[Visual Basic]

You can exchange messages with the lobby by using the DirectPlayLobby3.SendLobbyMessage and DirectPlayLobby3.ReceiveLobbyMessage methods.

Information is sent to the lobby by setting properties. The application must create a DirectPlayMessage object containing data in the same order as in the DPLMSG_SETPROPERTY C structure, using the DirectPlayMessage.WriteLong and DirectPlayMessage.WriteGuid methods.

Information is obtained from the lobby in a similar fashion, by requesting properties. The application creates a message containing data equivalent to that in the DPLMSG_GETPROPERTY C structure and sends it to the lobby. The lobby sends back a DPLMSG_GETPROPERTYRESPONSE message containing the property data that was requested. Data can be extracted by using the DirectPlayMessage.ReadLong and DirectPlayMessage.ReadGuid methods.

For more information, see the C++ text for this topic.


DirectPlay Messages

Once an application has created a player, it can start exchanging player messages with other participants in the session. In addition, DirectPlay itself generates system messages to notify players of events such as a player joining or leaving the session.

A player message can be sent to an individual player, to all players, or to a subset of players defined as a group, and is identified by the sending player's ID. System messages are sent to all the players in a session, and have a sender ID equal to the constant DPID_SYSMSG.

All the messages received by an application are put into a receive queue. The application must retrieve individual messages from the queue and act on them. The application can either poll the receive queue for messages or rely on a synchronization event for notification that a new message has arrived.

The following sections give more information on how to use messages in DirectPlay.

  • Receiving Messages
  • Synchronization
  • Using Player Messages
  • Using System Messages
  • Asynchronous Messaging
  • Using Lobby Messages


Receiving Messages

[C++]

An application retrieves the next message in the queue by calling IDirectPlay4::Receive.

If there is more than one local player—that is, more than one player has been created by this instance of the application—then the ID of the player for whom messages are desired must be passed to the Receive method in the lpidTo parameter, and the DPRECEIVE_TOPLAYER flag must be set.

In order to retrieve the message data, it is first necessary to allocate the right amount of memory. To determine the necessary buffer size, first call the method with the lpData parameter set to NULL, or pass in a pointer to an existing buffer of any size and set *lpdwDataSize to the current length. If there is a message waiting, but lpData is NULL or the buffer is not big enough, the method fails with DPERR_BUFFERTOOSMALL and returns the required amount of memory in *lpdwDataSize. Reallocate and try again.

Once the method succeeds and fills the buffer with the message data, *lpidFrom equals DPID_SYSMSG if this is a system message. If so, follow the steps outlined under Using System Messages. If not, follow the procedure in Using Player Messages.

For an example of this process, see the ReceiveMessages function in the Duel sample.

[Visual Basic]

The DirectPlay4.Receive method retrieves the next message in the queue and returns a DirectPlayMessage object containing the message data. In addition, the method returns the ID of the sending player (DPID_SYSMSG if it is a system message) and the ID of the receiving player these are returned in variables that have been passed to the method.

If there is more than one local player—that is, more than one player has been created by this instance of the application—then the ID of the player for whom messages are desired must be passed to the Receive method in the toPlayerId parameter, and the DPRECEIVE_TOPLAYER flag must be set.

The following sample function retrieves all waiting messages:

' gObjDPlay is the DirectPlay4 object.
' gMyPlayerID is the ID for this player.

Sub ReceiveMessages
    Dim MsgCount as Long
    Dim MsgType as Long
    Dim FromPlayerID As Long
    Dim ToPlayerID As Long
    Dim dpMsg as DirectPlayMessage

    MsgCount = gObjDPlay.GetMessageCount(gMyPlayerID)
    For X% = 1 to MsgCount
        Set dpMsg = gObjDPlay.Receive(FromPlayerID, _
            ToPlayerID, DPRECEIVE_ALL)
        If FromPlayerID = DPID_SYSMSG Then
            MsgType = dpMsg.ReadLong()
           ' Process system message here
        Else
           'Process player message here
        End If
    Next X
End Sub

For more information on how to handle messages after receiving them, see the following topics:

  • Using System Messages
  • Using Player Messages
  • Using Lobby Messages


Synchronization

[C++]

An application can use two techniques to receive DirectPlay messages. The first is to check the receive queue during the main loop of the application. Typically, this means the application is single-threaded.

Alternatively, an application can have a separate thread to wait for messages and process them. In this case the application should supply a handle to a non-NULL, auto-reset synchronization event (see the Win32® CreateEvent function) when it creates players. DirectPlay will set this event when a message arrives for that player.

The message processing thread should then use the Win32 WaitForSingleObject function to wait until the event is set. Continue calling IDirectPlay4::Receive until it returns DPERR_NOMESSAGES, indicating that there are no more messages in the message queue.

If an application creates more than one local player, all can share the same event or each can have a separate event.

[Visual Basic]

An application can use two techniques to receive DirectPlay messages. The first is to check the receive queue during the main loop of the application. In Visual Basic, you might poll for messages in Sub Main, as in the following sample code:

Public Sub Main()

    Do While DoEvents()  ' Allow event processing
        ReceiveMessages  ' See Receiving Messages
    Loop
End Sub

Alternatively, the application can create an event that will be signaled whenever a player receives a message. In order to do so, you must implement the DirectXEvent class in a form or class module and supply a DirectXEvent.DXCallBack method. You then pass the DirectXEvent object (typically the form that implements the DirectXEvent class) to the DirectX7.CreateEvent method in order to get an event handle, and pass this handle to the DirectPlay4.CreatePlayer method in the receiveEvent parameter. Now, whenever a message is placed in the receive queue for that player, the DXCallBack method is automatically called, and within this procedure the application can retrieve any pending messages from the queue.

If an application creates more than one local player, all can share the same event or each can have a separate event.


Using Player Messages

[C++]

Player messages can be sent by using IDirectPlay4::Send or IDirectPlay4::SendEx. Messages sent by using SendEx can be assigned a priority. Higher-priority messages are sent first. Priority does not affect the order in which messages are received.

The organization of data within a player message is determined solely by the application. Conventionally, the first element is an application-defined message identifier.

Typically, the C++ application will use IDirectPlay4::Receive to obtain the message buffer, cast it to DPMSG_GENERIC, and check to see whether the message is from DPID_SYSMSG. If it is not, the application casts the data to an application-defined generic type, checks the message type within this structure, then casts once again to a application-defined type appropriate for the message. For an example, see the Duel sample, in particular the ReceiveMessages and DoApplicationMessage functions.

[Visual Basic]

Player messages can be sent by using DirectPlay4.Send or DirectPlay4.SendEx. Messages sent by SendEx can be assigned a priority. Higher-priority messages are sent first. Priority does not affect the order in which messages are received.

The organization of data within a player message is determined solely by the application. Conventionally, the first element is an application-defined message identifier.

Message data is represented by DirectPlayMessage object. The sending application obtains this object by using the DirectPlay4.CreateMessage method.

There are two ways to construct player message data. The first way is to write the data one element at a time, using the various write methods of DirectPlayMessage. As each element is written, an internal write pointer is advanced. The second way is to pass a user-defined type to DirectPlayMessage.SetMessageData. Most applications should use the first technique, because SetMessageData requires you to know the exact size of the data being passed to the method, which is not always straightforward.

Note You cannot mix these two ways of setting the message data. For example, you cannot use DirectPlayMessage.WriteLong to write the message type, then SetMessageData to write additional data. SetMessageData sets the entire contents of the message.

Data is retrieved from the message by using the corresponding read methods of DirectPlayMessage, or by using DirectPlayMessage.GetMessageData. When using the read methods, the application must read the elements in the same order as they were written. GetMessageData should be used only if the data was set by SetMessageData.


Using System Messages

[C++]

Messages returned by the IDirectPlay4::Receive method from player ID DPID_SYSMSG are system messages. All system messages begin with an identifier specified by the dwType value. You can cast the buffer returned by the IDirectPlay4::Receive method to a generic message (DPMSG_GENERIC) and examine the dwType element, which will have a value equal to one of the message type identifiers with the DPSYS_ prefix. After the application has determined which system message it is, the buffer should be cast to the appropriate structure (beginning with the DPMSG_ prefix) to read the data.

Your application should be prepared to handle the following system messages.

Value of dwType | Message structure | Cause
DPSYS _ADDGROUPTOGROUP | DPMSG_ADDGROUPTOGROUP | An existing group has been added to an existing group.
DPSYS _ADDPLAYERTOGROUP | DPMSG_ADDPLAYERTOGROUP | An existing player has been added to an existing group.
DPSYS_CHAT | DPMSG_CHAT | A chat message has been received.
DPSYS _CREATEPLAYERORGROUP | DPMSG_CREATEPLAYERORGROUP | A new player or group has been created.
DPSYS _DELETEGROUPFROMGROUP | DPMSG_DELETEGROUPFROMGROUP | A group has been removed from a group.
DPSYS _DELETEPLAYERFROMGROUP | DPMSG_DELETEPLAYERFROMGROUP | A player has been removed from a group.
DPSYS _DESTROYPLAYERORGROUP | DPMSG_DESTROYPLAYERORGROUP | An existing player or group has been destroyed.
DPSYS_HOST | DPMSG_HOST | The current host has left the session and this application is the new host.
DPSYS _SECUREMESSAGE | DPMSG_SECUREMESSAGE | A digitally signed or encrypted message has been received.
DPSYS _SENDCOMPLETE | DPMSG_SENDCOMPLETE | An asynchronous send is complete.
DPSYS _SESSIONLOST | DPMSG_SESSIONLOST | The connection with the session has been lost.
DPSYS _SETGROUPOWNER | DPMSG_SETGROUPOWNER | The owner of the group has changed.
DPSYS _SETPLAYERORGROUPDATA | DPMSG_SETPLAYERORGROUPDATA | Player or group data has changed.
DPSYS _SETPLAYERORGROUPNAME | DPMSG_SETPLAYERORGROUPNAME | Player or group name has changed.
DPSYS _SETSESSIONDESC | DPMSG_SETSESSIONDESC | Session description has changed.
DPSYS _STARTSESSION | DPMSG_STARTSESSION | Lobby server is requesting that a session be started.

[Visual Basic]

Messages returned by the DirectPlay4.Receive method that are marked as being from player ID DPID_SYSMSG are system messages. All system messages begin with a Long type identifier.

In order to parse a system message, you must first retrieve its type identifier by using DirectPlayMessage.ReadLong method. You then use the various read methods of DirectPlayMessage in order to extract elements of the message data. Elements must be extracted in the order documented for the message type. (See CONST_DPSYSMSGTYPES.)

In addition to all the standard read methods that are used for player messages as well as system messages, DirectPlay provides the following methods for parsing system messages:

  • DirectPlayMessage.MoveToSecureMessage
  • DirectPlayMessage.ReadSysMsgData
  • DirectPlayMessage.ReadSysChatString
  • DirectPlayMessage.ReadSysMsgConnection
  • DirectPlayMessage.ReadSysMsgSessionDesc

Note that ReadSysChatString, ReadSysMsgConnection, and ReadSysMsgSessionDesc can be called regardless of the position of the read pointer, and calling these methods does not advance the read pointer. On the other hand, ReadSysMsgData can be called only when all preceding data in the message has been retrieved, and calling it advances the read pointer. The reason for this behavior is that the first three methods always know where to find their data in the underlying message structure, whereas ReadSysMsgData can be used to extract data from different locations in different message types.


Asynchronous Messaging

The ability to send messages asynchronously frees the application's communication code from blocking while each message is transmitted. It offloads management of outgoing messages to DirectPlay while still giving the application the ability to monitor the message queue and to cancel messages.

The asynchronous messaging feature is only available if the session is using the DirectPlay protocol or if it is supported by the service provider. For example, the TCP/IP service provider supports asynchronous messages only when the computer is using Windows Sockets 2.0 or later.

[C++]

If the DirectPlay protocol is not being used, it is important to use the IDirectPlay4::GetCaps method to check the DPCAPS_ASYNCSUPPORTED flag after the session has been established, to determine whether asynchronous messages are supported.

To send an asynchronous message, you must use the IDirectPlay4::SendEx method with the DPSEND_ASYNC flag set in the dwFlags parameter. SendEx will return immediately. Later, the application will receive a DPMSG_SENDCOMPLETE system message with the status result for the sent message. You can disable the notification by setting the DPSEND_NOSENDCOMPLETEMSG flag when the message is sent. The application can track individual messages using the dwMsgID parameter returned by SendEx. This ID can be used to cancel individual messages or to match completion notification messages.

SendEx can be used to assign a timeout value and a priority to a message in sessions that support these properties. You can also cancel messages in the send queue by using the IDirectPlay4::CancelMessage or IDirectPlay4::CancelPriority method. Timeout, priority, and cancellation functionality require the DirectPlay protocol or service provider support, as determined by the IDirectPlay4::GetCaps method.

[Visual Basic]

If the DirectPlay protocol is not being used, after the session has been established it is important to use the DirectPlay4.GetCaps method to check for the DPCAPS_ASYNCSUPPORTED flag, to determine whether asynchronous messages are supported.

To send an asynchronous message, you must use the DirectPlay4.SendEx method with the DPSEND_ASYNC flag set in the flags parameter. SendEx will return immediately. Later, the application will receive a DPMSG_SENDCOMPLETE system message with the status result for the sent message. You can disable the notification by setting the DPSEND_NOSENDCOMPLETEMSG flag when the message is sent. The application can track individual messages using the ID returned by SendEx. This ID can be used to cancel individual messages or to match completion notification messages.

SendEx can be used to assign a timeout value and a priority to a message in sessions that support these properties. You can also cancel messages in the send queue by using the DirectPlay4.CancelMessage or DirectPlay4.CancelPriority method. Timeout, priority, and cancellation functionality require the DirectPlay protocol or service provider support, as determined by the DirectPlay4.GetCaps method.

You should exercise great care when mixing asynchronous and synchronous messages. A synchronous message will be sent after any asynchronous messages ahead of it in the queue and will then block until completed.

If supported, timeouts and priorities can be used with synchronous messages. Message tracking by ID and cancellation do not apply to synchronous messages.

Asynchronous messaging does not increase bandwidth or decrease latency.

For more information on how to use asynchronous messages effectively, see Asynchronous Networking with the DirectPlay Protocol.


Using Lobby Messages

Lobby messages fall into two categories: DirectPlay-defined messages and application-defined messages.

DirectPlay-defined messages can be system messages, generated automatically by DirectPlay and sent to the lobby to inform it of changes in the status of the application, or standard message types, sent from the application to the lobby or from the lobby to the application.

The advantage of standard messages over application-defined messages is that the receiver can always interpret a standard message. A lobby client is not necessarily going to be able to handle custom messages from an application, just as an application may not be able to handle custom messages from a lobby client.

[C++]

Lobby messages are retrieved by using the IDirectPlayLobby3::ReceiveLobbyMessage method. The message category can be identified by the value returned in the variable pointed to by the lpdwMessageFlags parameter. If neither DPLMSG_SYSTEM or DPLMSG_STANDARD is present, the message is application-defined.

Lobbies should be prepared to handle all the standard message types. If an application uses the DPLMSG_GETPROPERTY message, it must be able to handle DPLMSG_GETPROPERTYRESPONSE messages. (See Staying in Touch with the Lobby.)

DirectPlay-defined messages all start with a DWORD value that identifies the message type. After retrieving a message using ReceiveLobbyMessage, cast *lpData to the DPLMSG_GENERIC structure and examine the structure's dwType member. Then cast *lpData to the appropriate message structure for further processing.

The following table shows the possible values of DPLMSG_GENERIC.dwType for standard messages, and the structure and message cause associated with each value.

Value of dwType | Message structure | Cause
DPLSYS _APPTERMINATED | DPLMSG_SYSTEMMESSAGE | The application has terminated.
DPLSYS _CONNECTIONSETTINGSREAD | DPLMSG_SYSTEMMESSAGE | The application has read the connection settings.
DPLSYS _DPLAYCONNECTFAILED | DPLMSG_SYSTEMMESSAGE | The application failed to connect to the DirectPlay session.
DPLSYS _DPLAYCONNECTSUCCEEDED | DPLMSG_SYSTEMMESSAGE | The application successfully connected to the DirectPlay session.
DPLSYS _GETPROPERTY | DPLMSG_GETPROPERTY | The application is requesting a property from the lobby. See Staying in Touch with the Lobby.
DPLSYS _GETPROPERTYRESPONSE | DPLMSG_GETPROPERTYRESPONSE | The lobby is responding to a DPLMSG_GETPROPERTY message. See Staying in Touch with the Lobby.
DPLSYS _NEWCONNECTIONSETTINGS | DPLMSG_SYSTEMMESSAGE | A waiting application was found when a lobby client called RunApplication. See Supporting Dynamic Lobby Connection.
DPLSYS _NEWSESSIONHOST | DPLMSG_NEWSESSIONHOST | The application session has a new host.
DPLSYS _SETPROPERTY | DPLMSG_SETPROPERTY | The application is setting a property on the lobby. See Staying in Touch with the Lobby.
DPLSYS _SETPROPERTYRESPONSE | DPLMSG_SETPROPERTYRESPONSE | The lobby is responding to a DPLMSG_SETPROPERTY message. See Staying in Touch with the Lobby.

[Visual Basic]

Lobby messages are retrieved by using the DirectPlayLobby3.ReceiveLobbyMessage method. The message category can be identified by the value returned in the messageFlags parameter. If neither DPLMSG_SYSTEM or DPLMSG_STANDARD is present, the message is application-defined.

Lobbies should be prepared to handle all the standard message types. If an application uses the DPLSYS_GETPROPERTY message, it must be able to handle DPLSYS_GETPROPERTYRESPONSE messages. (See Staying in Touch with the Lobby.)

DirectPlay-defined messages all start with a value from the CONST_DPSYSMSGTYPES enumeration that identifies the message type. You retrieve this value by using DirectPlayMessage.ReadLong.

The following table shows the message type and the message cause associated with each value.

Message Type | Cause
DPLSYS _APPTERMINATED | The application has terminated.
DPLSYS _CONNECTIONSETTINGSREAD | The application has read the connection settings.
DPLSYS _DPLAYCONNECTFAILED | The application failed to connect to the DirectPlay session.
DPLSYS _DPLAYCONNECTSUCCEEDED | The application successfully connected to the DirectPlay session.
DPLSYS _GETPROPERTY | The application is requesting a property from the lobby. See Staying in Touch with the Lobby.
DPLSYS _GETPROPERTYRESPONSE | The lobby is responding to a DPLMSG_GETPROPERTY message. See Staying in Touch with the Lobby.
DPLSYS _NEWCONNECTIONSETTINGS | A waiting application was found when a lobby client called RunApplication. See Supporting Dynamic Lobby Connection.
DPLSYS _NEWSESSIONHOST | The application session has a new host.
DPLSYS _SETPROPERTY | The application is setting a property on the lobby. See Staying in Touch with the Lobby.
DPLSYS _SETPROPERTYRESPONSE | The lobby is responding to a DPLMSG_SETPROPERTY message. See Staying in Touch with the Lobby.


DirectPlay Address

A DirectPlay address is a data format that DirectPlay uses to pass addressing information between lobby servers, applications, DirectPlay, and service providers. The address consists of a sequence of variable-length data chunks tagged with a GUID, containing all the address information needed by DirectPlay. Examples are the network address of a server, the network address of a player, the network address of a session, or the modem and phone number for a dial-up connection.

You do not need to understand DirectPlay addresses in order to use DirectPlay. You need to learn about DirectPlay addresses only if you want to do one of the following:

  • Override the dialog boxes of the standard service provider. You create a DirectPlay address that specifies which service provider to use and contains all the information the service provider needs to establish a connection. Then you initialize the connection with this address.
  • Write a lobby client that will launch an external DirectPlay application. The lobby client needs to create a DirectPlay address that specifies which service provider to use and contains all the information the service provider needs to establish a connection and automatically connect the client to a session. This information is then passed to the application when it is launched.

More information is contained in the following topics:

  • Overriding Service Provider Dialogs
  • DirectPlay Address Data Types
  • Examples of Using DirectPlay Addresses


Overriding Service Provider Dialogs

The DirectPlay addresses obtained when DirectPlay enumerates connections are simply registered DirectPlay providers that the user can choose from, and do not necessarily contain all the information needed to establish a connection. When one of these addresses is used to enumerate sessions, the service provider might ask the user for more information.

For example, if the user selects "Modem Connection for DirectPlay" from a list of service providers and the application initializes that connection and then begins session enumeration, a dialog box asks the user to select a modem and enter a telephone number. If the user cancels this dialog, he or she cannot join an existing session, though it is still possible to create one. If the user chooses to create a session, the service provider displays another dialog box giving an opportunity to choose and configure a modem for answering a call.

[C++]

Sometimes this might not be the desired behavior. An application might already have the necessary connection information (for example, the IP address of a central site where games are being hosted), or it might get the information from the user through its own interface. In this case, the application can pass the complete connection information to IDirectPlay4::InitializeConnection and thus prevent the service provider from asking for more.

To create a DirectPlay address, call the IDirectPlayLobby3::CreateAddress or IDirectPlayLobby3::CreateCompoundAddress methods. CreateAddress can be used only for simple addresses containing a single element—for example, an IP address. CreateCompoundAddress can be used to create more complex addresses, such as a telephone address that includes both a modem and a phone number. For the types of elements defined by DirectPlay, see DirectPlay Address Data Types.

[Visual Basic]

Sometimes this might not be the desired behavior. An application might already have the necessary connection information (for example, the IP address of a central site where games are being hosted), or it might get the information from the user through its own interface. In this case, the application can pass the complete connection information to DirectPlay4.InitializeConnection and thus prevent the service provider from asking for more.

The DirectPlayLobby3 class has the following methods for creating various kinds of DirectPlayAddress objects:

  • CreateComPortAddress
  • CreateCustomAddress
  • CreateINetAddress
  • CreateLobbyProviderAddress
  • CreateModemAddress
  • CreateServiceProviderAddress


DirectPlay Address Data Types

[Visual Basic]

This topic pertains only to applications written in C++. In DirectX for Visual Basic, the data format of the DirectPlayAddress object is determined by which method of DirectPlayLobby3 is used to create it.

[C++]

The following table shows the standard types of data chunks (DPCOMPOUNDADDRESSELEMENT) in a DirectPlay address created by using IDirectPlayLobby3::CreateCompoundAddress.

GuidDataType | lpData
DPAID_ComPort | A DPCOMPORTADDRESS structure that contains all the settings for the COM port. The serial connection service provider will use this information to configure the serial port.
DPAID_INet | Null-terminated ANSI string containing an IP address (for example, "192.168.0.1") or a domain name ("microsoft.com"). The dwDataSize value must include the terminator. If a blank address is supplied, the Internet TCP/IP connection service provider will use this information to enumerate sessions on the specified network address or to broadcast on the subnet. A blank address is a string that contains only the ANSI terminator (0x00) and has a length of 1 byte.
DPAID_INetW | Null-terminated Unicode string containing an IP address or a domain name. The dwDataSize value must include the terminator. If a blank address is supplied, the Internet TCP/IP connection service provider will use this information to enumerate sessions on the specified network address or broadcast on the subnet. A blank address is a string that contains only the Unicode terminator (0x0000) and has a length of 2 bytes.
DPAID_INetPort | Integer containing the specific port number to use. See the section on selecting a specific port in the TCP/IP topic or see Firewall Support for information about using this DirectPlay address.
DPAID _LobbyProvider | GUID that specifies the lobby provider this DirectPlay address applies to.
DPAID_Modem | Variable-length null-terminated ANSI string specifying which installed modem to use. The dwDataSize value must include the terminator. The modem service provider will use this modem without displaying a dialog box asking the user which modem to use.
DPAID_ModemW | Variable-length null-terminated Unicode string specifying which installed modem to use. The dwDataSize value must include the terminator. The modem service provider will use this modem without displaying a dialog box asking the user which modem to use. Use the IDirectPlay4::GetPlayerAddress method to determine which modems are available.
DPAID_Phone | Variable-length, null-terminated ANSI string containing a phone number. The dwDataSize value must include the terminator. The modem service provider will call this phone number on the IDirectPlay4::EnumSessions method. If no modem is specified, the first modem will be used.
DPAID_PhoneW | A variable-length null-terminated Unicode string (LPWSTR) containing a phone number. The dwDataSize value must include the terminator. The modem service provider will call this phone number on the IDirectPlay4::EnumSessions method. If no modem is specified, the first modem will be used.
DPAID _ServiceProvider | The 16-byte GUID that specifies the service provider this DirectPlay address applies to.
DPAID_TotalSize | A DWORD containing the size of the entire DirectPlay address. This chunk is added automatically by CreateCompoundAddress.


Examples of Using DirectPlay Addresses

[Visual Basic]

This topic pertains only to applications written in C++. In DirectX for Visual Basic, an object of the DirectPlayAddress class encapsulates address information. The object is created by one of the methods of DirectPlayLobby3. For more information, see Overriding Service Provider Dialogs.

[C++]

This topic contains examples of DirectPlay addresses and the data they contain for different connection types.

A DirectPlay address describing an IPX connection

Initializing this connection will bind the DirectPlay object to the IPX service provider.

guidDataType | dwDataSize | Data
DPAID_ServiceProvider | 16 | {685BC400-9D2C-11cf-A9CD-00AA006886E3}

A DirectPlay address describing a modem connection

Initializing this connection binds DirectPlay to the modem service provider and stores the phone number. When the application initiates session enumeration, the service provider dials the number without asking the user for a phone number.

guidDataType | dwDataSize | Data
DPAID_ServiceProvider | 16 | {44EAA760-CB68-11cf-9C4E-00A0C905425E}
DPAID_Phone | 9 (including NULL terminator) | "555-8237"

A DirectPlay address describing a TCP/IP connection

Initializing this connection binds DirectPlay to the TCP/IP service provider and stores the IP address. When the application initiates session enumeration, the service provider does not ask the user for an IP address.

guidDataType | dwDataSize | Data
DPAID_ServiceProvider | 16 | {36E95EE0-8577-11cf-960C-0080C7534E82}
DPAID_INet | 10 (including NULL terminator) | "127.0.0.1"


DirectPlay Protocol

The DirectPlay protocol is an implementation of guaranteed messaging on nonguaranteed service providers. For example, the Internetwork Packet Exchange (IPX) service provider does not inherently support guaranteed messaging. When an application tries to send a guaranteed message on IPX, the DirectPlay protocol will take care of doing all the handshaking necessary to guarantee delivery of the message.

The DirectPlay protocol also implements asynchronous messaging and message throttling, although the service provider may optimize this functionality.

An application invokes the DirectPlay protocol by setting the DPSESSION_DIRECTPLAYPROTOCOL flag when creating a session.

System messages are always sent guaranteed, whether or not the service provider natively supports guaranteed messages, and whether or not you set the DirectPlay protocol flag. The DirectPlay protocol will be used automatically to send system messages guaranteed.

[C++]

For non-system messages, if an application sets the DirectPlay protocol flag and sends a message guaranteed (by setting the DPSEND_GUARANTEED flag in IDirectPlay4::SendEx), the message will be sent guaranteed whether the service provider supports guaranteed messages or not.

[Visual Basic]

For non-system messages, if an application sets the DirectPlay protocol flag and sends a message guaranteed (by setting the DPSEND_GUARANTEED flag in DirectPlay4.SendEx), the message will be sent guaranteed whether the service provider supports guaranteed messages or not.

If an application does not set the DirectPlay protocol flag and sends a message guaranteed, delivery will be guaranteed only if the service provider supports it, regardless of the DPSEND_GUARANTEED flag.

An application also can also specify that the DirectPlay protocol be used instead of the default guaranteed messaging implemented by the service provider. This is also done by specifying the DPSESSION_DIRECTPLAYPROTOCOL flag when creating a session.

The following table summarizes how non-system messages are sent.

If the DirectPlay protocol flag is not set:

Service Provider | Messages Sent Guaranteed Use: | Messages Sent Nonguaranteed Use:
IPX | IPX, won't be sent guaranteed | IPX
TCP/IP | TCP | UDP
Modem | Modem, won't be sent guaranteed | Modem

If the DirectPlay protocol flag is set:

Service Provider | Messages Sent Guaranteed Use: | Messages Sent Nonguaranteed Use:
IPX | DirectPlayProtocol/IPX | DirectPlayProtocol/IPX
TCP/IP | DirectPlayProtocol/UDP | DirectPlayProtocol/UDP
Modem | DirectPlayProtocol/Modem | DirectPlayProtocol/Modem

When the DirectPlay protocol flag is not set, the application must examine the capabilities of the service provider (after the session has been opened) to determine what functionality is available in terms of asynchronous messaging, canceling messages, timeouts on messages, and prioritization of messages. If the DirectPlay protocol flag is set, all this functionality is available.


Asynchronous Networking with the DirectPlay Protocol

When you are designing a network gaming application, the object of the networking code is to provide the basis for a synchronized game environment to many players. The networking code must handle many different network environments which may provide low or high latency, low or high bandwidth, and varying reliability.

Before the advent of DirectPlay, it was left to the game developer to determine the characteristics of the network link and adapt the game appropriately. Typically, the solution developers applied was to minimize the amount and frequency of the data sent. Although this approach provides a solution that works well in the harshest environments, it does not provide the best gaming experience to the end user. In many cases, the game could send many more updates or more information per update to enhance the user experience and keep tighter synchronization of the gaming environment.

The goal of the network code should be to use all available bandwidth for updating the game state. At the same time, the code must avoid backlogging the connection by sending faster than the link can handle, which leads to higher latencies and worse game synchronization.

The DirectPlay protocol and asynchronous messaging provide an environment where the network code in an application can determine the abilities of the link and adapt its behavior to make the greatest use of available bandwidth.

The DirectPlay protocol uses feedback from the receiver, letting the protocol know how much data is arriving at the receiver. Unlike existing network protocols, the feedback allows the DirectPlay protocol to precisely control its sending rate so as not to build up a backlog of message packets between the sender and the receiver.

The DirectPlay protocol also applies this feedback to nonguaranteed messages. This throttling of sent messages not only guarantees that the client application does not introduce excessive latencies into the game by creating a backlog, it also allows the client to adapt itself. By viewing the send queue, the client can recognize when it is sending data faster than the link can deliver the data or when the client is not using nearly the available bandwidth. This gives the client the opportunity to adjust its sending strategy to the capabilities of the existing link.

In order to take maximum advantage of the DirectPlay protocol, you should send messages asynchronously. (For information on how to do this, see Asynchronous Messaging.) Messages sent asynchronously do not block. When you send a message asynchronously, the send is not completed when the call to SendEx returns. Instead, the send will complete at a later time and inform you by posting a completion message to the receive queue.

If you use asynchronous sends, the DirectPlay protocol can be sending many messages, both guaranteed and nonguaranteed, simultaneously on a link. That is, the protocol does not wait for the completion of one message before sending another. This prevents single packet losses from hurting link use. It also prevents the loss of one guaranteed packet from slowing the delivery of other guaranteed messages.

Typically, network games have used nonguaranteed messages only for transferring a real-time game state. The primary reasons for this strategy are that sending a nonguaranteed message generally does not block and that many nonguaranteed messages can be sent without waiting. The DirectPlay protocol enables you to send guaranteed messages that do not block and to have many outstanding guaranteed sends on each connection. This means your game can use guaranteed sends and be just as responsive as a game that uses nonguaranteed sends. This can greatly simplify the design of your game state updates and allows you to use incremental updates, which are almost impossible with nonguaranteed sends.

There are a few things you must watch out for when using the DirectPlay protocol:

  • When the DirectPlay protocol is active, synchronous nonguaranteed sends may block because of throttling. By setting the asychronous flag on your sends, you can get the nonguaranteed sends to return immediately and prevent your game thread from blocking.
  • Even though the DirectPlay protocol makes better use of the network link, you still have to think carefully and minimize the amount of data you send. Always, less data per state update is better, and the goal is to get more updates per second to improve the user experience.
  • When you are making asynchronous sends, the protocol makes a copy of the send data so you can reuse your buffer (or allocate your messages on the stack), so remember that every sent message that is still in the pending queue represents a memory allocation as big as that send, and don't let the send queue grow without limits. There is generally no advantage to letting the send queue to a particular player grow beyond 16 sends. The number of messages in the send queue is absolutely limited to 29 by the current implementation of the DirectPlay protocol. Any additional sends will not be sent concurrently—that is, they will wait for other sends to finish before they put any packets on the network link. You can check the send or receive queue for an individual player by using GetMessageQueue.
  • Do not get confused by the difference between the send queue to a particular player and all the send queues. When you are throttling sends, you generally want to get the queue for the player you are sending to and not for all the players. This also means you will probably want to use directed sends rather than group sends.
  • If you always find the send queue is empty, you should send at a higher data rate in order to improve game synchronization. Since the protocol feeds back from the receiver, there is no danger of swamping the receiver. An empty queue is wasted bandwidth.
  • Don't loop tightly when checking the queue—sleep in between. A constantly spinning thread can use all the CPU cycles. You can adapt the sleep period based on how long it takes the queue to get down to a level where you usually issue another send.
  • The send queue represents a backlog. The longer the send queue is, the longer the latency of additional sends. If the queue is growing too large or too long, cancel messages.


Security and Authentication

DirectPlay security allows an application running on a server to authenticate users against a database of known users before allowing them to join a session. Once a user has been authenticated, all communications between the client and server can be done securely either by digitally signing messages (to verify the identity of the sender) or by encrypting the messages.

For an architectural overview, see Security.

More information is contained in the following topics:

  • User and Message Authentication
  • Message Encryption
  • Firewall Support
  • Secure Sessions


User and Message Authentication

DirectPlay provides user and message authentication (digital signing) support through the Windows® Security Support Provider Interface (SSPI). The default security package that DirectPlay uses is called NTLM Security Support Provider.

[Visual Basic]

A DirectPlay application can choose to use a different SSPI security package when it creates a session by using DirectPlay4.SecureOpen. For example, DPA (Distributed Password Authentication) Security Support Provider is another security package that organizations can use to provide membership services to a large customer base (hundreds of thousands). This security package is available through the Microsoft Commercial Internet Services (MCIS) Membership Server.

[C++]

A DirectPlay application can choose to use a different SSPI security package when it creates a session by using IDirectPlay4::SecureOpen. For example, DPA (Distributed Password Authentication) Security Support Provider is another security package that organizations can use to provide membership services to a large customer base (hundreds of thousands). This security package is available through the Microsoft Commercial Internet Services (MCIS) Membership Server.


Message Encryption

DirectPlay provides message encryption support through the Windows Cryptography Application Programming Interface (CAPI). The default CAPI provider for DirectPlay cryptography services is the Microsoft RSA Base Cryptographic Provider version 1.0. The default CAPI provider type is PROV_RSA_FULL, and the default encryption algorithm is the CALG_RC4 stream cipher.

[C++]

A DirectPlay application can choose to use a different cryptographic provider when it creates a session by using the IDirectPlay4::SecureOpen method. Please note that DirectPlay supports only stream ciphers.

[Visual Basic]

A DirectPlay application can choose to use a different cryptographic provider when it creates a session by using the DirectPlay4.SecureOpen method. Note that DirectPlay supports only stream ciphers.


Firewall Support

Applications do not need to be rewritten to take advantage of the firewall support of DirectPlay. The default behavior is to use a dynamically allocated port from DirectPlay's range. This provides backward compatibility with existing applications, as well as the ability to use multiple DirectPlay applications on a single computer.

Additionally, applications can be written to take advantage of the new fixed-port feature of DirectPlay. You can choose a port number specifically for the application, and a firewall administrator need only open that particular port. See the section on selecting a specific port in the TCP/IP topic.

Users of DirectX 6.0 or later can still communicate with DirectX 5.0 users as long as no firewall is involved. This means that if even one computer is behind a firewall, peer-to-peer games with DirectX 5.0 computers will not work. Client/server games are allowed, as long as the host is DirectX 6.0 or later, and in each case where the line of communication between the host and a client will pass through a firewall, that client is DirectX 6.0 or later, as well.

Because of proxy architecture, you are limited to using a single computer. However, multiple applications (each using the dynamic DirectPlay range or unique application-defined ports) on the computer are still allowed.

For more information about using DirectPlay for firewall support, please see the following topics.

  • Setup for Client Firewall Support Using the DirectPlay Dynamic Range
  • Setup for Host Firewall Support Using the DirectPlay Dynamic Range
  • Using an Application-Specified Fixed Port
  • Setup for Client Firewall Support Using an Application-Specified Fixed Port
  • Setup for Host Firewall Support Using an Application-Specified Fixed Port
  • Dynamic Range Port Reference Chart
  • DirectX 5.0-DirectX 6.0 Cross-Compatibility Reference Chart


Setup for Client Firewall Support Using the DirectPlay Dynamic Range

To join a game through a firewall, the client must be using DirectX 6.0 or later and communicating with a host using DirectX 6.0 or later. To support applications using the DirectPlay dynamic range, a firewall administrator needs to allow an initial outbound TCP connection on port 47624, with subsequent connections of inbound TCP ports 2300-2400, outbound TCP ports 2300-2400, inbound UDP ports 2300-2400, and outbound UDP ports 2300-2400. For a chart highlighting these requirements, see the Dynamic Range Port Reference Chart.

Example of a Microsoft Proxy Server 2.0 Configuration:

  • Internet Service Manager, Windows Sockets Proxy service: Service Properties
    • Add protocol "DirectPlay (client)" under Protocols tab.
      • Initial connection
        • 47624 TCP Outbound
      • Subsequent connections
        • 2300-2400 TCP Inbound
        • 2300-2400 TCP Outbound
        • 2300-2400 UDP Inbound
        • 2300-2400 UDP Outbound
    • Give appropriate permissions to "DirectPlay (client)" under Permissions tab.
  • Add to file "mspclnt.ini", which is in the C:\Msp\Clients folder by default.
    • [Common Configuration]
    • RemoteBindUdpPorts=2300-2400
    • ServerBindTcpPorts=2300-2400
    • KillOldSession=1


Setup for Host Firewall Support Using the DirectPlay Dynamic Range

To host a game through a firewall, the host must be using DirectX 6.0 or later, and the clients beyond the firewall must be using DirectX 6.0 or later, as well. To support applications using the DirectPlay dynamic range, a firewall administrator needs to allow an initial inbound TCP connection on port 47624, with subsequent connections of inbound TCP ports 2300-2400, outbound TCP ports 2300-2400, inbound UDP ports 2300-2400, and outbound UDP ports 2300-2400. For a chart highlighting these requirements, see the Dynamic Range Port Reference Chart.

Theoretical Microsoft Proxy Server 2.0 configuration:

  • Internet Service Manager, Windows Sockets Proxy service: Service Properties
    • Add protocol "DirectPlay (host)" under Protocols tab.
      • Initial connection
        • 47624 TCP Inbound
      • Subsequent connections
        • 2300-2400 TCP Inbound
        • 2300-2400 TCP Outbound
        • 2300-2400 UDP Inbound
        • 2300-2400 UDP Outbound
    • Give appropriate permissions to "DirectPlay (host)" under Permissions tab.
  • Add to file "mspclnt.ini", which is in the C:\Msp\Clients folder by default.
    • [Common Configuration]
    • RemoteBindUdpPorts=2300-2400
    • ServerBindTcpPorts=2300-2400
    • KillOldSession=1

Unfortunately, some firewall solutions, including Microsoft Proxy Server 2.0, won't recognize additional inbound connections as subsequent connections. The workaround for this is that each port in the range (2300, 2301, 2302, and so on) must get its own protocol definition, as if it were an application-specified fixed port. For more information, see Setup for Host Firewall Support Using an Application-Specified Fixed Port. Practically, only as many ports as active DirectPlay applications need to be opened, that is, to run both the applications "SuperDuperGame" and "WackyFunGame" at the same time, only ports 2300 and 2301 will be used.


Using an Application-Specified Fixed Port

[Visual Basic]

This topic pertains only to applications written in C++.

[C++]

An application can choose to use a fixed port rather than the DirectPlay default ports. If this is done, only the one port needs to be opened to allow that application (and only that application) to operate through a firewall.

To specify a fixed port, the application must create a DirectPlay address that contains the data chunk for DPAID_InetPort. The application can append the chunk to the lpAddress returned by IDirectPlay4::EnumConnections before passing it to IDirectPlay4::InitializeConnection. Alternatively, the application can create the DirectPlay address completely (specifying the service provider, IP address and port number) and pass that to InitializeConnection.

For more information, see DirectPlay Address.


Setup for Client Firewall Support Using an Application-Specified Fixed Port

To join a game through a firewall, the client must be using DirectX 6.0 or later and communicating with a host using DirectX 6.0 or later. To support applications using an application-specified fixed port n, a firewall administrator needs to allow an initial outbound TCP connection on port n, with subsequent connections of inbound TCP port n, inbound UDP port n, and outbound UDP port n.

Example of a Microsoft Proxy Server 2.0 configuration, where the application "SuperDuperGame" (superdg.exe) specifies the port as 12345:

  • Internet Service Manager, Windows Sockets Proxy service: Service Properties
    • Add protocol "SuperDuperGame (client)" under Protocols tab.
      • Initial connection
        • 12345 TCP Outbound
      • Subsequent connections
        • 12345 TCP Inbound
        • 12345 UDP Inbound
        • 12345 UDP Outbound
    • Give appropriate permissions to "SuperDuperGame" under Permissions tab.
  • Add to file "mspclnt.ini", which is in the C:\msp\Clients folder by default:
    • [superdg]
    • RemoteBindUdpPorts=12345
    • ServerBindTcpPorts=12345
    • KillOldSession=1


Setup for Host Firewall Support Using an Application-Specified Fixed Port

To host a game through a firewall, the host must be using DirectX 6.0 or later, and the clients beyond the firewall must be DirectX 6.0 or later as well. To support applications using an application-specified fixed port n, a firewall administrator needs to allow an initial inbound TCP connection on port n, with subsequent connections of outbound TCP port n, inbound UDP port n, and outbound UDP port n.

Example of a Microsoft Proxy Server 2.0 configuration, where the application "SuperDuperGame" (superdg.exe) specifies the port as 12345.

  • Internet Service Manager, Windows Sockets Proxy service: Service Properties
    • Add protocol "SuperDuperGame (host)" under Protocols tab.
      • Initial connection
        • 12345 TCP Inbound
      • Subsequent connections
        • 12345 TCP Outbound
        • 12345 UDP Inbound
        • 12345 UDP Outbound
    • Give appropriate permissions to "SuperDuperGame" under Permissions tab.
  • Add to file "mspclnt.ini", which is in the C:\msp\Clients folder by default:
    • [superdg]
    • RemoteBindUdpPorts=12345
    • ServerBindTcpPorts=12345
    • KillOldSession=1


Dynamic Range Port Reference Chart

The following chart shows which ports an administrator needs to open for a given desired style of play for applications using the dynamic range of DirectPlay.

Connection | Client configuration | Host configuration
Initial TCP Connection | 47624 Outbound | 47624 Inbound
Subsequent Inbound TCP Connections | 2300-2400 | 2300-2400
Subsequent Outbound TCP Connections | 2300-2400 | 2300-2400
Subsequent Inbound UDP Connections | 2300-2400 | 2300-2400
Subsequent Outbound UDP Connections | 2300-2400 | 2300-2400


DirectX 5.0-DirectX 6.0 Cross-Compatibility Reference Chart

The following chart shows which versions work with each other, assuming there are only two computers, and the firewall referred to is physically the same firewall for both (that is, both the client and host are behind the same firewall). Note that DirectX 6.0 means "DirectX 6.0 or later."

 | Internet DirectX 5.0 Host | DirectX 5.0 Host Behind Firewall | Internet DirectX 6.0 Host | DirectX 6.0 Host Behind Firewall
Internet DirectX 5.0 Client | yes | no | yes | no
DirectX 5.0 Client behind firewall | no | yes | no | yes
Internet DirectX 6.0 Client | yes | no | yes | yes
DirectX 6.0 Client behind firewall | no | yes | yes | yes

The chart still holds true for more than two computers if the session is client/server. If there are more than two computers, the session is peer-to-peer, and there is a firewall involved anywhere, then all computers must be using DirectX 6.0 or later.


Secure Sessions

A secure session is one that can be joined only by authenticated users. This is not the same as password protection. Authentication verifies that the user is allowed access to the server by virtue of having been added to the membership database by the administrator of the server. Only users that are part of the membership database are permitted to join the session. A password can be added to any session, regardless of whether it is a secure session. Secure sessions can be hosted only on computers that support authentication, but any computer can put a password on a session.

[C++]

Creating a secure DirectPlay session simply requires the server application to set the DPSESSION_SECURESERVER flag in the DPSESSIONDESC2 structure passed to IDirectPlay4::Open or IDirectPlay4::SecureOpen. Open can be used to create a session that uses the default security package and does not require authentication at the time when clients join the session.

A DirectPlay application can choose to use alternate providers when it creates a session by calling the SecureOpen method and specifying the providers to use in the DPSECURITYDESC structure. For a different SSPI provider (for user and message authentication), an application needs to specify the provider name in the lpszSSPIProvider member of the DPSECURITYDESC structure. For a different CryptoAPI provider (for message privacy), an application needs to specify the provider name, provider type, and encryption algorithm in the lpszCAPIProvider, dwCAPIProviderType, and dwEncryptionAlgorithm members respectively.

When a client enumerates this session, the DPSESSIONDESC2 structure returned by IDirectPlay4::EnumSessions will have the DPSESSION_SECURESERVER flag set. This tells the client that authentication credentials will be required to join the session. If the client attempts to join the session using IDirectPlay4::Open, the security package may allow the user in if the user's credentials were already established through a system log on. Otherwise, a DPERR_LOGONDENIED error is returned. The application must then collect credentials from the user, put them in a DPCREDENTIALS structure, and try to join the session again by calling IDirectPlay4::SecureOpen, passing in the DPCREDENTIALS structure. SecureOpen is recommended for security.

[Visual Basic]

Creating a secure DirectPlay session simply requires the server application to set the DPSESSION_SECURESERVER flag in the DirectPlaySessionData object passed to DirectPlay4.Open or DirectPlay4.SecureOpen. Open can be used to create a session that uses the default security package and does not require authentication at the time when clients join the session.

A DirectPlay application can choose to use alternate providers when it creates a session by calling the SecureOpen method and specifying the providers to use in the DPSECURITYDESC type. For a different SSPI provider (for user and message authentication), an application needs to specify the provider name in the strSSPIProvider member of the DPSECURITYDESC type. For a different CryptoAPI provider (for message privacy), an application needs to specify the provider name, provider type, and encryption algorithm in the strCAPIProvider, lCAPIProviderType, and lEncryptionAlgorithm members respectively.

When a client enumerates this session, the DirectPlaySessionData object returned by DirectPlayEnumSessions.GetItem will have the DPSESSION_SECURESERVER flag set. This tells the client that authentication credentials will be required to join the session. If the client attempts to join the session using DirectPlay4.Open, the security package may allow the user in if the user's credentials were already established through a system log on. Otherwise, a DPERR_LOGONDENIED error is returned. The application must then collect credentials from the user, put them in a DPCREDENTIALS type, and try to join the session again by calling DirectPlay4.SecureOpen, passing in the DPCREDENTIALS type.

Within a secure session, all DirectPlay system messages are digitally signed to verify the identity of the sender. Certain system messages that carry sensitive information are encrypted. System messages that originate from one player and need to be broadcast to all the other players in the session are first sent to the server. The server then puts its signature on the message and forwards the message to all the other computers in the session. By default, player-to-player messages are not signed and are not routed through the server.

An application can choose to sign or encrypt specific player-to-player messages by setting the DPSEND_SIGNED and DPSEND_ENCRYPTED flags when the message is sent. Signed and encrypted player messages are routed through the server and delivered as secure system messages. When a secure message is received by a player, the message will contain flags indicating whether the message came in signed or encrypted. Messages that do not pass the verification are dropped.


Migrating from Previous Versions of DirectX

DirectX SDK

Migrating from Previous Versions of DirectPlay

[Visual Basic]

The information in this topic pertains only to applications developed in C++.

[C++]

The current version of the DirectPlay API is fully compatible with applications written for any previous version of DirectX. That is, you can recompile your application for the current version of DirectX without making any changes to the code. However, you will probably want to revise your code to take advantage of new features.

For specific information, see:

  • Migrating from DirectX 3.0 or Later
  • Migrating from DirectX 2.0


Migrating from DirectX 3.0 or Later

[Visual Basic]

The information in this topic pertains only to applications developed in C++.

[C++]

If you are migrating to the current version of DirectPlay from the version that was part of DirectX version 3.0 or later, you do not have to make any changes. However, you should upgrade your application to use the new IDirectPlay4 or IDirectPlay4A interfaces.

Some system messages were changed in DirectX 6.0, with new data members added to the end. These new members are continued in the current version. Applications that need to be backward-compatible with older run-time files should do one of the following:

  • Compile with the DirectX 3.0 header files and libraries.
  • Avoid any references to new data members.
  • Test with both the DirectX 3.0 and the current run-time file.

The system message structures that had new members added for version 5.0 were:

Structure | New members
DPMSG_CREATEPLAYERORGROUP | DPID dpIdParent
 | DWORD dwFlags
DPMSG_DESTROYPLAYERORGROUP | DPNAME dpnName
 | DPID dpIdParent
 | DWORD dwFlags


Migrating from DirectX 2.0

[Visual Basic]

The information in this topic pertains only to applications developed in C++.

[C++]

The names of the DirectPlay DLLs in DirectX version 3.0 and later are different from those in previous versions. Applications compiled with DirectX 2.0 or earlier do not use the new DirectPlay DLLs. To use the new DLLs, the application must be recompiled and linked to the Dplayx.lib import library.

It is also recommended that you add the code necessary to make the application lobby-aware. This means that an external lobby or matchmaking program can start the application and supply it with all the information necessary to connect to a session. The application need not ask the user to decide on a service provider, select a session, or supply any other information (such as a telephone number or network address).

In addition, several other new features were added to DirectPlay in DirectX version 6.0. The new features include:

  • Guaranteed messaging.
  • Asynchronous messaging.
  • Message throttling.
  • Firewall support.
  • Lobby improvements.
  • Security improvements.
  • Improved localization support.
  • APIs to register and unregister applications.
  • Better management of group ownership.
  • Improved keep-alive support.
  • Private service providers.

To migrate an application created with DirectPlay version 2.0 or earlier, carry out the following steps:

Find out if your application was launched from a lobby client. For more information, see Step 2: Retrieve the Connection Settings.

If your application is enumerating service providers, use the DirectPlay4::EnumConnections method to determine if a service provider is available. If so, call the DirectPlay4::InitializeConnection method on the service provider. If InitializeConnection returns an error, the service provider cannot run on the system, and you should not add that service provider to the list to show to the user. If the call succeeds, use the Release method to release the DirectPlay object and add the service provider to the list.

Call the QueryInterface method on the IDirectPlay interface to obtain an IDirectPlay4 (Unicode) or IDirectPlay4A (ANSI) interface. The only difference between the two interfaces is how strings in the structures are read and written. For the Unicode interface, Unicode strings are read and written to the member of the structure that is of the LPWSTR type. For the ANSI interface, ANSI strings are read and written to the member of the structure that is of the LPSTR type.

Make all the changes necessary to use the new structures in existing APIs. For example, instead of the following:

lpDP->SetPlayerName(pidPlayer, lpszFriendlyName, lpszFormalName)

where lpDP is an IDirectPlay interface, use the following:

DPNAME PlayerName, *lpPlayerName
PlayerName.dwSize = sizeof(DPNAME)
lpPlayerName = &PlayerName

lpPlayerName->lpszShortNameA = lpszFriendlyName
lpPlayerName->lpszLongNameA = lpszFormalName
lpDP4A->SetPlayerName(pidPlayer, lpPlayerName, 0)

where lpDP4A is an IDirectPlay4A interface. If the application is using Unicode strings (and therefore creates an instance of the IDirectPlay4 interface), use the following:

lpPlayerName->lpszShortName = lpwszFriendlyName
lpPlayerName->lpszLongName = lpwszFormalName
lpDP4->SetPlayerName(pidPlayer, lpPlayerName, 0)

where lpDP4 is an IDirectPlay4 interface.

Update the following system messages:

DPSYS_ADDPLAYER has been replaced by DPSYS_CREATEPLAYERORGROUP.

DPSYS_DELETEPLAYER and DPSYS_DELETEGROUP have been combined in a single DPSYS_DESTROYPLAYERORGROUP message.

DPSYS_DELETEPLAYERFROMGRP has been changed to DPSYS_DELETEPLAYERFROMGROUP.

Update your application to generate a DPSYS_SETPLAYERORGROUPNAME message when a player or group name changes, and a DPSYS_SETPLAYERORGROUPDATA message when the player or group data changes.

Update the DPSESSIONDESC structure to DPSESSIONDESC2, and add the new members to the DPCAPS structure.

Update the callback functions for IDirectPlay4::EnumSessions, IDirectPlay4::EnumGroups, IDirectPlay4::EnumGroupPlayers, and IDirectPlay4::EnumPlayers.

Update the manner in which the hEvent parameter is supplied to the IDirectPlay4::CreatePlayer method. In previous versions of DirectPlay, this parameter was lpEvent. DirectPlay does not return an event instead, the application must create it. This allows the application the flexibility of creating one event for all the players.

Set the DPSESSION_KEEPALIVE flag in the DPSESSIONDESC2 structure if the application needs DirectPlay to detect when players drop out of the game abnormally.

Update your application to create sessions with the DPSESSION_MIGRATEHOST flag. This enables another computer to become the host if the current host drops out of the session. If your application has any special code that only the host runs, then your application should set this flag when it creates a session. It should also add support for the DPSYS_HOST system message. For a list of system messages, see Using System Messages.

Become familiar with the new methods of the IDirectPlay4 interface and use them in your application. You might be able to substitute the code where you broadcast player state information to all the other players by using the IDirectPlay4::SendEx and IDirectPlay4::Receive methods.


DirectPlay Tutorials

This section contains tutorials demonstrating how to implement DirectPlay functionality in an application. The tutorials are divided by language into the following groups:

  • DirectPlay C/C++ Tutorials
  • DirectPlay Visual Basic Tutorials


DirectPlay C/C++ Tutorials

[Visual Basic]

The information in this section pertains only to applications written in C++. See DirectPlay Visual Basic Tutorials.

[C++]

This section contains the following tutorials that provide step-by-step instructions for implementing DirectPlay.

  • Tutorial 1: Connecting by Using the Lobby (DPChat)
  • Tutorial 2: Connecting by Using a Dialog Box (DPChat)
  • Tutorial 3: Overriding the Service Provider Dialogs
  • Tutorial 4: Creating Self-Refreshing Session Lists

Note The sample code in these tutorials is written in C++. If you are using a C compiler, you must make the appropriate changes to the files for them to successfully compile. For more information, see Accessing COM Objects by Using C.


Tutorial 1: Connecting by Using the Lobby

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectPlay Visual Basic Tutorials.

[C++]

An application written to use the IDirectPlayLobby3 interface can be connected to a session without requiring the user to manually enter connection information in a dialog box. To demonstrate how to create a lobbied application, the SimpleConnect Sample performs the following steps:

  • Step 1: Create a DirectPlayLobby Object
  • Step 2: Retrieve the Connection Settings
  • Step 3: Configure the Session Description
  • Step 4: Connect to a Session
  • Step 5: Create a Player


Step 1: Create a DirectPlayLobby Object

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectPlay Visual Basic Tutorials.

[C++]

To use a DirectPlay lobby, you first create an instance of a DirectPlayLobby object by calling CoCreateInstance. The following example shows one way to create a DirectPlayLobby object:

// Create an IDirectPlayLobby3A interface.
if ( FAILED( hr = CoCreateInstance( CLSID_DirectPlayLobby, NULL,
        CLSCTX_INPROC_SERVER,
        IID_IDirectPlayLobby3A,
        (VOID**)&g_pDPLobby ) ) )
    return hr;

Next: Step 2: Retrieve the Connection Settings


Step 2: Retrieve the Connection Settings

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectPlay Visual Basic Tutorials.

[C++]

After the DirectPlayLobby object has been created, use the IDirectPlayLobby3::GetConnectionSettings method to retrieve the connection settings returned from the lobby. If this method returns DPERR_NOTLOBBIED, the lobby did not start this application, and the user will have to configure the connection manually. If any other error occurs, your application should report an error that indicates that lobbying the application failed.

The following example shows how to retrieve the connection settings:

// Get connection settings from the lobby (into g_pdplConnection).
hr = g_pDPLobby->GetConnectionSettings( 0, NULL, &dwSize );
if ( FAILED(hr) && (DPERR_BUFFERTOOSMALL != hr) )
{
    if( DPERR_NOTLOBBIED == hr )
    {
        *pbLaunchedByLobby = FALSE;

        // Clean up since we were not launched from the lobby.
        SAFE_DELETE_ARRAY( g_pDPLConnection );
        SAFE_RELEASE( g_pDPLobby );

        return S_OK;
    }

    return hr;
}

// Allocate memory for the connection.
SAFE_DELETE_ARRAY( g_pDPLConnection );
g_pDPLConnection = (DPLCONNECTION*)new BYTE[ dwSize ];

// Get the connection settings.
if ( FAILED( hr = g_pDPLobby->GetConnectionSettings(
         0, g_pDPLConnection, &dwSize ) ) )
    return hr;

Next: Step 3: Configure the Session Description


Step 3: Configure the Session Description

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectPlay Visual Basic Tutorials.

[C++]

You should examine the DPSESSIONDESC2 structure to ensure that all the flags and properties that your application needs are set properly. If modifications are necessary, store the modified connection settings by using the IDirectPlayLobby3::SetConnectionSettings method.

The following example shows how to configure the session description and set the connection settings:

// Set our session flags
g_pDPLConnection->lpSessionDesc->dwFlags =
        DPSESSION_KEEPALIVE | DPSESSION_MIGRATEHOST;

// Let lobby know our connection flags
if ( FAILED( hr = g_pDPLobby->SetConnectionSettings(
        0, 0, g_pDPLConnection ) ) )
    return hr;

Next: Step 4: Connect to a Session


Step 4: Connect to a Session

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectPlay Visual Basic Tutorials.

[C++]

After the session description is properly configured, your application can use the IDirectPlayLobby3::ConnectEx method to start and connect itself to a session. If this method returns DP_OK, you can create one or more players. If it returns DPERR_NOTLOBBIED, the user will have to manually select a communication medium for your application. (You can identify the service providers installed on the system by using the IDirectPlay4::EnumConnections method.) If any other error value is returned, your application should report an error that indicates that lobbying the application failed.

The following example shows how to connect to a session:

if ( FAILED( hr = g_pDPLobby->ConnectEx( 0, IID_IDirectPlay4A,
        (VOID**)&g_pDP, NULL ) ) )
    return hr;

Next: Step 5: Create a Player


Step 5: Create a Player

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectPlay Visual Basic Tutorials.

[C++]

If the application was successfully started by using the IDirectPlayLobby3::ConnectEx method, it can now create one or more players. It can use the IDirectPlay4::CreatePlayer method to create a player with the name specified in the DPNAME structure (which was filled in by the IDirectPlayLobby3::GetConnectionSettings method).

The following example shows how to create a player:

DPNAME dpname;
ZeroMemory( &dpname, sizeof(DPNAME) );
dpname.dwSize  = sizeof(DPNAME);
dpname.lpszShortNameA = g_strLocalPlayerName;

if ( FAILED( hr = g_pDP->CreatePlayer( &g_LocalPlayerDPID, &dpname,
        NULL, NULL, 0, 0 ) ) )
    return hr;

Now your application is connected and you are ready to play.


Tutorial 2: Connecting by Using a Dialog Box

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectPlay Visual Basic Tutorials.

[C++]

If a lobby did not start your application, you should include code that allows the user to manually enter the connection information. To demonstrate how to manually connect to the session and create one or more players, the SimpleConnect Sample performs the following steps:

  • Step 1: Create the DirectPlay Object
  • Step 2: Enumerate and Initialize the Service Providers
  • Step 3: Join a Session
  • Step 4: Create a Session
  • Step 5: Create a New Player


Step 1: Create the DirectPlay Object

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectPlay Visual Basic Tutorials.

[C++]

Before any methods can be called, the application must obtain an interface to a DirectPlay object.

The following example shows how to obtain the IDirectPlay4 interface:

if ( FAILED( hr = CoCreateInstance( CLSID_DirectPlay, NULL,
        CLSCTX_ALL, IID_IDirectPlay4A, (VOID**)&g_pDP ) ) )
    return hr;

Next: Step 2: Enumerate and Initialize the Service Providers


Step 2: Enumerate and Initialize the Service Providers

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectPlay Visual Basic Tutorials.

[C++]

The next step in creating a manual connection is to request that the user select a communication medium for the application. Your application can identify the service providers installed on a personal computer by using the EnumConnections method.

The following example shows how to enumerate the service providers:

// Enumerate all DirectPlay connections and store them
// in the listbox
if ( FAILED( hr = pDP->EnumConnections( &g_AppGUID,
        DPConnect_EnumConnectionsCallback, hWndListBox, 0 ) ) )
{
    SAFE_RELEASE( pDP );
    return hr;
}

The second parameter in the EnumConnections method is a callback that enumerates service providers registered with DirectPlay. The following example shows how the SimpleConnect Sample implements this callback function:

BOOL FAR PASCAL DPConnect_EnumConnectionsCallback(
        LPCGUID   pguidSP,
        VOID*     pConnection,
        DWORD     dwConnectionSize,
        LPCDPNAME pName,
        DWORD     dwFlags,
        VOID*     pvContext )
{
    HRESULT       hr;
    LPDIRECTPLAY4 pDP = NULL;
    VOID*         pConnectionBuffer = NULL;
    HWND          hWndListBox = (HWND)pvContext;
    LRESULT       iIndex;

    // Create a IDirectPlay object.
    if ( FAILED( hr = CoCreateInstance( CLSID_DirectPlay, NULL,
            CLSCTX_ALL, IID_IDirectPlay4A, (VOID**)&pDP ) ) )
            return FALSE; // Error, stop enumerating

    // Test the if the connection is available
    // by attempting to initialize.
        // the connection
    if( FAILED( hr = pDP->InitializeConnection( pConnection, 0 ) ) )
    {
        SAFE_RELEASE( pDP );
        return TRUE; // Unavailable connection, keep enumerating
    }

    // Don't need the IDirectPlay interface any more, so release it.
    SAFE_RELEASE( pDP );

    // Found a good connection, so put it in the listbox.
    iIndex = SendMessage( hWndListBox, LB_ADDSTRING, 0,
            (LPARAM)pName->lpszShortNameA );
    if( iIndex == CB_ERR )
        return FALSE; // Error, stop enumerating

    pConnectionBuffer = new BYTE[ dwConnectionSize ];
    if( pConnectionBuffer == NULL )
        return FALSE; // Error, stop enumerating

    // Store pointer to GUID in listbox.
    memcpy( pConnectionBuffer, pConnection, dwConnectionSize );
    SendMessage( hWndListBox, LB_SETITEMDATA, iIndex,
            (LPARAM)pConnectionBuffer );

    return TRUE; // Keep enumerating
}

Once the user selects which connection to use, you need to retrieve the connection data that comes back with the enumeration, and initialize the DirectPlay object with this data.

if ( FAILED( hr = g_pDP->InitializeConnection( pConnection, 0 ) ) )
    return hr;

Next: Step 3: Join a Session


Step 3: Join a Session

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectPlay Visual Basic Tutorials.

[C++]

If the user wants to join an existing session, enumerate the available sessions by using the IDirectPlay4::EnumSessions method, present the choices to the user, and then connect to that session by using the IDirectPlay4::Open method, specifying the DPOPEN_JOIN flag. The service provider might display a dialog box requesting some information from the user before it can enumerate the sessions.

See Tutorial 4 for details on the asynchronous EnumSessions functionality.

The following example shows how to enumerate the available sessions:

// Enum sessions and let DirectPlay decide the timeout.
ZeroMemory( &dpsd, sizeof(dpsd) );
dpsd.dwSize          = sizeof(dpsd);
dpsd.guidApplication = g_AppGUID;

// Enumerate all the active DirectPlay games
//  on the selected connection.
hr = g_pDP->EnumSessions( &dpsd, 0,
        DPConnect_EnumSessionsCallback, NULL,
        DPENUMSESSIONS_ALL | DPENUMSESSIONS_ASYNC );

The third parameter in the IDirectPlay4::EnumSessions method is a callback that enumerates the available sessions. The following code shows how the SimpleConnect Sample implements this callback function:

BOOL FAR PASCAL DPConnect_EnumSessionsCallback(
        LPCDPSESSIONDESC2 pdpsd,
        DWORD*            pdwTimeout,
        DWORD             dwFlags,
        VOID*             pvContext )
{
    DPSessionInfo* pDPSINew = NULL;

    if ( dwFlags & DPESC_TIMEDOUT )
        return FALSE; // Timed out, so stop the enumeration.

    // Found a good session, save it.
    pDPSINew = new DPSessionInfo;
    if ( NULL == pDPSINew )
        return FALSE;

    ZeroMemory( pDPSINew, sizeof(DPSessionInfo) );

    // Copy the information into pDPSINew.
    pDPSINew->guidSession = pdpsd->guidInstance;
    sprintf( pDPSINew->szSession, "%s (%d/%d)",
            pdpsd->lpszSessionNameA,
            pdpsd->dwCurrentPlayers,
            pdpsd->dwMaxPlayers );

    // Add pDPSINew to the circular linked list, g_pDPSIFirst.
    pDPSINew->pDPSINext = g_DPSIHead.pDPSINext;
    g_DPSIHead.pDPSINext = pDPSINew;

    return TRUE;
}

After the user has selected a session, your application can allow the user to join an existing session. The following example shows how to join an existing session:

// Set up the DPSESSIONDESC2, and get the session GUID from
// the selected listbox item.
ZeroMemory( &dpsd, sizeof(dpsd) );
dpsd.dwSize          = sizeof(dpsd);
dpsd.guidInstance    = pDPSISelected->guidSession;
dpsd.guidApplication = g_AppGUID;

// Join the session
g_bHostPlayer = FALSE;
if ( FAILED( hr = g_pDP->Open( &dpsd, DPOPEN_JOIN ) ) )
    return hr;

Next: Step 4: Create a Session


Step 4: Create a Session

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectPlay Visual Basic Tutorials.

[C++]

If the user wants to create a new session, your application can create it by using the IDirectPlay4::Open method and specifying the DPOPEN_CREATE flag. Again, the service provider might display a dialog box requesting information from the user before it can create the session.

The following example shows how to create a new session:

ZeroMemory( &dpsd, sizeof(dpsd) );
dpsd.dwSize           = sizeof(dpsd);
dpsd.guidApplication  = g_AppGUID;
dpsd.lpszSessionNameA = g_strSessionName;
dpsd.dwMaxPlayers     = 10;
// The DPSESSION_KEEPALIVE flag keeps the session alive
//  if players abnormally exit.
dpsd.dwFlags          = DPSESSION_KEEPALIVE | DPSESSION_MIGRATEHOST;
if ( g_bUseProtocol )
    dpsd.dwFlags |= DPSESSION_DIRECTPLAYPROTOCOL;

// Create a new session.
g_bHostPlayer = TRUE;
if ( FAILED( hr = g_pDP->Open( &dpsd, DPOPEN_CREATE ) ) )
    return hr;

Next: Step 5: Create a New Player


Step 5: Create a New Player

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectPlay Visual Basic Tutorials.

[C++]

After a session has been created or joined, your application can create one or more players by using the IDirectPlay4::CreatePlayer method. The following code shows how this is done in the SimpleConnect Sample.

DPNAME dpname;
ZeroMemory( &dpname, sizeof(DPNAME) );
dpname.dwSize         = sizeof(DPNAME);
dpname.lpszShortNameA = g_strLocalPlayerName;

if ( FAILED( hr = g_pDP->CreatePlayer( &g_LocalPlayerDPID, &dpname,
        NULL, NULL, 0, 0 ) ) )
    return hr;

Your application can determine a player's communication capabilities by using the IDirectPlay4::GetCaps and IDirectPlay4::GetPlayerCaps methods. Your application can find other players by using the IDirectPlay4::EnumPlayers method.

Now your application is connected and you are ready to play.


Tutorial 3: Overriding the Service Provider Dialogs

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectPlay Visual Basic Tutorials.

[C++]

DirectPlay now gives applications the ability to suppress the standard service provider dialogs. The following is a brief outline of how this is done. A code example can be found in the Override sample application.

It is generally not possible to suppress all service provider dialogs. The standard TCP/IP, modem, and serial service provider dialogs can be suppressed (IPX has no dialog box). However, there is the possibility that third party service providers might require fairly complex information from the user which cannot be overridden in any general way. The solution is to simply allow these dialog boxes to appear over your application user interface. If the application is a DirectDraw® full-screen application, be sure to turn off page flipping before calling IDirectPlay4::EnumSessions or IDirectPlay4::Open to create a session.

Another way to suppress service provider dialog boxes is to make your application lobby-aware. Most third party service providers will also have a lobby from which to launch games, and games launched from a lobby do not display a connection dialog box.

An application first calls IDirectPlay4::EnumConnections to see which connections are available, presents the list to the user, and allows the user to select one. Once the user has selected one, the application can attempt to override the dialog box before calling IDirectPlay4::EnumSessions or IDirectPlay4::Open.

These are the steps you should follow to suppress service provider dialog boxes:

Examine the service provider GUID of the selected service provider to see if it matches one of the known service providers that the application knows how to override. If the service provider GUID is unknown, then skip the remaining steps and be prepared to allow a dialog box to appear.

Display the appropriate user interface to collect the information needed from the user for that specific service provider. IPX requires no information. TCP/IP requires an IP address for EnumSessions (DPAID_INet or DPAID_INetW), but requires nothing to create a session using Open. Modem-to-modem requires the user to select a modem (DPAID_Modem or DPAID_ModemW) and also needs a phone number (DPAID_Phone or DPAID_PhoneW) when calling EnumSessions. Serial link needs the DPCOMPORTADDRESS structure (DPAID_ComPort) filled in to configure the COM port for both EnumSessions and Open.

Build a DirectPlay Address using the IDirectPlayLobby3::CreateCompoundAddress method. The address elements that must be passed in are the service provider GUID (DPAID_ServiceProvider) and the individual address components for the selected service provider.

Initialize the DirectPlay object by calling InitializeConnection with the DirectPlay Address.

Call EnumSessions with the DPENUMSESSIONS_RETURNSTATUS flag. This will prevent any status dialog boxes from appearing and, if the connection cannot be made immediately, EnumSessions will return with a DPERR_CONNECTING error. Your application must periodically call EnumSessions until DP_OK is returned (meaning the enumeration was successful) or some other error is returned (meaning it failed).

If a session is to be created using the Open method with DPOPEN_CREATE, specify the DPOPEN_RETURNSTATUS flag as well. Like DPENUMSESSIONS_RETURNSTATUS, this will suppress status dialog boxes and return DPERR_CONNECTING until the function is complete.

Note In some cases, the application will need to query the service provider at run time to obtain a list of valid choices for a particular DirectPlay Address element. For example, to obtain a list of the modems installed in the system. The application must create a separate DirectPlay object, initialize the modem service provider, and then call IDirectPlay4::GetPlayerAddress with a DirectPlay ID of zero to obtain a DirectPlay Address that will contain the list of modems. After releasing the DirectPlay object, the application must parse the address using IDirectPlayLobby3::EnumAddress and extract the modem list to present to the user.


Tutorial 4: Creating Self-Refreshing Session Lists

DirectX SDK

Tutorial 4: Create Self-Refreshing Session Lists

[Visual Basic]

This tutorial pertains only to applications written in C++. See DirectPlay Visual Basic Tutorials.

[C++]

An application can maintain a self-refreshing session list by calling IDirectPlay4::EnumSessions asynchronously. This technique is used in five of the DirectPlay samples: Bellhop, DPChat, DPSlots, Duel, and Override. You can find a code example in any of these sample applications.

The steps you need to follow to create a self-refreshing session list are as follows:

  1. Call IDirectPlay4::EnumSessions with the DPENUMSESSIONS_ASYNC flag and a time-out of zero (which will use the service provider default). The method will not enumerate any sessions and will return immediately. However, DirectPlay is enumerating sessions in the background.
  2. Display the user interface in which all the sessions will appear. Set a timer to go off at whatever interval you want to refresh your session list. The application can find out what the default time-out interval of the enumeration is by calling IDirectPlay4::GetCaps.
  3. Each time the timer goes off, call EnumSessions to obtain the current session list. This is a complete active session list with stale sessions deleted, new sessions added, and existing sessions updated. Delete all the items from the list before calling EnumSessions and add the sessions back to the list in the EnumSessionsCallback2 function.
  4. Check the error result returned by EnumSessions and stop the timer if an error other than DPERR_CONNECTING is returned. It is possible for the connection to be lost or canceled by the user.


DirectPlay Visual Basic Tutorials

[C++]

The information in this section pertains only to applications written in Visual Basic. See DirectPlay C/C++ Tutorials.

[Visual Basic]

This section contains the following tutorials demonstrating how to implement DirectPlay in a Visual Basic application:

  • Tutorial 1: Creating a Simple Network Game
  • Tutorial 2: Supporting Lobby Launch


Tutorial 1: Creating a Simple Network Game

[C++]

This tutorial pertains only to applications written in Visual Basic. See DirectPlay C/C++ Tutorials

[Visual Basic]

This tutorial covers the essential steps in writing a DirectPlay application using DirectX for Visual Basic. The example code is based on the Memory sample application.

The tutorial is divided into the following steps:

  • Step 1: Initialize DirectPlay and Enumerate Providers
  • Step 2: Initialize the Connection and Enumerate Sessions
  • Step 3: Create or Join a Session
  • Step 4: Create a Player
  • Step 5: Start the Game and Exchange Messages


Step 1: Initialize DirectPlay and Enumerate Providers

[C++]

This tutorial pertains only to applications written in Visual Basic. See DirectPlay C/C++ Tutorials

[Visual Basic]

The first step toward implementing DirectPlay in any application is to create a DirectPlay4 object and enumerate the available connections, or service providers. After some global declarations, the Memory sample takes these steps in the InitDPlay procedure:

Public gObjDX As New DirectX7
Public gObjDPlay As DirectPlay4
Public gObjEnumConnections As DirectPlayEnumConnections

Public Sub InitDPlay()

  On Error GoTo FAILED
  Set gObjDPlay = gObjDX.DirectPlayCreate("")
  Set gObjEnumConnections = gObjDPlay.GetDPEnumConnections( _
          "", DPCONNECTION_DIRECTPLAY)
  Exit Sub

FAILED:
  MsgBox ("Failed to initialize DirectPlay.")
  End
End Sub

The call to DirectPlay4.GetDPEnumConnections builds a collection of service providers. An empty string is passed in as the guid parameter. You would pass the application GUID only if you were looking for a service provider specifically designed for your application. The DP_CONNECTION_DIRECTPLAY flag indicates that the application is not interested in lobby providers.

The InitDPlay procedure is called from the InitConnectionList function, which then goes on to populate a list box with the available service providers. The complete function follows:

Public Function InitConnectionList() As Boolean

  Dim NumConnections As Long
  Dim strName As String
  Dim X As Long

  Call InitDPlay     ' Program aborts on failure

  lstConnections.Clear

  On Error GoTo FAILED
  NumConnections = gObjEnumConnections.GetCount
  For X = 1 To NumConnections
    strName = gObjEnumConnections.GetName(X)
    Call lstConnections.AddItem(strName)
  Next X

  ' Initialize selection
  lstConnections.ListIndex = 0
  InitConnectionList = True
  Exit Function

  ' Error handlers
FAILED:
  InitConnectionList = False
  Exit Function

End Function

Note that the DirectPlayEnumConnections collection is 1-based, like other enumeration collections in DirectX for Visual Basic.

Next: Step 2: Initialize the Connection and Enumerate Sessions


Step 2: Initialize the Connection and Enumerate Sessions

[C++]

This tutorial pertains only to applications written in Visual Basic. See DirectPlay C/C++ Tutorials

[Visual Basic]

When the user has chosen a service provider and player name in the Multiple Player dialog and clicked OK, the Memory application initializes the selected connection. DirectPlay4.InitializeConnection binds the connection to DirectPlay, so that subsequent method calls go to that connection, but it does not actually establish the physical connection. That is done when sessions are enumerated.

When an attempt is made to enumerate sessions on the connection, some service providers (such as the modem service provider) present dialog boxes asking for further information in order to establish the physical connection. If users wish to create a new game rather than joining an existing one, they can simply cancel out of these dialogs.

Memory attempts to enumerate sessions even though the user might not be interested in viewing existing sessions but would rather go directly to creating a new one. In your application you might want to do things differently and not call DirectPlay4.GetDPEnumSessions unless the user requests a list of existing sessions. Not calling this method can simplify things for users in certain cases. For example, the modem service provider has two separate dialog boxes, one for dialing and one for answering. A player creating a new game is not interested in the dialing prompt, because the host of a modem game always waits for the other player to call in. Skipping session enumeration and going straight to DirectPlay4.Open will ensure that the host never has to see the dialing prompt.

The following procedure in frmMultiplayer initializes the selected connection and puts any available sessions in a list box to be displayed in the next dialog box:

Private Sub cmdOK_Click()

  Dim CIndex As Long
  Dim ConnectionMade As Boolean
  Dim objDPAddress As DirectPlayAddress

  CIndex = lstConnections.ListIndex + 1

Remember, enumeration collections are 1-based, but lists in list boxes are 0-based, so the index into the collection has to be adjusted.

The application now gets the DirectPlay address for the connection and initializes it:

  On Error GoTo INITIALIZEFAILED
  Set objDPAddress = gObjEnumConnections.GetAddress(CIndex)
  Call gObjDPlay.InitializeConnection(objDPAddress)
  On Error GoTo 0

The next call is discussed in more detail later.

  ConnectionMade = frmSessions.UpdateSessionList

The form is then closed, and the user is shown a new one that contains the list of sessions as well as buttons allowing the user to join or create a session.

  If ConnectionMade Then
    Hide
    frmSessions.Show
  Else
    InitDPlay
  End If
  Exit Sub
  ' Error handlers

INITIALIZEFAILED:
  If Err.Number <> DPERR_ALREADYINITIALIZED Then
    MsgBox ("Failed to initialize connection.")
    Exit Sub
  End If

End Sub

Session enumeration is done in the following function, which is also used to update the session list as new sessions become available or old ones disappear:

Public Function UpdateSessionList() As Boolean

  Dim SessionCount As Integer
  Dim X As Integer
  Dim SessionData As DirectPlaySessionData
  Dim Details As String

  ' Delete the old list
  lstSessions.Clear

  Set SessionData = gObjDPlay.CreateSessionData

The DirectPlaySessionData object describes the sessions to be enumerated. Because Memory is not interested in sessions of other applications, it specifies its privately defined application GUID (in string form). If enumeration was to be restricted to sessions with a particular password, the password would also be set in the session description here.

  Call SessionData.SetGuidApplication(AppGuid)
  Call SessionData.SetSessionPassword("")

The call to DirectPlay4.GetDPEnumSessions specifies that only available sessions are wanted, not those that have reached their maximum number of players or otherwise can't be joined:

  On Error GoTo USERCANCEL
  Set gObjDPEnumSessions = gObjDPlay.GetDPEnumSessions(SessionData, _
          0, DPENUMSESSIONS_AVAILABLE)
  On Error GoTo 0

Note that the method fails if the user has canceled out of any service provider dialogs. The function assumes that the player might want to create a new session, so it does not treat this error as fatal.

If enumeration succeeds, the application now uses the DirectPlayEnumSessions object to extract information about each session, including its name, the current number of players, and the maximum number of players. This information is combined in a string that is then put in the list box:

  On Error GoTo ENUM_ERROR
  SessionCount = gObjDPEnumSessions.GetCount
  For X = 1 To SessionCount
    Set SessionData = gObjDPEnumSessions.GetItem(X)
    Details = SessionData.GetSessionName & " (" _
            & SessionData.GetCurrentPlayers _
            & "/" & SessionData.GetMaxPlayers & ")"
    Call lstSessions.AddItem(Details)
  Next X

The rest of the function, not shown here, updates the interface and handles errors.

Next: Step 3: Create or Join a Session


Step 3: Create or Join a Session

[C++]

This tutorial pertains only to applications written in Visual Basic. See DirectPlay C/C++ Tutorials

[Visual Basic]

On the frmSessions form of the Memory sample, the user has the choice of joining a listed session or creating a new one.

In both cases the procedure is the same: describe the session in a DirectPlaySessionData object, then pass this object to DirectPlay4.Open.

The following code, from the cmdCreate_Click method in frmCreateGame, creates a new game that will accept from two to four players, as specified by the choice of option buttons:

Dim SessionData As DirectPlaySessionData

Set SessionData = gObjDPlay.CreateSessionData
.
.
.
  ' Set number of players
If Option1.Value = True Then
    Call SessionData.SetMaxPlayers(2)
ElseIf Option2.Value = True Then
    Call SessionData.SetMaxPlayers(3)
Else
    Call SessionData.SetMaxPlayers(4)
End If

' Finish describing the session
Call SessionData.SetSessionName(txtGameName.Text)
Call SessionData.SetGuidApplication(AppGuid)
Call SessionData.SetFlags(DPSESSION_MIGRATEHOST)

' Create (and join) the session.
' Failure can result from the user cancelling out of the service
' provider dialog. In the case of the modem, this is the "answer"
' dialog.

  On Error GoTo FAILEDOPEN
  Call gObjDPlay.Open(SessionData, DPOPEN_CREATE)
.
.
.
End Sub

Joining a session is a bit simpler, because the application just has to retrieve the session description from the enumeration, as in the cmdJoin_Click method of frmSessions:

Dim SessionData As DirectPlaySessionData

Set SessionData = gObjDPEnumSessions.GetItem( _
        lstSessions.ListIndex + 1)
On Error GoTo NOSESSION
Call gObjDPlay.Open(SessionData, DPOPEN_JOIN)

Next: Step 4: Create a Player


Step 4: Create a Player

[C++]

This tutorial pertains only to applications written in Visual Basic. See DirectPlay C/C++ Tutorials

[Visual Basic]

The application is now part of an open session, but the user cannot participate until a player has been created.

This is a very simple step. The application passes a couple of names to DirectPlay4.CreatePlayer, and the method returns a unique numerical ID for the player. This ID is important because it identifies the player in messages. In Memory it is kept in the global variable gMyPlayerID.

In the Memory sample, the PlayerName string is the name supplied by the user. (A default string is retrieved from the system by a call to the Win32 GetUserName function.) The application uses this as a friendly name for the player. PlayerHandle can be used internally for other purposes but is not needed by Memory.

PlayerName = frmMultiplayer.txtYourName.Text
PlayerHandle = "Player"

On Error GoTo FAILEDCREATE
gMyPlayerID = gObjDPlay.CreatePlayer(PlayerName, PlayerHandle, 0, 0)

Next: Step 5: Start the Game and Exchange Messages


Step 5: Start the Game and Exchange Messages

[C++]

This tutorial pertains only to applications written in Visual Basic. See DirectPlay C/C++ Tutorials

[Visual Basic]

DirectPlay starts sending messages as soon as at least one player has joined the session. Each time a player joins or leaves the session, a system message is sent. In the Memory sample, this message triggers an update of the list of players in frmWaiting.

The manner in which the game (or other form of DirectPlay session) starts is entirely up to the application. As far as DirectPlay is concerned, a session is just a session, whether or not the application is sending messages to update the game state.

The Memory sample gives the host an opportunity to start the game when at least one other player has joined. When the host clicks the Start button, the application first disables joining so that the session is no longer available to new players:

Set SessionData = gObjDPlay.CreateSessionData
Call gObjDPlay.GetSessionDesc(SessionData)
Call SessionData.SetFlags(SessionData.GetFlags + _
        DPSESSION_JOINDISABLED)
Call gObjDPlay.SetSessionDesc(SessionData)

The application then generates a message that contains a type identifier, a list of the player IDs in the order in which they will play, and the arrangement of the tiles on the game board. In response to this message, other instances of the application update their information about the play order and game board. This message is an example of how players exchange information about the game state.

Data is first packed into the message by using the various write methods of DirectPlayMessage:

Dim dpMsg As DirectPlayMessage

Set dpMsg = gObjDPlay.CreateMessage

' Pack message type
Call dpMsg.WriteLong(MSG_SETUPBOARD)

' Pack number of players
Call dpMsg.WriteByte(gNumPlayers)

' Pack player IDs.
Dim PlayerID As Long
For X = 0 To gNumPlayers - 1
    PlayerID = objDPEnumPlayers.GetDPID(X + 1)
    dpMsg.WriteLong (PlayerID)
    ' Keep local copy of player IDs
    gPlayerIDs(X) = PlayerID
    ' Assign place in play order to the host
    If PlayerID = gMyPlayerID Then gMyTurn = X
Next X

' Pack tile arrangement
For X = 0 To NumCells - 1
    dpMsg.WriteByte (gPicArray(X))
Next X

Note that the host application instance needs to update its own game state here. An application instance doesn't receive any of the messages it sends, so this is the host's last chance to perform the updating that other instances will perform when they receive the message.

The application now sends the message to all the other players, using the DPSEND_GUARANTEED flag because it is essential that all other players receive this information. (Nonguaranteed messages would be appropriate for small changes in the state of a fast-moving action game.)

Call gObjDPlay.Send(gMyPlayerID, DPID_ALLPLAYERS, _
        DPSEND_GUARANTEED, dpMsg)

At the receiving end, the application looks for messages in the Sub Main procedure, relying on DoEvents to let other things happen while polling:

Do While DoEvents()
    GetDPMessages
Loop

In the GetDPMessages procedure, the application checks to see how many messages are pending:

Dim MsgCount As Long
MsgCount = gObjDPlay.GetMessageCount(gMyPlayerID)

It then retrieves each message in turn, encapsulating it in the DirectPlayMessage object dpMsg. It extracts the message type, which is always the first Long both in system messages and in messages defined by Memory.

Dim FromPlayerID As Long
Dim ToPlayerID As Long
Dim dpMsg As DirectPlayMessage
Dim MsgType As Long
' Some other declarations omitted; see GlobalModule.bas
.
.
.
Do While MsgCount > 0
    Set dpMsg = gObjDPlay.Receive(FromPlayerID, ToPlayerID, _
            DPRECEIVE_ALL)
    MsgType = dpMsg.ReadLong()

    MsgCount = MsgCount - 1

System messages are identified by DPSYS_MESSAGE in FromPlayerID. All others are application-defined. When Memory finds an application-defined message of type MSG_SETUPBOARD, it reads out the data in the same order as it was put in, and does a few more things to update the game state and allow play to begin:

    Select Case MsgType

        Case MSG_SETUPBOARD

          ' Number of players
          gNumPlayers = dpMsg.ReadByte

          ' Play IDs, in play order. Unused players have ID of 0.
          For X = 0 To gNumPlayers - 1
              gPlayerIDs(X) = dpMsg.ReadLong
              If gPlayerIDs(X) = gMyPlayerID Then gMyTurn = X
          Next X

          ' Tile arrangement
          For X = 0 To NumCells - 1
              gPicArray(X) = dpMsg.ReadByte
          Next X

          ' Show the game board.
          frmWaiting.Hide
          gGameUnderway = True
          frmGameBoard.Show
.
.
.
    End Select
.
.
.
Loop


Tutorial 2: Supporting Lobby Launch

This tutorial shows how an application can support external launching by a lobby and connection with a lobby-launched session. An application using these techniques can be launched either by a lobby or by the user, and will automatically join an application session created in the lobby.

For an overview of these topics, see Building Lobby-Aware Applications.

The tutorial is divided into the following steps:

  • Step 1: Register the Application
  • Step 2: Get Connection Settings
  • Step 3: Join the Session

The sample code is based on the Chat sample.


Step 1: Register the Application

In order for the application to be visible to the lobby client, it must be registered. You can register a lobbyable application by using the DirectXRegisterApplication C/C++ function in DirectSetup, or you can supply your own registration utility that uses the DirectPlayLobby3.RegisterApplication method. The following sample procedure registers DXVBChat.exe, which must be in the same folder as the registration application:

Dim dx As New DirectX7
Dim dpl As DirectPlayLobby3
Const AppGuid = "{EB5E7E20-0303-11d3-9AAB-00104BCC1EAA}"

Private Sub RegisterApp()

  Dim dpappdesc As DPAPPLICATIONDESC2
  Dim dpl as DirectPlayLobby3

  With dpappdesc
    .strApplicationName = "DXVBChat"
    .strCommandLine = ""
    .strCurrentDirectory = App.Path
    .strDescription = "Chat (DirectX for Visual Basic)"
    .strFilename = "DXVBChat.exe"
    .strGuid = AppGuid
    .strPath = App.Path
  End With

  On Local Error GoTo ERRORS

  Set dpl = dx.DirectPlayLobbyCreate
  Call dpl.RegisterApplication(dpappdesc)
  Exit Sub

ERRORS:
  MsgBox "Failed to register application."
  Unload Me

End Sub

The following procedure unregisters the same application:

Private Sub UnregisterApp()

  On Local Error GoTo FAILED
  Call dpl.UnregisterApplication(AppGuid)
  MsgBox "Unregistration successful."
  Exit Sub

FAILED:
  If Err.Number = DPERR_UNKNOWNAPPLICATION Then
    MsgBox "Application not registered."
  End If
  Unload Me

End Sub

Next: Step 2: Get Connection Settings


Step 2: Get Connection Settings

In this step you will initialize DirectPlay in your application and determine whether the application was launched from a lobby. If it was, you will retrieve connection settings immediately; otherwise you will wait for them.

First, create the DirectPlayLobby3 object, using the initialized DirectX7 object objDX:

Public Function InitDPlay() As Boolean

  InitDPlay = True

  On Local Error GoTo FAILED
  Set objDPLobby = objDX.DirectPlayLobbyCreate

Then call DirectPlayLobby3.GetConnectionSettings. If the application was launched in response to a call to DirectPlayLobby3.RunApplication in the lobby client, GetConnectionSettings should succeed. Otherwise it should return DPERR_NOTLOBBIED.

  On Local Error Resume Next
  Set objDPLConnection = objDPLobby.GetConnectionSettings(0)

  ' The app was launched by a lobby.
  If Err.Number = 0 Then GoTo GOTCONNECTION

If the application was not launched by a lobby, at this point you might want to give the user the option of starting a single-player game, or of connecting to a session through an internal lobby client. The sample application instead waits for a lobby connection. First it enters wait mode by calling DirectPlayLobby3.WaitForConnectionSettings. This step simply ensures that RunApplication will not launch another instance of the program but will make connection settings available to this one when the user starts or joins an open application session in the lobby client.

  On Local Error GoTo FAILED
  Call objDPLobby.WaitForConnectionSettings(DPLWAIT_DEFAULT)

The sample application now shows a dialog box that remains active until the connection is established or the user cancels:

  frmWaiting.Show
  Call WaitForConnectionMessage

This is where the application actually waits. The WaitForConnectionMessage function blocks until it receives a DPLSYS_NEWCONNECTIONSETTINGS message from the lobby, or until the user cancels:

Public Sub WaitForConnectionMessage()
  Dim msg As DirectPlayMessage
  Dim flags As Long
  Dim MsgType As Long

  On Local Error Resume Next
  gGotConnection = False
  Do While DoEvents
      Set msg = objDPLobby.ReceiveLobbyMessage(0, flags)
      If Not (msg Is Nothing) Then
        MsgType = msg.ReadLong
        If MsgType = DPLSYS_NEWCONNECTIONSETTINGS Then
          gGotConnection = True
          Exit Do
        End If
      End If
  Loop
  Exit Sub
End Sub

Note that in the sample application, this function returns False when the user cancels out of the dialog, because there are no other visible forms and DoEvents returns False. An application with another visible form would have to use some other means of breaking out of the loop in the event of a user cancel.

Back in the calling procedure, if DPLSYS_NEWCONNECTIONSETTINGS was received, the status dialog is closed and the DirectPlayLobbyConnection object is retrieved:

  If gGotConnection Then
    frmWaiting.Hide
    Set objDPLConnection = objDPLobby.GetConnectionSettings(0)
  Else
    GoTo FAILED  ' User cancelled
  End If

Next: Step 3: Join the Session


Step 3: Join the Session

At this point the two code branches—lobby launch and user launch—converge. The program has retrieved the connection settings from the lobby and can proceed to connect the application session to a local DirectPlay4 object, represented here by objDPlay:

GOTCONNECTION:
  On Local Error GoTo FAILED
  Set objDPlay = objDPLobby.Connect(0)

Now the application can get whatever information it needs about the session and can create a player based on the information in the connection data:

  ' The following were declared globally:
  ' Dim objDPSessionData as DirectPlaySessionData
  ' Dim gMyPlayerName As String
  ' Dim gMyPlayerID As Long

  Set objDPSessionData = objDPLConnection.GetSessionDesc
  ' The session data includes the name of the session, number
  ' of players, and so on, all of which was set in the staging area.

  gMyPlayerName = objDPLConnection.GetPlayerShortName
  gMyPlayerID = objDPlay.CreatePlayer(gMyPlayerName, "PLAYER", _
          0, DPPLAYER_DEFAULT)
  Exit Function

Now everything is in place for the player to begin sending and receiving messages.

If anything has gone awry, the error handler sets the return value of InitDPlay to False and the application can exit gracefully:

FAILED:
  InitDPlay = False

End Function


DirectPlay Reference

This section contains reference information for the application programming interface (API) elements provided by DirectPlay® in C/C++ and Visual Basic®. Reference material is organized by language:

  • DirectPlay C/C++ Reference
  • DirectPlay Visual Basic Reference


DirectPlay C/C++ Reference

Reference material for the DirectPlay C/C++ application programming interface is divided into the following categories:

  • Interfaces
  • Functions
  • Callback Functions
  • Structures
  • System Messages
  • Standard Lobby Messages
  • DirectPlay Defined Properties
  • Return Values


Interfaces

This section contains references for methods of the following DirectPlay interfaces:

  • IDirectPlay4
  • IDirectPlayLobby3


IDirectPlay4

Applications use the methods of the IDirectPlay4 interface to create DirectPlay objects and work with system-level variables. (The IDirectPlay4A interface is the same as the IDirectPlay4 interface, except that IDirectPlay4A uses ANSI characters, and IDirectPlay4 uses Unicode.)

The methods of the IDirectPlay4 interface can be organized into the following groups.

Session management | Close
 | EnumConnections
 | EnumSessions
 | GetCaps
 | GetGroupConnectionSettings
 | GetSessionDesc
 | InitializeConnection
 | Open
 | SecureOpen
 | SetGroupConnectionSettings
 | SetSessionDesc
 | StartSession
Player management | CreatePlayer
 | DestroyPlayer
 | EnumPlayers
 | GetPlayerAccount
 | GetPlayerAddress
 | GetPlayerCaps
 | GetPlayerData
 | GetPlayerFlags
 | GetPlayerName
 | SetPlayerData
 | SetPlayerName
Message management | CancelMessage
 | CancelPriority
 | GetMessageCount
 | GetMessageQueue
 | Receive
 | Send
 | SendChatMessage
 | SendEx
Group management | AddGroupToGroup
 | AddPlayerToGroup
 | CreateGroup
 | CreateGroupInGroup
 | DeleteGroupFromGroup
 | DeletePlayerFromGroup
 | DestroyGroup
 | EnumGroupPlayers
 | EnumGroups
 | EnumGroupsInGroup
 | GetGroupData
 | GetGroupFlags
 | GetGroupName
 | GetGroupOwner
 | GetGroupParent
 | SetGroupData
 | SetGroupName
 | SetGroupOwner
Initialization | Initialize

The IDirectPlay4 interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.


IDirectPlay4::AddGroupToGroup

The IDirectPlay4::AddGroupToGroup method adds a shortcut to a group to an already existing group. This allows the linked group to be enumerated by the IDirectPlay4::EnumGroupsInGroup method. To remove a group's shortcut from another group, call DeleteGroupFromGroup.

HRESULT AddGroupToGroup(
  DPID idParentGroup,
  DPID idGroup
);

Parameters

idParentGroup
ID of the group to which the shortcut will be added. Can be any valid group ID.
idGroup
The group ID of the group whose shortcut will be added. Can be any valid group ID.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_ACCESSDENIED
DPERR_CONNECTIONLOST
DPERR_INVALIDGROUP

Remarks

This method can be used to place a group "inside" more than one group.

A DPMSG_ADDGROUPTOGROUP system message is generated to inform players of this change.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlay4::CreateGroupInGroup, IDirectPlay4::DeleteGroupFromGroup, IDirectPlay4::EnumGroupsInGroup, DPMSG_ADDGROUPTOGROUP


IDirectPlay4::AddPlayerToGroup

The IDirectPlay4::AddPlayerToGroup method adds a player to an existing group. A player can be a member of multiple groups. Groups cannot be added to other groups using this API (see IDirectPlay4::AddGroupToGroup). An application can add any player to any group (including players and groups that weren't created locally).

HRESULT AddPlayerToGroup(
  DPID idGroup,
  DPID idPlayer
);

Parameters

idGroup
Group ID of the group to be augmented.
idPlayer
Player ID of the player to be added to the group.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_CANTADDPLAYER
DPERR_CONNECTIONLOST
DPERR_INVALIDGROUP
DPERR_INVALIDPLAYER
DPERR_NOSESSIONS

This method returns DPERR_INVALIDPLAYER if idPlayer is not a player ID or if the ID is not for a local player.

Remarks

A DPMSG_ADDPLAYERTOGROUP system message will be generated and sent to all the other players.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlay4::CreateGroup, IDirectPlay4::DeletePlayerFromGroup, DPMSG_ADDPLAYERTOGROUP


IDirectPlay4::CancelMessage

The IDirectPlay4::CancelMessage method is used to cancel a specific message (or all the messages) that are still in the send queue. CancelMessage applies only to asynchronous messages.

In order to cancel a specific message, the application must obtain and save the message ID returned by the IDirectPlay4::SendEx method.

Messages that have left the message queue and are partially sent cannot be canceled. A message sent to a group cannot be canceled after it has been sent to at least one member of the group.

Canceling a message still generates a DPMSG_SENDCOMPLETE system message indicating the message was canceled.

HRESULT CancelMessage(
  DWORD dwMsgID,
  DWORD dwFlags
);

Parameters

dwMsgID
ID of the specific message to be canceled. This ID is returned when the message is sent using IDirectPlay4::SendEx. Specify 0 to cancel all messages.
dwFlags
This parameter is reserved. Must be 0.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_CANCELFAILED
DPERR_INVALIDFLAGS
DPERR_INVALIDPARAMS
DPERR_UNKNOWNMESSAGE
DPERR_UNSUPPORTED

This method returns DPERR_CANCELFAILED if the message cannot be canceled. This method returns DPERR_UNKNOWNMESSAGE if the ID of the message to be canceled is invalid. It returns DP_OK if there are no messages in the send queue.

Remarks

If the DirectPlay Protocol was specified in the session description, then all the options on CancelMessage are available. Otherwise, an application should call GetCaps to determine what options the service provider has implemented.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlay4::SendEx, IDirectPlay4::Send, IDirectPlay4::GetMessageQueue, DPMSG_SENDCOMPLETE, IDirectPlay4::CancelPriority


IDirectPlay4::CancelPriority

The IDirectPlay4::CancelPriority method is used to cancel all messages of a particular priority or range of priorities that are still in the send queue. CancelPriority applies only to asynchronous messages.

Messages that have left the message queue and are partially sent cannot be canceled. A message sent to a group cannot be canceled once it has been sent to at least one member of the group.

Canceling a message still generates a DPMSG_SENDCOMPLETE system message indicating the message was canceled.

HRESULT CancelPriority(
  DWORD dwMinPriority,
  DWORD dwMaxPriority,
  DWORD dwFlags
);

Parameters

dwMinPriority
The minimum priority in the range to be canceled.
dwMaxPriority
The maximum priority in the range to be canceled. Must be greater than dwMinPriority. Set to MAXPRIORITY for the maximum possible priority.
dwFlags
This parameter is reserved. Must be 0.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_INVALIDFLAGS
DPERR_INVALIDPARAMS
DPERR_UNSUPPORTED

This method returns DP_OK if there are no messages in the send queue.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlay4::SendEx, IDirectPlay4::Send, IDirectPlay4::GetMessageQueue, DPMSG_SENDCOMPLETE, IDirectPlay4::CancelMessage


IDirectPlay4::Close

The IDirectPlay4::Close method closes a previously opened session. Any locally created groups will migrate to be owned by the host of the session.

HRESULT Close( );

Parameters

None.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_NOSESSIONS

Remarks

All locally created players will be destroyed and appropriate DPMSG_DELETEPLAYERFROMGROUP and DPMSG_DESTROYPLAYERORGROUP system messages will be sent to other session participants.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlay4::DestroyPlayer, DPMSG_DESTROYPLAYERORGROUP, IDirectPlay4::Open


IDirectPlay4::CreateGroup

The IDirectPlay4::CreateGroup method creates a group in the current session. A group is a logical collection of players or other groups.

HRESULT CreateGroup(
  LPDPID lpidGroup,
  LPDPNAME lpGroupName,
  LPVOID lpData,
  DWORD dwDataSize,
  DWORD dwFlags
);

Parameters

lpidGroup
Pointer to a variable that will be filled with the DirectPlay group ID. This value is defined by DirectPlay.
lpGroupName
Pointer to a DPNAME structure that holds the name of the group. NULL indicates that the group has no initial name. The name in lpGroupName is provided for human use only; it is not used internally and need not be unique.
lpData
Pointer to a block of application-defined remote data to associate initially with the group ID. NULL indicates that the group has no initial data. The data specified here is assumed to be remote data that will be propagated to all the other applications in the session as if IDirectPlay4::SetGroupData were called.
dwDataSize
Size, in bytes, of the data block that lpData points to.
dwFlags
Flag indicating what type of group to create. By default (dwFlags = 0), ownership of the group will migrate to the host when the owner leaves the session, and the group persists until it is explicitly destroyed.

Can be one of the following values:

DPGROUP_HIDDEN
Creates the group with the hidden flag. When the group is enumerated, the hidden flag is set. In a lobby session, hidden groups are only available through shortcuts created with IDirectPlay4::AddGroupToGroup. This flag works much like the DPPLAYER_SPECTATOR flag for players.
DPGROUP_STAGINGAREA
Creates the group as a staging area. A staging area is used to marshal players together in order to launch a new session.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_CANTADDPLAYER
DPERR_CONNECTIONLOST
DPERR_INVALIDFLAGS
DPERR_INVALIDPARAMS

Remarks

If the group is created in a client/server session, no group notification messages are sent. Groups are only visible on the machine that created them, regardless of whether the machine is the client or the host.

If the group is created in a peer-to-peer session, CreateGroup will generate a DPMSG_CREATEPLAYERORGROUP system message that will be sent to all the other players. The application can then use IDirectPlay4::Send to send a message to all the players in a group by sending one message to the group ID. DirectPlay will either use multicast to send the message (if the service provider supports it) or send individual messages to each player in the group.

The group ID returned to the application should be used to identify the group for message passing and data association. Player and group IDs assigned by DirectPlay will always be unique within the session.

Groups created with CreateGroup are top-level groups in the session. They are enumerated with IDirectPlay4::EnumGroups. In contrast, the IDirectPlay4::CreateGroupInGroup method creates a group that is a subgroup of a parent group.

Groups can also be used by the application for general organization. In a lobby session, a staging area is used as the mechanism for collecting players for the purpose of starting a new application session using IDirectPlay4::StartSession.

The player who creates a group is the default owner of it. Only the owner can change group properties such as the name and remote data. If the owner leaves the session, ownership is transferred to the host of the session.

Any player aware of a group in a session can change the membership of the group or delete the group.

Groups will persist in the session until they are explicitly destroyed.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

DPNAME, DPMSG_CREATEPLAYERORGROUP, IDirectPlay4::AddGroupToGroup,IDirectPlay4::DestroyGroup, IDirectPlay4::EnumGroups, IDirectPlay4::EnumGroupPlayers, IDirectPlay4::Send, IDirectPlay4::SetGroupData, IDirectPlay4::SetGroupName, IDirectPlay4::CreateGroupInGroup, IDirectPlay4::GetGroupFlags


IDirectPlay4::CreateGroupInGroup

The IDirectPlay4::CreateGroupInGroup method creates a group within an existing group. A group created within another group can only be enumerated using the IDirectPlay4::EnumGroupsInGroup method. A group created this way can be destroyed by calling the IDirectPlay4::DestroyGroup method.

HRESULT CreateGroupInGroup(
  DPID idParentGroup,
  LPDPID lpidGroup,
  LPDPNAME lpGroupName,
  LPVOID lpData,
  DWORD dwDataSize,
  DWORD dwFlags
);

Parameters

idParentGroup
ID of the group within which a group will be created. Must be an already existing group.
lpidGroup
Address of a variable to receive the DirectPlay group ID of the created group.
lpGroupName
Pointer to a DPNAME structure that holds the name of the group to be created. NULL indicates that the group has no initial name.
lpData
Pointer to a block of application-defined remote data to associate initially with the group ID. NULL indicates that the group has no initial data. The data specified here is assumed to be remote data that will be propagated to all the other applications in the session as if the IDirectPlay4::SetGroupData method had been called.
dwDataSize
Size, in bytes, of the data block that the lpData parameter points to.
dwFlags
Flag indicating what type of group to create. Default (dwFlags = 0) is a normal group.
DPGROUP_HIDDEN
Creates the group with the hidden flag. When the group is enumerated, the hiddle flag is set. In a lobby session, hidden groups are only available through shortcuts created with IDirectPlay4::AddGroupToGroup.
DPGROUP_STAGINGAREA
Creates the group as a staging area. A staging area can be used to launch DirectPlay sessions using the IDirectPlay4::StartSession method.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_CANTADDPLAYER
DPERR_CONNECTIONLOST
DPERR_INVALIDFLAGS
DPERR_INVALIDGROUP
DPERR_INVALIDPARAMS

This method returns DPERR_CANTADDPLAYER if the group could not be created. It returns DPERR_INVALIDGROUP if the parent group ID is invalid.

Remarks

If the group is created in a client/server session, no group notification messages are sent. Groups are only visible on the machine that created them, regardless of whether the machine is the client or the host.

If the group is created in a peer-to-peer session, CreateGroupInGroup will generate a DPMSG_CREATEPLAYERORGROUP system message generated to inform players of this change.

If you destroy a top-level group, any member groups it contains are destroyed as well, and the appropriate destruction messages are sent.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlay4::DestroyGroup, IDirectPlay4::EnumGroupsInGroup, DPMSG_CREATEPLAYERORGROUP


IDirectPlay4::CreatePlayer

The IDirectPlay4::CreatePlayer method creates a local player for the current session.

HRESULT CreatePlayer(
  LPDPID lpidPlayer,
  LPDPNAME lpPlayerName,
  HANDLE hEvent,
  LPVOID lpData,
  DWORD dwDataSize,
  DWORD dwFlags
);

Parameters

lpidPlayer
Pointer to a variable that will be filled with the DirectPlay player ID. This value is defined by DirectPlay.
lpPlayerName
Pointer to a DPNAME structure that holds the name of the player. NULL indicates that the player has no initial name information. The name in lpPlayerName is provided for human use only. It is not used internally and need not be unique.
hEvent
An event object created by the application that will be signaled by DirectPlay when a message addressed to this player is received.
lpData
Pointer to a block of application-defined data to associate with the player ID. NULL indicates that the player has no initial data. The data specified in this parameter is assumed to be remote data that will be propagated to all the other applications in the session, as if IDirectPlay4::SetPlayerData were called.
dwDataSize
Size, in bytes, of the data block that lpData points to.
dwFlags
Flags indicating what type of player this is. Default (dwFlags = 0) is a nonspectator, nonserver player.
DPPLAYER_SERVERPLAYER
The player is a server player for client/server communications. Only the host can create a server player. There can only be one server player in a session. CreatePlayer will always return a player ID of DPID_SERVERPLAYER if this flag is specified.
DPPLAYER_SPECTATOR
The player is created as a spectator. A spectator player behaves exactly as a normal player except the player is flagged as a spectator. The application can then limit what a spectator player can do. The behavior of a spectator player is completely defined by the application. DirectPlay simply propagates this flag.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_CANTADDPLAYER
DPERR_CANTCREATEPLAYER
DPERR_CONNECTIONLOST
DPERR_INVALIDFLAGS
DPERR_INVALIDPARAMS
DPERR_NOCONNECTION

Remarks

A single process can have multiple local players that communicate through a DirectPlay object with other players on the same computer or players on remote computers.

Upon successful completion, this method sends a DPMSG_CREATEPLAYERORGROUP system message to all the other players in the session announcing that a new player has joined the session. By default, all local players receive copies of all the system messages.

Your application should use the player ID returned to the application to identify the player for message passing and data association. Player and group IDs assigned by DirectPlay will always be unique within the session.

Only the application that created the player can:

  • change the player's name.
  • change the player's remote data.
  • send messages from the player.

If the application closes the session, any local players created will be automatically destroyed. Using IDirectPlay4::DestroyPlayer, the session host or the application that created the player can destroy the player at any time.

If the application uses a separate thread to retrieve DirectPlay messages, it is highly recommended that a non-NULL hEvent be supplied and used for synchronization. This event will be set when this player receives a message. Within the message receive thread, use the Win32® API WaitForSingleObject (or use WaitForMultipleObjects if more than one event is used) within the thread to determine if a player has messages. It is inefficient to loop on IDirectPlay4::Receive inside a separate thread waiting for a message. The same event can be used for all the local players, or the application can supply different events for each player. The application is responsible for creating and destroying the event. See Synchronization for more information.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

DPNAME, DPMSG_CREATEPLAYERORGROUP, IDirectPlay4::DestroyPlayer, IDirectPlay4::EnumPlayers, IDirectPlay4::Receive, IDirectPlay4::Send, IDirectPlay4::SetPlayerData, IDirectPlay4::SetPlayerName, IDirectPlay4::GetPlayerFlags


IDirectPlay4::DeleteGroupFromGroup

The IDirectPlay4::DeleteGroupFromGroup method removes a shortcut to a group previously added with the IDirectPlay4::AddGroupToGroup method from a group. Deleting the shortcut does not destroy the group.

HRESULT DeleteGroupFromGroup(
  DPID idParentGroup,
  DPID idGroup
);

Parameters

idParentGroup
ID of the group containing the shortcut to be deleted. Can be any valid group ID.
idGroup
ID of the group to delete. Can be any valid group ID.

Return Values

Returns DP_OK if successful, or one of the following error messages otherwise:

DPERR_ACCESSDENIED
DPERR_CONNECTIONLOST
DPERR_INVALIDGROUP

Remarks

A DPMSG_DELETEGROUPFROMGROUP system message is generated to inform players of this change.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlay4::AddGroupToGroup, DPMSG_DELETEGROUPFROMGROUP


IDirectPlay4::DeletePlayerFromGroup

The IDirectPlay4::DeletePlayerFromGroup method removes a player from a group.

HRESULT DeletePlayerFromGroup(
  DPID idGroup,
  DPID idPlayer
);

Parameters

idGroup
Group ID of the group to be adjusted.
idPlayer
Player ID of the player to be removed from the group.

Return Values

Returns DP_OK if successful, or one of the following error messages otherwise:

DPERR_CONNECTIONLOST
DPERR_INVALIDGROUP
DPERR_INVALIDOBJECT
DPERR_INVALIDPLAYER

Remarks

A DPMSG_DELETEPLAYERFROMGROUP system message is generated to inform the other players of this change. For a list of system messages, see Using System Messages.

A player can delete any player from a group, even if that group was created by some other computer.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlay4::AddPlayerToGroup, DPMSG_DELETEPLAYERFROMGROUP


IDirectPlay4::DestroyGroup

The IDirectPlay4::DestroyGroup method deletes a group from the session. The ID belonging to this group will not be reused during the current session.

HRESULT DestroyGroup(
  DPID idGroup
);

Parameters

idGroup
The ID of the group being removed from the game.

Return Values

Returns DP_OK if successful, or one of the following error messages otherwise:

DPERR_CONNECTIONLOST
DPERR_INVALIDGROUP
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_INVALIDPLAYER

Remarks

It is not necessary to empty a group before deleting it. The individual players belonging to the group are not destroyed. This method will generate a DPMSG_DELETEPLAYERFROMGROUP system message for each player in the group, and then a DPMSG_DESTROYPLAYERORGROUP system message. For a list of system messages, see Using System Messages.

Any application can destroy any group even if the group was not created locally.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlay4::CreateGroup, DPMSG_DESTROYPLAYERORGROUP


IDirectPlay4::DestroyPlayer

The IDirectPlay4::DestroyPlayer method deletes a local player from the session, removes any pending messages destined for that player from the message queue, and removes the player from any groups to which the player belonged. The player ID will not be reused during the current session.

In general, only the application that created the player can destroy the player. However, the host of the session can also destroy the player.

HRESULT DestroyPlayer(
  DPID idPlayer
);

Parameters

idPlayer
Player ID of the locally owned player to be removed from the session. When DestroyPlayer is called by the host of the session, this ID can be that of any player, local or remote.

Return Values

Returns DP_OK if successful, or one of the following error messages otherwise:

DPERR_ACCESSDENIED
DPERR_CONNECTIONLOST
DPERR_INVALIDOBJECT
DPERR_INVALIDPLAYER
DPERR_UNAVAILABLE

Remarks

This method generates a DPMSG_DELETEPLAYERFROMGROUP system message for each group that the player belongs to and then generates a DPMSG_DESTROYPLAYERORGROUP system message.

A player cannot be destroyed if the player has pending asynchronous messages in the send queue. All messages must either be completed or canceled.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlay4::CreatePlayer, DPMSG_DESTROYPLAYERORGROUP


IDirectPlay4::EnumConnections

The IDirectPlay4::EnumConnections method enumerates all the registered service providers and lobby providers that are available to the application. These should be presented to the user to make a selection. The connection that the user selects should be passed to the IDirectPlay4::InitializeConnection method.

HRESULT EnumConnections(
  LPCGUID lpguidApplication,
  LPDPENUMCONNECTIONSCALLBACK lpEnumCallback,
  LPVOID lpContext,
  DWORD dwFlags
);

Parameters

lpguidApplication
Pointer to an application globally unique identifier (GUID). Only service providers and lobby providers that are usable by this application will be returned. If set to a NULL pointer, a list of all the connections is enumerated regardless of the application GUID.
lpEnumCallback
Pointer to a user-supplied EnumConnectionsCallback function that will be called for each available connection.
lpContext
Pointer to a user-defined context that is passed to the callback function.
dwFlags
Flags that specify the type of connections to be enumerated. The default (dwFlags = 0) gives the same results as DPCONNECTION_DIRECTPLAY.

Possible values are:

DPCONNECTION_DIRECTPLAY
Enumerate only DirectPlay service providers to communicate in an application session.
DPCONNECTION_DIRECTPLAYLOBBY
Enumerate DirectPlay lobby providers to communicate with a lobby server.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_CONNECTIONLOST
DPERR_INVALIDFLAGS
DPERR_INVALIDPARAMS

Remarks

This method replaces the DirectPlayEnumerate function. DirectPlayEnumerate still works, but only returns registered service providers.

The order in which the service and lobby providers are returned is not guaranteed to be the same in subsequent calls to EnumConnections.

Not all the enumerated connections are available for use. For example, this method will return the modem service provider even if the user has no modem installed. The application can call the IDirectPlay4::InitializeConnection method on each connection and check for an error code to determine whether the service provider can be used.

Calling this method on the IDirectPlay4A (ANSI) interface always returns a suitably localized, single-byte character string. No multi-byte characters are used, so there will be no problems displaying strings using fonts that do not support multi-byte characters. Calling this method on the IDirectPlay4 (Unicode) interface returns a localized, wide character description.

Some service providers can register themselves as private. These service providers are not enumerated using this method. To use private service providers, you must explicitly reference them by their GUID, either by lobby launching the application or by creating a DirectPlay address and passing it to InitializeConnection.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlay4::InitializeConnection, EnumConnectionsCallback


IDirectPlay4::EnumGroupPlayers

The IDirectPlay4::EnumGroupPlayers method enumerates the players belonging to a specific group in the currently open session. If there is no open session, players in a remote session can be enumerated by specifying the DPENUMPLAYERS_SESSION flag and the guidInstance of the session. Password-protected remote sessions cannot be enumerated.

A pointer to an application-implemented callback function must be supplied, and DirectPlay calls it once for each player in the group that matches the criteria specified in dwFlags.

You cannot use EnumGroupPlayers in a lobby session you are not connected to.

HRESULT EnumGroupPlayers(
  DPID idGroup,
  LPGUID lpguidInstance,
  LPDPENUMPLAYERSCALLBACK2 lpEnumPlayersCallback2,
  LPVOID lpContext,
  DWORD dwFlags
);

Parameters

idGroup
ID of the group whose players are to be enumerated.
lpguidInstance
Pointer to a globally unique identifier (GUID) identifying the session to be enumerated. This parameter is ignored unless the DPENUMPLAYERS_SESSION flag is specified. The GUID must be equal to one of the sessions enumerated by IDirectPlay4::EnumSessions.
lpEnumPlayersCallback2
Pointer to the EnumPlayersCallback2 function that will be called for every player in the group that matches the criteria specified in dwFlags.
lpContext
Pointer to an application-defined context that is passed to each enumeration callback.
dwFlags
Flags specifying how the enumeration is to be done. The default (dwFlags = 0) enumerates players in a group in the current active session. You should use a logical OR operation to combine the flags that you want to specify. Only players that meet all the criteria of the combined flags will be enumerated. For example, if you specify (DPENUMPLAYERS_LOCAL | DPENUMPLAYERS_SPECTATOR) only players in the group that are local and are spectator players will be enumerated. If you specify (DPENUMPLAYERS_LOCAL | DPENUMPLAYERS_REMOTE), no players will be enumerated because no player can be both local and remote.

Can be one or more of the following values:

DPENUMPLAYERS_LOCAL
Enumerates players created locally by this DirectPlay object.
DPENUMPLAYERS_OWNER
Enumerates only the player that is the owner of this group.
DPENUMPLAYERS_REMOTE
Enumerates players created by remote DirectPlay objects.
DPENUMPLAYERS_SERVERPLAYER
Enumerates the server player.
DPENUMPLAYERS_SESSION
Enumerates the players for the session identified by lpguidInstance. This flag can only be used if there is no current open session. This flag cannot be used in a lobby session.
DPENUMPLAYERS_SPECTATOR
Enumerates players who are spectator players.

Return Values

Returns DP_OK if successful, or one of the following error messages otherwise:

DPERR_ACCESSDENIED
DPERR_CONNECTIONLOST
DPERR_INVALIDPARAMS
DPERR_INVALIDGROUP
DPERR_NOSESSIONS
DPERR_UNAVAILABLE

This method returns DPERR_ACCESSDENIED if the session is a lobby session you are not connected to. It returns DPERR_INVALIDPARAMS if an invalid callback, an invalid guidInstance, or if invalid flags were supplied. It returns DPERR_NOSESSIONS if there is no active session. It returns DPERR_UNAVAILABLE if the session could not be enumerated.

Remarks

By default, this method will enumerate all players in the current session. The DPENUMPLAYERS_SESSION flag can be used, along with a session instance GUID, to request that a session's host provide its list for enumeration. Use of the DPENUMPLAYERS_SESSION flag with this method must occur after the IDirectPlay4::EnumSessions method has been called, and before any calls to the IDirectPlay4::Close or IDirectPlay4::Open methods.

The DPENUMPLAYERS_OWNER flag is returned in the callback, indicating which player is the owner of the group.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlay4::CreatePlayer, IDirectPlay4::DestroyPlayer, IDirectPlay4::AddPlayerToGroup, IDirectPlay4::DeletePlayerFromGroup


IDirectPlay4::EnumGroups

The IDirectPlay4::EnumGroups method enumerates all the top-level groups in the current session. Top-level groups are groups that were created with the IDirectPlay4::CreateGroup method. If there is no open session, groups in a remote session can be enumerated by specifying the DPENUMGROUPS_session flag and the guidInstance of the session. Password-protected remote sessions cannot be enumerated.

A pointer to an application-implemented callback function must be supplied, and DirectPlay calls it once for each group in the session that matches the criteria specified in dwFlags.

You cannot use EnumGroups in a lobby session you are not connected to.

HRESULT EnumGroups(
  LPGUID lpguidInstance,
  LPDPENUMPLAYERSCALLBACK2 lpEnumPlayersCallback2,
  LPVOID lpContext,
  DWORD dwFlags
);

Parameters

lpguidInstance
This parameter should be NULL to enumerate groups in the currently open session. If there is no open session, this parameter can be a pointer to a globally unique identifier (GUID) identifying the session to be enumerated. The GUID must be equal to one of the sessions enumerated by IDirectPlay4::EnumSessions. This parameter is ignored unless the DPENUMGROUPS_SESSION flag is specified.
lpEnumPlayersCallback2
Pointer to the EnumPlayersCallback2 function that will be called for every group in the session that matches the criteria specified in dwFlags.
lpContext
Pointer to an application-defined context that is passed to each enumeration callback.
dwFlags
Flags specifying how the enumeration is to be done. Default (dwFlags = 0) enumerates all groups in the current active session. You should use a logical OR operation to combine the flags that you want to specify. Only groups that meet all the criteria of the combined flags will be enumerated. For example, if you specify (DPENUMGROUPS_LOCAL | DPENUMGROUPS_STAGINGAREA) only groups that are local and are staging areas will be enumerated. If you specify (DPENUMGROUPS_LOCAL | DPENUMGROUPS_REMOTE), no groups will be enumerated because no group can be both local and remote.

Can be one or more of the following values:

DPENUMGROUPS_ALL
Enumerates all groups in this session.
DPENUMGROUPS_HIDDEN
Enumerates only hidden groups that are currently available.
DPENUMGROUPS_LOCAL
Enumerates groups created locally by this DirectPlay object.
DPENUMGROUPS_REMOTE
Enumerates groups created by remote DirectPlay objects.
DPENUMGROUPS_SESSION
Performs enumeration in the session identified by the lpguidInstance parameter. This flag can only be used if there is no current active session. You cannot use this flag in a lobby session.
DPENUMGROUPS_STAGINGAREA
Enumerates groups that are staging areas. (Staging areas are used to marshal players together in order to launch a new session.)

Return Values

Returns DP_OK if successful, or one of the following error messages otherwise:

DPERR_CONNECTIONLOST
DPERR_INVALIDPARAMS
DPERR_NOSESSIONS
DPERR_UNAVAILABLE

This method returns DPERR_INVALIDPARAMS if an invalid callback, an invalid guidInstance, or invalid flags were supplied. It returns DPERR_NOSESSIONS if there is no open session. It returns DPERR_UNAVAILABLE if the remote session could not be enumerated.

Remarks

To enumerate the subgroups in a group, use IDirectPlay4::EnumGroupsInGroup.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

EnumPlayersCallback2, IDirectPlay4::CreateGroup, IDirectPlay4::DestroyGroup, IDirectPlay4::EnumSessions


IDirectPlay4::EnumGroupsInGroup

The IDirectPlay4::EnumGroupsInGroup method enumerates all groups and shortcuts to groups that are contained within another group. Groups are placed inside other groups by creating them with the IDirectPlay4::CreateGroupInGroup method or by adding them to a group with the IDirectPlay4::AddGroupToGroup method. This method is not recursive.

You cannot use EnumGroupsInGroup in a lobby session you are not connected to.

HRESULT EnumGroupsInGroup(
  DPID idGroup,
  LPGUID lpguidInstance,
  LPDPENUMPLAYERSCALLBACK2 lpEnumCallback,
  LPVOID lpContext,
  DWORD dwFlags
);

Parameters

idGroup
ID of the group whose subgroups are to be enumerated.
lpguidInstance
Pointer to a globally unique identifier (GUID) identifying the session to be enumerated. This parameter is ignored unless the DPENUMPLAYERS_SESSION flag is specified. The GUID must equal one of the sessions enumerated by the IDirectPlay4::EnumSessions method.
lpEnumCallback
Pointer to the EnumPlayersCallback2 function that will be called for every group in the group that matches the criteria specified in dwFlags.
lpContext
Pointer to an application-defined context that is passed to each enumeration callback.
dwFlags
Flags specifying how the enumeration will be done. The default (dwFlags = 0) enumerates all groups in the current active session. You should use a logical OR operation to combine the flags that you want to specify. Only groups that meet all the criteria of the combined flags will be enumerated. For example, if you specify (DPENUMGROUPS_LOCAL | DPENUMGROUPS_STAGINGAREA) only groups that are local and are staging areas will be enumerated. If you specify (DPENUMGROUPS_LOCAL | DPENUMGROUPS_REMOTE), no groups will be enumerated because no group can be both local and remote.

Can be one or more of the following values:

DPENUMGROUPS_ALL
Enumerates all groups in the group.
DPENUMGROUPS_HIDDEN
Enumerates only the currently available hidden groups in the group.
DPENUMGROUPS_LOCAL
Enumerates groups in the group created locally by this DirectPlay object.
DPENUMGROUPS_REMOTE
Enumerates groups in the group created by remote DirectPlay objects.
DPENUMGROUPS_SESSION
Performs enumeration in the session identified by the lpguidInstance parameter. This flag can only be used if there is no current active session. This flag cannot be used in lobby sessions.
DPENUMGROUPS_SHORTCUT
Enumerates groups that are shortcuts added to the group using IDirectPlay4::AddGroupToGroup. (A shortcut is a link to another group.)
DPENUMGROUPS_STAGINGAREA
Enumerates groups in the group that are staging areas. (Staging areas are used to marshal players together in order to launch a new session.)

Return Values

Returns DP_OK if successful, or one of the following error messages otherwise:

DPERR_CONNECTIONLOST
DPERR_INVALIDFLAGS
DPERR_INVALIDGROUP
DPERR_INVALIDPARAMS
DPERR_NOSESSIONS
DPERR_UNSUPPORTED

This method returns DPERR_INVALIDPARAMS if an invalid callback or an invalid guidInstance is supplied. It returns DPERR_NOSESSIONS if there is no active session. It returns DPERR_UNSUPPORTED if the session could not be enumerated.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlay4::CreateGroupInGroup, IDirectPlay4::DestroyGroup, IDirectPlay4::AddGroupToGroup, IDirectPlay4::DeleteGroupFromGroup


IDirectPlay4::EnumPlayers

The IDirectPlay4::EnumPlayers method enumerates the players in the current open session. If there is no open session, players in a remote session can be enumerated by specifying the DPENUMPLAYERS_SESSION flag and the guidInstance of the session. Password protected remote sessions cannot be enumerated.

A pointer to an application-implemented callback function must be supplied and DirectPlay calls it once for each player in the session that matches the criteria specified in dwFlags.

Within a lobby session, this method will always return DPERR_ACCESSDENIED.

HRESULT EnumPlayers(
  LPGUID lpguidInstance,
  LPDPENUMPLAYERSCALLBACK2 lpEnumPlayersCallback2,
  LPVOID lpContext,
  DWORD dwFlags
);

Parameters

lpguidInstance
This parameter should be NULL to enumerate players in the currently open session. If there is no open session, this parameter can be a pointer to a GUID identifying the session to be enumerated. The GUID must be equal to one of the sessions enumerated by IDirectPlay4::EnumSessions. This parameter is ignored unless the DPENUMPLAYERS_SESSION flag is specified.
lpEnumPlayersCallback2
Pointer to the EnumPlayersCallback2 function that will be called for every player in the session that matches the criteria specified in dwFlags.
lpContext
Pointer to an application-defined context that is passed to each enumeration callback.
dwFlags
Flags specifying how the enumeration is to be done. Default (dwFlags = 0) enumerates all players in the current active session. You should OR together the flags that you want to specify. Only players that meet all the criteria of the combined flags will be enumerated. For example, if you specify (DPENUMPLAYERS_LOCAL | DPENUMPLAYERS_SPECTATOR) only players that are local and are spectator players will be enumerated. If you specify (DPENUMPLAYERS_LOCAL | DPENUMPLAYERS_REMOTE), no players will be enumerated because no player can be both local and remote.

Can be one or more of the following values:

DPENUMPLAYERS_ALL
Enumerates all players in this session.
DPENUMPLAYERS_GROUP
Includes groups in the enumeration of players.
DPENUMPLAYERS_LOCAL
Enumerates players created locally by this DirectPlay object.
DPENUMPLAYERS_REMOTE
Enumerates players created by remote DirectPlay objects.
DPENUMPLAYERS_SERVERPLAYER
Enumerates the server player.
DPENUMPLAYERS_SESSION
Enumerates the players for the session identified by lpguidInstance. This flag can only be used if there is no current open session.
DPENUMPLAYERS_SPECTATOR
Enumerates players who are spectator players.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_CONNECTIONLOST
DPERR_INVALIDPARAMS
DPERR_NOSESSIONS
DPERR_UNAVAILABLE

This method returns DPERR_INVALIDPARAMS if an invalid callback, an invalid guidInstance, or invalid flags were supplied. It returns DPERR_NOSESSIONS if there is no open session. It returns DPERR_UNAVAILABLE if the remote session could not be enumerated.

Remarks

By default, this method will enumerate players in the current open session. Groups can also be included in the enumeration by using the DPENUMPLAYERS_GROUP flag. The DPENUMPLAYERS_SESSION flag can be used, along with a session instance GUID, to request that a session's host provide its list for enumeration. This method cannot be called from within an IDirectPlay4::EnumSessions enumeration. Furthermore, use of the DPENUMPLAYERS_SESSION flag with this method must occur after the IDirectPlay4::EnumSessions method has been called, and before any calls to the IDirectPlay4::Close or IDirectPlay4::Open methods.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlay4::CreatePlayer, IDirectPlay4::DestroyPlayer, IDirectPlay4::EnumSessions


IDirectPlay4::EnumSessions

The IDirectPlay4::EnumSessions method enumerates all the active sessions for a particular application and/or all the active lobby sessions that serve a particular application. This method can be called after a DirectPlay object has been created and initialized either by DirectPlayCreate or IDirectPlay4::InitializeConnection.

This method returns an error if called while a session is already open.

HRESULT EnumSessions(
  LPDPSESSIONDESC2 lpsd,
  DWORD dwTimeout,
  LPDPENUMSESSIONSCALLBACK2 lpEnumSessionsCallback2,
  LPVOID lpContext,
  DWORD dwFlags
);

Parameters

lpsd
Pointer to the DPSESSIONDESC2 structure describing the sessions to be enumerated. Only those sessions that meet the criteria set in this structure will be enumerated. The guidApplication member can be set to the globally unique identifier (GUID) of an application of interest if it is known, or to GUID_NULL to obtain all sessions. The lpszPassword member is only needed if you want private sessions. All data members besides guidApplication and lpszPassword are ignored.
dwTimeout
In the synchronous case, the total amount of time, in milliseconds, that DirectPlay will wait for replies to the enumeration request (not the time between each enumeration). Any replies received after this time-out will be ignored. The application will be blocked until the time-out expires.

In the asynchronous case, this is the interval, in milliseconds, that enumeration requests will be broadcast by DirectPlay in order to update the internal sessions list.

If the time-out is set to 0, a default time-out appropriate for the service provider and connection type will be used. It is recommended that you set this value to 0. The application can determine this time-out by calling IDirectPlay4::GetCaps and examining the dwTimeout data member of the DPCAPS structure.

lpEnumSessionsCallback2
Pointer to the application-supplied EnumSessionsCallback2 function to be called for each DirectPlay session responding.
lpContext
Pointer to a user-defined context that is passed to each enumeration callback.
dwFlags
The default is 0, which is equivalent to DPENUMSESSIONS_AVAILABLE. When enumerating sessions with DPENUMSESSIONS_ALL or DPENUMSESSIONS_PASSWORDREQUIRED, it is important for the application to know which sessions cannot be joined and which sessions are password-protected so the user can be warned or prompted for a password.
DPENUMSESSIONS_ALL
Enumerate all active sessions, whether they are accepting new players or not. Sessions in which the player limit has been reached, new players have been disabled, or joining has been disabled will be enumerated.

Password-protected sessions will not be enumerated unless the DPENUMSESSIONS_PASSWORDREQUIRED flag is also specified.

If DPENUMSESSIONS_ALL is not specified, DPENUMSESSIONS_AVAILABLE is assumed.

DPENUMSESSIONS_ASYNC
Enumerates all the current sessions in the session cache and returns immediately. Starts the asynchronous enumeration process if not already started. Updates to the session list continue until canceled by calling EnumSessions with the DPENUMSESSIONS_STOPASYNC flag, or by calling Open, or Release.

If this flag is not specified, the enumeration is done synchronously.

DPENUMSESSIONS_AVAILABLE
Enumerate all sessions that are accepting new players to join. Sessions that have reached their maximum number of players, or have disabled new players, or have disabled joining will not be enumerated.

Password-protected sessions will not be enumerated unless the DPENUMSESSIONS_PASSWORDREQUIRED flag is also specified.

DPENUMSESSIONS_PASSWORDREQUIRED
When used in combination with one of the two flags DPENUMSESSIONS_AVAILABLE or DPENUMSESSIONS_ALL, enables password-protected sessions to be enumerated in addition to sessions without password protection.

If this flag is not specified, no password-protected sessions will be returned.

DPENUMSESSIONS_RETURNSTATUS
If this flag is specified, the enumeration will not display any dialog boxes showing the connection progress status. If the connection cannot be made immediately, the method will return with the DPERR_CONNECTING error. The application must keep calling EnumSessions until either DP_OK is returned, indicating successful completion, or some other error code is returned, indicating an error.
DPENUMSESSIONS_STOPASYNC
Enumerates all the current sessions in the session cache and cancels the asynchronous enumeration process.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_CONNECTING
DPERR_CONNECTIONLOST
DPERR_EXCEPTION
DPERR_GENERIC
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_NOCONNECTION
DPERR_UNINITIALIZED
DPERR_USERCANCEL

This method returns DPERR_GENERIC if the session is already open. It returns DPERR_UNINITIALIZED if the DirectPlay object has not been initialized. It returns DPERR_USERCANCEL if the user canceled the enumeration process (usually by canceling a service provider dialog box), or DPERR_INVALIDPARAMS if the user entered a computer name in the TCP/IP service provider dialog that could not be resolved to an IP address. It returns DPERR_CONNECTING if the method is in the process of connecting to the network.

Remarks

EnumSessions works by requesting that the service provider locate one or more hosts on the network and send them an enumeration request. The replies that are received make up the sessions that are enumerated.

EnumSessions can be called synchronously (default) or asynchronously. When called synchronously, DirectPlay will clear the internal session cache, send out an enumeration request, and collect replies until the specified time-out expires. Each session will then be returned to the application through the callback function. The application will be blocked until all the sessions have been returned through the callback function.

When called asynchronously (DPENUMSESSIONS_ASYNC), all the current sessions (if any) in the session cache will be returned to the application through the callback function and then the method will return. DirectPlay will then automatically send out enumeration requests with the period of the time-out parameter and listen for replies. Each reply will be used to update the session cache:

  • Sessions already in the cache will be updated.
  • Sessions that have not been updated for a set period of time (and thus have expired) will be deleted.
  • New sessions will be added.

The application must call EnumSessions (with the DPENUMSESSIONS_ASYNC flag) again to obtain the most up-to-date session list with all the expired sessions deleted, new sessions added, and updated sessions. Subsequent calls to EnumSessions will not generate an enumeration request. Enumeration requests will be generated periodically by DirectPlay until the process is either canceled by calling EnumSessions with the DPENUMSESSIONS_STOPASYNC flag, a session is opened using the IDirectPlay4::Open method, or the DirectPlay object is released.

To change the description of the sessions being enumerated asynchronously, you must stop the asynchronous enumeration and then start it up again. For example, you cannot start an enumeration without a password and then later, during an asychronous call, add a password and have it begin enumerating private sessions using that password. Conversely, if you specify the correct password, then change to an incorrect password, you will still enumerate the session. However, you can call EnumSessions with the DPENUMSESSIONS_STOPASYNC flag, then specify the password, and the private session will be enumerated.

Once enumeration of the available sessions is complete, the application can join one of the sessions using the IDirectPlay4::Open method. Only sessions in the session cache can be opened. An application may attempt to open a session that has expired since the last time EnumSessions was called in which case an error will be returned.

No authentication is performed when enumerating sessions on a secure server. All sessions that meet the enumeration criteria will be returned. Authentication will be done when the application attempts to open one of these sessions with IDirectPlay4::Open or IDirectPlay4::SecureOpen.

If the application was not started by a lobby, the service provider can display a dialog box asking the user for information (such as a phone number or IP address) in order to perform the enumeration on the network, if that information was not provided in IDirectPlay4::InitializeConnection. If the service provider can do a broadcast enumeration and requires no extra information from the user, no dialog box will appear. If the user cancels a service provider dialog box, EnumSessions returns DPERR_USERCANCEL.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

DPSESSIONDESC2, IDirectPlay4::Open, IDirectPlay4::SecureOpen


IDirectPlay4::GetCaps

The IDirectPlay4::GetCaps method obtains the capabilities of this DirectPlay object.

HRESULT GetCaps(
  LPDPCAPS lpDPCaps,
  DWORD dwFlags
);

Parameters

lpDPCaps
Pointer to a DPCAPS structure that will be filled with the capabilities of the DirectPlay object. The dwSize member of the DPCAPS structure must be filled in before using IDirectPlay4::GetCaps.
dwFlags
If this parameter is set to 0, the capabilities will be computed for nonguaranteed messaging.
DPGETCAPS_GUARANTEED
Retrieves the capabilities for a guaranteed message delivery.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS

Remarks

This method returns the capabilities of the current session, while the IDirectPlay4::GetPlayerCaps method returns the capabilities of the requested player.

Note that capabilities indicating which aspects of SendEx are supported are not available until after the session has been opened. If the application hosting the session has specified the DPSESSION_DIRECTPLAYPROTOCOL flag in the DPSESSIONDESC2 structure, then all the SendEx options are supported.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

DPCAPS, IDirectPlay4::GetPlayerCaps, IDirectPlay4::Send


IDirectPlay4::GetGroupConnectionSettings

The IDirectPlay4::GetGroupConnectionSettings method retrieves the connection settings for a group from the DPLCONNECTION structure. Any sessions launched from this group will use these settings. This method can only be used in a lobby session.

HRESULT GetGroupConnectionSettings(
  DWORD dwFlags,
  DPID idGroup,
  LPVOID lpData,
  LPDWORD lpdwDataSize
);

Parameters

dwFlags
Not used. Must be 0.
idGroup
ID of the group to get the connection settings for.
lpData
Pointer to a buffer into which the DPLCONNECTION structure and all its data will be copied. Set this parameter to NULL to request only the size of data. The lpdwDataSize parameter will be set to the minimum size required to hold the data.
lpdwDataSize
Pointer to a variable that is initialized to the size of the buffer before calling this method. After the method returns, this parameter will be set to the size, in bytes, of the data. If the buffer was too small (DPERR_BUFFERTOOSMALL), then this parameter will be set to the minimum buffer size required.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_ACCESSDENIED
DPERR_BUFFERTOOSMALL
DPERR_INVALIDGROUP
DPERR_INVALIDFLAGS
DPERR_INVALIDPARAMS
DPERR_UNSUPPORTED

Remarks

Group connection settings are only relevant for staging area groups.

You can see if a game has been launched by looking at the guidInstance data member of the DPSESSIONDESC2 structure, whose pointer is contained in the lpSessionDesc data member of the DPLCONNECTION structure returned by this method. The guidInstance will be GUID_NULL until a game has been launched.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

DPLCONNECTION, IDirectPlayLobby3::RunApplication, IDirectPlay4::SetGroupConnectionSettings


IDirectPlay4::GetGroupData

The IDirectPlay4::GetGroupData method retrieves an application-specific data block that was associated with a group ID by using IDirectPlay4::SetGroupData.

HRESULT GetGroupData(
  DPID idGroup,
  LPVOID lpData,
  LPDWORD lpdwDataSize,
  DWORD dwFlags
);

Parameters

idGroup
Group ID for which data is being requested.
lpData
Pointer to a buffer where the application-specific group data is to be written. Set this parameter to NULL to request only the size of data. The lpdwDataSize parameter will be set to the size required to hold the data.
lpdwDataSize
Pointer to a variable that is initialized to the size of the buffer before calling the method. After the method returns, this parameter will be set to the size, in bytes, of the group data. If the buffer was too small (DPERR_BUFFERTOOSMALL), then this parameter will be set to the buffer size required.
dwFlags
If this parameter is set to 0, the remote data will be retrieved.
DPGET_LOCAL
Retrieves the local data set by this application
DPGET_REMOTE
Retrieves the current data from the remote shared data space.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_BUFFERTOOSMALL
DPERR_INVALIDGROUP
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_INVALIDPLAYER

Remarks

DirectPlay can maintain two types of group data: local and remote. The application must specify which type of data to retrieve. Local data was set by this DirectPlay object by using the DPSET_LOCAL flag. Remote data might have been set by any application in the session by using the DPSET_REMOTE flag.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlay4::SetGroupData


IDirectPlay4::GetGroupFlags

The IDirectPlay4::GetGroupFlags method returns the flags describing the group.

HRESULT GetGroupFlags(
  DPID idGroup,
  LPDWORD lpdwFlags
);

Parameters

idGroup
ID of the group whose flag settings are to be retrieved.
lpdwFlags
Pointer to a DWORD to be set to the group flag settings. Can be one or more of the following:
DPGROUP_LOCAL
The group was created by this application. If this flag is not specified, the group is a remote group.
DPGROUP_STAGINGAREA
The group is a staging area.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_INVALIDGROUP
DPERR_INVALIDPARAMS

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlay4::CreateGroup


IDirectPlay4::GetGroupName

The IDirectPlay4::GetGroupName method returns the name associated with a group.

HRESULT GetGroupName(
  DPID idGroup,
  LPVOID lpData,
  LPDWORD lpdwDataSize
);

Parameters

idGroup
ID of the group whose name is being requested.
lpData
Pointer to a buffer where the name data is to be written. Set this parameter to NULL to request only the size of data. lpdwDataSize will be set to the size required to hold the data.
lpdwDataSize
Pointer to a variable that is initialized to the size of the buffer before calling the method. After the method returns, this parameter will be set to the size, in bytes, of the name data. If the buffer was too small (DPERR_BUFFERTOOSMALL), then this parameter will be set to the buffer size that is required.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_BUFFERTOOSMALL
DPERR_INVALIDGROUP
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_INVALIDPLAYER

Remarks

After the method returns, the pointer lpData should be cast to the DPNAME structure to read the group name data.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

DPNAME, IDirectPlay4::SetGroupName


IDirectPlay4::GetGroupOwner

The IDirectPlay4::GetGroupOwner method returns the ID of the current owner of the group. This method is only valid in a lobby session.

HRESULT GetGroupOwner(
  DPID idGroup,
  LPDPID lpidOwner
);

Parameters

idGroup
ID of the group whose owner is being requested.
lpidOwner
Address of a variable to receive the ID of the owner.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_GENERIC
DPERR_INVALIDGROUP
DPERR_INVALIDPARAMS
DPERR_UNAVAILABLE

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlay4::SetGroupOwner


IDirectPlay4::GetGroupParent

The IDirectPlay4::GetGroupParent method returns the ID of the parent of the group.

HRESULT GetGroupParent(
  DPID idGroup,
  LPDPID lpidParent
);

Parameters

idGroup
ID of the group whose parent is being requested.
lpidParent
Address of a variable to receive the ID of the parent group. If this method returns a parent ID of 0, the group is a root group.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_INVALIDGROUP
DPERR_INVALIDPARAMS

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlay4::CreateGroupInGroup


IDirectPlay4::GetMessageCount

The IDirectPlay4::GetMessageCount method queries for the number of messages in the receive queue for a specific local player.

HRESULT GetMessageCount(
  DPID idPlayer,
  LPDWORD lpdwCount
);

Parameters

idPlayer
ID of the player whose message count is requested. The player must be local.
lpdwCount
Pointer to a variable that will be set to the message count when this method returns.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_INVALIDPLAYER

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlay4::Receive


IDirectPlay4::GetMessageQueue

The IDirectPlay4::GetMessageQueue method determines how many messages are in the send or receive queue. By monitoring the status of the send queue, an application can regulate how many messages to send to other players in the session based on the bandwidth of the underlying network.

Note that the queue size on a machine is for all players in the session on that machine, not for an individual player, if there is more than one player in the session on a single machine.

HRESULT GetMessageQueue(
  DPID idFrom,
  DPID idTo,
  DWORD dwFlags,
  LPDWORD lpdwNumMsgs,
  LPDWORD lpdwNumBytes
);

Parameters

idFrom
ID of the player sending the messages whose queue status is desired. Zero returns information about all sent messages. If idTo is also specified, only information about messages that are both from the player with idFrom and to the player with idTo is returned.
idTo
ID of the player sent the messages whose queue status is desired. Zero returns information about all sent messages. If idFrom is also specified, only information about messages that are both from the player with idFrom and to the player with idTo is returned. Note that you cannot specify a group ID for idTo.
dwFlags
Determines what type of information about the queue to obtain. Default (dwFlags = 0) returns information about the send queue. Can be one, and only one, of the following values:
DPMESSAGEQUEUE_SEND
Retrieves information about the send queue.
DPMESSAGEQUEUE_RECEIVE
Retrieves information about the receive queue.
lpdwNumMsgs
Pointer to a DWORD that will be filled with the number of messages in the queue. If NULL, no value is returned.
lpdwNumBytes
Pointer to a DWORD that will be filled with the total number of bytes in the queue. If NULL, no value is returned.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_INVALIDFLAGS
DPERR_INVALIDPARAMS
DPERR_INVALIDPLAYER
DPERR_UNSUPPORTED

Returns DPERR_INVALIDPLAYER if you check the receive queue (DPMESSAGEQUEUE_RECEIVE) while specifying idTo for a remote player. Returns DPERR_INVALIDPLAYER if you check the send queue (DPMESSAGEQUEUE_SEND) while specifying idFrom for a remote player. Returns DPERR_INVALIDFLAGS if you specify both the receive queue and the send queue flags (dwFlags = DPMESSAGEQUEUE_RECEIVE|DPMESSAGEQUEUE_SEND). Returns DPERR_UNSUPPORTED if you attempt to check the send queue when DirectPlay protocol is not turned on and the service provider does not support checking the send queue.

Remarks

You cannot check message queues on remote machines.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlay4::Send, IDirectPlay4::SendEx


IDirectPlay4::GetPlayerAccount

The IDirectPlay4::GetPlayerAccount method in a secure session, can be called by the session host to obtain account information about the specified player.

HRESULT GetPlayerAccount(
  DPID idPlayer,
  DWORD dwFlags,
  LPVOID lpData,
  LPDWORD lpdwDataSize
);

Parameters

idPlayer
ID of the player whose account information is to be retrieved.
dwFlags
Not used. Must be 0.
lpData
A pointer to a buffer (allocated by the application) where the account data is to be written. A DPACCOUNTDESC structure will be copied as well as any data referenced by the members of the structure; therefore, the number of bytes copied is variable. Cast the lpData parameter to LPDPACCOUNTDESC in order to read the name. By passing NULL, the application can request the number of bytes required be put in the lpdwDataSize parameter. The application can then allocate the space and call this method again.
lpdwDataSize
A pointer to a DWORD that is initialized with the size of the buffer. After the method returns, lpdwDataSize will be set to the number of bytes that were actually copied into the buffer. If the buffer was too small the method returns DPERR_BUFFERTOOSMALL, and lpdwDataSize is set to the minimum required buffer size.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_ACCESSDENIED
DPERR_BUFFERTOOSMALL
DPERR_INVALIDFLAGS
DPERR_INVALIDPARAMS
DPERR_INVALIDPLAYER

Remarks

The information returned by GetPlayerAccount uniquely identifies an account. This information can be used to record the transactions or other activities of a logged-on player.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlay4::SecureOpen


IDirectPlay4::GetPlayerAddress

The IDirectPlay4::GetPlayerAddress method retrieves the DirectPlay address for a player.

The DirectPlay address is a network address for a player using a specific service provider. You should call the IDirectPlayLobby3::EnumAddress method to parse the buffer retrieved by IDirectPlay4::GetPlayerAddress.

If this method is called on a local player, it returns the network address of the computer if it is available. In some cases, more than one address can be returned (for example, with TCP/IP where the computer has both a network card and a dial-up Internet connection).

HRESULT GetPlayerAddress(
  DPID idPlayer,
  LPVOID lpData,
  LPDWORD lpdwDataSize
);

Parameters

idPlayer
Player ID that the address is being requested for. Pass in 0 to obtain a list of valid address options for a service provider (for example, a list of valid modem choices for the modem-to-modem service provider).
lpData
Pointer to a buffer where the DirectPlay address is to be written. Set this parameter to NULL to request only the size of data. The lpdwDataSize parameter will be set to the size required to hold the data.
lpdwDataSize
Pointer to a variable that is initialized to the size of the buffer before calling this method. After the method returns, this parameter will be set to the size, in bytes, of the DirectPlay address data. If the buffer was too small, then this parameter will be set to the buffer size that is required and the method will return DPERR_BUFFERTOOSMALL.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_BUFFERTOOSMALL
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_INVALIDPLAYER
DPERR_UNAVAILABLE

This method returns DPERR_UNAVAILABLE if the address for the requested player ID is not available.

Remarks

To get a list of valid modem choices, pass in 0 for the idPlayer parameter. A list of modem choices will be returned as a list of ANSI or Unicode strings with a zero-length string at the end.

The DirectPlay address will contain both ANSI and Unicode strings with the address, regardless of what interface this method is called on.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlayLobby3::EnumAddress, DirectPlay Address


IDirectPlay4::GetPlayerCaps

The IDirectPlay4::GetPlayerCaps method retrieves the current capabilities of a specified player.

HRESULT GetPlayerCaps(
  DPID idPlayer,
  LPDPCAPS lpPlayerCaps,
  DWORD dwFlags
);

Parameters

idPlayer
Player ID for which the capabilities should be computed.
lpPlayerCaps
Pointer to a DPCAPS structure that will be filled with the capabilities. The dwSize member of the DPCAPS structure must be filled in before using IDirectPlay4::GetPlayerCaps.
dwFlags
If this parameter is set to 0, the capabilities will be computed for nonguaranteed messaging.
DPGETCAPS_GUARANTEED
Retrieves the capabilities for a guaranteed message delivery.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_INVALIDPLAYER

Remarks

This method returns the capabilities of the requested player, while the IDirectPlay4::GetCaps method returns the capabilities of the current session.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

DPCAPS, IDirectPlay4::GetCaps, IDirectPlay4::Send


IDirectPlay4::GetPlayerData

The IDirectPlay4::GetPlayerData method retrieves an application-specific data block that was associated with a player ID by using IDirectPlay4::SetPlayerData.

HRESULT GetPlayerData(
  DPID idPlayer,
  LPVOID lpData,
  LPDWORD lpdwDataSize,
  DWORD dwFlags
);

Parameters

idPlayer
ID of the player for which data is being requested.
lpData
Pointer to a buffer where the application-specific player data is to be written. Set this parameter to NULL to request only the size of data. The lpdwDataSize parameter will be set to the size required to hold the data.
lpdwDataSize
Pointer to a variable that is initialized to the size of the buffer before calling this method. After the method returns, this parameter will be set to the size, in bytes, of the player data. If the buffer was too small (DPERR_BUFFERTOOSMALL), then this parameter will be set to the buffer size required.
dwFlags
If this parameter is set to 0, the remote data will be retrieved.
DPGET_LOCAL
Retrieves the local data set by this application.
DPGET_REMOTE
Retrieves the current data from the remote shared data space.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_BUFFERTOOSMALL
DPERR_INVALIDFLAGS
DPERR_INVALIDOBJECT
DPERR_INVALIDPLAYER

Remarks

DirectPlay can maintain two types of player data: local and remote. The application must specify which type of data to retrieve. Local data was set by this DirectPlay object by using the DPSET_LOCAL flag. Remote data might have been set by any application in the session by using the DPSET_REMOTE flag.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlay4::SetPlayerData


IDirectPlay4::GetPlayerFlags

The IDirectPlay4::GetPlayerFlags method returns the flags describing the player.

HRESULT GetPlayerFlags(
  DPID idPlayer,
  LPDWORD lpdwFlags
);

Parameters

idPlayer
ID of the player whose flag settings are to be retrieved.
lpdwFlags
Pointer to a DWORD to be set to the player's flag settings. Can be one or more of the following:
DPPLAYER_LOCAL
The player was created by this application. If this flag is not specified, the player is a remote player.
DPPLAYER_SERVERPLAYER
The player is a server player for client/server communications.
DPPLAYER_SPECTATOR
The player was created as a spectator.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_INVALIDPARAMS
DPERR_INVALIDPLAYER

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlay4::CreatePlayer


IDirectPlay4::GetPlayerName

The IDirectPlay4::GetPlayerName method retrieves the name associated with a player.

HRESULT GetPlayerName(
  DPID idPlayer,
  LPVOID lpData,
  LPDWORD lpdwDataSize
);

Parameters

idPlayer
ID of the player whose name is requested.
lpData
Pointer to a buffer where the name data is to be written. Set this parameter to NULL to request only the size of data. The lpdwDataSize parameter will be set to the size required to hold the data.
lpdwDataSize
Pointer to a variable that is initialized to the size of the buffer before calling this method. After the method returns, this parameter will be set to the size, in bytes, of the name data. If the buffer was too small (DPERR_BUFFERTOOSMALL), then this parameter will be set to the buffer size required.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_BUFFERTOOSMALL
DPERR_INVALIDOBJECT
DPERR_INVALIDPLAYER

Remarks

After this method returns, the pointer lpData should be cast to the DPNAME structure to read the group name data.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

DPNAME, IDirectPlay4::SetPlayerName


IDirectPlay4::GetSessionDesc

The IDirectPlay4::GetSessionDesc method retrieves the properties of the current open session.

HRESULT GetSessionDesc(
  LPVOID lpData,
  LPDWORD lpdwDataSize
);

Parameters

lpData
Pointer to a buffer where the session description data is to be written. Set this parameter to NULL to request only the size of data. The lpdwDataSize parameter will be set to the size required to hold the data.
lpdwDataSize
Pointer to a variable that is initialized to the size of the buffer before calling this method. After the method returns, this parameter will be set to the size, in bytes, of the session data. If the buffer was too small (DPERR_BUFFERTOOSMALL), then this parameter will be set to the buffer size required. If this parameter is NULL, the method returns DPERR_INVALIDPARAM.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_BUFFERTOOSMALL
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_NOCONNECTION

Remarks

After this method returns, the pointer lpData should be cast to the DPSESSIONDESC2 structure to read the session description data.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

DPSESSIONDESC2, IDirectPlay4::EnumSessions, IDirectPlay4::Open


IDirectPlay4::Initialize

The IDirectPlay4::Initialize method this method is provided for compliance with the COM protocol.

HRESULT Initialize(
  LPGUID lpGUID
);

Parameters

lpGUID
Pointer to the globally unique identifier (GUID) used as the interface identifier.

Return Values

The method returns DPERR_ALREADYINITIALIZED.

Remarks

Because the DirectPlay object is initialized when it is created, this method always returns the DPERR_ALREADYINITIALIZED return value.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

IUnknown::AddRef, IUnknown::QueryInterface


IDirectPlay4::InitializeConnection

The IDirectPlay4::InitializeConnection method initializes a DirectPlay connection. All the information about the connection, including the service provider to use, the network address of the server, and the GUID of the session, is passed in through the lpConnection parameter.

HRESULT InitializeConnection(
  LPVOID lpConnection,
  DWORD dwFlags
);

Parameters

lpConnection
Pointer to a buffer that contains all the information about the connection to be initialized as a DirectPlay address.
dwFlags
Not used. Must be 0.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_ALREADYINITIALIZED
DPERR_INVALIDFLAGS
DPERR_INVALIDPARAMS
DPERR_UNAVAILABLE

This method returns DPERR_ALREADYINITIALIZED if InitializeConnection has previously been called on this object. It returns DPERR_UNAVAILABLE if the service provider could not be initialized. This can be because the resources necessary to operate this service provider are not present (for example, TCP/IP stack not present).

Remarks

The lpConnection parameter supplied to this method can be obtained from the IDirectPlay4::EnumConnections method, or the application can create one directly using the IDirectPlayLobby3::CreateCompoundAddress method.

This method loads and initializes the appropriate service provider. The lpConnection parameter is passed on to the service provider, which extracts and saves any relevant information. This information is used when the IDirectPlay4::EnumSessions or IDirectPlay4::Open method is called so that the service provider does not pop up a dialog box asking for that information.

This method replaces DirectPlayCreate as the means of binding a service provider to a DirectPlay object. The primary benefits of InitializeConnection are that you can override the service provider dialogs, and you can initialize a lobby provider.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlay4::EnumConnections, IDirectPlayLobby3::CreateCompoundAddress, DirectPlay Address


IDirectPlay4::Open

The IDirectPlay4::Open method is used to join a session that has been enumerated by a previous call to IDirectPlay4::EnumSessions or to create a new session that other users can enumerate and join.

HRESULT Open(
  LPDPSESSIONDESC2 lpsd,
  DWORD dwFlags
);

Parameters

lpsd
Pointer to the DPSESSIONDESC2 structure describing the session to be created or joined. If a session is being joined, then only the dwSize, guidInstance, and lpszPassword data members need to be specified. A password need only be supplied if the enumerated session had the DPSESSION_PASSWORD flag set.

If a session is being created, then the application must completely fill out the DPSESSIONDESC2 structure with the properties of the sessions to be created. The guidInstance will be generated by DirectPlay.

dwFlags
One and only one of the following flags:
DPOPEN_CREATE
Create a new instance of an application session. The local computer will be the name server and host of the session.
DPOPEN_JOIN
Join an existing instance of an application session for the purpose of participating. The application will be able to create players and send and receive messages.
DPOPEN_RETURNSTATUS
If this flag is specified, the method will not display any dialog boxes showing the connection progress status. If the connection cannot be made immediately, the method will return with the DPERR_CONNECTING error. The application must keep calling Open until either DP_OK is returned, indicating successful completion, or some other error code is returned, indicating an error.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_ACCESSDENIED
DPERR_ALREADYINITIALIZED
DPERR_AUTHENTICATIONFAILED
DPERR_CANNOTCREATESERVER
DPERR_CANTCREATEPLAYER
DPERR_CANTLOADCAPI
DPERR_CANTLOADSECURITYPACKAGE
DPERR_CANTLOADSSPI
DPERR_CONNECTING
DPERR_CONNECTIONLOST
DPERR_ENCRYPTIONFAILED
DPERR_ENCRYPTIONNOTSUPPORTED
DPERR_INVALIDFLAGS
DPERR_INVALIDPARAMS
DPERR_INVALIDPASSWORD
DPERR_LOGONDENIED
DPERR_NOCONNECTION
DPERR_NONEWPLAYERS
DPERR_NOSESSIONS
DPERR_SIGNFAILED
DPERR_TIMEOUT
DPERR_UNINITIALIZED
DPERR_USERCANCEL

This method returns DPERR_ALREADYINITIALIZED if there is already an open session on this DirectPlay object.

It return DPERR_CANTCREATEPLAYER if the maximum number of players in the session description has already been reached.

It returns DPERR_TIMEOUT if the session did not respond to the Open request.

It returns DPERR_USERCANCEL if the user canceled the enumeration process(usually by canceling a service provider dialog box).

It returns DPERR_NOSESSIONS if it is called to join an existing session but the session isn't in the internal session list (or the session guidInstance is corrupted).

Remarks

Once an application has joined a session, it can create a player and start communicating with other players in the session. The application will not receive any messages nor can it send any messages on this DirectPlay object until it creates a local player using IDirectPlay4::CreatePlayer.

In order to have two sessions open simultaneously, the application must create two DirectPlay objects and open a session on each one.

To join a session, it is only necessary to fill in the dwSize and guidInstance members of the DPSESSIONDESC2 structure. The lpszPassword member must also be filled in if the session was marked as password protected. An enumerated session will have the DPSESSION_PASSWORDREQUIRED flag set if it requires a password.

If joining a secure session, you must use SecureOpen to provide logon credentials. The enumerated session will have the DPSESSION_SECURESERVER flag set if it requires credentials.

If you specify the DPSESSION_SECURESERVER flag in the DPSESSIONDESC2 structure, the session will be opened with the default security package, NTLM (NT LAN Manager). To specify an alternate security package, use SecureOpen.

When an application attempts to join a session, the server can reject the Open request or ignore it (in which case Open will time-out). Attempting to join a session where new players are disabled, joining is disabled, the player limit has been reached, or an incorrect password is supplied will result in a DPERR_NONEWPLAYERS or DPERR_INVALIDPASSWORD error.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

DPSESSIONDESC2, IDirectPlay4::Close, IDirectPlay4::SecureOpen, IDirectPlay4::EnumSessions


IDirectPlay4::Receive

The IDirectPlay4::Receive method retrieves a message from the message queue.

HRESULT Receive(
  LPDPID lpidFrom,
  LPDPID lpidTo,
  DWORD dwFlags,
  LPVOID lpData,
  LPDWORD lpdwDataSize
);

Parameters

lpidFrom
Address of a variable to receive the sender's player ID. If the DPRECEIVE_FROMPLAYER flag is specified, this variable must be initialized with the player ID before calling this method.
lpidTo
Address of a variable to receive the receiver's player ID. If the DPRECEIVE_TOPLAYER flag is specified, this variable must be initialized with the player ID before calling this method.
dwFlags
One or more of the following control flags can be set. By default (dwFlags = 0), the first available message will be retrieved.
DPRECEIVE_ALL
Returns the first available message. This is the default.
DPRECEIVE_PEEK
Returns a message as specified by the other flags, but does not remove it from the message queue. This flag must be specified if lpData is NULL.
DPRECEIVE_TOPLAYER and DPRECEIVE_FROMPLAYER
If both DPRECEIVE_TOPLAYER and DPRECEIVE_FROMPLAYER are specified, Receive will only return messages that are: 1) sent to the player specified by lpidTo and 2) sent from the player specified by lpidFrom. Note that both conditions must be met.

If only DPRECEIVE_TOPLAYER is specified, Receive will only return messages sent to the player specified by lpidTo.

If only DPRECEIVE_FROMPLAYER is specified, Receive will only return messages sent from the player specified by lpidFrom.

If neither DPRECEIVE_TOPLAYER nor DPRECEIVE_FROMPLAYER is set, Receive will return the first available message.

lpData
Pointer to a buffer where the message data is to be written. Set this parameter to NULL to request only the size of data. The lpdwDataSize parameter will be set to the size required to hold the data. If the message came from player ID DPID_SYSMSG, the application should cast lpData to DPMSG_GENERIC and check the dwType member to see what type of system message it is before processing it.
lpdwDataSize
Pointer to a DWORD that is initialized to the size of the buffer before calling this method. After the method returns, this parameter will be set to the number of bytes copied into the buffer. If the buffer was too small (DPERR_BUFFERTOOSMALL), then this parameter will be set to the buffer size required.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_BUFFERTOOSMALL
DPERR_GENERIC
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_INVALIDPLAYER
DPERR_NOMESSAGES

Remarks

Any message received from a player ID defined as DPID_SYSMSG is a system message used to notify the application of a change in the session. In those cases, the lpData of system messages should be cast to DPMSG_GENERIC and the dwType member should be examined to see what specific system message it is.

Messages that were sent to a player ID defined as DPID_ALLPLAYERS or to a group ID still appear to come from the sending player ID. An application will only receive messages directed to a local player. A player cannot receive a message in which the values pointed to by lpidFrom and lpidTo are equal.

If DPSESSION_NOMESSAGEID is specified in the session description, the lpidFrom will always be 0xFFFFFFFF and the lpidTo value is arbitrary.

All the service providers shipped with DirectPlay perform integrity checks on the data to protect against corruption. Any message retrieved using Receive is guaranteed to be free from corruption.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

DPMSG_GENERIC, IDirectPlay4::Send


IDirectPlay4::SecureOpen

The IDirectPlay4::SecureOpen method creates or joins a secure session. When joining a secure session, use this method to supply logon credentials.

When creating a new session, the host computer can specify an alternate security package to use. When joining a session, a computer can specify a user name and password.

HRESULT SecureOpen(
  LPCDPSESSIONDESC2 lpsd,
  DWORD dwFlags,
  LPCDPSECURITYDESC lpSecurity,
  LPCDPCREDENTIALS lpCredentials
);

Parameters

lpsd
Pointer to the DPSESSIONDESC2 structure describing the session to be created or joined. If a session is to be joined, then only the guidInstance and lpszPassword members need to be specified. The password need only be supplied if the enumerated session had the DPSESSION_PASSWORDREQUIRED flag set.

If a session is to be created, then the application must completely fill out the DPSESSIONDESC2 structure with the properties of the sessions to be created. The guidInstance will be generated by DirectPlay. Note: The DPSESSION_SECURESERVER flag must be set to indicate that all computers attempting to open the session must be authenticated.

If you don't specify the DPSESSION_SECURESERVER flag when filling out the DPSESSIONDESC2 structure, SecureOpen will open an unsecure session, just as if you had called Open.

dwFlags
One of the following flags:
DPOPEN_CREATE
Creates a new instance of a secured session.
DPOPEN_JOIN
Joins an existing instance of a secured session.
DPOPEN_RETURNSTATUS
If this flag is specified, the method will not display any dialog boxes showing the connection progress status. If the connection cannot be made immediately, the method will return with the DPERR_CONNECTING error. The application must keep calling SecureOpen until either DP_OK is returned, indicating successful completion, or some other error code is returned, indicating an error.
lpSecurity
Pointer to a DPSECURITYDESC structure containing the security package to use. Set this parameter to NULL to use the default security package (NT LAN Manager) and CryptoAPI package (Microsoft RSA Base Cryptographic Provider). Relevant only when creating a session. Must be set to NULL when joining a session.
lpCredentials
Pointer to a DPCREDENTIALS structure containing the logon name, password, and domain to be authenticated on the server. NULL if there are no credentials. Credentials are ignored when creating a session.

Return Values

Returns DP_OK if successful or one of the following error values:

DPERR_ACCESSDENIED
DPERR_ALREADYINITIALIZED
DPERR_AUTHENTICATIONFAILED
DPERR_CANNOTCREATESERVER
DPERR_CANTLOADCAPI
DPERR_CANTLOADSECURITYPACKAGE
DPERR_CANTLOADSSPI
DPERR_CONNECTING
DPERR_CONNECTIONLOST
DPERR_ENCRYPTIONFAILED
DPERR_ENCRYPTIONNOTSUPPORTED
DPERR_INVALIDFLAGS
DPERR_INVALIDPARAMS
DPERR_INVALIDPASSWORD
DPERR_LOGONDENIED
DPERR_NOCONNECTION
DPERR_NONEWPLAYERS
DPERR_SIGNFAILED
DPERR_TIMEOUT
DPERR_UNINITIALIZED
DPERR_USERCANCEL

This method DPERR_LOGONDENIED after being called with invalid creadentials or without credentials when credentials are required. The application must collect the user's credentials and call SecureOpen again.

Remarks

When joining a session, first call SecureOpen with no credentials. If the method returns DPERR_LOGONDENIED, then the application must collect the user name and password from the user and call SecureOpen again, passing in the user's credentials through the lpCredentials parameter. If the method returns DP_OK, then the player was able to logon with the credentials he or she had specified earlier during system logon (network logon in NTLM).

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlay4::Open


IDirectPlay4::Send

The IDirectPlay4::Send method sends a message to another player, to a group of players, or to all players in the session. To send a message to another player, specify the target player's player ID. To send a message to a group of players, send the message to the group ID assigned to the group. To send a message to the entire session, send the message to the player ID DPID_ALLPLAYERS. Messages can be sent using either a guaranteed or nonguaranteed protocol on a per message basis. If the session is being hosted on a secure server, messages can be sent encrypted (to ensure privacy) or digitally signed (to ensure authenticity) on a per message basis.

HRESULT Send(
  DPID idFrom,
  DPID idTo,
  DWORD dwFlags,
  LPVOID lpData,
  DWORD dwDataSize
);

Parameters

idFrom
ID of the sending player. The player ID must correspond to one of the local players on this computer.
idTo
The destination ID of the message. To send a message to another player, specify the ID of the player. To send a message to all the players in a group, specify the ID of the group. To send a message to all the players in the session, use the constant symbol DPID_ALLPLAYERS. To send a message to the server player, specify the constant symbol DPID_SERVERPLAYER. A player cannot send a message to itself.
dwFlags
Indicates how the message should be sent. By default (dwFlags = 0), the message is sent nonguaranteed.
DPSEND_ENCRYPTED
Sends the messages encrypted. This can only be done in a secure session. This flag can only be used if the DPSEND_GUARANTEED flag is also set. The message will be sent as a DPMSG_SECUREMESSAGE system message.
DPSEND_GUARANTEED
Sends the message by using a guaranteed method of delivery.
DPSEND_SIGNED
Sends the message with a digital signature. This can only be done in a secure session. This flag can only be used if the DPSEND_GUARANTEED flag is also set. The message will be sent as a DPMSG_SECUREMESSAGE system message.
lpData
Pointer to the data being sent.
dwDataSize
Length of the data being sent.

Return Values

Returns DP_OK if successful or one of the following error values:

DPERR_BUSY
DPERR_CONNECTIONLOST
DPERR_INVALIDPARAMS
DPERR_INVALIDPLAYER
DPERR_NOTLOGGEDIN
DPERR_SENDTOOBIG

This method returns DPERR_INVALIDPARAMS if the encrypted or signed flag is specified for a message that is not also specified as guaranteed. It returns DPERR_NOTLOGGEDIN when the client application tries to send a secure message without first logging on.

If a message is sent to a group, a return value of DP_OK does not necessarily mean that every player in the group got the message. If the message was sent guaranteed, DP_OK means that DirectPlay made a best effort to send it to all the players in the group. Typically, players that don't receive the message are killed because there is a problem with their connection.

Remarks

Use IDirectPlay4::SendEx for asynchronous send options.

Messages can be sent guaranteed or nonguaranteed. By default, messages are sent nonguaranteed, which means that DirectPlay does no verification that the message reached the intended recipient. Sending a guaranteed message takes much longer—a minimum of two to three times longer than nonguaranteed messages. Applications should try to minimize sending guaranteed messages as much as possible and to design the application to tolerate lost messages. All the service providers shipped with DirectPlay perform integrity checks on the data to protect against corruption. Any message sent using this method is guaranteed to be free from corruption.

System messages are always sent guaranteed, whether or not the service provider natively supports guaranteed messages, and whether or not you set the DirectPlay protocol flag. The DirectPlay protocol will be used automatically to send system messages guaranteed.

For non-system messages, if an application sets the DirectPlay protocol flag and sends a message guaranteed (by setting the DPSEND_GUARANTEED flag), the message will be sent guaranteed whether the service provider supports guaranteed messages or not.

For non-system messages, if an application does not set the DirectPlay protocol flag and sends a message guaranteed, the message will be sent guaranteed only if the service provider supports it. If the service provider does not support guaranteed messages, the message will not be sent guaranteed, regardless of the DPSEND_GUARANTEED flag.

An application invokes the DirectPlay protocol by setting the DPSESSION_DIRECTPLAYPROTOCOL flag when creating a session.

Players cannot send a message to themselves. If a player sends a message to a group that it is part of or to DPID_ALLPLAYERS, the player will not receive a copy of that message. The exception to this rule is if the DPSESSION_NOMESSAGEID was specified in the session description (DPSESSIONDESC2). Then it is possible for a player to receive a message that it sent to a group. Because there is no DirectPlay message ID header on the message (indicating who sent the message), it cannot filter out messages based on the message ID.

When DPSESSION_NOMESSAGEID is used, the idFrom parameter has no meaning and the idTo parameter is used simply to direct the message to the correct target computer. If the target computer has more than one player on it, it cannot be determined whose receive queue the message will appear in. When the message is received, it will appear to have come from player DPID_UNKNOWN.

There is no limit to the size of messages that can be transmitted using the Send method. DirectPlay will automatically break up large messages into packets and reassemble them on the receiving end. Beware of sending large messages nonguaranteed—if even one of the packets fails to reach the receiver, the entire message is ignored. The application can determine the greatest message size that can be sent in a single packet by calling GetCaps and examining the dwMaxBufferSize member of the DPCAPS structure.

When you send an encryted or signed message, it is not delivered as an application message, but as a system message, DPMSG_SECUREMESSAGE.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlay4::Receive, IDirectPlay4::SendEx, IDirectPlay4::SendChatMessage, DPMSG_SECUREMESSAGE


IDirectPlay4::SendChatMessage

The IDirectPlay4::SendChatMessage method sends a text message to another player, a group of players, or all players. This method supports both Unicode (the IDirectPlay4 interface) and ANSI strings (the IDirectPlay4A interface). The player receiving the chat message is informed through a DPMSG_CHAT system message in the player's receive queue. This method must be used in a lobby session.

HRESULT SendChatMessage(
  DPID idFrom,
  DPID idTo,
  DWORD dwFlags,
  LPDPCHAT lpChatMessage
);

Parameters

idFrom
ID of the sending player. The player ID must correspond to one of the local players on this computer.
idTo
ID of the player to send the message to, the group ID of the group of players to send the message to, or DPID_ALLPLAYERS to send the message to all players in the session.
dwFlags
Indicates how the message should be sent. If this parameter is set to 0, the message is sent nonguaranteed.
DPSEND_GUARANTEED
Sends the message by using a guaranteed method of delivery if it is available.
lpChatMessage
Pointer to a DPCHAT structure containing the message to be sent.

Return Values

Returns DP_OK if successful or one of the following error values:

DPERR_ACCESSDENIED
DPERR_CONNECTIONLOST
DPERR_INVALIDFLAGS
DPERR_INVALIDPARAMS
DPERR_INVALIDPLAYER

This method returns DPERR_INVALIDPARAMS if the idTo ID is not a valid player or group. It returns DPERR_INVALIDPLAYER if the idFrom ID is not a valid player. It returns DPERR_ACCESSDENIED if the idFrom ID is not a local player.

Remarks

This method facilitates player-to-player chatting within a lobby session where it is possible for different client applications to be connected. You must use this method in a lobby session. Use is optional in an application session.

The receiving player will receive a system message (idFrom = DPID_SYSMSG). The DPCHAT structure will specify which player the chat message came from.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

DPCHAT, DPMSG_CHAT, IDirectPlay4::Send


IDirectPlay4::SendEx

The IDirectPlay4::SendEx method sends a message to another player, to a group of players, or to all players in the session. SendEx is an enhanced version of the Send method and has more options available. SendEx supports both guaranteed and nonguaranteed messages. It also enables you to send asynchronous messages and to set the priority and time-out of a message.

HRESULT SendEx(
  DPID idFrom,
  DPID idTo,
  DWORD dwFlags,
  LPVOID lpData,
  DWORD dwDataSize,
  DWORD dwPriority,
  DWORD dwTimeout,
  LPVOID lpContext,
  LPDWORD lpdwMsgID
);

Parameters

idFrom
ID of the sending player. The player ID must correspond to one of the local players on the computer from which the message is sent.
idTo
The destination ID of the message. To send a message to another player, specify the ID of the player. To send a message to all the players in a group, specify the ID of the group. To send a message to all the players in the session, use the constant symbol DPID_ALLPLAYERS. To send a message to the server player, specify the constant symbol DPID_SERVERPLAYER. A player cannot send a message to himself or herself.
dwFlags
Indicates how the message should be sent. By default (dwFlags = 0), the message is sent nonguaranteed.
DPSEND_ASYNC
Sends the message asynchronously. The function returns immediately and fills in the lpdwMsgID parameter. If this flag is not specified, the function does not return until the message has been sent (and acknowledged, if sent guaranteed). A DPMSG_SENDCOMPLETE system message is posted when the send has completed.

When this flag is used, the return value will be DPERR_PENDING if the message is put in the send queue. This is not a fatal error, but just a return value that lets you know the message did not get sent immediately.

DPSEND_ENCRYPTED
Sends the messages encrypted. This can only be done in a secure session. This flag can only be used if the DPSEND_GUARANTEED flag is also set. The message will be sent as a DPMSG_SECUREMESSAGE system message.
DPSEND_GUARANTEED
Sends the message by using a guaranteed method of delivery if it is available.
DPSEND_NOSENDCOMPLETEMSG
If this flag is set, no completion message is posted. This flag can only be used if the DPSEND_ASYNC flag is also set.
DPSEND_SIGNED
Sends the message with a digital signature. This can only be done in a secure session. This flag can only be used if the DPSEND_GUARANTEED flag is also set. The message will be sent as a DPMSG_SECUREMESSAGE system message.
lpData
Pointer to the data being sent.
dwDataSize
Length of the data being sent.
dwPriority
Priority of the message in the range from 0 to 65535. Zero is the lowest priority message. A larger number indicates a message with a higher priority. A message with a given priority will only be sent when there are no messages in the queue with a higher priority.

Note Not all service providers support this option. If it is not supported, specifying a nonzero priority will return a DPERR_UNSUPPORTED error. Call GetCaps to determine is this option is supported or not.

dwTimeout
Optional application-supplied time-out, in milliseconds, that specifies a time limit for delivering the message. If the message cannot be delivered within this time, it is automatically canceled and a DPMSG_SENDCOMPLETE message is posted. Zero indicates that no time-out should be used.

Note Not all service providers support this option. If it is not supported, specifying a nonzero time-out will return a DPERR_UNSUPPORTED error. Call GetCaps to determine is this option is supported or not.

lpContext
An application-defined context that is returned to the application as part of the completion message when the send has been completed. Can be NULL.
lpdwMsgID
Pointer to a DWORD that will be filled in with a DirectPlay-generated ID for the message. Use this ID to check the status of the message or to cancel it. Pass NULL if no message ID is needed. This parameter is only returned for asynchronous messages.

Return Values

For synchronous messages, returns DP_OK if successful. For asynchronous messages, returns DPERR_PENDING if the send reaches the point where it is successfully queued. You will then get the completion status from the DPMSG_SENDCOMPLETE message. Otherwise, returns one of the following error values:

DPERR_BUSY
DPERR_CONNECTIONLOST
DPERR_INVALIDFLAGS
DPERR_INVALIDPARAMS
DPERR_INVALIDPLAYER
DPERR_INVALIDPRIORITY
DPERR_NOTLOGGEDIN
DPERR_SENDTOOBIG
DPERR_UNSUPPORTED

This method returns DPERR_INVALIDPARAMS if the encrypted or signed flag is specified for a message that is not also specified as guaranteed, or if the DPSEND_NOCOMPLETEMSG flag is specified for a message that is not asynchronous. It returns DPERR_INVALIDPRIORITY if the priority value is not between 0 and 65535. It returns DPERR_NOTSUPPORTED if you specify a nonzero priority and the service provider does not support priorities, or if you specify a nonzero time-out and the service provider does not support this option.

Remarks

If the DirectPlay Protocol was specified in the session description (by setting the DPSESSION_DIRECTPLAYPROTOCOL flag in the DPSESSIONDESC2 structure), then all the options on SendEx are available. Otherwise, an application should call GetCaps to determine what options the service provider has implemented. SendEx supports guaranteed and nonguaranteed messages. Messages sent guaranteed will not be blocked if there are pending messages waiting to be acknowledged by the receiver.

If a message is sent asynchronously (by setting the DPSEND_ASYNC flag), the message will be put into a send queue and the SendEx function will return immediately. A system message (DPMSG_SENDCOMPLETE) will be posted to the receive queue of the sending player indicating the result of the send.

You can give messages priorities. A message is sent when there are no higher priority messages waiting to be sent and when there is available bandwidth.

You can give a message a time-out. If DirectPlay cannot deliver the message in the time specified, it will be canceled.

The DPSEND_SIGNED and DPSEND_ENCRYPTED flags cannot be used if the order of delivery of guaranteed messages is not preserved because the DPSESSION_NOPRESERVEORDER flag is set in the session description (DPSESSIONDESC2).

If messages are sent using different priorities, signing and encryption may not work. It is best for the application to decide on one priority level for secure messages and only use the security flag on that priority level. This is because validation of secure messages depends on the order in which they are received and prioritization may change this order.

If the DirectPlay Protocol is active, it will attempt to throttle outbound network traffic. That is, it will not always send packets as fast as possible. It will send packets as fast as it can without overwhelming the inbound bandwidth of the receiving computer.

System messages are always sent guaranteed, whether or not the service provider natively supports guaranteed messages, and whether or not you set the DirectPlay protocol flag. The DirectPlay protocol will be used automatically to send system messages guaranteed.

For non-system messages, if an application sets the DirectPlay protocol flag and sends a message guaranteed (by setting the DPSEND_GUARANTEED flag), the message will be sent guaranteed whether the service provider supports guaranteed messages or not.

For non-system messages, if an application does not set the DirectPlay protocol flag and sends a message guaranteed, the message will be sent guaranteed only if the service provider supports it. If the service provider does not support guaranteed messages, the message will not be sent guaranteed, regardless of the DPSEND_GUARANTEED flag.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlay4::Send, IDirectPlay4::CancelMessage, IDirectPlay4::CancelPriority, IDirectPlay4::GetMessageQueue, DPMSG_SENDCOMPLETE


IDirectPlay4::SetGroupConnectionSettings

The IDirectPlay4::SetGroupConnectionSettings method sets the connection settings for a session that will be launched from this group. This method can only be used in a lobby session.

HRESULT SetGroupConnectionSettings(
  DWORD dwFlags,
  DPID idGroup,
  LPDPLCONNECTION lpConnection
);

Parameters

dwFlags
Not used. Must be 0.
idGroup
ID of the group to set the connection settings on.
lpConnection
Pointer to a DPLCONNECTION structure describing the application to be launched, the service provider to use, and the session description of the session to be created.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_ACCESSDENIED
DPERR_CONNECTIONLOST
DPERR_INVALIDGROUP
DPERR_INVALIDPARAMS
DPERR_UNSUPPORTED

Remarks

Call IDirectPlay4::GetGroupConnectionSettings before calling SetGroupConnectionSettings to see if any of the DPLCONNECTION structure members already have default values (non-NULL or nonzero). If so, you may get an error if you try to change these default values.

You do not have to set the lpAddress and dwAddressSize data members of the DPLCONNECTION structure with SetGroupConnectionSettings. In the DPSESSIONDESC2 structure within the DPLCONNECTION structure, you do not have to fill in the guidInstance member.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

DPLCONNECTION, IDirectPlayLobby3::RunApplication, IDirectPlay4::GetGroupConnectionSettings


IDirectPlay4::SetGroupData

The IDirectPlay4::SetGroupData method associates an application-specific data block with a group ID. Only the computer that created the group can change the remote data associated with it.

HRESULT SetGroupData(
  DPID idGroup,
  LPVOID lpData,
  DWORD dwDataSize,
  DWORD dwFlags
);

Parameters

idGroup
Group ID for which data is being set.
lpData
Pointer to the data to be set. Set to NULL to clear any existing group data.
dwDataSize
Size of the data buffer. If lpData is NULL and this parameter does not equal 0, the method returns DPERR_INVALIDPARAMS.
dwFlags
Flag indicating how the group data is propagated. If this parameter is set to 0, the remote group data will be set and propagated using nonguaranteed messaging.
DPSET_GUARANTEED
Propagates the data by using guaranteed messaging (if available). This flag can only be used with DPSET_REMOTE.
DPSET_LOCAL
This data is for local use only and will not be propagated.
DPSET_REMOTE
This data is for use by all the applications and will be propagated to all the other applications in the session. This flag can only be used on groups owned by the local session.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_ACCESSDENIED
DPERR_CONNECTIONLOST
DPERR_INVALIDGROUP
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS

Remarks

DirectPlay can maintain two types of group data: local and remote. Local data is available only to the application on the local computer. Remote data is propagated to all the other applications in the session. A DPMSG_SETPLAYERORGROUPDATA system message will be sent to all players (including the sender) notifying them of the change unless DPSESSION_NODATAMESSAGES is set in the session description. You can safely store pointers to resources in the local data; the local data block is available (in the DPMSG_DESTROYPLAYERORGROUP system message) when the group is being destroyed, so that the application can free those resources.

This method should not be used for updating real-time information (such as position updates) because of the overhead introduced. IDirectPlay4::Send is much more efficient for updating real-time information. IDirectPlay4::SetGroupData is more appropriate for shared-state information that does not change often and is not time-critical (such as a team color).

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

DPMSG_SETPLAYERORGROUPDATA, IDirectPlay4::GetGroupData, IDirectPlay4::Send


IDirectPlay4::SetGroupName

The IDirectPlay4::SetGroupName method sets the name of a group after it has been created. Only the computer that created the group can set the name of the group. A DPMSG_SETPLAYERORGROUPNAME system message will be sent to all the other players notifying them of the change unless DPSESSION_NODATAMESSAGES is set in the session description.

HRESULT SetGroupName(
  DPID idGroup,
  LPDPNAME lpGroupName,
  DWORD dwFlags
);

Parameters

idGroup
ID of the group for which the name is being set.
lpGroupName
Pointer to a DPNAME structure containing the name information for the group. Set this parameter to NULL if the group has no name information.
dwFlags
If this parameter is set to 0, the name will be propagated to all the remote systems by using nonguaranteed message passing. This value can only be used on groups owned by the local session.
DPSET_GUARANTEED
Propagates the data using guaranteed messaging (if available).
DPSET_LOCAL
This data is for local use only and will not be propagated.
DPSET_REMOTE
This data is for use by all the applications, and will be propagated to all the other applications in the session. This flag can only be used on groups owned by the local session.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_CONNECTIONLOST
DPERR_INVALIDGROUP
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_INVALIDPLAYER

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

DPNAME, DPMSG_SETPLAYERORGROUPNAME, IDirectPlay4::GetGroupName, IDirectPlay4::Send


IDirectPlay4::SetGroupOwner

The IDirectPlay4::SetGroupOwner method changes the owner of a group. This method is only available in a lobby session. It generates a DPMSG_SETGROUPOWNER system message.

HRESULT SetGroupOwner(
  DPID idGroup,
  DPID idOwner
);

Parameters

idGroup
ID of the group whose owner is being changed.
idOwner
ID of the player to be set as the owner of the group.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_CONNECTIONLOST
DPERR_GENERIC
DPERR_INVALIDGROUP
DPERR_INVALIDPLAYER
DPERR_UNAVAILABLE

This method returns DPERR_UNAVAILABLE if the session is not a lobby session.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlay4::GetGroupOwner, DPMSG_SETGROUPOWNER


IDirectPlay4::SetPlayerData

The IDirectPlay4::SetPlayerData method associates an application-specific data block with a player ID.

HRESULT SetPlayerData(
  DPID idPlayer,
  LPVOID lpData,
  DWORD dwDataSize,
  DWORD dwFlags
);

Parameters

idPlayer
ID of the player for which data is being set.
lpData
Pointer to the data to be set. Set this parameter to NULL and dwDataSize to 0 to clear out any existing player data.
dwDataSize
Size of the data buffer. If lpData is NULL and this parameter does not equal 0, the method returns DPERR_INVALIDPARAMS.
dwFlags
If this parameter is set to 0, the remote player data will be set and propagated by using nonguaranteed messaging.
DPSET_GUARANTEED
Propagates the data by using guaranteed messaging (if available). This flag can only be used with DPSET_REMOTE.
DPSET_LOCAL
This data is for local use only and will not be propagated.
DPSET_REMOTE
This data is for use by all the applications, and will be propagated to all the other applications in the session.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_ACCESSDENIED
DPERR_CONNECTIONLOST
DPERR_INVALIDFLAGS
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_INVALIDPLAYER

Remarks

SetPlayerData should not be used for updating real-time information (such as position updates) due to the overhead introduced. It is much more efficient to use Send for this. SetPlayerData is more appropriate for shared state information that doesn't change very often and is not time critical (such as a player's name).

DirectPlay can maintain two types of player data: local and remote. Local data is available only to the application on the local computer. Remote data is propagated to all the other applications in the session. This method returns DPERR_ACCESSDENIED if you try to set player data for a remote player. A DPMSG_SETPLAYERORGROUPDATA system message will be sent to all players (including the sender) notifying them of the change unless DPSESSION_NODATAMESSAGES is set in the session description. It is safe to store pointers to resources in the local data; the local data block is available (in the DPMSG_DESTROYPLAYERORGROUP system message) when the player is being destroyed, so the application can free those resources. For a list of system messages, see Using System Messages.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

DPMSG_SETPLAYERORGROUPDATA, IDirectPlay4::GetPlayerData, IDirectPlay4::Send


IDirectPlay4::SetPlayerName

The IDirectPlay4::SetPlayerName method sets the name of a local player after it has been changed. Only the computer that created the player can change the name. A DPMSG_SETPLAYERORGROUPNAME system message will be sent to all the other players notifying them of the change unless DPSESSION_NODATAMESSAGES is set in the session description.

HRESULT SetPlayerName(
  DPID idPlayer,
  LPDPNAME lpPlayerName,
  DWORD dwFlags
);

Parameters

idPlayer
ID of the local player for which data is being sent.
lpPlayerName
Pointer to a DPNAME structure containing the name information for the player. Set this parameter to NULL if the player has no name information.
dwFlags
Flags indicating how the name will be propagated. It can be one of the following values:
DPSET_GUARANTEED
Propagates the data by using guaranteed messaging (if available).
DPSET_LOCAL
Data is not propagated to other players.
DPSET_REMOTE
Propagates the data to all players in the session using nonguaranteed message passing. This is the default value.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_CONNECTIONLOST
DPERR_INVALIDOBJECT
DPERR_INVALIDPLAYER

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

DPNAME, DPMSG_SETPLAYERORGROUPNAME, IDirectPlay4::GetPlayerName, IDirectPlay4::Send


IDirectPlay4::SetSessionDesc

The IDirectPlay4::SetSessionDesc method changes the properties of the current session. Only the host of the session can change the session properties. If a nonhost attempts to call it, the method returns DPERR_ACCESSDENIED.

The updated session description will be propagated to all the other computers in the session. Each player will receive a DPMSG_SETSESSIONDESC system message.

You can't use SetSessionDesc in a lobby session.

HRESULT SetSessionDesc(
  LPDPSESSIONDESC2 lpSessDesc,
  DWORD dwFlags
);

Parameters

lpSessDesc
Pointer to the DPSESSIONDESC2 structure containing the new settings.
dwFlags
No flags are currently used by this method.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_ACCESSDENIED
DPERR_CONNECTIONLOST
DPERR_INVALIDPARAMS
DPERR_NOSESSIONS

This method returns DPERR_ACCESSDENIED if this computer does not have permission to change the session. Only the host can change the session properties. It returns DPERR_INVALIDPARAMS if the application attempts to change a property in the session description that cannot be changed or tries to give a property an invalid value.

Remarks

Changing the session description will cause a DPMSG_SETSESSIONDESC system message to be generated on all the other computers in the session.

The following members and flags of the DPSESSIONDESC2 structure can be changed using IDirectPlay4::SetSessionDesc:

dwFlags
DPSESSION_JOINDISABLED

DPSESSION_NEWPLAYERSDISABLED

DPSESSION_NODATAMESSAGES

DPSESSION_PRIVATE

dwMaxPlayers
If you set the maximum players to a value less than the current number of players, the method returns DPERR_INVALIDPARAMS.
lpszSessionName / lpszSessionNameA
lpszPassword / lpszPasswordA
dwUser1
dwUser2
dwUser3
dwUser4

If the following members and flags of the DPSESSIONDESC2 structure are changed, an error will occur (for example, if the DPSESSION_KEEPALIVE flag is currently set and you try to set this bit, you will not get an error, but if you try to clear this bit, you will get an error and IDirectPlay4::SetSessionDesc will fail):

dwSize
dwFlags
DPSESSION_NOMESSAGEID

DPSESSION_KEEPALIVE

The following members of the DPSESSIONDESC2 structure are ignored (that is, it does not matter what you pass in these members; DirectPlay will always use the values passed when IDirectPlay4::Open was called):

guidInstance
guidApplication
dwCurrentPlayers
dwReserved1
dwReserved2

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

DPSESSIONDESC2, IDirectPlay4::GetSessionDesc


IDirectPlay4::StartSession

The IDirectPlay4::StartSession method launches a DirectPlay session from a staging area. Call SetGroupConnectionSettings first to specify what application to launch, which service provider to use, and what session description to use.

When StartSession is called, each player in the group receives a DPMSG_STARTSESSION instructing the player to launch the session.

HRESULT StartSession(
  DWORD dwFlags,
  DPID idGroup
);

Parameters

dwFlags
Not used. Must be 0.
idGroup
The ID of the group to send start session commands to. The group must be a staging area.

Return Values

Returns DP_OK if successful or one of the following error values:

DPERR_ACCESSDENIED
DPERR_CONNECTIONLOST
DPERR_INVALIDFLAGS
DPERR_INVALIDGROUP
DPERR_INVALIDPARAMS

This method returns DPERR_INVALIDGROUP if the given group ID is not a valid staging area.

Remarks

A player joining a staging area group for which the session has already started can call this method to join the session. The player will receive a DPMSG_STARTSESSION message instructing it how to join the session.

You can determine if a session is already in progress by calling IDirectPlay4::GetGroupConnectionSettings and examining the guidInstance parameter it returns through a pointer in the DPLCONNECTION structure to the DPSESSIONDESC2 structure. If guidInstance is GUID_NULL, no session is in progress. If it is any other value, a session is already in progress.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

Synchronized Launching


IDirectPlayLobby3

Applications use the methods of the IDirectPlayLobby3 interface to manage applications and their associated data. This section is a reference to the methods of this interface.

The methods of the IDirectPlayLobby3 interface can be organized into the following groups:

Address management | CreateAddress
 | CreateCompoundAddress
 | EnumAddress
 | EnumAddressTypes
Application management | Connect
 | ConnectEx
 | EnumLocalApplications
 | RegisterApplication
 | RunApplication
 | UnregisterApplication
 | WaitForConnectionSettings
Data management | GetConnectionSettings
 | ReceiveLobbyMessage
 | SendLobbyMessage
 | SetConnectionSettings
 | SetLobbyMessageEvent

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.
Import Library: Use dplayx.lib.


IDirectPlayLobby3::Connect

The IDirectPlayLobby3::Connect method connects an application to the session specified by the DPLCONNECTION structure currently stored with the DirectPlayLobby object.

Note This method will return an IDirectPlay2 or IDirectPlay2A interface. If this is not the desired DirectPlay COM interface, the application must obtain the correct interface (for example, IDirectPlay4 or IDirectPlay4A) by using QueryInterface and release this interface. A newer method, IDirectPlayLobby3::ConnectEx, allows the application to specify which DirectPlay COM interface to return.

By default, Connect returns after a connection is made or when the connection has timed out. If you use the DPCONNECT_RETURNSTATUS flag, Connect returns immediately with a DPERR_CONNECTING error code indicating the connection is in progress. The application must continue calling this method periodically until DP_OK or a failure code is returned. The application can cancel the connection by releasing the IDirectPlayLobby3 interface.

HRESULT Connect(
  DWORD dwFlags,
  LPDIRECTPLAY2 *lplpDP,
  IUnknown FAR *pUnk
);

Parameters

dwFlags
Flags indicating how the connection is to be done. By default (dwFlags = 0), the method returns once a connection has been established or the operation has timed out.
DPCONNECT_RETURNSTATUS
Returns immediately with the status of the connection. The application must continue calling Connect until a success or error code is returned.
lplpDP
Pointer to a pointer to be initialized with a valid interface—either IDirectPlay2 (if called on IDirectPlayLobby3) or IDirectPlay2A (if called on IDirectPlayLobby3A). Note that if some other interface is desired, the application should use QueryInterface to obtain a pointer to the new interface and to release this one. Alternatively, the ConnectEx method can be used.
pUnk
Pointer to the containing IUnknown interface. This parameter is provided for future compatibility with COM aggregation features. Presently, however, IDirectPlayLobby3::Connect returns an error if this parameter is anything but NULL.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

CLASS_E_NOAGGREGATION
DPERR_CONNECTING
DPERR_INVALIDFLAGS
DPERR_INVALIDINTERFACE
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_NOTLOBBIED
DPERR_OUTOFMEMORY

The method returns DPERR_CONNECTING while the connection operation is in progress. Call the methods again to get an updated status.

Remarks

There is an upper limit of one minute on connection time-out.

After this method is successfully completed, the application can skip the process of calling IDirectPlay4::InitializeConnection, IDirectPlay4::EnumSessions, and IDirectPlay4::Open. The application should not ask the user a name but instead create a player using the player name information in the DPLCONNECTION structure.

Before calling this method, the application can examine the connection settings that will be used to start the application by using the IDirectPlayLobby3::GetConnectionSettings method. The application then can modify these settings and set them by using the IDirectPlayLobby3::SetConnectionSettings method. The application should pay particular attention to the DPSESSIONDESC2 structure to ensure that the proper session properties are set, especially dwFlags, dwMaxPlayers, and the dwUser members.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlayLobby3::ConnectEx


IDirectPlayLobby3::ConnectEx

The IDirectPlayLobby3::ConnectEx method connects an application to the session specified by the DPLCONNECTION structure currently stored with the DirectPlayLobby object.

This method is an extended version of the Connect method. This version allows the application to specify which version of the DirectPlay\ COM interface to return.

By default, ConnectEx returns after a connection is made or the connection has timed out. If you use the DPCONNECT_RETURNSTATUS flag, ConnectEx returns immediately with a DPERR_CONNECTING error code indicating the connection is in progress. The application must continue calling this method periodically until DP_OK or a failure code is returned. The application can cancel the connection by releasing the IDirectPlayLobby3 interface.

HRESULT ConnectEx(
  DWORD dwFlags,
  REFIID riid,
  LPVOID *lplpDP,
  IUnknown FAR *pUnk
);

Parameters

dwFlags
Flags indicating how the connection is to be done. By default (dwFlags = 0), the method returns after a connection has been established or the operation has timed out.
DPCONNECT_RETURNSTATUS
Returns immediately with the status of the connection. The application must continue calling ConnectEx until a success or error code is returned.
riid
The IID of the specific DirectPlay COM interface to be returned; for example, IID_IDirectPlay4A.
lplpDP
Pointer to a pointer to be initialized with the DirectPlay interface as specified by the riid parameter.
pUnk
Pointer to the containing IUnknown interface. This parameter is provided for future compatibility with COM aggregation features. Presently, however, IDirectPlayLobby3::ConnectEx returns an error if this parameter is anything but NULL.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_CONNECTING
DPERR_INVALIDFLAGS
DPERR_INVALIDPARAMS

The method returns DPERR_CONNECTING while the connection operation is in progress. Call the methods again to get an updated status.

Remarks

There is an upper limit of one minute on connection time-out.

After this method is successfully completed, the application can skip the process of calling IDirectPlay4::InitializeConnection, IDirectPlay4::EnumSessions, and IDirectPlay4::Open. The application should not ask the user a name but instead create a player using the player name information in the DPLCONNECTION structure.

Before calling this method, the application can examine the connection settings that will be used to start the application by using the IDirectPlayLobby3::GetConnectionSettings method. The application then can modify these settings and set them by using the IDirectPlayLobby3::SetConnectionSettings method. The application should pay particular attention to the DPSESSIONDESC2 structure to ensure that the proper session properties are set, especially dwFlags, dwMaxPlayers, and the dwUser members.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlayLobby3::ConnectEx

Built on Thursday, September 02, 1999


IDirectPlayLobby3::CreateAddress

The IDirectPlayLobby3::CreateAddress method creates a DirectPlay address, given a service provider-specific network address. The resulting address contains the globally unique identifier (GUID) of the service provider and data that the service provider can interpret as a network address.

Note that with IDirectPlayLobby3::CreateCompoundAddress you can create addresses with more than one data chunk. Therefore, you should use IDirectPlayLobby3::CreateCompoundAddress.

HRESULT CreateAddress(
  REFGUID guidSP,
  REFGUID guidDataType,
  LPCVOID lpData,
  DWORD dwDataSize,
  LPVOID lpAddress,
  LPDWORD lpdwAddressSize
);

Parameters

guidSP
Pointer to the GUID of the service provider. (In C++, it is a reference to the GUID.)
guidDataType
Pointer to the GUID identifying the specific network address type being used. (In C++, it is a reference to the GUID.) For information about predefined network address types, see DirectPlay Address.
lpData
Pointer to a buffer containing the specific network address.
dwDataSize
Size, in bytes, of the network address in lpData.
lpAddress
Pointer to a buffer in which the constructed DirectPlay address is to be written.
lpdwAddressSize
Pointer to a variable containing the size of the DirectPlay address buffer. Before calling this method, the service provider must initialize lpdwAddressSize to the size of the buffer. After the method has returned, this parameter will contain the number of bytes written to lpAddress. If the buffer was too small (DPERR_BUFFERTOOSMALL), this parameter will be set to the size required to store the DirectPlay address.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_BUFFERTOOSMALL
DPERR_INVALIDPARAMS

Remarks

The IDirectPlayLobby3::CreateCompoundAddress method can be used to create longer DirectPlay addresses than CreateAddress allows.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlayLobby3::EnumAddress, IDirectPlayLobby3::CreateCompoundAddress, DirectPlay Address, DirectPlay Address Data Types


IDirectPlayLobby3::CreateCompoundAddress

The IDirectPlayLobby3::CreateCompoundAddress method creates a DirectPlay address from a list of individual data chunks. This method can be used to create longer DirectPlay addresses than IDirectPlayLobby3::CreateAddress allows.

HRESULT CreateCompoundAddress(
  LPDPCOMPOUNDADDRESSELEMENT lpElements,
  DWORD dwElementCount,
  LPVOID lpAddress,
  LPDWORD lpdwAddressSize
);

Parameters

lpElements
Pointer to the first element in an array of DPCOMPOUNDADDRESSELEMENT structures that will be used to generate the DirectPlay address.
dwElementCount
The number of address elements in the array pointed to by the lpElements parameter.
lpAddress
Pointer to a buffer that the complete DirectPlay address is to be written to. Pass NULL if only the required size of the buffer is desired.
lpdwAddressSize
Pointer to a DWORD with the size of the lpAddress buffer. The DWORD will be modified to reflect the actual number of bytes copied into the buffer. If the buffer was too small, it will contain the number of bytes required.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_BUFFERTOOSMALL
DPERR_INVALIDFLAGS
DPERR_INVALIDPARAMS

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlayLobby3::CreateAddress, IDirectPlayLobby3::EnumAddress, DPCOMPOUNDADDRESSELEMENT, DirectPlay Address


IDirectPlayLobby3::EnumAddress

The IDirectPlayLobby3::EnumAddress method parses out chunks from the DirectPlay address buffer.

HRESULT EnumAddress(
  LPDPENUMADDRESSCALLBACK lpEnumAddressCallback,
  LPCVOID lpAddress,
  DWORD dwAddressSize,
  LPVOID lpContext
);

Parameters

lpEnumAddressCallback
Pointer to a EnumAddressCallback function that will be called for each information chunk in the DirectPlay address.
lpAddress
Pointer to the start of the DirectPlay address buffer.
dwAddressSize
Size of the DirectPlay address.
lpContext
Context that will be passed to the callback function.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_EXCEPTION
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlayLobby3::CreateAddress, DirectPlay Address


IDirectPlayLobby3::EnumAddressTypes

The IDirectPlayLobby3::EnumAddressTypes method enumerates all the address types that a given service provider needs to build the DirectPlay address. The application or lobby can use this information to obtain the correct information from the user and create a DirectPlay address.

HRESULT EnumAddressTypes(
  LPDPLENUMADDRESSTYPESCALLBACK lpEnumAddressTypeCallback,
  REFGUID guidSP,
  LPVOID lpContext,
  DWORD dwFlags
);

Parameters

lpEnumAddressTypeCallback
Pointer to the EnumAddressTypeCallback function that will be called for each address type for a service provider. If the service provider takes no address type, the callback will not be called.
guidSP
Pointer to the GUID of the service provider whose address types are to be enumerated. (In C++, it is a reference to the GUID.)
lpContext
Context that will be passed to the callback function.
dwFlags
Reserved; must be 0.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_EXCEPTION
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS

Remarks

You can use EnumAddressTypes to determine if a service provider displays dialog boxes prompting the user for information; for example, a dialog box that asks for an IP address. If the service provider takes no address types, then it needs no information and will not display the dialog boxes.

An application can call IDirectPlay4::GetPlayerAddress to obtain a list of valid choices for an address type. This is only available for the modem-to-modem service providers. DirectPlay address data types that are null-terminated Unicode strings end in W (for example, DPAID_INetW), while DirectPlay address data types that are null-terminated ANSI strings do not (for example, DPAID_INet). For a list of predefined Microsoft data types, see DirectPlay Address Data Types.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.
Import Library: Use dplayx.lib.

See Also

DirectPlay Address, IDirectPlayLobby3::CreateAddress


IDirectPlayLobby3::EnumLocalApplications

The IDirectPlayLobby3::EnumLocalApplications method enumerates what applications are registered with DirectPlay.

Calling this method on the IDirectPlayLobby3A (ANSI) interface returns a suitably localized, single-byte character string. No multi-byte characters are used so there are no problems displaying the strings using fonts that do not support multi-byte characters. Calling this method on the IDirectPlayLobby3 (Unicode) interface returns a localized, wide character description. Lobbies that are specifically localized should call this method on the Unicode interface.

HRESULT EnumLocalApplications(
  LPDPENUMLOCALAPPLICATIONSCALLBACK lpEnumLocalAppCallback,
  LPVOID lpContext,
  DWORD dwFlags
);

Parameters

lpEnumLocalAppCallback
Pointer to the EnumLocalApplicationsCallback function that will be called for each enumerated application.
lpContext
Context passed to the callback function.
dwFlags
Reserved; must be 0.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_GENERIC
DPERR_INVALIDINTERFACE
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_OUTOFMEMORY

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.
Import Library: Use dplayx.lib.

See Also

DPLAPPINFO


IDirectPlayLobby3::GetConnectionSettings

The IDirectPlayLobby3::GetConnectionSettings method retrieves the DPLCONNECTION structure that contains all the information needed to start and connect an application. The data returned is the same data that was passed to the IDirectPlayLobby3::RunApplication method by the lobby client, or set by calling the IDirectPlayLobby3::SetConnectionSettings method.

HRESULT GetConnectionSettings(
  DWORD dwAppID,
  LPVOID lpData,
  LPDWORD lpdwDataSize
);

Parameters

dwAppID
Identifies which application's connection settings to retrieve when called from a lobby client (that communicates with several applications). When called from an application (that only communicates with one lobby client), this parameter must be 0. This ID number is obtained from IDirectPlayLobby3::RunApplication.
lpData
Pointer to a buffer in which the connection settings are to be written. Set this parameter to NULL to request only the size of data. The lpdwDataSize parameter will be set to the minimum size required to hold the data.
lpdwDataSize
Pointer to a variable that is initialized to the size of the buffer before calling this method. After the method returns, this parameter will be set to the size, in bytes, of the data. If the buffer was too small (DPERR_BUFFERTOOSMALL), then this parameter will be set to the minimum buffer size required.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_BUFFERTOOSMALL
DPERR_GENERIC
DPERR_INVALIDINTERFACE
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_NOTLOBBIED
DPERR_OUTOFMEMORY

Remarks

The lpData member should be cast to the DPLCONNECTION structure when the method returns to read the data from it.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.
Import Library: Use dplayx.lib.

See Also

DPLCONNECTION, IDirectPlayLobby3::RunApplication, IDirectPlayLobby3::SetConnectionSettings, IDirectPlayLobby3::WaitForConnectionSettings


IDirectPlayLobby3::ReceiveLobbyMessage

The IDirectPlayLobby3::ReceiveLobbyMessage method retrieves the message sent between a lobby client application and a DirectPlay application. Messages are queued, so there is no danger of losing data if it is not read in time.

HRESULT ReceiveLobbyMessage(
  DWORD dwFlags,
  DWORD dwAppID,
  LPDWORD lpdwMessageFlags,
  LPVOID lpData,
  LPDWORD lpdwDataSize
);

Parameters

dwFlags
Reserved; must be 0.
dwAppID
Identifies which application's message to retrieve when called from a lobby client (that communicates with several applications). When called from an application (that communicates only with one lobby client), this parameter must be set to 0. This ID number is obtained by using the IDirectPlayLobby3::RunApplication method.
lpdwMessageFlags
Flags indicating what type of message is being returned. The default (lpdwMessageFlags = 0) indicates that the message is custom-defined by the sender. Processing of this type of message is optional. The receiver must interpret this message based on the identity of the sending application. A lobby can identify the sending application based on the GUID of the application that was launched. An application will need to identify the lobby by sending the lobby a standard message requesting an identifying GUID.
DPLMSG_STANDARD
Indicates that this is a DirectPlay-defined message. Processing of this type of message is optional.
DPLMSG_SYSTEM
Indicates that this is a DirectPlay-generated system message used to inform the lobby of changes in the status of the application it launched.
lpData
Pointer to a buffer in which the message is to be written. Set this parameter to NULL to request only the size of message. The lpdwDataSize parameter will be set to the minimum size required to hold the message.
lpdwDataSize
Pointer to a variable that is initialized to the size of the buffer before calling this method. After the method returns, this parameter will be set to the size, in bytes, of the message. If the buffer was too small (DPERR_BUFFERTOOSMALL), then this parameter will be set to the minimum buffer size required.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_APPNOTSTARTED
DPERR_BUFFERTOOSMALL
DPERR_GENERIC
DPERR_INVALIDINTERFACE
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_NOMESSAGES
DPERR_OUTOFMEMORY

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlayLobby3::RunApplication, IDirectPlayLobby3::SendLobbyMessage


IDirectPlayLobby3::RegisterApplication

The IDirectPlayLobby3::RegisterApplication method registers a lobby-aware application with DirectPlay. An application must be registered so that a DirectPlay lobby can launch it.

The application needs to be registered only once. The application must also be unregistered (see IDirectPlayLobby3::UnregisterApplication) when it is uninstalled.

HRESULT RegisterApplication(
  DWORD  dwFlags,
  LPVOID lpAppDesc
);

Parameters

dwFlags
Reserved; must be 0.
lpAppDesc
Pointer to a DPAPPLICATIONDESC or DPAPPLICATIONDESC2 structure that has been filled in with all the registration values for the application.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_INVALIDFLAGS
DPERR_INVALIDPARAMS

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlayLobby3::UnregisterApplication, DirectXRegisterApplication


IDirectPlayLobby3::RunApplication

The IDirectPlayLobby3::RunApplication method starts an application and passes to it all the information necessary to connect it to a session. This method is used by a lobby client.

HRESULT RunApplication(
  DWORD dwFlags,
  LPDWORD lpdwAppID,
  LPDPLCONNECTION lpConn,
  HANDLE hReceiveEvent
);

Parameters

dwFlags
Reserved; must be 0.
lpdwAppID
Pointer to a variable that will be filled with an ID identifying the application that was started. The lobby client must save this application ID for use on with any calls to the IDirectPlayLobby3::SendLobbyMessage and IDirectPlayLobby3::ReceiveLobbyMessage methods.
lpConn
Pointer to a DPLCONNECTION structure that contains all the information necessary to specify which application to start and how to get it connected to a session instance without displaying any user dialog boxes.
hReceiveEvent
Specifies a synchronization event that will be set when a lobby message is received. This event can be changed later by using the IDirectPlayLobby3::SetLobbyMessageEvent method.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_CANTCREATEPROCESS
DPERR_GENERIC
DPERR_INVALIDINTERFACE
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_OUTOFMEMORY
DPERR_UNKNOWNAPPLICATION

Remarks

This method will return after the application process has been created. The lobby client will receive a system message indicating the status of the application. If the lobby client is starting an application that will be hosting a session, it should wait until it receives a DPLSYS_DPLAYCONNECTSUCCEEDED system message before starting the other applications that will be joining the session. If the application was unable to create or join a session, a DPLSYS_DPLAYCONNECTFAILED message will be generated. The lobby client will also receive a DPLSYS_CONNECTIONSETTINGSREAD system message when the application has read the connection settings and a DPLSYS_APPTERMINATED system message when the application terminates.

It is important that the lobby client not release its IDirectPlayLobby3 interface before it receives a DPLSYS_CONNECTIONSETTINGSREAD system message. The lobby client can either check IDirectPlayLobby3::ReceiveLobbyMessage in a loop until it is received, or supply a synchronization event.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlayLobby3::ReceiveLobbyMessage, IDirectPlayLobby3::GetConnectionSettings, IDirectPlayLobby3::SetLobbyMessageEvent


IDirectPlayLobby3::SendLobbyMessage

The IDirectPlayLobby3::SendLobbyMessage method sends a message between the application and the lobby client.

HRESULT SendLobbyMessage(
  DWORD dwFlags,
  DWORD dwAppID,
  LPVOID lpData,
  DWORD dwDataSize
);

Parameters

dwFlags
Flags indicating the type of message being sent. The default (dwFlags = 0) is a custom message defined by the application sending it. Other possible values are:
DPLMSG_STANDARD
This is a standard message defined by DirectPlay.
dwAppID
Identifies which application to send a message to when called from a lobby client (that communicates with several applications). When called from an application (that communicates with only one lobby client), this parameter must be 0. This ID is obtained by using the IDirectPlayLobby3::RunApplication method.
lpData
Pointer to the buffer containing the message to send.
dwDataSize
Size, in bytes, of the buffer.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_APPNOTSTARTED
DPERR_BUFFERTOOLARGE
DPERR_GENERIC
DPERR_INVALIDINTERFACE
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_OUTOFMEMORY
DPERR_TIMEOUT

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlayLobby3::RunApplication, IDirectPlayLobby3::ReceiveLobbyMessage, DPLMSG_SETPROPERTY, DPLMSG_SETPROPERTYRESPONSE, DPLMSG_GETPROPERTY, DPLMSG_GETPROPERTYRESPONSE,


IDirectPlayLobby3::SetConnectionSettings

The IDirectPlayLobby3::SetConnectionSettings method modifies the settings used to start and connect an application.

HRESULT SetConnectionSettings(
  DWORD dwFlags,
  DWORD dwAppID,
  LPDPLCONNECTION lpConn
);

Parameters

dwFlags
Reserved; must be 0.
dwAppID
When called from a lobby client (that communicates with several applications), this parameter identifies which application's connection settings to set. When called from an application (that communicates with only one lobby client), this parameter must be 0. This ID is obtained by using the IDirectPlayLobby3::RunApplication method.
lpConn
Pointer to a DPLCONNECTION structure that contains all the information necessary to specify which application to start and how to get it connected to a session instance without displaying any user dialog boxes.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_GENERIC
DPERR_INVALIDINTERFACE
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_OUTOFMEMORY

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlayLobby3::GetConnectionSettings


IDirectPlayLobby3::SetLobbyMessageEvent

The IDirectPlayLobby3::SetLobbyMessageEvent method registers an event that will be set when a lobby message is received. The application must call this method if it needs to synchronize with messages. The lobby client can call this method to change the events specified in the call to the IDirectPlayLobby3::RunApplication method.

HRESULT SetLobbyMessageEvent(
  DWORD dwFlags,
  DWORD dwAppID,
  HANDLE hReceiveEvent
);

Parameters

dwFlags
Reserved; must be 0.
dwAppID
Identifies which application the event is associated with when called from a lobby client (that communicates with several applications). When called from an application (that communicates with only one lobby client), this parameter must be 0. This ID number is obtained from IDirectPlayLobby3::RunApplication.
hReceiveEvent
Event handle to be set when a message is received.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_GENERIC
DPERR_INVALIDINTERFACE
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_OUTOFMEMORY

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlayLobby3::ReceiveLobbyMessage, IDirectPlayLobby3::SendLobbyMessage


IDirectPlayLobby3::UnregisterApplication

The IDirectPlayLobby3::UnregisterApplication method deletes the registration entries for a DirectPlay application. The entries must be removed when the application is uninstalled.

HRESULT UnregisterApplication(
  DWORD dwFlags,
  REFGUID guidApplication
);

Parameters

dwFlags
Reserved; must be 0.
guidApplication
The globally unique identifier (GUID) of the application to remove from the registry. In C, this parameter is a pointer to a GUID. In C++, it is a reference to a GUID.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_INVALIDFLAGS
DPERR_INVALIDPARAMS
DPERR_UNKNOWNAPPLICATION

The method returns DPERR_UNKNOWNAPPLICATION if the GUID of the application could not be found in the registry.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlayLobby3::RegisterApplication, DirectXUnregisterApplication


IDirectPlayLobby3::WaitForConnectionSettings

The IDirectPlayLobby3::WaitForConnectionSettings method puts the application into wait mode, where the application waits for the connection settings. When the application is in wait mode, a lobby client that uses RunApplication will not launch a new instance of the application, but will send the connection settings directly to the application already running in wait mode.

When in wait mode, the application should poll for DPLSYS_NEWCONNECTIONSETTINGS system message. After that message is received, the application is automatically taken out of wait mode. The application can use ConnectEx to connect to a session.

HRESULT WaitForConnectionSettings(
  DWORD dwFlags
);

Parameters

dwFlags
Flag that puts the application into wait mode or takes it out of wait mode. By default (dwFlags = 0), the method puts the application into wait mode. Setting dwFlags to DPLWAIT_CANCEL takes the application out of wait mode. As soon as the connection settings are sent by the lobby client, the application will automatically be taken out of wait mode.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_INVALIDFLAGS
DPERR_UNAVAILABLE

The method returns DPERR_UNAVAILABLE if you set the flag to cancel wait mode and the application is not in wait mode.

Remarks

When the lobby client uses RunApplication, DirectPlay will look for any instances of the application that are waiting for connection settings. If none are found, then a new instance of the application is launched. If a waiting application is found, DirectPlay will send a DPLSYS_NEWCONNECTIONSETTINGS system message. The application can then read the connection settings with GetConnectionSettings and join a session using ConnectEx.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.
Import Library: Use dplayx.lib.


Functions

The DirectPlay functions are:

  • DirectPlayCreate. Note that this function is obsolete. It is recommended that you use CoCreateInstance instead.
  • DirectPlayEnumerate. Note that this function is obsolete. It is recommended that you use IDirectPlay4::EnumConnections instead.
  • DirectPlayLobbyCreate


DirectPlayCreate

This function is obsolete and remains for compatibility with applications written using DirectX 3. It is recommended that applications create the desired DirectPlay interface directly using CoCreateInstance. By using CoCreateInstance you can obtain an IDirectPlay4 interface directly rather than getting an IDirectPlay interface, having to use QueryInterface to access an IDirectPlay4 interface, and releasing the IDirectPlay interface.

The DirectPlayCreate function creates a new DirectPlay object and obtains an IDirectPlay interface pointer. If the application supplies GUID_NULL for the lpGUIDSP parameter, this function creates a DirectPlay object but does not initialize a service provider. The application can then call the IDirectPlay4::InitializeConnection method to initialize the service provider or lobby provider.

The application can supply a service provider GUID (see DirectPlayEnumerate) to indicate which service provider to bind.

In order to use the latest DirectPlay functionality, the application must obtain an IDirectPlay4 or IDirectPlay4A interface pointer using the QueryInterface method.

HRESULT WINAPI DirectPlayCreate(
  LPGUID lpGUIDSP,
  LPDIRECTPLAY FAR *lplpDP,
  IUnknown *lpUnk
);

Parameters

lpGUIDSP
Pointer to the GUID of the service provider that the DirectPlay object should be initialized with. Pass in a pointer to GUID_NULL to create an uninitialized DirectPlay object.
lplpDP
Pointer to an interface pointer to be initialized with a valid IDirectPlay interface. The application will need to use the QueryInterface method to obtain an IDirectPlay2, IDirectPlay4 Interface (UNICODE strings) or IDirectPlay2A, IDirectPlay4A (ANSI strings) interface.
lpUnk
Pointer to the containing IUnknown. This parameter is provided for future compatibility with COM aggregation features. Presently, however, the DirectPlayCreate function returns an error if this parameter is anything but NULL.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

CLASS_E_NOAGGREGATION
DPERR_EXCEPTION
DPERR_INVALIDPARAMS
DPERR_UNAVAILABLE

DPERR_UNAVAILABLE is returned if a DirectPlay object could not be created. DPERR_INVALIDPARAMS is returned if the GUID provided is invalid.

Remarks

This function attempts to initialize a DirectPlay object and sets a pointer to it if successful. Your application should call the DirectPlayEnumerate function immediately before initialization to determine what types of service providers are available (the DirectPlayEnumerate function fills in the lpGUIDSP parameter of DirectPlayCreate).

This function returns a pointer to an IDirectPlay interface. The current interfaces are IDirectPlay4 and IDirectPlay4A, which need to be obtained through a call to the QueryInterface method on this IDirectPlay interface. For more information, see Overview of DirectPlay Interfaces.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlay4::InitializeConnection, DirectPlayEnumerate


DirectPlayEnumerate

The DirectPlayEnumerate function enumerates the DirectPlay service providers installed on the system.

This function is obsolete and remains for compatibility with applications written using DirectX 3. It will only enumerate service providers, not DirectPlay addresses (connections). It is recommended that applications use the IDirectPlay4::EnumConnections method to enumerate all the connections available to the application after creating an IDirectPlay4 interface.

This function will not enumerate service providers that have the Enumerate value in the registry set to 0. For backward compatibility, this function will only return simple service providers registered under the "Service Providers" registry key.

HRESULT WINAPI DirectPlayEnumerate(
  LPDPENUMDPCALLBACK lpEnumCallback,
  LPVOID lpContext
);

Parameters

lpEnumCallback
Pointer to a callback function that will be called with a description of each DirectPlay service provider installed in the system. Depending on whether UNICODE is defined or not, the prototype for the callback function will have the service provider name lpSPName defined as a LPWSTR (for Unicode) or LPSTR (for ANSI).
lpContext
Pointer to an application-defined structure that will be passed to the callback function each time the function is called.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

DPERR_EXCEPTION
DPERR_GENERIC
DPERR_INVALIDPARAMS

DPERR_INVALIDPARAMS is returned if an invalid enumeration callback was supplied.

Remarks

This function will enumerate service providers installed in the system even though the system might not be capable of using those service providers. For example, a TAPI service provider will be part of the enumeration even though the system might not have a modem installed.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.
Import Library: Use dplayx.lib.

See Also

IDirectPlay4::EnumConnections, DirectPlayCreate


DirectPlayLobbyCreate

The DirectPlayLobbyCreate function creates an instance of a DirectPlayLobby object and returns a pointer to the IDirectPlayLobby interface.

HRESULT WINAPI DirectPlayLobbyCreate(
  LPGUID lpGUIDSP,
  LPDIRECTPLAYLOBBY *lplpDPL,
  IUnknown *lpUnk,
  LPVOID lpData,
  DWORD dwDataSize
);

Parameters

lpGUIDSP
Reserved for future use; must be set to NULL.
lplpDPL
Pointer to a pointer to be initialized with a valid IDirectPlayLobby interface. To get an IDirectPlayLobby3 interface, use this function to get an IDirectPlayLobby interface, then call QueryInterface, as follows:
IDirectPlayLobby->QueryInterface( IID_IDirectPlayLobby3,
        (LPVOID*) &lpDP2 );
lpUnk
Pointer to the containing IUnknown interface. This parameter is provided for future compatibility with COM aggregation features. Presently, however, DirectPlayLobbyCreate returns an error if this parameter is anything but NULL.
lpData
Extra data needed to create the DirectPlayLobby object. This parameter must be set to NULL.
dwDataSize
This parameter must be set to 0.

Return Values

Returns DP_OK if successful, or one of the following error values otherwise:

CLASS_E_NOAGGREGATION
DPERR_INVALIDPARAMS
DPERR_OUTOFMEMORY

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.
Import Library: Use dplayx.lib.


Callback Functions

The DirectPlay callback functions are:

  • EnumAddressCallback
  • EnumAddressTypeCallback
  • EnumConnectionsCallback
  • EnumDPCallback
  • EnumLocalApplicationsCallback
  • EnumPlayersCallback2
  • EnumSessionsCallback2


EnumAddressCallback

EnumAddressCallback is an application-defined callback function for the IDirectPlayLobby3::EnumAddress method.

BOOL FAR PASCAL EnumAddressCallback(
  REFGUID guidDataType,
  DWORD dwDataSize,
  LPCVOID lpData,
  LPVOID lpContext
);

Parameters

guidDataType
Pointer to a globally unique identifier (GUID) indicating the type of this data chunk. For example, this parameter might be &DPAID_Phone or &DPAID_INet. (In C++, it is a reference to the GUID.)
dwDataSize
Size, in bytes, of the data chunk.
lpData
Pointer to the constant data.
lpContext
Context passed to the callback function.

Return Values

Returns TRUE to continue the enumeration or FALSE to stop it.

Remarks

The service provider should examine the GUID in the guidDataType parameter and process or store the value specified in lpData. Unrecognized values in guidDataType can be ignored.

Any pointers returned in a callback function are temporary and are valid only in the body of the callback function. If the application needs to save pointer information, it must allocate memory to hold the data, copy the data, and then store the pointer to this new data. In this function, lpData is temporary.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.


EnumAddressTypeCallback

EnumAddressTypeCallback is an application-defined callback function for the IDirectPlayLobby3::EnumAddressTypes method.

BOOL FAR PASCAL EnumAddressTypeCallback(
  REFGUID guidDataType,
  LPVOID lpContext,
  DWORD dwFlags
);

Parameters

guidDataType
Pointer to a globally unique identifier (GUID) indicating the address type. (In C++, it is a reference to the GUID.) Predefined address types are DPAID_Phone, DPAID_INet, and DPAID_ComPort. For more information about these address types, see DirectPlay Address.
lpContext
Context passed to the callback function.
dwFlags
Reserved; do not use.

Return Values

Returns TRUE to continue the enumeration or FALSE to stop it.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in dplay.h.


EnumConnectionsCallback

EnumConnectionsCallback is an application-defined callback function for the IDirectPlay4::EnumConnections method.

BOOL FAR PASCAL EnumConnectionsCallback(
  LPCGUID lpguidSP,
  LPVOID lpConnection,
  DWORD dwConnectionSize,
  LPCDPNAME lpName,
  DWORD dwFlags,
  LPVOID lpContext
);

Parameters

lpguidSP
The GUID of the DirectPlay service provider or lobby provider associated with the connection. Use this GUID to uniquely identify the service or lobby provider, rather than using the order in the enumeration or the name.
lpConnection
A read-only pointer to a buffer that contains the connection. This parameter is passed to the IDirectPlay4::InitializeConnection method to initialize the DirectPlay object. This buffer contains a DirectPlay address.
dwConnectionSize
The size, in bytes, of the lpConnection buffer.
lpName
A read-only pointer to a DPNAME structure. The structure contains the short name of the connection that should appear to the user.

If IDirectPlay4::EnumConnections was called on an ANSI interface, reference the strings as ANSI. If EnumConnections was called on a Unicode interface, reference the strings as Unicode.

dwFlags
Flags to indicate the type of connection. Equivalent to the dwFlags passed to EnumConnections.
lpContext
Pointer to an application-defined context.

Return Values

Returns TRUE to continue the enumeration or FALSE to stop it.

Remarks

The application must implement this function in order to use the IDirectPlay4::EnumConnections method. It is called once for each connection that is enumerated.

The application should allocate memory and copy each of the connections for presentation to the user and for use in the IDirectPlay4::InitializeConnection method.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.

See Also

IDirectPlay4::EnumConnections, IDirectPlay4::InitializeConnection


EnumDPCallback

EnumDPCallback is an application-defined callback function for the DirectPlayEnumerate function. Depending on whether UNICODE is defined or not, the prototype for the callback function will have lpSPName defined as either the LPWSTR type (for Unicode) or the LPSTR type (for ANSI).

BOOL FAR PASCAL EnumDPCallback(
  LPGUID lpguidSP,
  LPSTR/LPWSTR lpSPName,
  DWORD dwMajorVersion,
  DWORD dwMinorVersion,
  LPVOID lpContext
);

Parameters

lpguidSP
Pointer to the unique identifier of the DirectPlay service provider.
lpSPName
Pointer to a string containing the driver description. Depending on whether the UNICODE symbol is defined or not, the parameter will be of the LPWSTR type (Unicode) or the LPSTR type (ANSI).
dwMajorVersion and dwMinorVersion
Major and minor version numbers of the driver.
lpContext
Pointer to an application-defined context.

Return Values

Returns TRUE to continue the enumeration or FALSE to stop it.

Remarks

Any pointers returned in a callback function are temporary and are valid only in the body of the callback function. If the application needs to save pointer information, it must allocate memory to hold the data, copy the data, and then store the pointer to this new data. In this function, lpguidSP and lpSPName are temporary.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.


EnumLocalApplicationsCallback

EnumLocalApplicationsCallback is an application-defined callback function for the IDirectPlayLobby3::EnumLocalApplications method.

BOOL FAR PASCAL EnumLocalApplicationsCallback(
  LPCDPLAPPINFO lpAppInfo,
  LPVOID lpContext,
  DWORD dwFlags
);

Parameters

lpAppInfo
Pointer to a read-only DPLAPPINFO structure containing information about the application being enumerated.
lpContext
Context passed from the IDirectPlayLobby3::EnumLocalApplications call.
dwFlags
Reserved; do not use.

Return Values

Returns TRUE to continue the enumeration or FALSE to stop it.

Remarks

Any pointers returned in a callback function are temporary and are valid only in the body of the callback function. If the application needs to save pointer information, it must allocate memory to hold the data, copy the data, and then store the pointer to this new data. In this function, lpAppInfo is temporary. Also note that the pointers inside the structure specified in the lpAppInfo parameter - lpszAppNameA and lpszAppName - are also temporary.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.


EnumPlayersCallback2

EnumPlayersCallback2 is an application-defined callback function. The application must implement this function and pass a pointer to it in the IDirectPlay4::EnumGroups, IDirectPlay4::EnumGroupPlayers, IDirectPlay4::EnumPlayers, and IDirectPlay4::EnumGroupsInGroup methods. The callback is called once for each player or group that is enumerated.

BOOL FAR PASCAL EnumPlayersCallback2(
  DPID dpId,
  DWORD dwPlayerType,
  LPCDPNAME lpName,
  DWORD dwFlags,
  LPVOID lpContext
);

Parameters

dpId
ID of the player or group being enumerated.
dwPlayerType
Type of entity, either DPPLAYERTYPE_GROUP or DPPLAYERTYPE_PLAYER.
lpName
Read-only pointer to a DPNAME structure containing the name of the player or group. This pointer is only valid for the duration of the callback function. Any data that is to be saved for future reference must be copied to some application-owned memory.
dwFlags
Flags describing the group or player being enumerated.
DPENUMGROUPS_HIDDEN
The group was created using the hidden flag.
DPENUMGROUPS_SHORTCUT
The group is a shortcut.
DPENUMGROUPS_STAGINGAREA
The group is a staging area.
DPENUMPLAYERS_GROUP
Both players and groups are being enumerated. This flag is returned only if it was specified in the enumeration method calling this callback.
DPENUMPLAYERS_LOCAL
The player or group exists on a local computer. This flag is returned only if it was specified in the enumeration method calling this callback.
DPENUMPLAYERS_OWNER
The player is the owner of the group. This flag is returned only if it was specified in the IDirectPlay4::EnumGroupPlayers method calling this callback.
DPENUMPLAYERS_REMOTE
The player or group exists on a remote computer. This flag is returned only if it was specified in the enumeration method calling this callback.
DPENUMPLAYERS_SERVERPLAYER
The player is the server player in an application/server session. Only one server player exists in each session.
DPENUMPLAYERS_SESSION
The player or group exists in the session identified by lpguidInstance in the enumeration method. This flag is returned only if it was specified in the enumeration method calling this callback.
DPENUMPLAYERS_SPECTATOR
The player is a spectator (applies to players only).
lpContext
Pointer to an application-defined context.

Return Values

Returns TRUE to continue the enumeration or FALSE to stop it.

Remarks

Any pointers returned in a callback function are temporary and are valid only in the body of the callback function. If the application needs to save pointer information, it must allocate memory to hold the data, copy the data, and then store the pointer to this new data.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.

See Also

DPNAME, IDirectPlay4::EnumGroups, IDirectPlay4::EnumPlayers, IDirectPlay4::EnumGroupPlayers, IDirectPlay4::EnumGroupsInGroup


EnumSessionsCallback2

EnumSessionsCallback2 is an application-defined callback function for the IDirectPlay4::EnumSessions method.

BOOL FAR PASCAL EnumSessionsCallback2(
  LPCDPSESSIONDESC2 lpThisSD,
  LPDWORD lpdwTimeOut,
  DWORD dwFlags,
  LPVOID lpContext
);

Parameters

lpThisSD
Pointer to a DPSESSIONDESC2 structure describing the enumerated session. This parameter will be set to NULL if the enumeration has timed out.
lpdwTimeOut
Pointer to a variable containing the current time-out value. This parameter can be reset when the DPESC_TIMEDOUT flag is returned if you want to wait longer for sessions to reply.
dwFlags
Typically, this flag is set to 0.
DPESC_TIMEDOUT
The enumeration has timed out. Reset lpdwTimeOut and return TRUE to continue, or FALSE to stop the enumeration.
lpContext
Pointer to an application-defined context.

Return Values

Returns TRUE to continue the enumeration or FALSE to stop it.

Remarks

The application must implement this function in order to use the IDirectPlay4::EnumSessions method. This callback function will be called once for each session that is enumerated. Once all the session are enumerated, the callback function will be called one additional time with the DPESC_TIMEDOUT flag.

Applications should look at the flags of the DPSESSIONDESC2 to determine the nature of the session.

For a secure session, the dwMaxPlayers and dwCurrentPlayers members of DPSESSIONDESC2 are set to 0.

Any pointers returned in a callback function are temporary and are valid only in the body of the callback function. If the application needs to save pointer information, it must allocate memory to hold the data, copy the data, and then store the pointer to this new data. In this function, lpThisSD is temporary. Also note that the pointers inside the structure specified in the lpThisSD parameter—lpszSessionName / lpszSessionNameA and lpszPassword / lpszPasswordA—are also temporary.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.


Structures

Several new data members were added to DirectPlay structures for DirectX 5.0, and these are supported in the current version. Applications that need to be backward-compatible with older versions of the DirectPlay run-time files should either:

  • Use the structures that existed in the DirectX 3.0 header files.
  • Check the dwSize member in each structure before attempting to access all members of the structure.

The DirectPlay structures are:

  • DPACCOUNTDESC
  • DPAPPLICATIONDESC
  • DPAPPLICATIONDESC2
  • DPCAPS
  • DPCHAT
  • DPCOMPORTADDRESS
  • DPCOMPOUNDADDRESSELEMENT
  • DPCREDENTIALS
  • DPLAPPINFO
  • DPLCONNECTION
  • DPNAME
  • DPSECURITYDESC
  • DPSESSIONDESC2


DPACCOUNTDESC

The DPACCOUNTDESC structure describes the account information for a specific player.

typedef struct {
    DWORD  dwSize;
    DWORD  dwFlags;
    union {
        LPWSTR  lpszAccountID;
        LPSTR   lpszAccountIDA;
    };
} DPACCOUNTDESC, FAR *LPDPACCOUNTDESC;

Members

dwSize
The size of the DPACCOUNTDESC structure, dwSize = sizeof(DPACCOUNTDESC).
dwFlags
Not used. Must be 0.
lpszAccountID
Pointer to a Unicode string containing the account identifier. This is a unique identifier that describes a player who is securely logged on. The format of the identifier depends on the Security Support Provider Interface (SSPI) package being used.
lpszAccountIDA
Pointer to an ANSI string containing the account identifier. This is a unique identifier that describes a player who is securely logged on. The format of the identifier depends on the SSPI package being used.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.

See Also

IDirectPlay4::GetPlayerAccount


DPAPPLICATIONDESC

The DPAPPLICATIONDESC structure describes all the information necessary to register a lobby-aware application using IDirectPlayLobby3::RegisterApplication.

typedef struct {
    DWORD   dwSize;
    DWORD   dwFlags;
    union {
      LPSTR    lpszApplicationNameA;
      LPWSTR   lpszApplicationName;
    }
    GUID    guidApplication;
    union {
      LPSTR     lpszFilenameA;
      LPWSTR    lpszFilename;
    }
    union {
      LPSTR   lpszCommandLineA;
      LPWSTR  lpszCommandLine;
    }
    union {
      LPSTR   lpszPathA;
      LPWSTR  lpszPath;
    }
    union {
      LPSTR    lpszCurrentDirectoryA;
      LPWSTR   lpszCurrentDirectory;
    }
    LPSTR   lpszDescriptionA;
    LPWSTR  lpszDescriptionW;
} DPAPPLICATIONDESC, *LPDPAPPLICATIONDESC;

Members

dwSize
Size of the DPAPPLICATIONDESC structure, dwSize = sizeof(DPAPPLICATIONDESC).
dwFlags
Not used. Must be 0.
lpszApplicationNameA, lpszApplicationName
Pointer to a string containing the name of the application. Note: This title should not be localized. Use the lpszDescriptionA and lpszDescriptionW members to localize the application name.
guidApplication
Globally unique identifier (GUID) of the application. This should be the same as the value used in the guidApplication member of the DPSESSIONDESC2 structure when hosting a game session.
lpszFilenameA, lpszFilename
Pointer to a string containing the name of the executable to be launched. Note: The use of a stub executable should be avoided when launching from a lobby. In a lobby launch scenario, the stub should be bypassed and the main executable should be launched.
lpszCommandLineA, lpszCommandLine
Pointer to a string containing command line arguments to be passed to the executable when launched by a lobby.
lpszPathA, lpszPath
Pointer to a string containing the path where the executable is located.
lpszCurrentDirectoryA, lpszCurrentDirectory
Pointer to a string containing the path that the current directory should be set to. Typically, this is the same as lpszPath or lpszPathA.
lpszDescriptionA
Pointer to an ANSI single-byte character string containing a localized description of the application. When EnumLocalApplications is called on an ANSI interface (such as IDirectPlayLobby3A), this string will be returned if it is present. Otherwise, the lpszApplicationName data member will be returned. Note: This string should not contain any multi-byte characters. Set to NULL if no localized ANSI description is needed.
lpszDescriptionW
Pointer to a Unicode sting containing a localized description of the application. When EnumLocalApplications is called on a Unicode interface (such as IDirectPlayLobby3), this string will be returned if it is present. If it is not present, the lpszDescriptionA data member will be converted to Unicode and returned. If neither lpszDescriptionA nor lpszDescriptionW is present, the lpszApplicationName data member will be returned. Note: This string must consist solely of Unicode characters. Set to NULL if no localized Unicode description is needed.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.

See Also

IDirectPlayLobby3::RegisterApplication, DPAPPLICATIONDESC2


DPAPPLICATIONDESC2

The DPAPPLICATIONDESC2 structure describes all the information necessary to register a lobby-aware application using IDirectPlayLobby3::RegisterApplication. It is used instead of DPAPPLICATIONDESC when the application is to be started by a launcher application.

typedef struct {
    DWORD   dwSize;
    DWORD   dwFlags;
    union {
      LPSTR    lpszApplicationNameA;
      LPWSTR   lpszApplicationName;
    }
    GUID    guidApplication;
    union {
      LPSTR     lpszFilenameA;
      LPWSTR    lpszFilename;
    }
    union {
      LPSTR   lpszCommandLineA;
      LPWSTR  lpszCommandLine;
    }
    union {
      LPSTR   lpszPathA;
      LPWSTR  lpszPath;
    }
    union {
      LPSTR    lpszCurrentDirectoryA;
      LPWSTR   lpszCurrentDirectory;
    }
    LPSTR   lpszDescriptionA;
    LPWSTR  lpszDescriptionW;
    union
    {
      LPSTR   lpszAppLauncherNameA;
      LPWSTR  lpszAppLauncherName;
    };
} DPAPPLICATIONDESC2, *LPDPAPPLICATIONDESC2;

Members

dwSize
Size of the DPAPPLICATIONDESC2 structure, dwSize = sizeof(DPAPPLICATIONDESC2).
dwFlags
Not used. Must be 0.
lpszApplicationNameA, lpszApplicationName
Pointer to a string containing the name of the application. Note: This title should not be localized. Use the lpszDescriptionA and lpszDescriptionW members to localize the application name.
guidApplication
Globally unique identifier (GUID) of the application. This should be the same as the value used in the guidApplication member of the DPSESSIONDESC2 structure when hosting a game session.
lpszFilenameA, lpszFilename
Pointer to a string containing the name of the executable to be launched. Note: The use of a stub executable should be avoided when launching from a lobby. In a lobby launch scenario, the stub should be bypassed and the main executable should be launched.
lpszCommandLineA, lpszCommandLine
Pointer to a string containing command line arguments to be passed to the executable when launched by a lobby.
lpszPathA, lpszPath
Pointer to a string containing the path where the executable is located.
lpszCurrentDirectoryA, lpszCurrentDirectory
Pointer to a string containing the path that the current directory should be set to. Typically, this is the same as lpszPath or lpszPathA.
lpszDescriptionA
Pointer to an ANSI single-byte character string containing a localized description of the application. When EnumLocalApplications is called on an ANSI interface (such as IDirectPlayLobby3A), this string will be returned if it is present. Otherwise, the lpszApplicationName data member will be returned. Note: This string should not contain any multi-byte characters. Set to NULL if no localized ANSI description is needed.
lpszDescriptionW
Pointer to a Unicode sting containing a localized description of the application. When EnumLocalApplications is called on a Unicode interface (such as IDirectPlayLobby3), this string will be returned if it is present. If it is not present, the lpszDescriptionA data member will be converted to Unicode and returned. If neither lpszDescriptionA nor lpszDescriptionW is present, the lpszApplicationName data member will be returned. Note: This string must consist solely of Unicode characters. Set to NULL if no localized Unicode description is needed.
lpszAppLauncherNameA, lpszAppLauncherName
Pointer to a string containing the name of a launcher executable. The launcher is started by the lobby, and it in turn is responsible for launching the application described in lpszApplicationName. The launcher must reside in the same directory as the application.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.

See Also

IDirectPlayLobby3::RegisterApplication


DPCAPS

The DPCAPS structure contains the capabilities of a DirectPlay object after a call to the IDirectPlay4::GetCaps or IDirectPlay4::GetPlayerCaps method. Any of these capabilities can differ, depending on whether guaranteed or nonguaranteed capabilities are requested. This structure is read-only. Note that capabilities indicating which aspects of the IDirectPlay4::SendEx method are supported, such as the DPCAPS_SENDPRIORITYSUPPORTED and DPCAPS_SENDTIMEOUTSUPPORTED flags in dwFlags, are not available until after the session has been opened. If the application hosting the session has specified the DPSESSION_DIRECTPLAYPROTOCOL flag in the DPSESSIONDESC2 structure, all the SendEx options are supported.

typedef struct {
    DWORD dwSize;
    DWORD dwFlags;
    DWORD dwMaxBufferSize;
    DWORD dwMaxQueueSize;
    DWORD dwMaxPlayers;
    DWORD dwHundredBaud;
    DWORD dwLatency;
    DWORD dwMaxLocalPlayers;
    DWORD dwHeaderLength;
    DWORD dwTimeout;
} DPCAPS, FAR *LPDPCAPS;

Members

dwSize
Size of the DPCAPS structure, dwSize = sizeof(DPCAPS). Your application must set this member before it uses this structure; otherwise, an error will result.
dwFlags
Flags that indicate the properties of the DirectPlay object.
DPCAPS_ASYNCCANCELALLSUPPORTED
Indicates that canceling all pending asynchronous messages is supported. This flag indicates that the only form of cancellation supported is the ability to cancel all unsent messages. Any attempt to cancel messages by specifying a priority range or a message ID will return DPERR_UNSUPPORTED. By contrast, the DPCAPS_ASYNCCANCELSUPPORTED flag indicates that all types of cancellation are supported. Note that capabilities indicating which aspects of SendEx are supported are not available until after the session has been opened.
DPCAPS_ASYNCCANCELSUPPORTED
Indicates that canceling asynchronous messages is supported. All types of cancellation are supported: canceling by message ID, canceling by priority range, and canceling all unsent messages. Note that capabilities indicating which aspects of SendEx are supported are not available until after the session has been opened.
DPCAPS_ASYNCSUPPORTED
Indicates that asynchronous messaging is supported. Thus, an application can use the DPSEND_ASYNC flag on SendEx. See Remarks for more information. Note that capabilities indicating which aspects of SendEx are supported are not available until after the session has been opened.
DPCAPS_ENCRYPTIONSUPPORTED
Indicates that message encryption is supported by this DirectPlay object, either because the session is a secure session, or because the service provider can encrypt messages.
DPCAPS_GROUPOPTIMIZED
Indicates that the service provider bound to this DirectPlay object can optimize group (multicast) messaging.
DPCAPS_GUARANTEEDOPTIMIZED
Indicates that the service provider bound to this DirectPlay object supports guaranteed message delivery.
DPCAPS_GUARANTEEDSUPPORTED
Indicates that the DirectPlay object supports guaranteed message delivery, either because the service provider supports it, or because DirectPlay implements it on a nonguaranteed service provider.
DPCAPS_ISHOST
Indicates that the DirectPlay object created by the calling application is the session host.
DPCAPS_KEEPALIVEOPTIMIZED
Indicates that the service provider can detect when the connection to the session has been lost.
DPCAPS_SENDPRIORITYSUPPORTED
Indicates that the message priority set in SendEx is supported. Note that capabilities indicating which aspects of SendEx are supported are not available until after the session has been opened.
DPCAPS_SENDTIMEOUTSUPPORTED
Indicates that the time-out for messages specified in SendEx is supported. This flag can be set by the service provider or by DirectPlay. Note that capabilities indicating which aspects of SendEx are supported are not available until after the session has been opened.
DPCAPS_SIGNINGSUPPORTED
Indicates that message authentication is supported by this DirectPlay object, either because it is a secure session, or because the service provider can sign messages.
dwMaxBufferSize
Maximum number of bytes that can be sent in a single packet by this service provider. Larger messages will be sent by using more than one packet.
dwMaxQueueSize
This member is no longer used.
dwMaxPlayers
Maximum number of local and remote players supported in a session by this DirectPlay object.
dwHundredBaud
Bandwidth specified in multiples of 100 bits per second. For example, a value of 24 specifies 2400 bits per second.
dwLatency
Estimate of latency by the service provider, in milliseconds. If this value is 0, DirectPlay cannot provide an estimate. Accuracy for some service providers rests on application-to-application testing, taking into consideration the average message size. Latency can differ, depending on whether the application uses guaranteed or nonguaranteed message delivery.
dwMaxLocalPlayers
Maximum number of local players supported in a session.
dwHeaderLength
Size, in bytes, of the header that will be added to player messages by this DirectPlay object. Note that the header size depends on which service provider is in use.
dwTimeout
Service provider's suggested time-out value. By default, DirectPlay will use this time-out value when waiting for replies to messages.

Remarks

The DPCAPS_ASYNCSUPPORTED, DPCAPS_SENDTIMEOUTSUPPORTED, DPCAPS_SENDPRIORITYSUPPORTED, DPCAPS_ASYNCCANCELSUPPORTED, and DPCAPS_ASYNCCANCELALLSUPPORTED flags indicate the communications capabilities of the current session.

In order for an application to be able to use DPSEND_ASYNC on SendEx one (or both) of the following conditions must be true.

You specified the DPSESSION_DIRECTPLAYPROTOCOL flag when the session was created.

The service provider supports asynchronous messaging.

This means that modem, serial, and Internetwork Packet Exchange (IPX) service providers have guaranteed messaging available to them, but they do not have asynchronous messaging, unless you explicitly set the DPSESSION_DIRECTPLAYPROTOCOL flag. The TCP/IP service provider implements asynchronous messaging when the computer has Windows Sockets 2.0 present.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.

See Also

IDirectPlay4::Send, IDirectPlay4::SendEx, IDirectPlay4::GetCaps, IDirectPlay4::GetPlayerCaps


DPCHAT

The DPCHAT structure contains a DirectPlay chat message. Chat messages are sent with the IDirectPlay4::SendChatMessage method.

typedef struct {
    DWORD dwSize;
    DWORD dwFlags;
    union{
      LPWSTR lpszMessage;
      LPSTR  lpszMessageA;
    };
} DPCHAT, FAR *LPDPCHAT;

Members

dwSize
The size of the DPCHAT structure, dwSize = sizeof(DPCHAT).
dwFlags
Not used. Must be 0.
lpszMessage
Pointer to a Unicode string containing the message to be sent. Can only be used with a Unicode interface (IDirectPlay4).
lpszMessageA
Pointer to an ANSI string containing the message to be sent. Can only be used with an ANSI interface (IDirectPlay4A).

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.

See Also

IDirectPlay4::SendChatMessage


DPCOMPORTADDRESS

The DPCOMPORTADDRESS structure contains information about the configuration of the COM port.

typedef struct DPCOMPORTADDRESS{
    DWORD dwComPort;
    DWORD dwBaudRate;
    DWORD dwStopBits;
    DWORD dwParity;
    DWORD dwFlowControl;
} DPCOMPORTADDRESS;

typedef DPCOMPORTADDRESS FAR* LPDPCOMPORTADDRESS;

Members

dwComPort
Indicates the number of the COM port to use. The value for this member can be 1, 2, 3, or 4.
dwBaudRate
Indicates the baud of the COM port. The value for this member can be one of the following:
CBR_110 | CBR_300 | CBR_600
CBR_1200 | CBR_2400 | CBR_4800
CBR_9600 | CBR_14400 | CBR_19200
CBR_38400 | CBR_56000 | CBR_57600
CBR_115200 | CBR_128000 | CBR_256000

dwStopBits
Indicates the number of stop bits. The value for this member can be ONESTOPBIT, ONE5STOPBITS, or TWOSTOPBITS.
dwParity
Indicates the parity used on the COM port. The value for this member can be NOPARITY, ODDPARITY, EVENPARITY, or MARKPARITY.
dwFlowControl
Indicates the method of flow control used on the COM port. The following values can be used for this member:
DPCPA_DTRFLOW
Indicates hardware flow control with DTR.
DPCPA_NOFLOW
Indicates no flow control.
DPCPA_RTSDTRFLOW
Indicates hardware flow control with RTS and DTR.
DPCPA_RTSFLOW
Indicates hardware flow control with RTS.
DPCPA_XONXOFFFLOW
Indicates software flow control (xon/xoff).

Remarks

The constants that define baud, stop bits, and parity are defined in Winbase.h.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.


DPCOMPOUNDADDRESSELEMENT

The DPCOMPOUNDADDRESSELEMENT structure describes a DirectPlay address data chunk.

typedef struct {
    GUID    guidDataType;
    DWORD   dwDataSize;
    LPVOID  lpData;
} DPCOMPOUNDADDRESSELEMENT, FAR *LPDPCOMPOUNDADDRESSELEMENT;

Members

guidDataType
GUID identifying the type of data contained in this structure.
dwDataSize
Size of the data in bytes.
lpData
Pointer to a buffer containing the data.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.

See Also

IDirectPlayLobby3::CreateCompoundAddress, DirectPlay Address Data Types


DPCREDENTIALS

The DPCREDENTIALS structure holds the user name, password, and domain to connect to a secure server.

typedef struct {
    DWORD  dwSize;
    DWORD  dwFlags;
    union {
           LPWSTR lpszUsername;
           LPSTR  lpszUsernameA;
          };
    union {
           LPWSTR lpszPassword;
           LPSTR  lpszPasswordA;
          };
    union {
           LPWSTR lpszDomain;
           LPSTR  lpszDomainA;
          };

} DPCREDENTIALS, FAR *LPDPCREDENTIALS;

Members

dwSize
The size of the DPCREDENTIALS structure, dwSize = sizeof(DPCREDENTIALS).
dwFlags
Not used. Must be 0.
lpszUsername, lpszPassword, lpszDomain
Pointers to Unicode strings containing the user name, password, and domain name. Can only be used with a Unicode interface.
lpszUsernameA, lpszPasswordA, lpszDomainA
Pointers to ANSI strings containing the user name, password, and domain name. Can only be used with an ANSI interface.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.

See Also

IDirectPlay4::SecureOpen


DPLAPPINFO

The DPLAPPINFO structure contains information about the application from the registry and is passed to the IDirectPlayLobby3::EnumLocalApplications callback function.

typedef struct {
    DWORD  dwSize;
    GUID   guidApplication;
    union {
           LPSTR  lpszAppNameA;
           LPWSTR lpszAppName;
          };
} DPLAPPINFO, FAR *LPDPLAPPINFO;

Members

dwSize
The size of the DPLAPPINFO structure, dwSize = sizeof(DPLAPPINFO). Your application must set this member before it uses this structure; otherwise, an error will result.
guidApplication
Globally unique identifier (GUID) of the application.
lpszAppNameA, lpszAppName
Name of the application in ANSI or Unicode, depending on what interface is in use.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.


DPLCONNECTION

The DPLCONNECTION structure contains the information needed to connect an application to a session.

typedef struct {
    DWORD            dwSize;
    DWORD            dwFlags;
    LPDPSESSIONDESC2 lpSessionDesc;
    LPDPNAME         lpPlayerName;
    GUID             guidSP;
    LPVOID           lpAddress;
    DWORD            dwAddressSize;
} DPLCONNECTION, FAR *LPDPLCONNECTION;

Members

dwSize
The size of the DPLCONNECTION structure, dwSize = sizeof(DPLCONNECTION). Your application must set this member before it uses this structure; otherwise, an error will result.
dwFlags
Indicates how to open a session.
DPLCONNECTION_CREATESESSION
Create a new session as described in the session description.
DPLCONNECTION_JOINSESSION
Join the existing session as described in the session description.
lpSessionDesc
Pointer to a DPSESSIONDESC2 structure describing the session to be created or the session to join.
lpPlayerName
Pointer to a DPNAME structure holding the name the player should be created with. This will be the name of the person registered in the lobby. The application can ignore this name.
guidSP
Globally unique identifier (GUID) of the service provider to use to connect to the session.
lpAddress
Pointer to a DirectPlay address that contains the information that the service provider needs to connect to a session.
dwAddressSize
Size, in bytes, of the address data.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.

See Also

IDirectPlayLobby3::RunApplication, IDirectPlayLobby3::GetConnectionSettings, IDirectPlayLobby3::SetConnectionSettings, DirectPlay Address


DPNAME

The DPNAME structure contains name information for a DirectPlay entity, such as a player or group.

typedef struct {
    DWORD dwSize;
    DWORD dwFlags;
    union {
        LPWSTR lpszShortName;
        LPSTR  lpszShortNameA;
    };
    union {
        LPWSTR lpszLongName;
        LPSTR  lpszLongNameA;
    };
} DPNAME, FAR *LPDPNAME;

Members

dwSize
The size of the DPNAME structure, dwSize = sizeof(DPNAME). Your application must set this member before it uses this structure; otherwise, an error will result.
dwFlags
Structure-specific flags. Currently set to 0.
lpszShortName and lpszLongName
Pointers to Unicode strings containing the short (friendly) and long (formal) names of a player or group. Use these members only if the IDirectPlay4 interface is in use.
lpszShortNameA and lpszLongNameA
Pointers to ANSI strings containing the short (friendly) and long (formal) names of a player or group. Use these members only if the IDirectPlay4A interface is in use.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.

See Also

IDirectPlay4::CreateGroup, IDirectPlay4::CreatePlayer, IDirectPlay4::GetGroupName, IDirectPlay4::GetPlayerName, IDirectPlay4::SetGroupName, IDirectPlay4::SetPlayerName


DPSECURITYDESC

The DPSECURITYDESC structure describes the security properties of a DirectPlay session instance.

typedef struct {
    DWORD  dwSize;
    DWORD  dwFlags;
    union {
        LPWSTR  lpszSSPIProvider;
        LPSTR   lpszSSPIProviderA;
    };
    union {
        LPWSTR lpszCAPIProvider;
        LPSTR  lpszCAPIProviderA;
    };
    DWORD  dwCAPIProviderType;
    DWORD  dwEncryptionAlgorithm;
} DPSECURITYDESC, FAR *LPDPSECURITYDESC;

Members

dwSize
The size of the DPSECURITYDESC structure, dwSize = sizeof(DPSECURITYDESC).
dwFlags
Not used. Must be 0.
lpszSSPIProvider, lpszSSPIProviderA
Pointer to a Unicode or ANSI string describing the Security Support Provider Interface (SSPI) package to use for authenticated logons. Pass NULL to use the default, the NTLM (NT LAN Manager) security provider.
lpszCAPIProvider, lpszCAPIProviderA
Pointer to a Unicode or ANSI string describing the CryptoAPI package to use for cryptography services. Pass NULL to use the default, the Microsoft RSA Base Cryptographic Provider v. 1.0.
dwCAPIProviderType
CryptoAPI service provider type. Pass 0 to use the default type, PROV_RSA_FULL.
dwEncryptionAlgorithm
Encryption algorithm to use. DirectPlay only supports stream ciphers. Pass 0 to use the default, the CALG_RC4 stream cipher.

Remarks

DirectPlay does not support block encryption.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.

See Also

IDirectPlay4::SecureOpen


DPSESSIONDESC2

The DPSESSIONDESC2 structure contains a description of a session's capabilities.

Note that some of the session description flags are read-only and cannot be changed, and the rest can be changed only by the host. See the description of the dwFlags member.

typedef struct {
    DWORD dwSize;
    DWORD dwFlags;
    GUID  guidInstance;
    GUID  guidApplication;
    DWORD dwMaxPlayers;
    DWORD dwCurrentPlayers;
    union  {
        LPWSTR lpszSessionName;
        LPSTR  lpszSessionNameA;
    };
    union  {
        LPWSTR lpszPassword;
        LPSTR  lpszPasswordA;
    };
    DWORD dwReserved1;
    DWORD dwReserved2;
    DWORD dwUser1;
    DWORD dwUser2;
    DWORD dwUser3;
    DWORD dwUser4;
} DPSESSIONDESC2, FAR *LPDPSESSIONDESC2;

Members

dwSize
Size of the DPSESSIONDESC2 structure. The application must set this member before it uses the structure.
dwFlags
Combination of the following flags. The following flags cannot be changed once the session has started: DPSESSION_CLIENTSERVER, DPSESSION_DIRECTPLAYPROTOCOL, DPSESSION_KEEPALIVE, DPSESSION_MIGRATEHOST, DPSESSION_MULTICASTSERVER, DPSESSION_NOMESSAGEID, DPSESSION_OPTIMIZELATENCY, and DPSESSION_SECURESERVER. The other flags, DPSESSION_JOINDISABLED, DPSESSION_NEWPLAYERSDISABLED, DPSESSION_NODATAMESSAGES, DPSESSION_NOPRESERVEORDER, DPSESSION_PASSWORDREQUIRED, and DPSESSION_PRIVATE, can be changed after a session has started by using IDirectPlay4::SetSessionDesc, but only by the host.
DPSESSION_CLIENTSERVER
Specifies that this is a client/server session that is being hosted by an application-server process. This flag must be specified at the time the session is created. Any clients that join this session will only be able to enumerate the server player and any local players. The host of the session will see all the players. If this flag is not set, the session is a peer-to-peer session. If this flag is set, the host can only create a server player. This flag cannot be used with DPSESSION_MIGRATEHOST.
DPSESSION_DIRECTPLAYPROTOCOL
Specifies that this session should use the DirectPlay guaranteed protocol instead of the one implemented by the service provider. Use this flag if message throttling is desired (and you want the performance gains it provides), or if you want to ensure the availability of all the features of IDirectPlay4::SendEx. This flag also enables guaranteed sends on unreliable providers and uses DirectPlay's reliability code on TCP/IP, which generally gives better performance both in throughput and delivery.
DPSESSION_JOINDISABLED
Specifies that no new applications can join this session. Any call to the IDirectPlay4::Open method with the DPOPEN_JOIN flag and the globally unique identifier (GUID) of this session instance will cause an error. If this flag is not specified, new remote applications can join the session until the session player limit is reached.
DPSESSION_KEEPALIVE
Specifies that this session will automatically detect when remote players drop out of the game abnormally. Those players will be deleted from the session. If a temporary network outage caused the loss of the players, they will be informed when they return that they were dropped from the session through the DPMSG_SESSIONLOST system message. This flag must be specified at the time the session is created. If this flag is not specified, DirectPlay will not automatically keep the session alive if players are abnormally terminated.
DPSESSION_MIGRATEHOST
Specifies that if the current host exits, another computer in the session will become the host. The players on the new host computer will receive a DPMSG_HOST system message. This flag must be specified at the time the session is created. If this flag is not specified, the host will not migrate, new computers cannot join the session, and new players cannot be created if the current host leaves. Note that the DPSESSION_MIGRATEHOST flag cannot be used with the DPSESSION_CLIENTSERVER, DPSESSION_MULTICASTSERVER, or DPSESSION_SECURESERVER flags.
DPSESSION_MULTICASTSERVER
Specifies that in a peer-to-peer session, broadcast and group messages are routed through the host that acts like a multicast server. This flag must be specified at the time the session is created. The flag is only useful if the host has a high bandwidth connection to the network. If this flag is not specified, broadcast and group messages are sent directly between peers. This flag cannot be used with DPSESSION_MIGRATEHOST.
DPSESSION_NEWPLAYERSDISABLED
Specifies that new players cannot be created in the session. Any call to the IDirectPlay4::CreatePlayer method by an application in the session will result in an error. Also, new applications cannot join the session. If this flag is not specified, players can be created until the session player limit is reached.
DPSESSION_NODATAMESSAGES
Specifies that the session does not send system messages when remote player data, group data, or session data is changed with the IDirectPlay4::SetPlayerData, IDirectPlay4::SetGroupData, IDirectPlay4::SetPlayerName, IDirectPlay4::SetGroupName, or IDirectPlay4::SetSessionDesc method. If this flag is not specified, messages will be generated that indicate that the data changed.

Note that setting this flag also suppresses the DPMSG_SETSESSIONDESC message.

DPSESSION_NOMESSAGEID
Specifies that the session does not attach data to messages that indicate which player the message is from and to whom it is sent. Setting this flag saves message overhead if this information is not relevant. (For more information, see the IDirectPlay4::Receive method.) If this flag is not specified, the message ID will be added. This flag must be specified at the time the session is created.
DPSESSION_NOPRESERVEORDER
Specifies that this session does not preserve the order in which guaranteed messages are received. By default, the receive order of guaranteed messages is preserved. If the order is not needed, this flag can be used to eliminate possible delays in delivery.
DPSESSION_OPTIMIZELATENCY
Asks the service provider to optimize for latency (which turns off nagling in TCP/IP). The default is to optimize for bandwidth.
DPSESSION_PASSWORDREQUIRED
Specifies that this session is password-protected. Any applications wishing to join the session must supply the password in the IDirectPlay4::Open call. This is a read-only flag. It will be set automatically by DirectPlay when the host of the session specifies a non-NULL password.
DPSESSION_PRIVATE
Specifies that this is a private session. It cannot respond to enumeration requests unless the request contains a non-NULL, matching password. If this flag is not specified, the session will respond to enumeration requests.
DPSESSION_SECURESERVER
Specifies that this session is being hosted on a secure server that will require authentication credentials before it can be opened. The host must specify this flag when the session is created. It cannot be changed later through IDirectPlay4::SetSessionDesc. This flag cannot be used with the DPSESSION_MIGRATEHOST flag.
guidInstance
GUID of the session instance.
guidApplication
GUID for the application running in the session instance. It uniquely identifies the application so that DirectPlay connects only to other computers running the same application. This member can be set to GUID_NULL to enumerate sessions for any application.
dwMaxPlayers
Maximum number of players allowed in this session. A value of 0 means there is no maximum.
dwCurrentPlayers
Number of players currently in the session.
lpszSessionName
Pointer to a Unicode string containing the name of the session. Use only if a Unicode DirectPlay interface (IDirectPlay4 Interface) is being used.
lpszSessionNameA
Pointer to an ANSI string containing the name of the session. Use only if an ANSI DirectPlay interface (IDirectPlay4A) is being used.
lpszPassword
Pointer to a Unicode string containing the password used to join the session for participation. Use only if a Unicode DirectPlay interface (IDirectPlay4 Interface) is being used.
lpszPasswordA
Pointer to an ANSI string containing the password used to join the session for participation. Use only if an ANSI DirectPlay interface (IDirectPlay4A) is being used.
dwReserved1 and dwReserved2
Must be 0.
dwUser1, dwUser2, dwUser3, and dwUser4
Application-specific data for the session.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.

See Also

IDirectPlay4::EnumSessions, IDirectPlay4::GetSessionDesc, IDirectPlay4::Open, IDirectPlay4::SecureOpen, IDirectPlay4::SetSessionDesc, IDirectPlay4::CreatePlayer


System Messages

The DirectPlay system messages are:

  • DPMSG_ADDGROUPTOGROUP
  • DPMSG_ADDPLAYERTOGROUP
  • DPMSG_CHAT
  • DPMSG_CREATEPLAYERORGROUP
  • DPMSG_DELETEGROUPFROMGROUP
  • DPMSG_DELETEPLAYERFROMGROUP
  • DPMSG_DESTROYPLAYERORGROUP
  • DPMSG_GENERIC
  • DPMSG_HOST
  • DPMSG_SECUREMESSAGE
  • DPMSG_SENDCOMPLETE
  • DPMSG_SESSIONLOST
  • DPMSG_SETGROUPOWNER
  • DPMSG_SETPLAYERORGROUPDATA
  • DPMSG_SETPLAYERORGROUPNAME
  • DPMSG_SETSESSIONDESC
  • DPMSG_STARTSESSION


DPMSG_ADDGROUPTOGROUP

DirectPlay generates a DPMSG_ADDGROUPTOGROUP structure and sends it to every player when a group is added to a group.

typedef struct{
    DWORD    dwType;
    DPID     dpIdParentGroup;
    DPID     dpIdGroup;
} DPMSG_ADDGROUPTOGROUP, FAR *LPDPMSG_ADDGROUPTOGROUP;
dwType
Identifies the message. This member is DPSYS_ADDGROUPTOGROUP.
dpIdParentGroup
ID of the group to which the group was added.
dpIdGroup
ID of the group that was added to the group.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.

See Also

IDirectPlay4::AddGroupToGroup


DPMSG_ADDPLAYERTOGROUP

The DPMSG_ADDPLAYERTOGROUP structure contains information for the DPSYS_ADDPLAYERTOGROUP system message. DirectPlay generates this message and sends it to every player when a player is added to a group.

The application can use IDirectPlay4::GetPlayerCaps, IDirectPlay4::GetPlayerName, and IDirectPlay4::GetPlayerData for information about the player involved int his message, or IDirectPlay4::GetGroupName and IDirectPlay4::GetGroupData to get more information about the group involved in this message.

typedef struct{
    DWORD dwType;
    DPID  dpIdGroup;
    DPID  dpIdPlayer;
} DPMSG_ADDPLAYERTOGROUP, FAR *LPDPMSG_ADDPLAYERTOGROUP;
dwType
Identifies the message. This member is DPSYS_ADDPLAYERTOGROUP.
dpIdGroup
ID of the group to which the player was added.
dpIdPlayer
ID of the player that was added to the group.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.

See Also

IDirectPlay4::AddPlayerToGroup


DPMSG_CHAT

The DPMSG_CHAT structure contains information for the DPSYS_CHAT system message. The system message is generated for a local player receiving a chat message from another player.

typedef struct{
    DWORD dwType;
    DWORD dwFlags;
    DPID  idFromPlayer;
    DPID  idToPlayer;
    DPID  idToGroup;
    LPDPCHAT  lpChat;
} DPMSG_CHAT, FAR *LPDPMSG_CHAT;
dwType
Identifies the message. This member has the value DPSYS_CHAT.
dwFlags
Not used.
idFromPlayer
ID of the player from whom the message originated. DPID_SERVERPLAYER indicates the message originated from the server.
idToPlayer
ID of the player to whom the message was directed. If this value is 0, then the message was sent to a group or broadcast to everyone.
idToGroup
ID of the group to whom the message was directed. If this value is 0 and idToPlayer is also 0, then the message was broadcast to everyone.
lpChat
Pointer to a DPCHAT structure containing the content of the chat message received.

Remarks

Use the idFromPlayer value to determine who sent the message. The value of lpidFrom available through Receive will always be 0, so you must retrieve the value of idFromPlayer in the DPMSG_CHAT structure.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.

See Also

IDirectPlay4::SendChatMessage, DPCHAT, IDirectPlay4::Receive


DPMSG_CREATEPLAYERORGROUP

The DPMSG_CREATEPLAYERORGROUP structure contains information for the DPSYS_CREATEPLAYERORGROUP system message. The system sends this message when players and groups are created in a session.

DirectPlay generates this message and sends it to each player when a new player or group is created in a session.

typedef struct{
    DWORD  dwType;
    DWORD  dwPlayerType;
    DPID   dpId;
    DWORD  dwCurrentPlayers;
    LPVOID lpData;
    DWORD  dwDataSize;
    DPNAME dpnName;
    DPID   dpIDParent;
    DWORD  dwFlags;
} DPMSG_CREATEPLAYERORGROUP, FAR *LPDPMSG_CREATEPLAYERORGROUP;
dwType
A DWORD that identifies the message. This member must be set to DPSYS_CREATEPLAYERORGROUP.
dwPlayerType
A DWORD that indicates whether the message applies to a player (DPPLAYERTYPE_PLAYER) or a group (DPPLAYERTYPE_GROUP).
dpId
ID of a player or group created.
dwCurrentPlayers
Current number of players in the session before this player was created.
lpData
Pointer to any application-specific, remote data associated with this player or group. If this member is NULL, there is no remote data.
dwDataSize
Size of the data contained in the buffer referenced by lpData.
dpnName
Structure containing the name of the player or group.
dpIDParent
ID of the parent group if this message is caused by a call to IDirectPlay4::CreateGroupInGroup; otherwise, the value is 0.
dwFlags
Player or group flags.
DPGROUP_HIDDEN
Set when a hidden group is created.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.

See Also

IDirectPlay4::CreateGroup, IDirectPlay4::CreatePlayer, IDirectPlay4::CreateGroupInGroup


DPMSG_DELETEGROUPFROMGROUP

DirectPlay generates the DPMSG_DELETEGROUPFROMGROUP structure and sends it to every player when a group is removed from a group. Note that this structure is identical to DPMSG_ADDGROUPTOGROUP.

typedef struct{
    DWORD    dwType;
    DPID     dpIdParentGroup;
    DPID     dpIdGroup;
} DPMSG_ADDGROUPTOGROUP, FAR *LPDPMSG_ADDGROUPTOGROUP;
typedef DPMSG_ADDGROUPTOGROUP DPMSG_DELETEGROUPFROMGROUP;
dwType
Identifies the message. This member is DPSYS_DELETEGROUPFROMGROUP.
dpIdParentGroup
ID of the group from which the group was removed.
dpIdGroup
ID of the group that was removed from the group.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.

See Also

IDirectPlay4::DeleteGroupFromGroup


DPMSG_DELETEPLAYERFROMGROUP

The DPMSG_DELETEPLAYERFROMGROUP structure contains information for the DPSYS_DELETEPLAYERFROMGROUP system message. DirectPlay generates this message and sends it to each local player on the computer when a player is deleted from a group.

For a description of the structure members, see the DPMSG_ADDPLAYERTOGROUP structure.

The application can use IDirectPlay4::GetPlayerCaps, IDirectPlay4::GetPlayerName, and IDirectPlay4::GetPlayerData for information about the player involved in this message, or IDirectPlay4::GetGroupName and IDirectPlay4::GetGroupData to get more information about the group involved in this message.

typedef struct{
    DWORD dwType;
    DPID  dpIdGroup;
    DPID  dpIdPlayer;
} DPMSG_ADDPLAYERTOGROUP, FAR *LPDPMSG_ADDPLAYERTOGROUP;
typedef DPMSG_ADDPLAYERTOGROUP DPMSG_DELETEPLAYERFROMGROUP;
dwType
Identifies the message. This member is DPSYS_DELETEPLAYERFROMGROUP.
dpIdGroup
ID of the group from which the player was removed.
dpIdPlayer
ID of the player that was removed from the group.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.

See Also

IDirectPlay4::DeletePlayerFromGroup


DPMSG_DESTROYPLAYERORGROUP

The DPMSG_DESTROYPLAYERORGROUP structure contains information for the DPSYS_DESTROYPLAYERORGROUP system message. DirectPlay generates this message and sends it to each player when a player or group is destroyed in a session.

typedef struct{
    DWORD  dwType;
    DWORD  dwPlayerType;
    DPID   dpId;
    LPVOID lpLocalData;
    DWORD  dwLocalDataSize;
    LPVOID lpRemoteData;
    DWORD  dwRemoteDataSize;
    DPNAME dpnName;
    DPID   dpIdParent;
    DWORD  dwFlags;
} DPMSG_DESTROYPLAYERORGROUP, FAR *LPDPMSG_DESTROYPLAYERORGROUP;
dwType
A DWORD that identifies the message. This member is DPSYS_DESTROYPLAYERORGROUP.
dwPlayerType
A DWORD that identifies whether the message applies to a player (DPPLAYERTYPE_PLAYER) or group (DPPLAYERTYPE_GROUP).
dpId
ID of a player or group that has been destroyed.
lpLocalData
Pointer to the local data associated with this player or group.
dwLocalDataSize
Size, in bytes, of the local data.
lpRemoteData
Pointer to the remote data associated with this player or group.
dwRemoteDataSize
Size, in bytes, of the remote data.
dpnName
Structure containing the name of the player or group.
dpIdParent
ID of the parent group if the group being destroyed is a subgroup of the parent group—that is, the group being destroyed was created by a call to IDirectPlay4::CreateGroupInGroup. Otherwise the value is 0.
dwFlags
Player or group flags. One or more of the following values:
DPGROUP_HIDDEN
Set when a hidden group is destroyed.
DPGROUP_STAGINGAREA
Set when a group that is a staging area is destroyed.
DPPLAYER_SERVERPLAYER
Set when the player being destroyed is a server player for client/server communications.
DPPLAYER_SPECTATOR
Set when the player destroyed is a spectator.

Remarks

The version of this structure in DirectX 5.0 added three members to the end, dpnName, dpIdParent, and dwFlags.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.

See Also

IDirectPlay4::DestroyGroup, IDirectPlay4::DestroyPlayer


DPMSG_GENERIC

The DPMSG_GENERIC structure is provided for message processing.

typedef struct{
    DWORD dwType;
} DPMSG_GENERIC, FAR *LPDPMSG_GENERIC;
dwType
Identifies the system message type. For a list of types, see Using System Messages.

Remarks

When a system message is received (that is, the value pointed to by the lpidFrom parameter equals DPID_SYSMSG), first cast the unknown message data to the DPMSG_GENERIC type, and then perform further processing based on the value of dwType. After the message type has been determined, the message can cast to one of the known types of system messages for further processing.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.


DPMSG_HOST

When the current session host exits the session, the DPMSG_HOST message is sent to all the players on the computer that inherits the host duties.

typedef DPMSG_GENERIC    DPMSG_HOST;
typedef DPMSG_HOST  FAR *LPDPMSG_HOST;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.

See Also

DPMSG_GENERIC


DPMSG_SECUREMESSAGE

DirectPlay generates the DPMSG_SECUREMESSAGE structure when it receives a signed or encrypted message from another player.

typedef struct {
    DWORD   dwType;
    DWORD   dwFlags;
    DPID    dpIdFrom;
    LPVOID  lpData;
    DWORD   dwDataSize;
} DPMSG_SECUREMESSAGE, FAR *LPDPMSG_SECUREMESSAGE;
dwType
Identifies the system message type. This is DPSYS_SECUREMESSAGE.
dwFlags
Flags indicating how the message was secured by the sender. One of the following values:
DPSEND_SIGNED
The message was signed by the sender and the signature was successfully verified.
DPSEND_ENCRYPTED
The messages was encrypted by the sender and successfully decrypted.
dpIdFrom
The DPID of the player that sent the secure message.
lpData
Pointer to a buffer containing the fully verified message.
dwDataSize
Size of the buffer containing the message.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.

See Also

IDirectPlay4::Send


DPMSG_SENDCOMPLETE

The DPMSG_SENDCOMPLETE structure is sent to the receive queue to inform the application of the completion status of an asynchronous send. This message is generated by default whenever an asynchronous message is sent using the DPSEND_ASYNC flag in IDirectPlay4::SendEx.

typedef struct{
    DWORD    dwType;
    DPID     idFrom;
    DPID     idTo;
    DWORD    dwFlags;
    DWORD    dwPriority;
    DWORD    dwTimeout;
    LPVOID   lpContext;
    DWORD    dwMsgID;
    HRESULT  hr;
    DWORD    dwSendTime;
} DPMSG_SENDCOMPLETE, FAR *LPDPMSG_SENDCOMPLETE;
dwType
Value that identifies the message. This member is DPSYS_SENDCOMPLETE.
idFrom
DPID of the player who sent the message.
idTo
DPID of the player the message was sent to.
dwFlags
Flags specified in SendEx when the message was sent.
dwPriority
Priority that the message was sent at.
dwTimeout
Time-out specified when the message was sent (specified in SendEx). Zero indicates the default time-out.
lpContext
lpContext parameter supplied by the application to SendEx.
dwMsgID
dwMsgID returned to the application by DirectPlay through SendEx.
hr
HRESULT of the asynchronous message. Can be one of the following values.
DP_OK
The message was successfully sent.
DPERR_ABORTED
The message was canceled while it was being transmitted.
DPERR_CANCELLED
The message was canceled while it was still in the send queue.
DPERR_GENERIC
The message could not be sent.
DPERR_TIMEOUT
The message timed out and was removed from the send queue.
dwSendTime
The elapsed time, in milliseconds, between the time the message was sent by the application (by calling SendEx) and the time DirectPlay was able to send the message. This includes the time spent in the send queue and the time to hand the message off to the service provider. For guaranteed messages, this also includes the time to acknowledge delivery of the message.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.

See Also

IDirectPlay4::SendEx


DPMSG_SESSIONLOST

The DPMSG_SESSIONLOST structure is generated by DirectPlay when the connection to all the other players in the session is lost. After the session is lost, messages cannot be sent to remote players, but all data at the time the session was lost is still available. Your applications should try to recover gracefully and exit if this message is received.

typedef DPMSG_GENERIC    DPMSG_SESSIONLOST;
typedef DPMSG_SESSIONLOST  FAR  *LPDPMSG_SESSIONLOST;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.

See Also

DPMSG_GENERIC


DPMSG_SETGROUPOWNER

The DPMSG_SETGROUPOWNER structure is generated by DirectPlay when the owner of a group has changed. Group ownership can be changed by the current owner leaving the session, by a call to IDirectPlay4::SetGroupOwner, or, arbitrarily, by the lobby server in a lobby session.

typedef struct{
  DWORD   dwType;
  DPID    idGroup;
  DPID    idNewOwner;
  DPID    idOldOwner;
} DPMSG_SETGROUPOWNER, FAR *LPDPMSG_SETGROUPOWNER;
dwType
Value that identifies the message. This member is DPSYS_SETGROUPOWNER.
idGroup
ID of the group whose owner changed.
idNewOwner
ID of the player who is the new owner of the group.
idOldOwner
ID of the player who was the old owner of the group.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.

See Also

IDirectPlay4::SetGroupOwner


DPMSG_SETPLAYERORGROUPDATA

The DPMSG_SETPLAYERORGROUPDATA message structure contains information for the DPSYS_SETPLAYERORGROUPDATA system message. DirectPlay generates this message and sends it to each player when the remote data of a player or group changes. This message will not be generated if the DPSESSION_ NODATAMESSAGES flag is specified in the session description.

typedef struct {
    DWORD  dwType;
    DWORD  dwPlayerType;
    DPID   dpId;
    LPVOID lpData;
    DWORD  dwDataSize;
} DPMSG_SETPLAYERORGROUPDATA, FAR *LPDPMSG_SETPLAYERORGROUPDATA;
dwType
Identifies the message. This value is always DPSYS_SETPLAYERORGROUPDATA.
dwPlayerType
Identifies whether the message applies to a player (DPPLAYERTYPE_PLAYER) or a group (DPPLAYERTYPE_GROUP).
dpId
ID of the player or group whose data changed.
lpData
Pointer to an application-specific block of data.
dwDataSize
Size of the data contained in the buffer referenced by lpData.

Remarks

It is not necessary for the application to save the data from this message because it can be retrieved at any time using IDirectPlay4::GetPlayerData or IDirectPlay4::GetGroupData.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.

See Also

IDirectPlay4::SetPlayerData, IDirectPlay4::SetGroupData


DPMSG_SETPLAYERORGROUPNAME

The DPMSG_SETPLAYERORGROUPNAME structure contains information for the DPSYS_SETPLAYERORGROUPNAME system message. DirectPlay generates this message and sends it to each local player on the computer when the name of a player or group changes. This message will not be generated if the DPSESSION_NODATAMESSAGES flag is specified in the session description.

typedef struct {
    DWORD  dwType;
    DWORD  dwPlayerType;
    DPID   dpId;
    DPNAME dpnName;
} DPMSG_SETPLAYERORGROUPNAME, FAR *LPDPMSG_SETPLAYERORGROUPNAME;
dwType
Identifies the message. This value is always DPSYS_SETPLAYERORGROUPNAME.
dwPlayerType
Identifies whether the message applies to a player (DPPLAYERTYPE_PLAYER) or a group (DPPLAYERTYPE_GROUP).
dpId
ID of the player or group whose name changed.
dpnName
Structure containing the new name information for the player or group.

Remarks

It is not necessary for the application to save the dpnName from this message because it can be retrieved at any time using IDirectPlay4::GetPlayerName or IDirectPlay4::GetGroupName.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.

See Also

IDirectPlay4::GetPlayerName, IDirectPlay4::GetGroupName, IDirectPlay4::SetPlayerName, IDirectPlay4::SetGroupName


DPMSG_SETSESSIONDESC

DPMSG_SETSESSIONDESC contains information for the DPSYS_SETSESSIONDESC system message. Every player will receive this system message when the session description changes.

This messages will not be generated if the DPSESSION_NODATAMESSAGES flag is specified in the session description.

typedef struct {
    DWORD           dwType;
    DPSESSIONDESC2  dpDesc;
} DPMSG_SETSESSIONDESC, FAR *LPDPMSG_SETSESSIONDESC;
dwType
Identifies the message. This value is always DPSYS_SETSESSIONDESC.
dpDesc
Pointer to a DPSESSIONDESC2 structure containing the updated session description.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.

See Also

IDirectPlay4::GetSessionDesc, IDirectPlay4::SetSessionDesc


DPMSG_STARTSESSION

The DPMSG_STARTSESSION message structure contains information for the DPSYS_STARTSESSION system message. The lobby server sends this message to each player in a group when it is time for that player to join an application session.

typedef struct {
   DWORD            dwType;
   LPDPLCONNECTION  lpConn;
} DPMSG_STARTSESSION, FAR *LPDPMSG_STARTSESSION;
dwType
Identifies the message. This value is always DPSYS_STARTSESSION.
lpConn
Pointer to a DPLCONNECTION structure that contains all the information needed to launch an application into a session. This structure can be passed into IDirectPlayLobby3::RunApplication (if an external application is to be launched) or passed into IDirectPlayLobby3::SetConnectionSettings and then followed by a call to IDirectPlayLobby3::Connect (to connect the current application to the session).

Remarks

Upon receipt of this message by a stand-alone lobby client, the client must launch the application by calling the IDirectPlayLobby3::RunApplication method with the DPLCONNECTION structure.

Upon receipt of this message by an application with an internal lobby, the application must set the connection settings by calling IDirectPlayLobby3::SetConnectionSettings and then connect to the session using the IDirectPlayLobby3::Connect method.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplay.h.

See Also

IDirectPlay4::StartSession, IDirectPlayLobby3::RunApplication, IDirectPlayLobby3::SetConnectionSettings, IDirectPlayLobby3::Connect


Standard Lobby Messages

To determine whether the lobby that launched your application supports standard lobby messages, it is necessary to send the lobby an initial DPLMSG_GETPROPERTY request and see whether it responds. The property that should be requested is DPLPROPERTY_MessagesSupported.

If the lobby responds with TRUE, then you can assume that it will respond to all further messages. If it responds with FALSE or does not respond at all within a specified time-out, then you can assume that messages are not supported.

If the application supports spectator players, the application should also request DPLPROPERTY_PlayerGuid before creating players in order to determine if they should be created as spectators or not.

The DirectPlay standard lobby messages are:

  • DPLMSG_GENERIC
  • DPLMSG_GETPROPERTY
  • DPLMSG_GETPROPERTYRESPONSE
  • DPLMSG_NEWSESSIONHOST
  • DPLMSG_SETPROPERTY
  • DPLMSG_SETPROPERTYRESPONSE
  • DPLMSG_SYSTEMMESSAGE

See Also

Using Lobby Messages, Staying in Touch with the Lobby


DPLMSG_GENERIC

DPLMSG_GENERIC is the generic structure of system messages passed between the lobby client and an application.

typedef struct {
    DWORD dwType;
} DPLMSG_GENERIC, FAR *LPDPLMSG_GENERIC;
dwType
Identifies what type of system message has been received.

Remarks

When a lobby system message is received (that is, the value pointed to by the lpidFrom parameter equals DPID_SYSMSG), first cast the unknown message data to the DPLMSG_GENERIC type, and then perform further processing based on the value of dwType. After the message type has been determined, the message can cast to one of the known types of lobby system messages for further processing.

See Using Lobby Messages for a list of lobby message types.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.

See Also

DPLMSG_SYSTEMMESSAGE


DPLMSG_GETPROPERTY

The DPLMSG_GETPROPERTY message is sent by an application to the lobby to request the current value of a property. These properties can be information such as the ranking of a player, a bitmap representing a player, or initial configuration information for the game or players that was done inside the lobby.

typedef struct {
    DWORD   dwType;
    DWORD   dwRequestID;
    GUID    guidPlayer;
    GUID    guidPropertyTag;
} DPLMSG_GETPROPERTY, FAR *LPDPLMSG_GETPROPERTY;
dwType
Identifies the message. This value is DPLSYS_ GETPROPERTY.
dwRequestID
An application generated ID to identify the request. When the lobby responds, it will be tagged with this request ID. The application can use the request ID to match responses to pending requests.
guidPlayer
GUID identifying the player that this property applies to (if applicable). If the property is not player-specific, this member should be set to GUID_NULL. The GUID for the player or players created by this application can be obtained from the lobby by requesting the DPLPROPERTY_PlayerGuid property.
guidPropertyTag
A GUID identifying the property that is being requested. The property can one of the predefined ones listed in the section DirectPlay Defined Properties, or the applicationm or obby can define its own GUIDs for additional properties.

Remarks

Each property is identified by a GUID (defined by the application developer or the lobby developer). When a request for a property is made, the lobby responds with a DPLMSG_GETPROPERTYRESPONSE message. Even if the lobby cannot supply the information, it should respond with an error indicating the information is unavailable.

The application should not block waiting for a response and should have a way to time-out pending requests that haven't been fulfilled.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.

See Also

DPLMSG_GETPROPERTYRESPONSE


DPLMSG_GETPROPERTYRESPONSE

The DPLMSG_GETPROPERTYRESPONSE message is sent by a lobby to an application in response to a DPLMSG_GETPROPERTY message. The request that is being filled is identified by the dwRequestID member.

typedef struct {
    DWORD    dwType;
    DWORD    dwRequestID
    GUID     guidPlayer;
    GUID     guidPropertyTag;
    HRESULT  hr;
    DWORD    dwDataSize;
    DWORD    dwPropertyData[1];
} DPLMSG_GETPROPERTYRESPONSE, FAR *LPDPLMSG_GETPROPERTYRESPONSE;
dwType
Identifies the message. This value is DPLSYS_ GETPROPERTYRESPONSE.
dwRequestID
The ID that identifies the DPLMSG_GETPROPERTY message that this message is in response to.
guidPlayer
GUID identifying the player that this property applies to (if applicable). If the property is not player-specific, this member will be set to GUID_NULL. This will be the same as the GUID from the DPLMSG_GETPROPERTY message.
guidPropertyTag
A GUID identifying the property that is being requested. This will be the same as the GUID from the DPLMSG_GETPROPERTY message.
hr
Return code for the get property request. One of the following values:
DP_OK
Successfully returned the property.
DPERR_UNKNOWNMESSAGE
The requested property is unknown to the lobby.
DPERR_UNAVAILABLE
The requested property is unavailable.
dwDataSize
The size, in bytes, of the property data.
dwPropertyData
A variable-size buffer that contains the property data. The property tag will define how to interpret this data.

Remarks

A lobby must either respond to all DPLMSG_GETPROPERTY requests or none of them.

When constructing this message, the lobby needs to allocate enough memory to hold the DPLMSG_GETPROPERTYRESPONSE structure and the complete property data. For example, if the property data requires 52 bytes, the lobby will allocate (sizeof(DPLMSG_GETPROPERTYRESPONSE) + 52) bytes and assign it to a DPLMSG_GETPROPERTYRESPONSE pointer.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.

See Also

DPLMSG_GETPROPERTY


DPLMSG_NEWSESSIONHOST

The DPLMSG_NEWSESSIONHOST message is generated by DirectPlay and sent to the lobby client/provider when the client on the computer becomes the new host of the application session.

typedef struct {
    DWORD    dwType;
    GUID     guidInstance;
} DPLMSG_NEWSESSIONHOST, FAR *LPDPLMSG_NEWSESSIONHOST;
dwType
Value that identifies the message. This value is DPLSYS_NEWSESSIONHOST.
guidInstance
Value that identifies the globally unique identifier (GUID) of this instance of the session.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.


DPLMSG_SETPROPERTY

The DPLMSG_SETPROPERTY message is sent by an application to the lobby to inform it that a property of a specific player or a property of the session has changed. These properties can range from the score or status of a player to the current level of a game or the current status of the session.

typedef struct {
    DWORD    dwType;
    DWORD    dwRequestID
    GUID     guidPlayer;
    GUID     guidPropertyTag;
    DWORD    dwDataSize;
    DWORD    dwPropertyData[1];
} DPLMSG_SETPROPERTY, FAR *LPDPLMSG_SETPROPERTY;
dwType
Identifies the message. This value is DPLSYS_SETPROPERTY.
dwRequestID
A nonzero request ID supplied by the application if it would like confirmation that the data was recognized and set appropriately. If no confirmation is required, set this to DPL_NOCONFIRMATION.
guidPlayer
GUID identifying the player that this property applies to (if applicable). If the property is not player-specific, this member should be set to GUID_NULL. The GUID for the player or players created by this application can be obtained from the lobby by requesting the DPLPROPERTY_PlayerGuid property.
guidPropertyTag
A GUID identifying the property that is being set. The property can be one of the predefined GUIDs listed in the section DirectPlay Defined Properties or the application/lobby can define its own GUIDs for additional properties.
dwDataSize
The size, in bytes, of the property data.
dwPropertyData
A variable size buffer that contains the property data. The property tag will define how to interpret this data.

Remarks

Each property is identified by a GUID (defined by the application developer or the lobby developer), and it is the responsibility of the lobby to maintain a mapping of property GUIDs of the various applications to their descriptions and data types. The lobby server can choose to act on the information or ignore it.

When constructing this message, the application needs to allocate enough memory to hold the DPLMSG_SETPROPERTY structure and the complete property data. For example, if the property data requires 52 bytes, the application will allocate (sizeof(DPLMSG_SETPROPERTY) + 52) bytes and assign it to a LPDPLMSG_SETPROPERTY pointer.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.

See Also

DPLMSG_SETPROPERTYRESPONSE


DPLMSG_SETPROPERTYRESPONSE

The DPLMSG_SETPROPERTYRESPONSE message is sent by a lobby to an application as confirmation of a DPLMSG_SETPROPERTY message. The message that is being confirmed is identified by the dwRequestID member.

typedef struct {
    DWORD    dwType;
    DWORD    dwRequestID
    GUID     guidPlayer;
    GUID     guidPropertyTag;
    HRESULT  hr;
} DPLMSG_SETPROPERTYRESPONSE, FAR *LPDPLMSG_SETPROPERTYRESPONSE;
dwType
Identifies the message. This value is DPLSYS_SETPROPERTYRESPONSE.
dwRequestID
The ID that identifies the DPLMSG_SETPROPERTY message being confirmed.
guidPlayer
GUID identifying the player that this property was set for (if applicable). If the property is not player-specific, this member is GUID_NULL. This must be the same as the GUID from the DPLMSG_SETPROPERTY message.
guidPropertyTag
A GUID identifying the property that was set. This must be the same as the GUID from the DPLMSG_SETPROPERTY message.
hr
Result of the confirmation. One of the following values:
DP_OK
The property was set correctly.
DPERR_ACCESSDENIED
An attempt was made to set a property the lobby will not allow to be changed.
DPERR_UNKNOWNMESSAGE
The property is unknown to the lobby.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.

See Also

DPLMSG_SETPROPERTY


DPLMSG_SYSTEMMESSAGE

The DPLMSG_SYSTEMMESSAGE structure is a system message passed between the lobby and an application.

typedef struct {
    DWORD    dwType;
    GUID     guidInstance;
} DPLMSG_SYSTEMMESSAGE, FAR *LPDPLMSG_SYSTEMMESSAGE;
dwType
Identifies what type of system message has been received.
DPLSYS_APPTERMINATED
Indicates the application started by IDirectPlayLobby3::RunApplication has terminated.
DPLSYS_CONNECTIONSETTINGSREAD
Indicates the application started by the IDirectPlayLobby3::RunApplication method has read the connection settings.
DPLSYS_DPLAYCONNECTFAILED
Indicates the application started by IDirectPlayLobby3::RunApplication failed to connect to a session.
DPLSYS_DPLAYCONNECTSUCCEEDED
Indicates the application started by IDirectPlayLobby3::RunApplication has created a session and is ready for other applications to join or has successfully joined a session.
DPLSYS_NEWCONNECTIONSETTINGS
Indicates that a waiting application was found when a lobby client called RunApplication. The waiting application can now read the connection settings with GetConnectionSettings and join a session using ConnectEx.
guidInstance
GUID identifying the instance of the DirectPlay session that this message corresponds to.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.


DirectPlay Defined Properties

This section describes the defined properties that can be set and retrieved by applications from a lobby.

When a DPLMSG_GETPROPERTYRESPONSE message is received, its guidPropertyTag member identifies the property and its dwPropertyData member contains the property information. To extract this information, cast the dwPropertyData member to the appropriate value. For example, the following routine retrieves the DPLDATA_PLAYERGUID structure from the given message. (See DPLPROPERTY_PlayerGuid.)

BOOL GetPlayerGuid(
        LPDPLMSG_GETPROPERTYRESPONSE lpPropertyResponseMsg,
        LPDPLDATA_PLAYERGUID lpPlayerGuid)
{
   if (IsEqualGUID(lpPropertyResponseMsg->guidPropertyTag,
           DPLPROPERTY_PlayerGuid))
   {
      *lpPlayerGuid = *((LPDPLDATA_PLAYERGUID)
              lpPropertyResponseMsg->dwPropertyData);
      return (TRUE);
   }
   else
   {
      return (FALSE);
   }
}

See the following descriptions of defined properties:.

  • DPLPROPERTY_LobbyGuid
  • DPLPROPERTY_MessagesSupported
  • DPLPROPERTY_PlayerGuid
  • DPLPROPERTY_PlayerScore


DPLPROPERTY_LobbyGuid

DPLPROPERTY_LobbyGuid is used to identify the lobby software. If an application was designed to interoperate with a specific lobby using custom messages, this property can be used to identify the lobby.

However, an application should attempt to use standard messages whenever possible to be able to interoperate with as many lobbies as possible.

For this property, the dwPropertyData member of the DPLMSG_GETPROPERTYRESPONSE structure will contain the following:

GUID  guidLobby;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.
Import Library: Use dplayx.lib.


DPLPROPERTY_MessagesSupported

DPLPROPERTY_MessagesSupported is a Boolean value indicating whether the lobby supports standard messages. An application can request this property from the lobby to determine if it supports standard messages. If the lobby does not respond to this message, or if it responds with FALSE, the application should assume that it does not support standard lobby messages and should not send any further messages. If the lobby returns TRUE, the application should freely send standard messages to the lobby and query for further properties of the lobby.

For this property, the dwPropertyData member of the DPLMSG_GETPROPERTYRESPONSE structure will contain the following:

BOOL  fMessagesSupported;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.
Import Library: Use dplayx.lib.


DPLPROPERTY_PlayerGuid

DPLPROPERTY_PlayerGuid is used to uniquely identify the application's local players. Any further DPLMSG_SETPROPERTY or DPLMSG_GETPROPERTY messages that require a player GUID will need to use this value to communicate with the lobby.

An application can manipulate properties for remote players on another computer. The application only needs to obtain the player GUID from the remote player (not from the lobby).

If an application supports spectator players, it should request this property before creating any players in order to determine what flags (if any) to use when creating the players; for example, DPPLAYER_SPECTATOR and DPPLAYER_SERVERPLAYER.

For this property, the dwPropertyData member of the DPLMSG_GETPROPERTYRESPONSE structure will contain the following:

typedef struct {
    GUID  guidPlayer;
    DWORD dwPlayerFlags;
} DPLDATA_PLAYERGUID, FAR *LPDPLDATA_PLAYERGUID;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.
Import Library: Use dplayx.lib.


DPLPROPERTY_PlayerScore

DPLPROPERTY_PlayerScore is a generic structure that can be used by an application to report a composite score value to the lobby. The guidPlayer GUID of the player the score applies to must be provided when setting or getting this property. This structure can handle an arbitrary list of long integer values that collectively represent the score of a player. The application must allocate enough memory to hold all the scores. For example, if the score was passed as N integers, the application must allocate ( sizeof(DPLDATA_PLAYERSCORE) + N*sizeof(LONG) ) bytes and cast the pointer to LPDPLDATA_PLAYERSCORE.

For this property, the dwPropertyData member of the DPLMSG_GETPROPERTYRESPONSE structure will contain the following:

typedef struct {
    DWORD   dwScoreCount;
    LONG    Score[1];
} DPLDATA_PLAYERSCORE, FAR *LPDPLDATA_PLAYERSCORE;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dplobby.h.
Import Library: Use dplayx.lib.


Return Values

Errors are represented by negative values and cannot be combined. This table lists the values that can be returned by all IDirectPlay4 interface and IDirectPlayLobby3 interface methods. For a list of the error values each method can return, see the individual method descriptions.

Many of the DirectPlay samples include a GetDirectPlayErrStr function that converts HRESULT values to string names for the DirectPlay errors. Developers can copy this code into their own applications for diagnostic traces or error reports.

CLASS_E_NOAGGREGATION
A non-NULL value was passed for the pUnkOuter parameter in DirectPlayCreate, DirectPlayLobbyCreate, or IDirectPlayLobby3::Connect.
DP_OK
The request completed successfully.
DPERR_ABORTED
The operation was canceled before it could be completed.
DPERR_ACCESSDENIED
The session is full, or an incorrect password was supplied.
DPERR_ACTIVEPLAYERS
The requested operation cannot be performed because there are existing active players.
DPERR_ALREADYINITIALIZED
This object is already initialized.
DPERR_APPNOTSTARTED
The application has not been started yet.
DPERR_AUTHENTICATIONFAILED
The password or credentials supplied could not be authenticated.
DPERR_BUFFERTOOLARGE
The data buffer is too large to store.
DPERR_BUFFERTOOSMALL
The supplied buffer is not large enough to contain the requested data.
DPERR_BUSY
A message cannot be sent because the transmission medium is busy.
DPERR_CANCELFAILED
The message could not be canceled, possibly because it is a group message that has already been to sent to one or more members of the group.
DPERR_CANCELLED
The operation was canceled.
DPERR_CANNOTCREATESERVER
The server cannot be created for the new session.
DPERR_CANTADDPLAYER
The player cannot be added to the session.
DPERR_CANTCREATEGROUP
A new group cannot be created.
DPERR_CANTCREATEPLAYER
A new player cannot be created.
DPERR_CANTCREATEPROCESS
Cannot start the application.
DPERR_CANTCREATESESSION
A new session cannot be created.
DPERR_CANTLOADCAPI
No credentials were supplied and the CryptoAPI package (CAPI) to use for cryptography services cannot be loaded.
DPERR_CANTLOADSECURITYPACKAGE
The software security package cannot be loaded.
DPERR_CANTLOADSSPI
No credentials were supplied, and the Security Support Provider Interface (SSPI) that will prompt for credentials cannot be loaded.
DPERR_CAPSNOTAVAILABLEYET
The capabilities of the DirectPlay object have not been determined yet. This error will occur if the DirectPlay object is implemented on a connectivity solution that requires polling to determine available bandwidth and latency.
DPERR_CONNECTING
The method is in the process of connecting to the network. The application should keep using the method until it returns DP_OK, indicating successful completion, or until it returns a different error.
DPERR_CONNECTIONLOST
The service provider connection was reset while data was being sent.
DPERR_ENCRYPTIONFAILED
The requested information could not be digitally encrypted. Encryption is used for message privacy. This error is only relevant in a secure session.
DPERR_ENCRYPTIONNOTSUPPORTED
The type of encryption requested in the DPSECURITYDESC structure is not available. This error is only relevant in a secure session.
DPERR_EXCEPTION
An exception occurred when processing the request.
DPERR_GENERIC
An undefined error condition occurred.
DPERR_INVALIDFLAGS
The flags passed to this method are invalid.
DPERR_INVALIDGROUP
The group ID is not recognized as a valid group ID for this game session.
DPERR_INVALIDINTERFACE
The interface parameter is invalid.
DPERR_INVALIDOBJECT
The DirectPlay object pointer is invalid.
DPERR_INVALIDPARAMS
One or more of the parameters passed to the method are invalid.
DPERR_INVALIDPASSWORD
An invalid password was supplied when attempting to join a session that requires a password.
DPERR_INVALIDPLAYER
The player ID is not recognized as a valid player ID for this game session.
DPERR_INVALIDPRIORITY
The specified priority is not within the range of allowed priorities, which is inclusively 0-65535.
DPERR_LOGONDENIED
The session could not be opened because credentials are required, and either no credentials were supplied, or the credentials were invalid.
DPERR_NOCAPS
The communication link that DirectPlay is attempting to use is not capable of this function.
DPERR_NOCONNECTION
No communication link was established.
DPERR_NOINTERFACE
The interface is not supported.
DPERR_NOMESSAGES
There are no messages in the receive queue.
DPERR_NONAMESERVERFOUND
No name server (host) could be found or created. A host must exist to create a player.
DPERR_NONEWPLAYERS
The session is not accepting any new players.
DPERR_NOPLAYERS
There are no active players in the session.
DPERR_NOSESSIONS
There are no existing sessions for this game.
DPERR_NOTLOBBIED
Returned by the IDirectPlayLobby3::Connect method if the application was not started by using the IDirectPlayLobby3::RunApplication method, or if there is no DPLCONNECTION structure currently initialized for this DirectPlayLobby object.
DPERR_NOTLOGGEDIN
An action cannot be performed because a player or client application is not logged on. Returned by the IDirectPlay4::Send method when the client application tries to send a secure message without being logged on.
DPERR_OUTOFMEMORY
There is insufficient memory to perform the requested operation.
DPERR_PENDING
Not an error, this return indicates that an asynchronous send has reached the point where it is successfully queued. See IDirectPlay4::SendEx for more information.
DPERR_PLAYERLOST
A player has lost the connection to the session.
DPERR_SENDTOOBIG
The message being sent by the IDirectPlay4::Send method is too large.
DPERR_SESSIONLOST
The connection to the session has been lost.
DPERR_SIGNFAILED
The requested information could not be digitally signed. Digital signatures are used to establish the authenticity of messages.
DPERR_TIMEOUT
The operation could not be completed in the specified time.
DPERR_UNAVAILABLE
The requested function is not available at this time.
DPERR_UNINITIALIZED
The requested object has not been initialized.
DPERR_UNKNOWNAPPLICATION
An unknown application was specified.
DPERR_UNKNOWNMESSAGE
The message ID isn't valid. Returned from IDirectPlay4::CancelMessage if the ID of the message to be canceled is invalid.
DPERR_UNSUPPORTED
The function or feature is not available in this implementation or on this service provider. Returned from IDirectPlay4::GetGroupConnectionSettings and IDirectPlay4::SetGroupConnectionSettings if they are called from a session that is not a lobby session. Returned from IDirectPlay4::SendEx if the priority or time-out is set, and these are not supported by the service provider and DirectPlay protocol is not on. Returned from IDirectPlay4::GetMessageQueue if you check the send queue and this is not supported by the service provider and DirectPlay protocol is not on.
DPERR_USERCANCEL
Can be returned in two ways. 1) The user canceled the connection process during a call to the IDirectPlay4::Open method. 2) The user clicked Cancel in one of the DirectPlay service provider dialog boxes during a call to IDirectPlay4::EnumSessions.
E_UNKNOWN
Usually indicates a catastrophic failure of some sort; for example, the service provider cannot initialize correctly or a protocol such as IPX is not installed correctly on the machine.


DirectPlay Visual Basic Reference

This section contains references for the application programming interface (API) elements of DirectPlay® for Visual Basic®. Information is divided into the following categories:

  • Classes
  • Types
  • Enumerations
  • Error Codes


Classes

This section contains references for methods of the following DirectPlay classes:

  • DirectPlay4
  • DirectPlayAddress
  • DirectPlayEnumConnections
  • DirectPlayEnumLocalApplications
  • DirectPlayEnumPlayers
  • DirectPlayEnumSessions
  • DirectPlayLobby3
  • DirectPlayLobbyConnection
  • DirectPlayMessage
  • DirectPlaySessionData


DirectPlay4

Applications use the methods of the DirectPlay4 class to create DirectPlay objects, perform enumerations, establish connections, and manage sessions, players, and groups.

A single DirectPlay4 object should be created for each application by using the DirectX7.DirectPlayCreate method.

The methods of the DirectPlay4 class can be organized into the following groups:

Connections | GetDPEnumConnections
 | InitializeConnection
 | SetGroupConnectionSettings
Sessions | Close
 | CreateSessionData
 | GetDPEnumSessions
 | GetCaps
 | GetSessionDesc
 | Open
 | SecureOpen
 | SetSessionDesc
 | StartSession
Players | CreatePlayer
 | DestroyPlayer
 | GetDPEnumPlayers
 | GetPlayerAccountId
 | GetPlayerAddress
 | GetPlayerCaps
 | GetPlayerData
 | GetPlayerFlags
 | GetPlayerFormalName
 | GetPlayerFriendlyName
 | SetPlayerData
 | SetPlayerName
Messages | CancelMessage
 | CancelPriority
 | CreateMessage
 | GetMessageCount
 | GetMessageQueue
 | Receive
 | Send
 | SendChatMessage
 | SendEx
Groups | AddGroupToGroup
 | AddPlayerToGroup
 | CreateGroup
 | CreateGroupInGroup
 | DeleteGroupFromGroup
 | DeletePlayerFromGroup
 | DestroyGroup
 | GetDPEnumGroupPlayers
 | GetDPEnumGroups
 | GetDPEnumGroupsInGroup
 | GetGroupData
 | GetGroupFlags
 | GetGroupLongName
 | GetGroupShortName
 | GetGroupOwner
 | GetGroupParent
 | SetGroupData
 | SetGroupName
 | SetGroupOwner


DirectPlay4.AddGroupToGroup

The DirectPlay4.AddGroupToGroup method adds a shortcut to a group to an already existing group. This enables the linked group to be enumerated by the DirectPlay4.GetDPEnumGroupsInGroup method. To remove a group's shortcut from another group, call DirectPlay4.DeleteGroupFromGroup.

object.AddGroupToGroup(ParentGroupId As Long, _
    GroupId As Long)

Parameters

object
Object expression that resolves to a DirectPlay4 object.
ParentGroupId
ID of the group to which the shortcut will be added. Can be any valid group ID.
GroupId
ID of the group whose shortcut will be added. Can be any valid group ID.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_ACCESSDENIED
DPERR_CONNECTIONLOST
DPERR_INVALIDGROUP

Remarks

You can use this method to place a group inside more than one group.

A DPSYS_ADDGROUPTOGROUP system message is generated to inform players of this change.

See Also

DirectPlay4.CreateGroupInGroup


DirectPlay4.AddPlayerToGroup

The DirectPlay4.AddPlayerToGroup method adds a player to an existing group. A player can be a member of multiple groups. An application can add any player to any group (including players and groups that were not created locally). A group cannot be added to another group by using this method (see DirectPlay4.AddGroupToGroup).

object.AddPlayerToGroup(GroupId As Long, _
    playerId As Long)

Parameters

object
Object expression that resolves to a DirectPlay4 object.
GroupId
ID of the group to be augmented.
playerId
ID of the player to be added to the group.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_CANTADDPLAYER
DPERR_CONNECTIONLOST
DPERR_INVALIDGROUP
DPERR_INVALIDPLAYER
DPERR_NOSESSIONS

This method returns DPERR_INVALIDPLAYER if the player DirectPlay ID is not a player ID or if the ID is not for a local player.

Remarks

A DPSYS_ADDPLAYERTOGROUP system message will be generated and sent to all the other players.

See Also

DirectPlay4.CreateGroup, DirectPlay4.DeletePlayerFromGroup


DirectPlay4.CancelMessage

The DirectPlay4.CancelMessage method cancels a specific message, or all the messages, in the send queue. CancelMessage applies only to asynchronous messages. To cancel a specific message, the application must obtain and save the message ID returned by the DirectPlay4.SendEx method.

Messages that have left the message queue and are partially sent cannot be canceled. A message sent to a group cannot be canceled after it has been sent to at least one member of the group.

object.CancelMessage(msgid As Long)

Parameters

object
Object expression that resolves to a DirectPlay4 object.
msgid
ID of the specific message to be canceled. This ID is returned when the message is sent using DirectPlay4.SendEx. Specify 0 to cancel all messages.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_CANCELFAILED
DPERR_INVALIDFLAGS
DPERR_INVALIDPARAMS
DPERR_UNKNOWNMESSAGE
DPERR_UNSUPPORTED

See Also

DirectPlay4.CancelPriority, DirectPlay4.Send


DirectPlay4.CancelPriority

The DirectPlay4.CancelPriority method cancels all messages of a particular priority or range of priorities that are still in the send queue. CancelPriority applies only to asynchronous messages.

Messages that have left the message queue and are partially sent cannot be canceled. A message sent to a group cannot be canceled after it has been sent to at least one member of the group.

object.CancelPriority(minPriority As Long, _
    maxPriority As Long)

Parameters

object
Object expression that resolves to a DirectPlay4 object.
minPriority
Minimum priority in the range to be canceled.
maxPriority
Maximum priority in the range to be canceled. Must be greater than minPriority.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_INVALIDFLAGS
DPERR_INVALIDPARAMS

See Also

DirectPlay4.SendEx, DirectPlay4.Send, DirectPlay4.CancelMessage


DirectPlay4.Close

The DirectPlay4.Close method closes a previously opened session. Any locally created groups will migrate to be owned by the host of the session.

object.Close()

Parameters

object
Object expression that resolves to a DirectPlay4 object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_NOSESSIONS

Remarks

All locally created players will be destroyed and appropriate DPSYS_DELETEPLAYERFROMGROUP and DPSYS_DESTROYPLAYERORGROUP system messages will be sent to other session participants.

See Also

DirectPlay4.DestroyPlayer, DirectPlay4.Open


DirectPlay4.CreateGroup

The DirectPlay4.CreateGroup method creates a group in the current session.

object.CreateGroup(friendlyName As String, _
    formalName As String, _
    flags As CONST_DPGROUPFLAGS) As Long

Parameters

object
Object expression that resolves to a DirectPlay4 object.
friendlyName
Handle that can be used to identify and access the created group. This token identifier should differ from formalName.
formalName
Handle that can be used to identify and access the created group. This token identifier should differ from friendlyName.
flags
Flag from the CONST_DPGROUPFLAGS enumeration indicating what type of group to create. Can be one of DPGROUP_DEFAULT, DPGROUP_HIDDEN, or DPGROUP_STAGINGAREA.

Return Values

The method returns the group ID.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_CANTADDPLAYER
DPERR_CONNECTIONLOST
DPERR_INVALIDFLAGS
DPERR_INVALIDPARAMS

Remarks

If the group is created in a client/server session, no group notification messages are sent. Groups are only visible on the computer that created them, regardless of whether the computer is the client or the host.

If the group is created in a peer-to-peer session, CreateGroup will generate a DPSYS_CREATEPLAYERORGROUP system message that will be sent to all the other players. The application can subsequently use the DirectPlay4.Send method to send a message to all the players in a group by sending one message to the group ID. DirectPlay will either use multicast to send the message (if the service provider supports it) or send individual messages to each player in the group.

The group ID returned to the application should be used to identify the group for message passing and data association. Player and group IDs assigned by DirectPlay will always be unique within the session.

Groups created with CreateGroup are top-level groups in the session. They are enumerated with DirectPlay4.GetDPEnumGroups. In contrast, the DirectPlay4.CreateGroupInGroup method creates a group that is a subgroup of a parent group.

The application can also use groups for general organization. In a lobby session, a staging area is used as the mechanism for collecting players for the purpose of starting a new application session using DirectPlay4.StartSession.

The player who creates a group is its default owner. Only the owner can change group properties such as the name and remote data, and only the group owner can change the membership of the group or delete the group. If the owner leaves the session, ownership is transferred to the host of the session.

Groups will persist in the session until they are explicitly destroyed.

See Also

DirectPlay4.AddGroupToGroup,DirectPlay4.DestroyGroup, DirectPlay4.GetDPEnumGroupPlayers, DirectPlay4.GetGroupFlags, DirectPlay4.SetGroupData, DirectPlay4.SetGroupName


DirectPlay4.CreateGroupInGroup

The DirectPlay4.CreateGroupInGroup method creates a group within an existing group. A group created within another group can be enumerated only by using the DirectPlay4.GetDPEnumGroupsInGroup method. A group created this way can be destroyed by calling the DirectPlay4.DestroyGroup method.

object.CreateGroupInGroup(parentid As Long,
  friendlyName As String,
  formalName As String,
  flags As CONST_DPGROUPFLAGS) As Long

Parameters

object
Object expression that resolves to a DirectPlay4 object.
parentid
DirectPlay ID of the existing group within which a group will be created.
friendlyName
Handle that can be used to identify and access the created group. This token identifier should differ from formalName.
formalName
Handle that can be used to identify and access the created group. This token identifier should differ from friendlyName.
flags
Flag from the CONST_FLAGS enumeration indicating what type of group to create. Can be DPGROUP_LOCAL or DPGROUP_STAGINGAREA. If DPGROUP_LOCAL is not set, the group is a remote group.

Return Values

Returns the created group's DirectPlay ID.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_CANTADDPLAYER
DPERR_CONNECTIONLOST
DPERR_INVALIDFLAGS
DPERR_INVALIDGROUP
DPERR_INVALIDPARAMS

This method returns DPERR_CANTADDPLAYER if the group could not be created. It returns DPERR_INVALIDGROUP if the parent group ID is invalid.

Remarks

If the group is created in a client/server session, no group notification messages are sent. Groups are only visible on the computer that created them, regardless of whether the computer is the client or the host.

If the group is created in a peer-to-peer session, CreateGroupInGroup will generate a DPSYS_CREATEPLAYERORGROUP system message generated to inform players of this change.

If you destroy a top-level group, any member groups it contains are destroyed as well, and the appropriate destruction messages are sent.


DirectPlay4.CreateMessage

The DirectPlay4.CreateMessage method creates a message object, which can be packed with data and sent.

object.CreateMessage() As DirectPlayMessage

Parameters

object
Object expression that resolves to a DirectPlay4 object.

Return Values

If it succeeds, the method returns a DirectPlayMessage object.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

See Also

DirectPlay4.Send


DirectPlay4.CreatePlayer

The DirectPlay4.CreatePlayer method creates a local player for the current session.

object.CreatePlayer(friendlyName As String, _
    formalName As String, _
    receiveEvent As Long, _
    flags As CONST_DPPLAYERFLAGS) As Long

Parameters

object
Object expression that resolves to a DirectPlay4 object.
friendlyName
Handle that can be used to identify and access the created player. This token identifier should differ from formalName.
formalName
Handle that can be used to identify and access the created player. This token identifier should differ from friendlyName.
receiveEvent
Handle for an event created by the application that DirectPlay will signal when a message addressed to this player is received.
flags
Flags indicating what type of player this is. Default (flags = 0) is a nonspectator, nonserver player.
DPPLAYER_SERVERPLAYER
The player is a server player for client/server communications. Only the host can create a server player. There can be only one server player in a session. CreatePlayer will always return a player ID of DPID_SERVERPLAYER if this flag is specified.
DPPLAYER_SPECTATOR
The player is created as a spectator. The behavior of a spectator player is completely defined by the application. DirectPlay simply propagates this flag.

Return Values

If it succeeds, the method returns a unique player ID.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_CANTADDPLAYER
DPERR_CANTCREATEPLAYER
DPERR_CONNECTIONLOST
DPERR_INVALIDFLAGS
DPERR_INVALIDPARAMS
DPERR_NOCONNECTION

Remarks

A single process can have multiple local players that communicate through a DirectPlay object with other players on the same computer or players on remote computers.

Upon successful completion, this method sends a DPSYS_CREATEPLAYERORGROUP system message to all the other players in the session announcing that a new player has joined the session. By default, all local players receive copies of all the system messages.

Your application should use the player ID returned to the application to identify the player for message passing and data association. Player and group IDs assigned by DirectPlay will always be unique within the session.

Only the application that created the player can:

  • Change the player's name.
  • Change the player's remote data.
  • Send messages from the player.

If the application closes the session, any local players created will be automatically destroyed. Using the DirectPlay4.DestroyPlayer method, the session host or the application that created the player can destroy the player at any time.

See Also

DirectPlay4.GetDPEnumPlayers, DirectPlay4.GetPlayerFlags, DirectPlay4.Send, DirectPlay4.SetPlayerData, DirectPlay4.SetPlayerName, DirectX7.CreateEvent


DirectPlay4.CreateSessionData

The DirectPlay4.CreateSessionData method creates an object that is used to set and retrieve information about a session.

object.CreateSessionData() As DirectPlaySessionData

Parameters

object
Object expression that resolves to a DirectPlay4 object.

Return Values

If it succeeds, the method returns a DirectPlaySessionData object.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlay4.DeleteGroupFromGroup

The DirectPlay4.DeleteGroupFromGroup method removes a shortcut to a group previously added with the DirectPlay4.AddGroupToGroup method from a group. Deleting the shortcut does not destroy the group.

object.DeleteGroupFromGroup(groupParentId As Long, _
    GroupId As Long)

Parameters

object
Object expression that resolves to a DirectPlay4 object.
groupParentId
DirectPlay ID of the group containing the shortcut to be removed.
GroupId
DirectPlay ID of the group to remove.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_ACCESSDENIED
DPERR_CONNECTIONLOST
DPERR_INVALIDGROUP

Remarks

A DPSYS_DELETEGROUPFROMGROUP system message is generated to inform players of this change.


DirectPlay4.DeletePlayerFromGroup

The DirectPlay4.DeletePlayerFromGroup method removes a player from a group.

object.DeletePlayerFromGroup(GroupId As Long, _
    playerId As Long)

Parameters

object
Object expression that resolves to a DirectPlay4 object.
GroupId
ID of the group from which the player is to be removed.
playerId
ID of the player to be removed from the group.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_CONNECTIONLOST
DPERR_INVALIDGROUP
DPERR_INVALIDOBJECT
DPERR_INVALIDPLAYER

Remarks

A DPSYS_DELETEPLAYERFROMGROUP system message is generated to inform the other players of this change.

A player can delete any player from a group, even if that group was created by some other computer.

See Also

DirectPlay4.AddPlayerToGroup


DirectPlay4.DestroyGroup

The DirectPlay4.DestroyGroup method deletes a group from the session.

object.DestroyGroup(GroupId As Long)

Parameters

object
Object expression that resolves to a DirectPlay4 object.
GroupId
ID of the group being removed from the game.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_CONNECTIONLOST
DPERR_INVALIDGROUP
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_INVALIDPLAYER

Remarks

It is not necessary to empty a group before deleting it. The individual players belonging to the group are not destroyed.

This method will generate a DPSYS_DELETEPLAYERFROMGROUP system message for each player in the group, and then a DPSYS_DESTROYPLAYERORGROUP system message.

Any application can destroy any group even if the group was not created locally.

The ID belonging to this group will not be reused during the current session.

See Also

DirectPlay4.CreateGroup


DirectPlay4.DestroyPlayer

The DirectPlay4.DestroyPlayer method deletes a local player from the session, removes any pending messages destined for that player from the message queue, and removes the player from any groups to which the player belonged.

In general, only the application that created the player can destroy the player. However, the host of the session can also destroy the player.

object.DestroyPlayer(playerId As Long)

Parameters

object
Object expression that resolves to a DirectPlay4 object.
playerId
ID of the locally owned player to be removed from the session. When DestroyPlayer is called by the host of the session, this ID can be that of any player, local or remote.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_ACCESSDENIED
DPERR_CONNECTIONLOST
DPERR_INVALIDOBJECT
DPERR_INVALIDPLAYER
DPERR_UNAVAILABLE

Remarks

This method generates a DPSYS_DELETEPLAYERFROMGROUP system message for each group that the player belongs to and then generates a DPSYS_DESTROYPLAYERORGROUP system message.

A player cannot be destroyed if the player has pending asynchronous messages in the send queue. This method removes any pending messages destined for that player from the message queue.

The player ID will not be reused during the current session.

See Also

DirectPlay4.CreatePlayer


DirectPlay4.GetCaps

The DirectPlay4.GetCaps method obtains the capabilities of the current DirectPlay connection and session.

object.GetCaps(caps As DPCAPS, _
    flags As CONST_DPGETCAPSFLAGS)

Parameters

object
Object expression that resolves to a DirectPlay4 object.
caps
DPCAPS type that will be filled with the capabilities of the DirectPlay object.
flags
One of the members of the CONST_DPGETCAPSFLAGS enumeration. If this parameter is set to DPGETCAPS_DEFAULT (or 0), the capabilities will be computed for nonguaranteed messaging. Setting DPGETCAPS_GUARANTEED retrieves the capabilities for a guaranteed message delivery.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_UNINITIALIZED

Remarks

The connection must be initialized before this method is called. If there is no open session, some members of DPCAPS will not return meaningful values.

See Also

DirectPlay4.GetPlayerCaps, DirectPlay4.InitializeConnection


DirectPlay4.GetDPEnumConnections

The DirectPlay4.GetDPEnumConnections method enumerates all the registered service providers and lobby providers available to the application. Typically these are presented to the user to make a selection, and the selected connection is passed to the DirectPlay4.InitializeConnection method.

object.GetDPEnumConnections(guid As String, _
    flags As CONST_DPENUMCONNECTIONFLAGS) _
    As DirectPlayEnumConnections

Parameters

object
Object expression that resolves to a DirectPlay4 object.
guid
Globally unique identifier for the application. Only service providers and lobby providers that are usable by this application will be returned. If set to "", a list of all the connections is enumerated regardless of the application GUID.
flags
CONST_DPENUMCONNECTIONFLAGS flags that specify the type of connections to be enumerated. The default (flags = 0) gives the same results as DPCONNECTION_DIRECTPLAY.

Return Values

If it succeeds, the method returns a DirectPlayEnumConnections object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_CONNECTIONLOST
DPERR_INVALIDFLAGS
DPERR_INVALIDPARAMS

Remarks

The order in which the service and lobby providers are returned is not guaranteed to be the same in subsequent calls to GetDPEnumConnections.

Not all the enumerated connections are available for use. For example, this method will return the modem service provider even if the user has no modem installed. The application can call the DirectPlay4.InitializeConnection method on each connection and check for an error code to determine whether the service provider can be used.

Some service providers can register themselves as private. These service providers are not enumerated by this method. To use private service providers, you must explicitly reference them by GUID, either by launching the application from a lobby or by creating a DirectPlay address and passing it to InitializeConnection.

See Also

Using GUIDs


DirectPlay4.GetDPEnumGroupPlayers

The DirectPlay4.GetDPEnumGroupPlayers method enumerates the players belonging to a specific group in the currently open session.

GetDPEnumGroupPlayers(GroupId As Long, _
    sessionGuid As String, _
    flags As CONST_DPENUMPLAYERFLAGS) _
    As DirectPlayEnumPlayers

Parameters

object
Object expression that resolves to a DirectPlay4 object.
GroupId
DirectPlay ID of the group whose players are to be enumerated.
sessionGuid
Globally unique identifier (GUID) identifying the session to be enumerated. This parameter is ignored unless the DPENUMPLAYERS_SESSION flag is specified. The GUID must be equal to one of the sessions enumerated by the DirectPlay4.GetDPEnumSessions method.
flags
Flags specifying how the enumeration is to be done. The default (flags = 0) enumerates players in a group in the current active session. You should use a logical Or operation to combine the flags that you want to specify. Only players that meet all the criteria of the combined flags will be enumerated. For example, if you specify (DPENUMPLAYERS_LOCAL Or DPENUMPLAYERS_SPECTATOR) only players in the group that are local and are spectator players will be enumerated. If you specify (DPENUMPLAYERS_LOCAL Or DPENUMPLAYERS_REMOTE), no players will be enumerated because no player can be both local and remote.

Can be one or more of the following values from the CONST_DPENUMPLAYERFLAGS enumeration:

DPENUMPLAYERS_LOCAL
DPENUMPLAYERS_OWNER
DPENUMPLAYERS_REMOTE
DPENUMPLAYERS_SERVERPLAYER
DPENUMPLAYERS_SESSION
DPENUMPLAYERS_SPECTATOR

Return Values

If the method succeeds, it returns a DirectPlayEnumPlayers object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_ACCESSDENIED
DPERR_CONNECTIONLOST
DPERR_INVALIDPARAMS
DPERR_INVALIDGROUP
DPERR_NOSESSIONS
DPERR_UNAVAILABLE

This method returns DPERR_ACCESSDENIED if the session is a lobby session you are not connected to. It returns DPERR_INVALIDPARAMS if an invalid sessionGuid or invalid flags were supplied. It returns DPERR_NOSESSIONS if there is no active session. It returns DPERR_UNAVAILABLE if the session could not be enumerated.

Remarks

Password-protected remote sessions cannot be enumerated. You cannot use the method in a lobby session you are not connected to.

By default, this method will enumerate all players in the current session. The DPENUMPLAYERS_SESSION flag can be used, along with a session instance GUID, to request that a session's host provide its list for enumeration. Use of the DPENUMPLAYERS_SESSION flag with this method must occur after the DirectPlay4.GetDPEnumSessions method has been called, and before any calls to the DirectPlay4.Close or DirectPlay4.Open methods.

See Also

DirectPlay4.CreatePlayer, DirectPlay4.DestroyPlayer, DirectPlay4.AddPlayerToGroup, DirectPlay4.DeletePlayerFromGroup, Using GUIDs


DirectPlay4.GetDPEnumGroups

The DirectPlay4.GetDPEnumGroups method enumerates all the top-level groups in the current session. Top-level groups are groups that were created by using the DirectPlay4.CreateGroup method.

object.GetDPEnumGroups(sessionGuid As String, _
    flags As CONST_DPENUMGROUPFLAGS) _
    As DirectPlayEnumPlayers

Parameters

object
Object expression that resolves to a DirectPlay4 object.
sessionGuid
Globally unique identifier (GUID) identifying the session to be enumerated. This parameter should be "" to enumerate groups in the currently open session. Otherwise the GUID must be equal to one of the sessions enumerated by DirectPlay4.GetDPEnumSessions. This parameter is ignored unless the DPENUMGROUPS_SESSION flag is specified.
flags
Flags specifying how the enumeration is to be done. By default (flags = 0), the method enumerates all groups in the current active session. Only groups that meet all the criteria of the combined flags will be enumerated. For example, if you specify (DPENUMGROUPS_LOCAL Or DPENUMGROUPS_STAGINGAREA) only groups that are local and are staging areas will be enumerated. If you specify (DPENUMGROUPS_LOCAL Or DPENUMGROUPS_REMOTE), no groups will be enumerated because no group can be both local and remote.

Can be one or more of the following values from the CONST_DPENUMGROUPFLAGS enumeration:

DPENUMGROUPS_ALL
Enumerates all groups in this session.
DPENUMGROUPS_LOCAL
Enumerates groups created locally by this DirectPlay object.
DPENUMGROUPS_REMOTE
Enumerates groups created by remote DirectPlay objects.
DPENUMGROUPS_SESSION
Performs enumeration in the session identified by the sessionGuid parameter. This flag can only be used if there is no current active session. You cannot use this flag in a lobby session.
DPENUMGROUPS_STAGINGAREA
Enumerates groups that are in staging areas. (Staging areas are used to marshal players together in order to launch a new session.)

Return Values

If it succeeds, the method returns a DirectPlayEnumPlayers object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_CONNECTIONLOST
DPERR_INVALIDPARAMS
DPERR_NOSESSIONS
DPERR_UNAVAILABLE

This method returns DPERR_INVALIDPARAMS if an invalid sessionGuid or invalid flags were supplied. It returns DPERR_NOSESSIONS if there is no open session. It returns DPERR_UNAVAILABLE if the remote session could not be enumerated.

Remarks

You cannot use GetDPEnumGroups in a lobby session you are not connected to.

If there is no open session, groups in a remote session can be enumerated by specifying the DPENUMGROUPS_SESSION flag and the sessionGuid of the session. Password-protected remote sessions cannot be enumerated.

To enumerate the subgroups in a group, use DirectPlay4.GetDPEnumGroupsInGroup.

See Also

DirectPlay4.DestroyGroup, DirectPlay4.GetDPEnumSessions, Using GUIDs


DirectPlay4.GetDPEnumGroupsInGroup

The DirectPlay4.GetDPEnumGroupsInGroup method enumerates all groups and shortcuts to groups that are contained within another group. Groups are placed inside other groups by creating them with the DirectPlay4.CreateGroupInGroup method or by adding them to a group with the DirectPlay4.AddGroupToGroup method. This method is not recursive.

object.GetDPEnumGroupsInGroup(GroupId As Long, _
    sessionGuid As String, _
    flags As CONST_DPENUMGROUPFLAGS) _
    As DirectPlayEnumPlayers

Parameters

object
Object expression that resolves to a DirectPlay4 object.
GroupId
ID of the group whose subgroups are to be enumerated.
sessionGuid
Globally unique identifier (GUID) of the session to be enumerated. This parameter is ignored unless the DPENUMPLAYERS_SESSION flag is specified. The GUID must belong to one of the sessions enumerated by the DirectPlay4.GetDPEnumSessions method.
flags
Flags specifying how the enumeration will be done. By default (flags = 0), the method enumerates all groups in the current active session. Only groups that meet all the criteria of the combined flags will be enumerated. For example, if you specify (DPENUMGROUPS_LOCAL Or DPENUMGROUPS_STAGINGAREA) only groups that are local and are staging areas will be enumerated. If you specify (DPENUMGROUPS_LOCAL Or DPENUMGROUPS_REMOTE), no groups will be enumerated, because no group can be both local and remote.

Can be one or more of the following values from the CONST_DPENUMGROUPFLAGS enumeration:

DPENUMGROUPS_ALL
Enumerates all groups in the group.
DPENUMGROUPS_HIDDEN
Enumerates only the currently available hidden groups in the group.
DPENUMGROUPS_LOCAL
Enumerates groups in the group created locally by this DirectPlay object.
DPENUMGROUPS_REMOTE
Enumerates groups in the group created by remote DirectPlay objects.
DPENUMGROUPS_SESSION
Performs enumeration in the session identified by the sessionGuid parameter. This flag can only be used if there is no current active session. This flag cannot be used in lobby sessions.
DPENUMGROUPS_SHORTCUT
Enumerates groups that are shortcuts added to the group using DirectPlay4.AddGroupToGroup. (A shortcut is a link to another group.)
DPENUMGROUPS_STAGINGAREA
Enumerates groups in the group that are staging areas. (Staging areas are used to marshal players together in order to launch a new session.)

Return Values

If the method succeeds, it returns a DirectPlayEnumPlayers object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_CONNECTIONLOST
DPERR_INVALIDFLAGS
DPERR_INVALIDGROUP
DPERR_INVALIDPARAMS
DPERR_NOSESSIONS
DPERR_UNSUPPORTED

This method returns DPERR_INVALIDPARAMS if an invalid sessionGuid is supplied. It returns DPERR_NOSESSIONS if there is no active session. It returns DPERR_UNSUPPORTED if the session could not be enumerated.

Remarks

You cannot use this method in a lobby session you are not connected to.

See Also

DirectPlay4.DeleteGroupFromGroup, DirectPlay4.DestroyGroup, Using GUIDs


DirectPlay4.GetDPEnumPlayers

The DirectPlay4.GetDPEnumPlayers method enumerates the players and, optionally, groups in the current open session. If there is no open session, players in a remote session can be enumerated.

object.GetDPEnumPlayers(sessionGuid As String, _
    flags As CONST_DPENUMPLAYERFLAGS) _
    As DirectPlayEnumPlayers

Parameters

object
Object expression that resolves to a DirectPlay4 object.
sessionGuid
This parameter should be "" to enumerate players in the currently open session. If there is no open session, this parameter can be a GUID identifying the session to be enumerated. The GUID must belong to one of the sessions enumerated by DirectPlay4.GetDPEnumSessions. This parameter is ignored unless the DPENUMPLAYERS_SESSION flag is specified.
flags
Flags specifying how the enumeration is to be done. Default (flags = 0) enumerates all players in the current active session. Only players that meet all the criteria of the combined flags will be enumerated. For example, if you specify (DPENUMPLAYERS_LOCAL Or DPENUMPLAYERS_SPECTATOR) only players that are local and are spectator players will be enumerated. If you specify (DPENUMPLAYERS_LOCAL Or DPENUMPLAYERS_REMOTE), no players will be enumerated, because no player can be both local and remote.

Can be one or more of the following values from the CONST_DPENUMPLAYERFLAGS enumeration:

DPENUMPLAYERS_ALL
DPENUMPLAYERS_GROUP
DPENUMPLAYERS_LOCAL
DPENUMPLAYERS_REMOTE
DPENUMPLAYERS_SERVERPLAYER
DPENUMPLAYERS_SESSION
DPENUMPLAYERS_SPECTATOR

Return Values

If the method succeeds, it returns a DirectPlayEnumPlayers object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_ACCESSDENIED
DPERR_CONNECTIONLOST
DPERR_INVALIDPARAMS
DPERR_NOSESSIONS
DPERR_UNAVAILABLE

This method returns DPERR_INVALIDPARAMS if an invalid sessionGuid or invalid flags were supplied. It returns DPERR_NOSESSIONS if there is no open session. It returns DPERR_UNAVAILABLE if the remote session could not be enumerated.

Within a lobby session, this method will always return DPERR_ACCESSDENIED.

Remarks

By default, this method will enumerate players in the current open session. Groups can also be included in the enumeration by using the DPENUMPLAYERS_GROUP flag. The DPENUMPLAYERS_SESSION flag can be used, along with a session instance GUID, to request that a session's host provide its list for enumeration. This method cannot be called from within a DirectPlay4.GetDPEnumSessions enumeration. Furthermore, use of the DPENUMPLAYERS_SESSION flag with this method must occur after the GetDPEnumSessions method has been called, and before any calls to the DirectPlay4.Close or DirectPlay4.Open methods.

See Also

DirectPlay4.CreatePlayer, DirectPlay4.DestroyPlayer, Using GUIDs


DirectPlay4.GetDPEnumSessions

The DirectPlay4.GetDPEnumSessions method enumerates all the active sessions for a particular application and/or all the active lobby sessions that serve a particular application. This method can be called after a connection has been created and initialized by DirectPlay4.InitializeConnection.

The method returns an error if called while a session is already open.

object.GetDPEnumSessions( _
    sessionDesc As DirectPlaySessionData, _
    timeOut As Long, _
    flags As CONST_DPENUMSESSIONFLAGS) _
    As DirectPlayEnumSessions

Parameters

object
Object expression that resolves to a DirectPlay4 object.
sessionDesc
DirectPlaySessionData object representing the description of the sessions to be enumerated. This object is obtained by using the DirectPlay4.CreateSessionData method. The GuidApplication member can be set to the globally unique identifier (GUID) of an application of interest if it is known, or to "" to obtain all sessions. The SessionPassword member is only needed if you want private sessions. All other data members are ignored.
timeOut
In the synchronous case, the total amount of time, in milliseconds, that DirectPlay will wait for replies to the enumeration request (not the time between each enumeration). Any replies received after this time-out will be ignored. The application will be blocked until the time-out expires.

In the asynchronous case, this is the interval, in milliseconds, that enumeration requests will be broadcast by DirectPlay in order to update the internal sessions list.

If the time-out is set to 0, a default time-out appropriate for the service provider and connection type will be used. It is recommended that you set this value to 0. The application can determine this time-out by calling DirectPlay4.GetCaps and examining the lTimeout member of the DPCAPS type.

flags
Zero or more flags from the CONST_DPENUMSESSIONFLAGS enumeration. The default is 0, which is equivalent to DPENUMSESSIONS_AVAILABLE. When enumerating sessions with DPENUMSESSIONS_ALL or DPENUMSESSIONS_PASSWORDREQUIRED, it is important for the application to know which sessions cannot be joined and which sessions are password-protected so the user can be warned or prompted for a password.

Return Values

If it succeeds, the method returns a DirectPlayEnumSessions object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_CONNECTING
DPERR_CONNECTIONLOST
DPERR_EXCEPTION
DPERR_GENERIC
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_NOCONNECTION
DPERR_UNINITIALIZED
DPERR_USERCANCEL

This method returns DPERR_GENERIC if the session is already open. It returns DPERR_UNINITIALIZED if the DirectPlay object has not been initialized. It returns DPERR_USERCANCEL if the user canceled the enumeration process (usually by canceling a service provider dialog box). It returns DPERR_CONNECTING if the method is in the process of connecting to the network.

Remarks

This method works by requesting that the service provider locate one or more hosts on the network and send them an enumeration request. The replies that are received make up the sessions that are enumerated.

This method can be called synchronously (default) or asynchronously. When called synchronously, DirectPlay will clear the internal session cache, send out an enumeration request, and collect replies until the specified time-out expires. Each session will then be returned to the application. The application will be blocked until all the sessions have been returned.

When called asynchronously (DPENUMSESSIONS_ASYNC), all the current sessions (if any) in the session cache will be returned to the application and then the method will return. DirectPlay will then automatically send out enumeration requests with the period of the time-out parameter and listen for replies. Each reply will be used to update the session cache:

  • Sessions already in the cache will be updated.
  • Sessions that have not been updated for a set period of time (and thus have expired) will be deleted.
  • New sessions will be added.

The application must call GetDPEnumSessions (with the DPENUMSESSIONS_ASYNC flag set) again to obtain the most up-to-date session list with all the expired sessions deleted, new sessions added, and updated sessions. Subsequent calls to GetDPEnumSessions will not generate an enumeration request. Enumeration requests will be generated periodically by DirectPlay until the process is either canceled by calling GetDPEnumSessions with the DPENUMSESSIONS_STOPASYNC flag, a session is opened by using the DirectPlay4.Open method, or the DirectPlay object is released.

To change the description of the sessions being enumerated asynchronously, you must stop the asynchronous enumeration and then start it up again. For example, you cannot start an enumeration without a password and then later, during an asynchronous call, add a password and have it begin enumerating private sessions using that password. Conversely, if you specify the correct password, then change to an incorrect password, you will still enumerate the session. However, you can call GetDPEnumSessions with the DPENUMSESSIONS_STOPASYNC flag, then specify the password, and the private session will be enumerated.

Once enumeration of the available sessions is complete, the application can join one of the sessions using the DirectPlay4.Open method. Only sessions in the session cache can be opened. An application may attempt to open a session that has expired since the last time GetDPEnumSessions was called in which case an error will be returned.

No authentication is performed when enumerating sessions on a secure server. All sessions that meet the enumeration criteria will be returned. Authentication will be done when the application attempts to open one of these sessions with the Open or DirectPlay4.SecureOpen method.

If the application was not started by a lobby, the service provider can display a dialog box asking the user for information (such as a phone number or IP address) in order to perform the enumeration on the network, if that information was not provided in DirectPlay4.InitializeConnection. If the service provider can do a broadcast enumeration and requires no extra information from the user, no dialog box will appear.


DirectPlay4.GetGroupData

The DirectPlay4.GetGroupData method retrieves an application-specific string associated with a group.

object.GetGroupData(GroupId As Long, _
    flags As CONST_DPGETFLAGS) As String

Parameters

object
Object expression that resolves to a DirectPlay4 object.
GroupId
Group ID for which data is being requested.
flags
Value from the CONST_DPGETFLAGS enumeration indicating the type of group data to retrieve: local or remote. If this parameter is set to 0, remote data will be retrieved.

Return Values

If it succeeds, the method returns a string containing the data associated with the group by using the DirectPlay4.SetGroupData method.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_INVALIDGROUP
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_INVALIDPLAYER

Remarks

DirectPlay can maintain two types of group data: local and remote. The application must specify which type of data to retrieve. Local data was set by this DirectPlay object by using the DPSET_LOCAL flag. Remote data might have been set by any application in the session by using the DPSET_REMOTE flag.


DirectPlay4.GetGroupFlags

The DirectPlay4.GetGroupFlags method retrieves the flags describing the specified group.

object.GetGroupFlags(GroupId As Long) As Long

Parameters

object
Object expression that resolves to a DirectPlay4 object.
GroupId
ID of the group whose flag settings are to be retrieved.

Return Values

If it succeeds, the method returns a value set to the group flag settings. This can be one or both of the following members of the CONST_DPGROUPFLAGS enumeration:

DPGROUP_LOCAL
The group was created by this application. If this flag is not specified, the group is a remote group.
DPGROUP_STAGINGAREA
The group is a staging area.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_INVALIDGROUP
DPERR_INVALIDPARAMS.

See Also

DirectPlay4.CreateGroup


DirectPlay4.GetGroupLongName

The DirectPlay4.GetGroupLongName method retrieves the long name associated with a group.

object.GetGroupLongName(GroupId As Long) As String

Parameters

object
Object expression that resolves to a DirectPlay4 object.
GroupId
ID of the group whose name is being requested.

Return Values

The method returns the long name of the group. This is equivalent to the value passed as the formalName parameter of the DirectPlay4.CreateGroup, DirectPlay4.CreateGroupInGroup, or DirectPlay4.SetGroupName method.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlay4.GetGroupOwner

The DirectPlay4.GetGroupOwner method retrieves the ID of the current owner of the group. This method is only valid in a lobby session.

object.GetGroupOwner(GroupId As Long) As Long

Parameters

object
Object expression that resolves to a DirectPlay4 object.
GroupId
ID of the group whose owner is being requested.

Return Values

The method returns the DirectPlay ID of the group's owner, as set by the DirectPlay4.SetGroupOwner method.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlay4.GetGroupParent

The DirectPlay4.GetGroupParent method retrieves the ID of the group containing a group.

object.GetGroupParent(GroupId As Long) As Long

Parameters

object
Object expression that resolves to a DirectPlay4 object.
GroupId
ID of the group whose parent is being requested.

Return Values

The method returns the DirectPlay ID of the parent, if the group was created within another group by using DirectPlay4.CreateGroupInGroup. If the group was not created in another group, the method returns 0.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

See Also

DirectPlay4.CreateGroupInGroup


DirectPlay4.GetGroupShortName

The DirectPlay4.GetGroupShortName method retrieves the short name associated with a group.

object.GetGroupShortName(GroupId As Long) As String

Parameters

object
Object expression that resolves to a DirectPlay4 object.
GroupId
ID of the group whose name is being requested.

Return Values

The method returns the short name of the group. This is equivalent to the value passed as the friendlyName parameter of the DirectPlay4.CreateGroup, DirectPlay4.CreateGroupInGroup, or DirectPlay4.SetGroupName method.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlay4.GetMessageCount

The DirectPlay4.GetMessageCount method retrieves the number of messages in the receive queue for a specified local player.

object.GetMessageCount(playerId As Long) As Long

Parameters

object
Object expression that resolves to a DirectPlay4 object.
playerId
ID of the player whose message count is requested. The player must be local.

Return Values

Returns the message count.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

See Also

DirectPlay4.Receive


DirectPlay4.GetMessageQueue

The DirectPlay4.GetMessageQueue method retrieves information about the send or receive queue for a local player. If there is more than one player in a session on a single machine, the data returned is valid for all those players combined.

object.GetMessageQueue(from As Long, _
    to As Long, _
    flags As CONST_DPMESSAGEQUEUEFLAGS, _
    nMessage As Long, _
    nBytes As Long)

Parameters

object
Object expression that resolves to a DirectPlay4 object.
from
ID of the player sending the messages whose queue status is desired. Zero returns information about all sent messages. If to is also specified, only information about messages that are both from player from and to player to is returned.
to
ID of the player sent the messages whose queue status is desired. Zero returns information about all sent messages. If from is also specified, only information about messages that are both from player from and to player to is returned. You cannot specify a group ID for to.
flags
Flags indicating what type of information to obtain about the queue. Default (flags = 0) returns information about the send queue. Can be only one of the following values:
DPMESSAGEQUEUE_SEND
Retrieves information about the send queue.
DPMESSAGEQUEUE_RECEIVE
Retrieves information about the receive queue.
nMessage
Variable to receive the number of messages in the queue.
nBytes
Variable to receive the number of bytes in all messages in the queue.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_INVALIDFLAGS
DPERR_INVALIDPARAMS
DPERR_INVALIDPLAYER
DPERR_UNSUPPORTED

The method returns DPERR_INVALIDPLAYER if you check the receive queue (DPMESSAGEQUEUE_RECEIVE) while specifying to for a remote player. It returns DPERR_INVALIDPLAYER if you check the send queue (DPMESSAGEQUEUE_SEND) while specifying from for a remote player. It returns DPERR_INVALIDFLAGS if flags is DPMESSAGEQUEUE_RECEIVE Or DPMESSAGEQUEUE_SEND. It returns DPERR_UNSUPPORTED if you attempt to check the send queue when DirectPlay protocol is not turned on and the service provider does not support checking the send queue.

Remarks

By monitoring the status of the send queue, an application can regulate how many messages to send to other players in the session based on the bandwidth of the underlying network.


DirectPlay4.GetPlayerAccountId

The DirectPlay4.GetPlayerAccountId method retrieves the account identifier of a specified player when called by the session host in a secure session.

object.GetPlayerAccountId(playerId As Long) As String

Parameters

object
Object expression that resolves to a DirectPlay4 object.
playerId
ID of the player whose account information is to be retrieved.

Return Values

The method returns a unique identifier that describes a player who is securely logged on. The format of the identifier depends on the Security Support Provider Interface (SSPI) package being used.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

Remarks

The information returned by this method uniquely identifies an account. You can use this information to record the transactions or other activities of a logged-on player.

See Also

DirectPlay4.SecureOpen


DirectPlay4.GetPlayerAddress

The DirectPlay4.GetPlayerAddress method retrieves the DirectPlay address for a player.

If this method is called on a local player, it returns the network address of the computer if it is available. In some cases, more than one address can be returned (for example, with TCP/IP where the computer has both a network card and a dial-up Internet connection).

object.GetPlayerAddress(playerId As Long) _
    As DirectPlayAddress

Parameters

object
Object expression that resolves to a DirectPlay4 object.
playerId
Player ID that the address is being requested for. Pass in 0 to obtain a list of valid address options for a service provider

Return Values

If it succeeds, the method returns a DirectPlayAddress object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DPERR_UNAVAILABLE if the address for the requested player ID is not available.


DirectPlay4.GetPlayerCaps

The DirectPlay4.GetPlayerCaps method retrieves the current capabilities of a specified player.

object.GetPlayerCaps(playerId As Long, _
    caps As DPCAPS, _
    flags As CONST_DPGETCAPSFLAGS)

Parameters

object
Object expression that resolves to a DirectPlay4 object.
playerId
ID of the players whose capabilities are to be retrieved.
caps
DPCAPS type that will be filled with the capabilities.
flags
Value indicating how capabilities will be computed. If set to 0, capabilities will be computed for nonguaranteed messaging. If set to DPGETCAPS_GUARANTEED, this method retrieves capabilities for a guaranteed message delivery.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_INVALIDPLAYER

See Also

DirectPlay4.GetCaps, DirectPlay4.Send


DirectPlay4.GetPlayerData

The DirectPlay4.GetPlayerData method retrieves an application-specific data block that was associated with a player ID by using DirectPlay4.SetPlayerData.

object.GetPlayerData(playerId As Long, _
    flags As CONST_DPGETFLAGS) As String

Parameters

object
Object expression that resolves to a DirectPlay4 object.
playerId
ID of the player for which data is being requested.
flags
Value from the CONST_DPGETFLAGS enumeration indicating the type of player data to retrieve: local or remote. If this parameter is set to 0, remote data will be retrieved.

Return Values

The method returns a string containing application-defined data.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_BUFFERTOOSMALL
DPERR_INVALIDFLAGS
DPERR_INVALIDOBJECT
DPERR_INVALIDPLAYER

Remarks

Local data was set by the current DirectPlay object by using the DPSET_LOCAL flag in DirectPlay4.SetPlayerData. Remote data might have been set by any application in the session by using the DPSET_REMOTE flag.


DirectPlay4.GetPlayerFlags

The DirectPlay4.GetPlayerFlags method retrieves flags used to describe the player when the player was created.

object.GetPlayerFlags(id As Long) As CONST_DPPLAYERFLAGS

Parameters

object
Object expression that resolves to a DirectPlay4 object.
id
ID of the player whose flag settings are to be retrieved.

Return Values

The method returns the player's flag settings. The return value can contain one or more of the following:

DPPLAYER_LOCAL
The player was created by this application. If this flag is not specified, the player is a remote player.
DPPLAYER_SERVERPLAYER
The player is a server player for client/server communications.
DPPLAYER_SPECTATOR
The player was created as a spectator.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

See Also

DirectPlay4.CreatePlayer


DirectPlay4.GetPlayerFormalName

The DirectPlay4.GetPlayerFormalName method retrieves the formal name associated with a player.

object.GetPlayerFormalName(playerId As Long) As String

Parameters

object
Object expression that resolves to a DirectPlay4 object.
playerId
ID of the player whose name is requested.

Return Values

If it succeeds, the method returns the formal name of the player.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_INVALIDOBJECT
DPERR_INVALIDPLAYER

See Also

DirectPlay4.CreatePlayer, DirectPlay4.GetPlayerFriendlyName, DirectPlay4.SetPlayerName


DirectPlay4.GetPlayerFriendlyName

The DirectPlay4.GetPlayerFriendlyName method retrieves the friendly name associated with a player.

object.GetPlayerFriendlyName(playerId As Long) As String

Parameters

object
Object expression that resolves to a DirectPlay4 object.
playerId
ID of the player whose name is requested.

Return Values

If it succeeds, the method returns the friendly name of the player.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_INVALIDOBJECT
DPERR_INVALIDPLAYER

See Also

DirectPlay4.CreatePlayer, DirectPlay4.GetPlayerFormalName, DirectPlay4.SetPlayerName


DirectPlay4.GetSessionDesc

The DirectPlay4.GetSessionDesc method retrieves the properties of the current open session.

object.GetSessionDesc(sessionDesc As DirectPlaySessionData))

Parameters

object
Object expression that resolves to a DirectPlay4 object.
sessionDesc
DirectPlaySessionData object to receive information about the session. This object is obtained by using the DirectPlay4.CreateSessionData method.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_BUFFERTOOSMALL
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_NOCONNECTION


DirectPlay4.InitializeConnection

The DirectPlay4.InitializeConnection method initializes a DirectPlay connection. All the information about the connection, including the service provider to use, the network address of the server, and the GUID of the session, is passed in through the addr parameter.

object.InitializeConnection(addr As DirectPlayAddress)

Parameters

object
Object expression that resolves to a DirectPlay4 object.
addr
DirectPlayAddress object providing access to all the information about the connection to be initialized. See Remarks.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_ALREADYINITIALIZED
DPERR_INVALIDFLAGS
DPERR_INVALIDPARAMS
DPERR_UNAVAILABLE

This method returns DPERR_ALREADYINITIALIZED if InitializeConnection has previously been called on this object. It returns DPERR_UNAVAILABLE if the service provider could not be initialized. This can be because the resources necessary to operate this service provider are not present (for example, TCP/IP stack not present).

Remarks

The addr parameter supplied to this method can be obtained from the DirectPlay4.GetDPEnumConnections method, or the application can create one directly by using one of the address creation methods of DirectPlayLobby3.

This method loads and initializes the appropriate service provider. The addr parameter is passed on to the service provider, which extracts and saves any relevant information. This information is used when the DirectPlay4.GetDPEnumSessions or DirectPlay4.Open method is called so that the service provider does not display a dialog box asking for that information.

See Also

DirectPlayAddress


DirectPlay4.Open

The DirectPlay4.Open method is used to join a session that has been enumerated by a previous call to the DirectPlay4.GetDPEnumSessions method or to create a new session that other users can enumerate and join.

object.Open(sessionDesc As DirectPlaySessionData, _
    flags As CONST_DPOPENFLAGS)

Parameters

object
Object expression that resolves to a DirectPlay4 object.
sessionDesc
DirectPlaySessionData object describing the session. This object is obtained by using the DirectPlay4.CreateSessionData method.

If a session is to be created, then the application must completely initialize the DirectPlaySessionData object with the properties of the session to be created, except for the GuidInstance, which DirectPlay will supply.

flags
Flags from the CONST_DPOPENFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_ACCESSDENIED
DPERR_ALREADYINITIALIZED
DPERR_AUTHENTICATIONFAILED
DPERR_CANNOTCREATESERVER
DPERR_CANTCREATEPLAYER
DPERR_CANTLOADCAPI
DPERR_CANTLOADSECURITYPACKAGE
DPERR_CANTLOADSSPI
DPERR_CONNECTING
DPERR_CONNECTIONLOST
DPERR_ENCRYPTIONFAILED
DPERR_INVALIDFLAGS
DPERR_INVALIDPARAMS
DPERR_INVALIDPASSWORD
DPERR_LOGONDENIED
DPERR_NOCONNECTION
DPERR_NONEWPLAYERS
DPERR_NOSESSIONS
DPERR_SIGNFAILED
DPERR_TIMEOUT
DPERR_UNINITIALIZED
DPERR_USERCANCEL

This method returns DPERR_ALREADYINITIALIZED if there is already an open session on this DirectPlay object.

It return DPERR_CANTCREATEPLAYER if the maximum number of players in the session description has already been reached.

It returns DPERR_TIMEOUT if the session did not respond to the Open request.

It returns DPERR_USERCANCEL if the user canceled the enumeration process (usually by canceling a service provider dialog box).

It returns DPERR_NOSESSIONS if there is no open session matching the description, if the session isn't in the internal session list, or the session GUID is corrupted.

Remarks

After an application has joined a session, it can create a player and start communicating with other players in the session. The application will not receive any messages nor can it send any messages on this DirectPlay object until it creates a local player using DirectPlay4.CreatePlayer.

In order to have two sessions open simultaneously, the application must create two DirectPlay objects and open a session on each one.

DirectPlaySessionData.SetSessionPassword must be called if the session was marked as password protected. An enumerated session will have the DPSESSION_PASSWORDREQUIRED flag set if it requires a password.

If joining a secure session, you must use DirectPlay4.SecureOpen to provide logon credentials. The enumerated session will have the DPSESSION_SECURESERVER flag set if it requires credentials.

If you specify the DPSESSION_SECURESERVER flag, the session will be opened with the default security package, NTLM. To specify an alternate security package, use SecureOpen.

When an application attempts to join a session, the server can reject the Open request or ignore it (in which case Open will time-out). Attempting to join a session where new players are disabled, joining is disabled, the player limit has been reached, or an incorrect password is supplied will result in a DPERR_NONEWPLAYERS or DPERR_INVALIDPASSWORD error.

See Also

DirectPlay4.Close


DirectPlay4.Receive

The DirectPlay4.Receive method retrieves a message from the message queue.

object.Receive(fromPlayerId As Long, _
    toPlayerId As Long, _
    flags As CONST_DPRECEIVEFLAGS) As DirectPlayMessage

Parameters

object
Object expression that resolves to a DirectPlay4 object.
fromPlayerId
Variable that will be set to the sender's player ID when this method returns. If the DPRECEIVE_FROMPLAYER flag is specified, this parameter must be initialized with the player ID before calling the method.
toPlayerId
Variable that will be set to the receiver's player ID when this method returns. If the DPRECEIVE_TOPLAYER flag is specified, this parameter must be initialized with the player ID before calling the method.
flags
Flags from the CONST_DPRECEIVEFLAGS enumeration indicating how messages should be received. One or more of the following control flags can be set. By default (flags = 0), the first available message will be retrieved.
DPRECEIVE_ALL
Returns the first available message, removing it from the message queue. This is the default.
DPRECEIVE_PEEK
Returns a message as specified by the other flags, but does not remove it from the message queue.
DPRECEIVE_TOPLAYER and DPRECEIVE_FROMPLAYER
If both DPRECEIVE_TOPLAYER and DPRECEIVE_FROMPLAYER are specified, Receive will only return messages that are: (1) sent to the player specified by toPlayerId and (2) sent from the player specified by fromPlayerId. Both conditions must be met.

If only DPRECEIVE_TOPLAYER is specified, Receive will only return messages sent to the player specified by toPlayerId.

If only DPRECEIVE_FROMPLAYER is specified, Receive will only return messages sent from the player specified by fromPlayerId.

If neither DPRECEIVE_TOPLAYER nor DPRECEIVE_FROMPLAYER is set, Receive will return the first available message.

Return Values

If the method succeeds, it returns a DirectPlayMessage object whose methods can be used to retrieve the contents of the message, or Nothing if there are no messages pending.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_GENERIC
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_INVALIDPLAYER

Remarks

Messages that were sent to a player ID defined as DPID_ALLPLAYERS or to a group ID still appear to come from the sending player ID. An application will only receive messages directed to a local player. A player cannot receive a message in which the values pointed to by fromPlayerId and toPlayerId are equal.

If DPSESSION_NOMESSAGEID is specified in the session description, the fromPlayerId will always be 0xFFFFFFFF and the toPlayerId value is arbitrary.

All the service providers shipped with DirectPlay perform integrity checks on the data to protect against corruption. Any message retrieved using Receive is guaranteed to be free from corruption.

See Also

DirectPlay4.Send


DirectPlay4.SecureOpen

The DirectPlay4.SecureOpen method creates or joins a secure session. When joining a secure session, use this method to supply logon credentials.

When creating a new session, the host computer can specify an alternate security package to use. When joining a session, a computer can specify a user name and password.

object.SecureOpen(sessionDesc DirectPlaySessionData, _
    flags As CONST_DPOPENFLAGS, _
    security As DPSECURITYDESC,
    credentials As DPCREDENTIALS))

Parameters

object
Object expression that resolves to a DirectPlay4 object.
sessionDesc
DirectPlaySessionData object describing the session to be created or joined. If a session is to be joined, then only the SetGuidInstance and SetSessionPassword methods need to be called to initialize the object. The password need only be supplied if the enumerated session had the DPSESSION_PASSWORDREQUIRED flag set.

If a session is to be created, then the application must completely initialize the DirectPlaySessionData object with the properties of the session to be created, except for the instance GUID, which DirectPlay will supply.

The DPSESSION_SECURESERVER flag must be set to indicate that all computers attempting to open the session must be authenticated. If you don't specify the DPSESSION_SECURESERVER flag, SecureOpen will open an unsecured session, just as if you had called DirectPlay4.Open.

flags
Flags from the CONST_DPOPENFLAGS enumeration.
security
DPSECURITYDESC type containing the security package to use. Initialize all members of this type to 0 in order to use the default security package (NTLM) and CryptoAPI package (Microsoft RSA Base Cryptographic Provider). Relevant only when creating a session. You may pass an uninitialized structure when joining a session.
credentials
DPCREDENTIALS type containing the logon name, password, and domain to be authenticated on the server. Initialize the members of this type to 0 if there are no credentials. Credentials are ignored when creating a session.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_ACCESSDENIED
DPERR_ALREADYINITIALIZED
DPERR_AUTHENTICATIONFAILED
DPERR_CANNOTCREATESERVER
DPERR_CANTLOADCAPI
DPERR_CANTLOADSECURITYPACKAGE
DPERR_CANTLOADSSPI
DPERR_CONNECTING
DPERR_CONNECTIONLOST
DPERR_ENCRYPTIONFAILED
DPERR_INVALIDFLAGS
DPERR_INVALIDPARAMS
DPERR_INVALIDPASSWORD
DPERR_LOGONDENIED
DPERR_NOCONNECTION
DPERR_NONEWPLAYERS
DPERR_SIGNFAILED
DPERR_TIMEOUT
DPERR_UNINITIALIZED
DPERR_USERCANCEL

This method returns DPERR_LOGONDENIED after being called with invalid credentials or without credentials when credentials are required. The application must collect the user's credentials and call SecureOpen again.

Remarks

When joining a session, first call SecureOpen with no credentials. If the method returns DPERR_LOGONDENIED, then the application must collect the user name and password from the user and call SecureOpen again, passing in the user's credentials through the credentials parameter. If the method returns DP_OK, then the player was able to log on with the credentials he or she had specified earlier during system log-on (network log-on in NTLM).


DirectPlay4.Send

The DirectPlay4.Send method sends a message to another player, to a group of players, or to all players in the session.

Messages can be sent using either a guaranteed or nonguaranteed protocol on a per-message basis. If the session is being hosted on a secure server, messages can be sent encrypted (to ensure privacy) or digitally signed (to ensure authenticity) on a per-message basis.

object.Send(fromPlayerId As Long, _
    toPlayerId As Long, _
    flags As CONST_DPSENDFLAGS, _
    msg As DirectPlayMessage)

Parameters

object
Object expression that resolves to a DirectPlay4 object.
fromPlayerId
ID of the sending player. The player ID must correspond to one of the local players on the computer.
toPlayerId
Destination ID of the message. To send a message to another player, specify the ID of the player. To send a message to all the players in a group, specify the ID of the group. To send a message to all the players in the session, use the constant DPID_ALLPLAYERS. To send a message to the server player, specify the constant DPID_SERVERPLAYER. A player cannot send a message to itself.
flags
Value indicating how the message should be sent. By default (flags = 0), the message is sent nonguaranteed.
DPSEND_ENCRYPTED
Sends the message encrypted. This can only be done in a secure session. This flag can only be used if the DPSEND_GUARANTEED flag is also set. The message will be sent as a DPSYS_SECUREMESSAGE system message.
DPSEND_GUARANTEED
Sends the message by using a guaranteed method of delivery.
DPSEND_SIGNED
Sends the message with a digital signature. This can only be done in a secure session. This flag can only be used if the DPSEND_SIGNED flag is also set. The message will be sent as a DPSYS_SECUREMESSAGE system message.
msg
DirectPlayMessage object representing the data being sent. This object is obtained by using the DirectPlay4.CreateMessage method, and its own methods can be used to pack it with data.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_BUSY
DPERR_CONNECTIONLOST
DPERR_INVALIDPARAMS
DPERR_INVALIDPLAYER
DPERR_NOTLOGGEDIN
DPERR_SENDTOOBIG

This method returns DPERR_INVALIDPARAMS if the encrypted or signed flag is specified for a message that is not also specified as guaranteed. It returns DPERR_NOTLOGGEDIN when the client application tries to send a secure message without first logging on.

If a message is sent to a group, a return value of DP_OK does not necessarily mean that every player in the group got the message. If the message was sent guaranteed, DP_OK means that DirectPlay made a best effort to send it to all the players in the group. Typically, players that don't receive the message are removed from the session because there is a problem with their connection.

Remarks

Use DirectPlay4.SendEx for asynchronous send options.

Nonsystem messages can be sent guaranteed or nonguaranteed. By default, nonsystem messages are sent nonguaranteed, which means that DirectPlay does not verify that the message reached the intended recipient. Sending a guaranteed message takes much longer—a minimum of two to three times longer than nonguaranteed messages. Applications should try to minimize sending guaranteed messages as much as possible and to design the application to tolerate lost messages.

System messages are always sent guaranteed, whether or not the service provider natively supports guaranteed messages, and whether or not you set the DirectPlay protocol flag. The DirectPlay protocol will be used automatically to send system messages guaranteed.

For nonsystem messages, if an application sets the DirectPlay protocol flag and sends a message guaranteed (by setting the DPSEND_GUARANTEED flag), the message will be sent guaranteed whether the service provider supports guaranteed messages or not.

For nonsystem messages, if an application does not set the DirectPlay protocol flag and sends a message guaranteed, the message will be sent guaranteed only if the service provider supports it. If the service provider does not support guaranteed messages, the message will not be sent guaranteed, regardless of the DPSEND_GUARANTEED flag.

An application invokes the DirectPlay protocol by setting the DPSESSION_DIRECTPLAYPROTOCOL flag when creating a session.

All the service providers shipped with DirectPlay perform integrity checks on the data to protect against corruption. Any message sent using this method is guaranteed to be free from corruption.

Players cannot send messages to themselves. If a player sends a message to a group that it is part of or to DPID_ALLPLAYERS, the player will not receive a copy of that message. The exception to this rule is if the DPSESSION_NOMESSAGEID was specified in the session description. Then a player can receive a message that it sent to a group. Because there is no DirectPlay message ID header on the message (indicating who sent the message), it cannot filter out messages based on the message ID.

If the target computer has more than one player on it, it cannot be determined whose receive queue the message will appear in. When the message is received, it will appear to have come from player DPID_UNKNOWN.

There is no limit to the size of messages that can be transmitted by using the Send method. DirectPlay will automatically break up large messages into packets (packetize) and reassemble them on the receiving end. Beware of sending large messages nonguaranteed—if even one of the packets fails to reach the receiver, the entire message is ignored. The application can determine the maximum size of a packet by calling GetCaps and examining the lMaxBufferSize member of the DPCAPS type.

When you send an encrypted or signed message, it is delivered not as an application message but as a DPSYS_SECUREMESSAGE system message.

See Also

DirectPlay4.Receive, DirectPlay4.SendChatMessage, CONST_DPIDFLAGS


DirectPlay4.SendChatMessage

The DirectPlay4.SendChatMessage method sends a text message to another player, a group of players, or all players. The player receiving the chat message is informed through a DPSYS_CHAT system message in the player's receive queue. This method must be used in a lobby session.

object.SendChatMessage(fromPlayerId As Long, _
    toPlayerId As Long, _
    flags As CONST_DPSENDFLAGS, _
    message As String)

Parameters

object
Object expression that resolves to a DirectPlay4 object.
fromPlayerId
ID of the sending player. The player ID must correspond to one of the local players on this computer.
toPlayerId
ID of the player to send the message to, the ID of the group of players to send the message to, or DPID_ALLPLAYERS to send the message to all players in the session.
flags
Value indicating how the message should be sent. If this parameter is set to 0, the message is sent nonguaranteed.
DPSEND_GUARANTEED
Sends the message by using a guaranteed method of delivery if it is available.
message
Message to be sent.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_ACCESSDENIED
DPERR_CONNECTIONLOST
DPERR_INVALIDFLAGS
DPERR_INVALIDPARAMS
DPERR_INVALIDPLAYER

This method returns DPERR_INVALIDPARAMS if the toPlayerId ID is not a valid player or group. It returns DPERR_INVALIDPLAYER if the fromPlayerId ID is not a valid player. It returns DPERR_ACCESSDENIED if the fromPlayerId ID is not a local player.

Remarks

This method facilitates player-to-player chatting within a lobby session where different client applications can be connected. In an application session, chat messages can be sent by using the DirectPlay4.Send method.

The receiving player will receive a system message (fromPlayerId = DPID_SYSMSG).


DirectPlay4.SendEx

The DirectPlay4.SendEx method sends a message to another player, to a group of players, or to all players in the session. SendEx is an enhanced version of the DirectPlay4.Send method and has more options available. SendEx supports both guaranteed and nonguaranteed messages. It also enables you to send asynchronous messages and to set the priority and time-out of a message.

object.SendEx(fromPlayerId As Long, _
    toPlayerId As Long, _
    flags As CONST_DPSENDFLAGS, _
    msg As DirectPlayMessage, _
    priority As Long, _
    timeOut As Long, _
    context As Long) As Long

Parameters

object
Object expression that resolves to a DirectPlay4 object.
fromPlayerId
ID of the sending player. The player ID must correspond to one of the local players on the computer from which the message is sent.
toPlayerId
Destination ID of the message. To send a message to another player, specify the ID of the player. To send a message to all the players in a group, specify the ID of the group. To send a message to all the players in the session, use the constant DPID_ALLPLAYERS. To send a message to the server player, specify the constant DPID_SERVERPLAYER. A player cannot send a message to itself.
flags
Flags from the CONST_DPSENDFLAGS enumeration indicating how the message should be sent. By default (flags = 0), the message is sent nonguaranteed.
DPSEND_ASYNC
Sends the message asynchronously. The method returns immediately. If this flag is not specified, the method does not return until the message has been sent (and acknowledged, if sent guaranteed). A DPSYS_SENDCOMPLETE system message is posted when the send has completed.

When this flag is used, the return value will be DPERR_PENDING if the message is put in the send queue. This is not a fatal error, but just a return value that lets you know the message did not get sent immediately.

DPSEND_ENCRYPTED
Sends the messages encrypted. This can only be done in a secure session. This flag can only be used if the DPSEND_GUARANTEED flag is also set. The message will be sent as a DPSYS_SECUREMESSAGE system message.
DPSEND_GUARANTEED
Sends the message by using a guaranteed method of delivery if it is available.
DPSEND_NOSENDCOMPLETEMSG
If this flag is set, no completion message is posted. This flag can be used only if the DPSEND_ASYNC flag is also set.
DPSEND_SIGNED
Sends the message with a digital signature. This can only be done in a secure session. This flag can only be used if the DPSEND_GUARANTEED flag is also set. The message will be sent as a DPSYS_SECUREMESSAGE system message.
msg
DirectPlayMessage object representing the data being sent. This object is obtained by using the DirectPlay4.CreateMessage method, and its own methods can be used to pack it with data.
priority
Priority of the message in the range from 0 to 65535. Zero is the lowest priority message. A larger number indicates a message with a higher priority. A message with a given priority will only be sent when there are no messages in the queue with a higher priority.

Not all service providers support this option. If it is not supported, specifying a nonzero priority will return a DPERR_UNSUPPORTED error. Call DirectPlay4.GetCaps to determine if this option is supported or not.

timeOut
Optional application-supplied time-out, in milliseconds, that specifies a time limit for delivering the message. If the message cannot be delivered within this time, it is automatically canceled. Zero indicates that no time-out should be used.

Not all service providers support this option. If it is not supported, specifying a nonzero time-out will return a DPERR_UNSUPPORTED error. Call DirectPlay4.GetCaps to determine if this option is supported or not.

context
Application-defined context that is returned to the application as part of the completion message when the send has been completed. Can be 0.

Return Values

Returns a DirectPlay-generated ID for the message.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_BUSY
DPERR_CONNECTIONLOST
DPERR_INVALIDFLAGS
DPERR_INVALIDPARAMS
DPERR_INVALIDPLAYER
DPERR_INVALIDPRIORITY
DPERR_NOTLOGGEDIN
DPERR_SENDTOOBIG
DPERR_UNSUPPORTED

This method returns DPERR_INVALIDPARAMS if the encrypted or signed flag is specified for a message that is not also specified as guaranteed. It returns DPERR_INVALIDPRIORITY if the priority value is not between 0 and 65535. It returns DPERR_UNSUPPORTED if you specify a nonzero priority and the service provider does not support priorities, or if you specify a nonzero time-out and the service provider does not support this option.

Remarks

This method supports guaranteed and nonguaranteed messages. Messages sent guaranteed will not be blocked if there are pending messages waiting to be acknowledged by the receiver.

If a message is sent asynchronously, the message will be put into a send queue and the SendEx method will return immediately. A system message will be posted to the receive queue of the sending player indicating the result of the send.

You can give messages priorities. A message is sent when there are no higher-priority messages waiting to be sent and when there is available bandwidth.

You can give a message a time-out. If DirectPlay cannot deliver the message in the time specified, it will be canceled.

The DPSEND_SIGNED and DPSEND_ENCRYPTED flags cannot be used if the order of delivery of guaranteed messages is not preserved because the flag is set in the session description.

If messages are sent using different priorities, signing and encryption might not work. It is best for the application to decide on one priority level for secure messages and only use the security flag on that priority level. This is because validation of secure messages depends on the order in which they are received and prioritization might change this order.

If the DirectPlay protocol is active, it will attempt to throttle outbound network traffic. That is, it will not always send packets as fast as possible. It will send packets as fast as it can without overwhelming the inbound bandwidth of the receiving computer.

System messages are always sent guaranteed, whether or not the service provider natively supports guaranteed messages, and whether or not you set the DirectPlay protocol flag. The DirectPlay protocol will be used automatically to send system messages guaranteed.

For nonsystem messages, if an application sets the DirectPlay protocol flag and sends a message guaranteed (by setting the DPSEND_GUARANTEED flag), the message will be sent guaranteed whether the service provider supports guaranteed messages or not.

For nonsystem messages, if an application does not set the DirectPlay protocol flag and sends a message guaranteed, the message will be sent guaranteed only if the service provider supports it. If the service provider does not support guaranteed messages, the message will not be sent guaranteed, regardless of the DPSEND_GUARANTEED flag.

See Also

DirectPlay4.Send, DirectPlay4.CancelMessage, DirectPlay4.CancelPriority


DirectPlay4.SetGroupConnectionSettings

The DirectPlay4.SetGroupConnectionSettings method sets the connection settings for a session that will be launched from this group. This method can only be used in a lobby session.

object.SetGroupConnectionSettings(id As Long, _
    connection As DirectPlayLobbyConnection)

Parameters

object
Object expression that resolves to a DirectPlay4 object.
id
ID of the group to set the connection settings on.
connection
DirectPlayLobbyConnection object providing access to a description of the application to be launched, the service provider to be used, and the description of the session to be created.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_ACCESSDENIED
DPERR_CONNECTIONLOST
DPERR_INVALIDGROUP
DPERR_INVALIDPARAMS
DPERR_UNSUPPORTED

See Also

DirectPlayLobby3.RunApplication


DirectPlay4.SetGroupData

The DirectPlay4.SetGroupData method associates an application-specific data block with a group ID. Only the computer that created the group can change the remote data associated with it.

object.SetGroupData(GroupId As Long, _
    data As String, _
    flags As CONST_DPSETFLAGS)

Parameters

object
Object expression that resolves to a DirectPlay4 object.
GroupId
Group ID for which data is being set.
data
Data to be stored. Set to "" to clear any existing data.
flags
Flags from the CONST_DPGETCAPSFLAGS enumeration indicating how the group data is propagated. If this parameter is set to 0, the remote group data will be set and propagated using nonguaranteed messaging.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_ACCESSDENIED
DPERR_CONNECTIONLOST
DPERR_INVALIDGROUP
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS

Remarks

DirectPlay can maintain two types of group data: local and remote. Local data is available only to the application on the local computer. Remote data is propagated to all the other applications in the session. A DPSYS_SETPLAYERORGROUPDATA system message will be sent to all players (including the sender) notifying them of the change unless DPSESSION_NODATAMESSAGES is set in the session description. You can safely store pointers to resources in the local data; the local data block is available (in the DPSYS_DESTROYPLAYERORGROUP system message) when the group is being destroyed, so that the application can free those resources.

This method should not be used for updating real-time information (such as position updates) because of the overhead introduced. DirectPlay4.Send is much more efficient for updating real-time information. SetGroupData is more appropriate for shared-state information that does not change often and is not time-critical (such as a team color).

See Also

DirectPlay4.GetGroupData


DirectPlay4.SetGroupName

The DirectPlay4.SetGroupName method sets the name of a group after it has been created. Only the computer that created the group can set the name of the group.

object.SetGroupName(GroupId As Long, _
    friendlyName As String, _
    formalName As String, _
    flags As CONST_DPSETFLAGS)

Parameters

object
Object expression that resolves to a DirectPlay4 object.
GroupId
ID of the group for which the name is being set.
friendlyName
Short name of the group. Set this parameter to "" if the group has no friendly name.
formalName
Long name of the group. Set this parameter to "" if the group has no formal name.
flags
Flag from the CONST_DPSETFLAGS enumeration that sets the data propagation options. If this parameter is set to 0, the name will be propagated to all the remote systems by using nonguaranteed message passing.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_CONNECTIONLOST
DPERR_INVALIDGROUP
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_INVALIDPLAYER

Remarks

A DPSYS_SETPLAYERORGROUPNAME system message will be sent to all the other players notifying them of the change unless DPSESSION_NODATAMESSAGES is set in the session description.

See Also

DirectPlay4.GetGroupLongName, DirectPlay4.GetGroupShortName, DirectPlay4.Send


DirectPlay4.SetGroupOwner

The DirectPlay4.SetGroupOwner method changes the owner of a group. This method is only available in a lobby session.

object.SetGroupOwner(GroupId As Long, _
    ownerId As Long)

Parameters

object
Object expression that resolves to a DirectPlay4 object.
GroupId
ID of the group whose owner is being changed.
ownerId
ID of the player to be set as the owner of the group.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_CONNECTIONLOST
DPERR_GENERIC
DPERR_INVALIDGROUP
DPERR_INVALIDPLAYER
DPERR_UNAVAILABLE

This method returns DPERR_UNAVAILABLE if the session is not a lobby session.

See Also

DirectPlay4.GetGroupOwner


DirectPlay4.SetPlayerData

The DirectPlay4.SetPlayerData method associates an application-specific data block with a player ID.

object.SetPlayerData(playerId As Long, _
    data As String, _
    flags As CONST_DPSETFLAGS)

Parameters

object
Object expression that resolves to a DirectPlay4 object.
playerId
ID of the player for which data is being set.
data
Data to be set. Set this parameter to "" in order to clear any existing player data.
flags
Flag from the CONST_DPSETFLAGS enumeration that sets the data-propagation options. If this parameter is set to 0 (DPGET_REMOTE), the remote player data will be set and propagated by using nonguaranteed messaging.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_ACCESSDENIED
DPERR_CONNECTIONLOST
DPERR_INVALIDFLAGS
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_INVALIDPLAYER

Remarks

This method should not be used for updating real-time information (such as position updates), because of the overhead introduced. It is much more efficient to use DirectPlay4.Send for this. SetPlayerData is more appropriate for shared state information that doesn't change very often and is not time-critical (such as a player's name).

DirectPlay can maintain two types of player data: local and remote. Local data is available only to the application on the local computer. Remote data is propagated to all the other applications in the session. This method returns DPERR_ACCESSDENIED if you try to set player data for a remote player. A DPSYS_SETPLAYERORGROUPDATA system message will be sent to all players (including the sender) notifying them of the change unless DPSESSION_NODATAMESSAGES is set in the session description. It is safe to store resources in the local data; the local data block is available (in the DPSYS_DESTROYPLAYERORGROUP system message) when the player is being destroyed, so the application can free those resources.

See Also

DirectPlay4.GetPlayerData


DirectPlay4.SetPlayerName

The DirectPlay4.SetPlayerName method changes the formal and friendly names of a local player. Only the computer that created the player can change the name.

object.SetPlayerName(playerId As Long, _
  friendlyName As String, _
  formalName As String, _
  flags As CONST_DPSETFLAGS)

Parameters

object
Object expression that resolves to a DirectPlay4 object.
playerId
ID of the local player for which data is being sent.
friendlyName
Friendly ("short") name of the player.
formalName
Formal ("long") name of the player.
flags
Flag from the CONST_DPSETFLAGS enumeration indicating how the name will be propagated.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_ACCESSDENIED
DPERR_CONNECTIONLOST
DPERR_INVALIDOBJECT
DPERR_INVALIDPLAYER

Remarks

A DPSYS_SETPLAYERORGROUPNAME system message will be sent to all the other players notifying them of the change unless DPSESSION_NODATAMESSAGES is set in the session description.

See Also

DirectPlay4.GetPlayerFriendlyName, DirectPlay4.GetPlayerFormalName


DirectPlay4.SetSessionDesc

The DirectPlay4.SetSessionDesc method changes the properties of the current session. Only the host of the session can change the session properties.

This method cannot be used in a lobby session.

object.SetSessionDesc(sessionDesc As DirectPlaySessionData)

Parameters

object
Object expression that resolves to a DirectPlay4 object.
sessionDesc
DirectPlaySessionData object containing the new settings. This object is obtained by using the DirectPlay4.GetSessionDesc method, and its methods are used to change the data. See Remarks.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_ACCESSDENIED
DPERR_CONNECTIONLOST
DPERR_INVALIDPARAMS
DPERR_NOSESSIONS

This method returns DPERR_ACCESSDENIED if this computer does not have permission to change the session. It returns DPERR_INVALIDPARAMS if the application attempts to change a property in the session description that cannot be changed or tries to give a property an invalid value.

Remarks

The updated session description will be propagated to all the other computers in the session. Each player will receive a DPSYS_SETSESSIONDESC system message.

The following methods can be used to set elements of the session description that can be changed:

DirectPlaySessionData.SetFlags
The following flags can be added or removed:

DPSESSION_JOINDISABLED
DPSESSION_NEWPLAYERSDISABLED
DPSESSION_NODATAMESSAGES
DPSESSION_PRIVATE

The following flags must remain unchanged, else an error will result when SetSessionDesc is called:
DPSESSION_NOMESSAGEID
DPSESSION_KEEPALIVE
DirectPlaySessionData.SetMaxPlayers
If you set the maximum players to a value less than the current number of players, the method returns DPERR_INVALIDPARAMS.
DirectPlaySessionData.SetSessionName
DirectPlaySessionData.SetSessionPassword
DirectPlaySessionData.SetUser1
DirectPlaySessionData.SetUser2
DirectPlaySessionData.SetUser3
DirectPlaySessionData.SetUser4

If you change other properties of the object by calling DirectPlaySessionData.SetGuidInstance or DirectPlaySessionData.SetGuidApplication, the new settings are ignored—that is, DirectPlay will always use the values set when DirectPlay4.Open was called.

See Also

DirectPlay4.GetSessionDesc


DirectPlay4.StartSession

The DirectPlay4.StartSession method launches a DirectPlay session from a staging area. Call SetGroupConnectionSettings first to specify what application to launch, which service provider to use, and what session description to use.

object.StartSession(id As Long)

Parameters

object
Object expression that resolves to a DirectPlay4 object.
id
ID of the group to send start session commands to. The group must be a staging area.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_ACCESSDENIED
DPERR_CONNECTIONLOST
DPERR_INVALIDFLAGS
DPERR_INVALIDGROUP
DPERR_INVALIDPARAMS

This method returns DPERR_INVALIDGROUP if the given group ID is not a valid staging area.

Remarks

When StartSession is called, each player in the group receives a DPSYS_STARTSESSION system message instructing the player to launch the session.

A player joining a staging area group for which the session has already started can call this method to join the session. The player will receive a DPSYS_STARTSESSION message with information on how to join the session.

See Also

Synchronized Launching


DirectPlayAddress

The DirectPlayAddress class represents a data format that DirectPlay uses to pass addressing information between lobby servers, applications, DirectPlay, and service providers. For an overview, see DirectPlay Address.

A DirectPlayAddress object is returned by the following methods:

  • DirectPlay4.GetPlayerAddress
  • DirectPlayEnumConnections.GetAddress
  • DirectPlayLobby3.CreateComPortAddress
  • DirectPlayLobby3.CreateCustomAddress
  • DirectPlayLobby3.CreateINetAddress
  • DirectPlayLobby3.CreateIPXAddress
  • DirectPlayLobby3.CreateLobbyProviderAddress
  • DirectPlayLobby3.CreateModemAddress
  • DirectPlayLobby3.CreateServiceProviderAddress
  • DirectPlayLobbyConnection.GetAddress

The DirectPlayAddress class itself has no public methods.

See Also

DirectPlay4.InitializeConnection, DirectPlayLobbyConnection.SetAddress


DirectPlayEnumConnections

The DirectPlayEnumConnections class enumerates connections. Applications use the methods of the DirectPlayEnumConnections class object to obtain information on enumerated items.

A DirectPlayEnumConnections object is obtained by using the DirectPlay4.GetDPEnumConnections method.

The DirectPlayEnumConnections class has the following methods.

Enumeration | GetAddress
 | GetCount
 | GetFlags
 | GetGuid
 | GetName


DirectPlayEnumConnections.GetAddress

The DirectPlayEnumConnections.GetAddress method retrieves an address object from the enumeration.

object.GetAddress(index As Long) As DirectPlayAddress

Parameters

object
Object expression that resolves to a DirectPlayEnumConnections object.
index
Element of the enumeration object for which to retrieve data.

Return Values

The method returns a DirectPlayAddress object.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlayEnumConnections.GetCount

The DirectPlayEnumConnections.GetCount method retrieves the number of entries in the enumeration object.

object.GetCount() As Long

Parameters

object
Object expression that resolves to a DirectPlayEnumConnections object.

Return Values

The method returns the number of entries in the enumeration object.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlayEnumConnections.GetFlags

The DirectPlayEnumConnections.GetFlags method retrieves the flags for an enumerated connection.

object.GetFlags(index As Long) As Long

Parameters

object
Object expression that resolves to a DirectPlayEnumConnections object.
index
Element of the enumeration object for which to retrieve data.

Return Values

The method returns the flags for the connection.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

Remarks

The return value is equivalent to the flags passed in to DirectPlay4.GetDPEnumConnections.


DirectPlayEnumConnections.GetGuid

The DirectPlayEnumConnections.GetGuid method retrieves the globally unique identifier for an enumerated connection.

object.GetGuid(index As Long) as String

Parameters

object
Object expression that resolves to a DirectPlayEnumConnections object.
index
Element of the enumeration object for which to retrieve data.

Return Values

The method returns the GUID of the connection.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

See Also

Using GUIDs


DirectPlayEnumConnections.GetName

The DirectPlayEnumConnections.GetName method retrieves a name object from the enumeration.

object.GetName(index As Long) As String

Parameters

object
Object expression that resolves to a DirectPlayEnumConnections object.
index
Element of the enumeration for which to retrieve data.

Return Values

The method returns the name of the connection—for example, "IPX Connection for DirectPlay".

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlayEnumLocalApplications

The DirectPlayEnumLocalApplications class enumerates local applications. Applications use the methods of the DirectPlayEnumLocalApplications class to obtain information on the enumerated items.

A DirectPlayEnumLocalApplications object is returned by the DirectPlayLobby3.GetDPEnumLocalApplications method.

The DirectPlayEnumLocalApplications class has the following methods:

Enumeration | GetCount
 | GetGuid
 | GetName


DirectPlayEnumLocalApplications.GetCount

The DirectPlayEnumLocalApplications.GetCount method retrieves the number of entries in the enumeration object.

object.GetCount() As Long

Parameters

object
Object expression that resolves to a DirectPlayEnumLocalApplications object.

Return Values

The method returns the number of entries in the enumeration object.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlayEnumLocalApplications.GetGuid

The DirectPlayEnumLocalApplications.GetGuid method retrieves the globally unique identifier of an enumerated application.

object.GetItem(index As Long) as String

Parameters

object
Object expression that resolves to a DirectPlayEnumLocalApplications object.
index
Element of the enumeration object for which to retrieve data.

Return Values

The method returns a string representing the application GUID.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

See Also

Using GUIDs


DirectPlayEnumLocalApplications.GetName

The DirectPlayEnumLocalApplications.GetName method retrieves the name of an enumerated application.

object.GetItem(index As Long) as String

Parameters

object
Object expression that resolves to a DirectPlayEnumLocalApplications object.
index
Element of the enumeration object for which to retrieve data.

Return Values

The method returns the name of the application.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlayEnumPlayers

The DirectPlayEnumPlayers class enumerates players or groups in a session or group. Applications use the methods of the DirectPlayEnumPlayers class to obtain information about enumerated players or groups.

A DirectPlayEnumPlayers object is returned by the following methods:

  • DirectPlay4.GetDPEnumGroups
  • DirectPlay4.GetDPEnumGroupsInGroup
  • DirectPlay4.GetDPEnumGroupPlayers
  • DirectPlay4.GetDPEnumPlayers

The DirectPlayEnumPlayers class has the following methods:

Enumeration | GetCount
 | GetDPID
 | GetFlags
 | GetLongName
 | GetShortName
 | GetType


DirectPlayEnumPlayers.GetCount

The DirectPlayEnumPlayers.GetCount method retrieves the number of entries in the enumeration object.

object.GetCount() As Long

Parameters

object
Object expression that resolves to a DirectPlayEnumPlayers object.

Return Values

The method returns the number of entries in the enumeration object.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlayEnumPlayers.GetDPID

The DirectPlayEnumPlayers.GetDPID method retrieves the numerical identifier of an enumerated player or group.

object.GetDPID(index As Long) As Long

Parameters

object
Object expression that resolves to a DirectPlayEnumPlayers object.
index
Element of the enumeration object for which to retrieve data.

Return Values

The method returns the unique identifier assigned when the player or group was created.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlayEnumPlayers.GetFlags

The DirectPlayEnumPlayers.GetFlags method retrieves miscellaneous information about an enumerated player or group.

object.GetFlags(index As Long) As Long

Parameters

object
Object expression that resolves to a DirectPlayEnumPlayers object.
index
Element of the enumeration object for which to retrieve data.

Return Values

The method returns the flags for a player. These include flags that were passed into the method that created the enumeration, combined with additional information about the particular player or group.

DIRECTPLAYENUMGROUPS_ALL
All groups in this session.
DIRECTPLAYENUMGROUPS_LOCAL
Groups created locally by this DirectPlay object.
DIRECTPLAYENUMGROUPS_REMOTE
Groups created by remote DirectPlay objects.
DIRECTPLAYENUMGROUPS_SESSION
Groups for the identified session.
DIRECTPLAYENUMGROUPS_SHORTCUT
Groups that are added to the group using DirectPlay4.AddGroupToGroup. (A shortcut is a link to another group).
DIRECTPLAYENUMGROUPS_STAGINGAREA
Groups in the group that are staging areas. (Staging areas are used to marshal players together in order to launch a new session.)
DIRECTPLAYENUMPLAYERS_LOCAL
Players created locally by this DirectPlay object.
DIRECTPLAYENUMPLAYERS_OWNER
The player that is the owner of this group.
DIRECTPLAYENUMPLAYERS_REMOTE
Players created by remote DirectPlay objects.
DIRECTPLAYENUMPLAYERS_SERVERPLAYER
The server player.
DIRECTPLAYENUMPLAYERS_SESSION
Players for the identified session. This flag can only be used if there is no current open session. This flag cannot be used in a lobby session.
DIRECTPLAYENUMPLAYERS_SPECTATOR
Players who are spectators.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

See Also

DirectPlay4.GetDPEnumGroups, DirectPlay4.GetDPEnumGroupsInGroup, DirectPlay4.GetDPEnumPlayers, DirectPlay4.GetDPEnumGroupPlayers


DirectPlayEnumPlayers.GetLongName

The DirectPlayEnumPlayers.GetLongName method retrieves the formal name of a player or group.

object.GetLongName(index As Long) As String

Parameters

object
Object expression that resolves to a DirectPlayEnumPlayers object.
index
Element of the enumeration object for which to retrieve data.

Return Values

The method returns the formal name, or handle, assigned when the player or group was created.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlayEnumPlayers.GetShortName

The DirectPlayEnumPlayers.GetShortName method retrieves the friendly name of a player or group

object.GetShortName(index As Long) As String

Parameters

object
Object expression that resolves to a DirectPlayEnumPlayers object.
index
Element of the enumeration object for which to retrieve data.

Return Values

The method returns the short or friendly name assigned when the player or group was created.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlayEnumPlayers.GetType

The DirectPlayEnumPlayers.GetType method ascertains whether an enumerated item is a player or group.

object.GetType(index As Long) As Long

Parameters

object
Object expression that resolves to a DirectPlayEnumPlayers object.
index
Element of the enumeration object for which to retrieve data.

Return Values

The method returns the type of the enumerated item, either DPPLAYERTYPE_GROUP or DPPLAYERTYPE_PLAYER (from the CONST_DPPLAYERTYPEFLAGS enumeration).

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlayEnumSessions

The DirectPlayEnumSessions class enumerates all the active sessionsfor a particular application or all the active lobby sessions that serve a particular application.

A DirectPlayEnumSessions object is obtained by using the DirectPlay4.GetDPEnumSessions method.

This class has the following methods.

Enumeration | GetCount
 | GetItem


DirectPlayEnumSessions.GetCount

The DirectPlayEnumSessions method retrieves the number of entries in the enumeration object.

object.GetCount() As Long

Parameters

object
Object expression that resolves to a DirectPlayEnumSessions object.

Return Values

The method returns the number of entries in the enumeration object.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlayEnumSessions.GetItem

the DirectPlayEnumSessions.GetItem method gets a DirectPlaySessionData object representing data for an enumerated session.

object.GetItem(index As Long) As DirectPlaySessionData

Parameters

object
Object expression that resolves to a DirectPlayEnumSessions object.
index
Element of the enumeration object for which to retrieve data.

Return Values

If it succeeds, the method returns a DirectPlaySessionData object.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlayLobby3

Applications use the methods of the DirectPlayLobby3 class to manage applications and their associated data.

A DirectPlayLobby3 object is obtained by using the DirectX7.DirectPlayLobbyCreate method.

The methods of the DirectPlayLobby3 interface can be organized in the following groups:

Addresses | CreateComPortAddress
 | CreateCustomAddress
 | CreateInetAddress
 | CreateIPXAddress
 | CreateLobbyProviderAddress
 | CreateModemAddress
 | CreateServiceProviderAddress
 | GetModemCount
 | GetModemName
Applications | Connect
 | GetDPEnumLocalApplications
 | RegisterApplication
 | RunApplication
 | UnregisterApplication
 | WaitForConnectionSettings
Messages | CreateMessage
 | ReceiveLobbyMessage
 | SendLobbyMessage
 | SetLobbyMessageEvent
Connections | CreateConnectionData
 | GetConnectionSettings
 | SetConnectionSettings


DirectPlayLobby3.Connect

The DirectPlayLobby3.Connect method connects an application to the session specified by the DirectPlayLobbyConnection object currently stored with the DirectPlayLobby3 object.

object.Connect(flags As Long) As DirectPlay4

Parameters

object
Object expression that resolves to a DirectPlayLobby3 object.
flags
Member of the CONST_DPCONNECTFLAGS enumeration indicating how the connection is to be done. By default (flags = 0 or DPCONNECTION_DEFAULT), the method returns after a connection has been established or the operation has timed out. If the flag is DPCONNECTION_RETURNSTATUS, the method returns immediately with the status of the connection.

Return Values

If it succeeds, the method returns a DirectPlay4 object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_CONNECTING
DPERR_INVALIDFLAGS
DPERR_INVALIDINTERFACE
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_NOTLOBBIED
DPERR_OUTOFMEMORY

Remarks

By default, Connect returns after a connection is made or when the connection has timed out. If you use the DPCONNECT_RETURNSTATUS flag, Connect returns immediately with a DPERR_CONNECTING error code indicating the connection is in progress. The application must continue calling this method periodically until it succeeds or another failure code is returned. The application can cancel the connection by releasing the DirectPlayLobby3 object.

There is an upper limit of one minute on connection time-out.

After this method is successfully completed, the application can skip the process of calling DirectPlay4.InitializeConnection, DirectPlay4.GetDPEnumSessions, and DirectPlay4.Open. The application should not ask the user for a name but instead create a player using the player name information in the DirectPlayLobbyConnection interface.

Before calling this method, the application can examine the connection settings that will be used to start the application by using the DirectPlayLobby3.GetConnectionSettings method. The application then can modify these settings and set them by using the DirectPlayLobby3.SetConnectionSettings method. The application should pay particular attention to the DirectPlaySessionData object to ensure that the proper session properties are set.


DirectPlayLobby3.CreateComPortAddress

The DirectPlayLobby3.CreateComPortAddress method creates a DirectPlay address for the COM port.

object.CreateComPortAddress(port As Long, _
    baudRate As Long, _
    stopBits As Long, _
    parity As Long, _
    flowcontrol As Long) As DirectPlayAddress

Parameters

object
Object expression that resolves to a DirectPlayLobby3 object.
port
Number of the COM port to use. The value can be 1, 2, 3, or 4.
baudRate
Baud rate of the port. Can be one of the following values:
110 | 300 | 600
1200 | 2400 | 4800
9600 | 14400 | 19200
38400 | 56000 | 57600
115200 | 128000 | 256000

stopBits
Number of stop bits. Can be 0 (one stop bit), 1 (1.5 stop bits), or 2 (two stop bits).
parity
Parity. Can be one of the following values:
0 | No parity
1 | Odd parity
2 | Even parity
3 | Mark parity

flowcontrol
Method of flow control. Can be one of the following values:
0 | No flow control
1 | Software flow control (xon/xoff)
2 | Hardware flow control with RTS
3 | Hardware flow control with DTR.
4 | hardware flow control with RTS and DTR

Return Values

If it succeeds, the method returns a DirectPlayAddress object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to the following value:

DPERR_INVALIDPARAMS


DirectPlayLobby3.CreateConnectionData

The DirectPlayLobby3.CreateConnectionData method creates an object that can be used to set connection settings.

object.CreateConnectionData() As DirectPlayLobbyConnection

Parameters

object
Object expression that resolves to a DirectPlayLobby3 object.

Return Values

If it succeeds, the method returns a DirectPlayLobbyConnection object.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

See Also

DirectPlayLobby3.SetConnectionSettings


DirectPlayLobby3.CreateCustomAddress

The DirectPlayLobby3.CreateCustomAddress method creates a DirectPlay address of a kind not supported by other address creation methods.

object.CreateCustomAddress(size As Long, _
    data As Any) As DirectPlayAddress

Parameters

object
Object expression that resolves to a DirectPlayLobby3 object.
size
Size of the data.
data
The data to be packed into the address.

Return Values

If it succeeds, the method returns a DirectPlayAddress object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to the following value:

DPERR_INVALIDPARAMS


DirectPlayLobby3.CreateINetAddress

The DirectPlayLobby3.CreateINetAddress method creates a DirectPlay address for an Internet address.

object.CreateINetAddress(addr As String, _
    port As Long) As DirectPlayAddress

Parameters

object
Object expression that resolves to a DirectPlayLobby3 object.
addr
IP address (for example, "192.168.0.1") or domain name (for example, "microsoft.com").
port
Port to use for communication. Can be 0 to specify the default port. For more information, see TCP/IP.

Return Values

If it succeeds, the method returns a DirectPlayAddress object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to the following value:

DPERR_INVALIDPARAMS


DirectPlayLobby3.CreateIPXAddress

The DirectPlayLobby3.CreateIPXAddress method creates a DirectPlay address for the IPX service provider.

object.CreateIPXAddress() As DirectPlayAddress

Parameters

object
Object expression that resolves to a DirectPlayLobby3 object.

Return Values

If it succeeds, the method returns a DirectPlayAddress object.

Error Codes

If the method fails, an error is raised and Err.Number may be set.

See Also

DirectPlayLobby3.CreateServiceProviderAddress


DirectPlayLobby3.CreateLobbyProviderAddress

The DirectPlayLobby3.CreateLobbyProviderAddress method creates a DirectPlay address for a lobby provider.

object.CreateLobbyProviderAddress( _
    guid As String) As DirectPlayAddress

Parameters

object
Object expression that resolves to a DirectPlayLobby3 object.
guid
Unique identifier for the lobby provider.

Return Values

If it succeeds, the method returns a DirectPlayAddress object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to the following value:

DPERR_INVALIDPARAMS


DirectPlayLobby3.CreateMessage

The DirectPlayLobby3.CreateMessage method creates a lobby message.

object.CreateMessage() As DirectPlayMessage

Parameters

object
Object expression that resolves to a DirectPlayLobby3 object.

Return Values

If it succeeds, the method returns a DirectPlayMessage object.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlayLobby3.CreateModemAddress

The DirectPlayLobby3.CreateModemAddress method creates a DirectPlay address for a modem.

object.CreateModemAddress( _
    modem As String, _
    phone as String) As DirectPlayAddress

Parameters

object
Object expression that resolves to a DirectPlayLobby3 object.
modem
Name of the modem. Names of available modems can be retrieved by using the DirectPlayLobby3.GetModemName method. Use an empty string to specify the default modem.
phone
Phone number to dial.

Return Values

If it succeeds, the method returns a DirectPlayAddress object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to the following value:

DPERR_INVALIDPARAMS


DirectPlayLobby3.CreateServiceProviderAddress

The DirectPlayLobby3.CreateServiceProviderAddress method creates a DirectPlay address for a service provider.

object.CreateServiceProviderAddress( _
    guid as String) As DirectPlayAddress

Parameters

object
Object expression that resolves to a DirectPlayLobby3 object.
guid
Unique identifier of the service provider.

Return Values

If it succeeds, the method returns a DirectPlayAddress object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to the following value:

DPERR_INVALIDPARAMS

See Also

DirectPlayLobby3.CreateIPXAddress


DirectPlayLobby3.GetConnectionSettings

The DirectPlayLobby3.GetConnectionSettings method retrieves the DirectPlayLobbyConnection object that contains all the information needed to start and connect an application. The data returned is the same data that was passed to the DirectPlayLobby3.RunApplication method by the lobby client, or set by calling the DirectPlayLobby3.SetConnectionSettings method.

object.GetConnectionSettings(applicationId As Long) _
    As DirectPlayLobbyConnection

Parameters

object
Object expression that resolves to a DirectPlayLobby3 object.
applicationId
Value that identifies which application's connection settings to retrieve when called from a lobby client (communicating with several applications). This ID number is obtained from DirectPlayLobby3.RunApplication. When called from an application (communicating with one lobby client), this parameter must be 0.

Return Values

If the method succeeds, it returns a DirectPlayLobbyConnection object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_BUFFERTOOSMALL
DPERR_GENERIC
DPERR_INVALIDINTERFACE
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_NOTLOBBIED
DPERR_OUTOFMEMORY

See Also

DirectPlayLobby3.WaitForConnectionSettings


DirectPlayLobby3.GetDPEnumLocalApplications

The DirectPlayLobby3.GetDPEnumLocalApplications method enumerates the applications that are registered with DirectPlay.

object.GetDPEnumLocalApplications() _
    As DirectPlayEnumLocalApplications

Parameters

object
Object expression that resolves to a DirectPlayLobby3 object.

Return Values

If the method succeeds, it returns a DirectPlayEnumLocalApplications object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_GENERIC
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_OUTOFMEMORY


DirectPlayLobby3.GetModemCount

The DirectPlayLobby3.GetModemCount method retrieves the number of modems available on the player's system.

object.GetModemCount() As Long

Parameters

object
Object expression that resolves to a DirectPlayLobby3 object.

Return Values

If the method succeeds, it returns the number of available modems whose names can be retrieved by using the DirectPlayLobby3.GetModemName method.

Error Codes

If the method fails, an error is raised and Err.Number may be set.


DirectPlayLobby3.GetModemName

The DirectPlayLobby3.GetModemName method retrieves the name of a modem available on the player's system.

object.GetModemName(index As Long) As String

Parameters

object
Object expression that resolves to a DirectPlayLobby3 object.
index
Index of the modem in the list of available modems. This must be in the range 1 to DirectPlayLobby3.GetModemCount.

Return Values

If the method succeeds, it returns the name of the modem.

Error Codes

If the method fails, an error is raised and Err.Number may be set.

See Also

DirectPlayLobby3.CreateModemAddress


DirectPlayLobby3.ReceiveLobbyMessage

The DirectPlayLobby3.ReceiveLobbyMessage method retrieves the message sent between a lobby client application and a DirectPlay application. Messages are queued, so there is no danger of losing data if it is not read in time.

object.ReceiveLobbyMessage(applicationId As Long, _
    messageFlags As Long) As DirectPlayMessage

Parameters

object
Object expression that resolves to a DirectPlayLobby3 object.
applicationId
Identifier of the application from which to receive a message. When called from a lobby client (communicating with several applications), this ID number is the one obtained from the DirectPlayLobby3.RunApplication method. When called from an application (communicating only with one lobby client), this parameter must be set to 0.
messageFlags
A variable to receive flags from the CONST_DPLMSG enumeration indicating what type of message is being returned. The default (messageFlags = 0 or DPLMSG_USERDEFINED) indicates that the message is custom-defined by the sender. Processing of this type of message is optional. The receiver must interpret this message based on the identity of the sending application. A lobby can identify the sending application based on the GUID of the application that was launched. An application has to identify the lobby by sending the lobby a standard message requesting an identifying GUID.

Return Values

If the method succeeds, it returns a DirectPlayMessage object whose methods can be used to extract the message data, or Nothing if there are no messages pending.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_APPNOTSTARTED
DPERR_GENERIC
DPERR_INVALIDINTERFACE
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_OUTOFMEMORY

See Also

DirectPlayLobby3.SendLobbyMessage


DirectPlayLobby3.RegisterApplication

The DirectPlayLobby3.RegisterApplication method registers a lobby-aware application with DirectPlay. An application must be registered so that a DirectPlay lobby can launch it.

The application needs to be registered only once. It must also be unregistered when it is uninstalled.

object.RegisterApplication( _
    ApplicationInfo As DPAPPLICATIONDESC2)

Parameters

object
Object expression that resolves to a DirectPlayLobby3 object.
ApplicationInfo
DPAPPLICATIONDESC2 type describing the application to be registered.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_INVALIDFLAGS
DPERR_INVALIDPARAMS.

See Also

DirectPlayLobby3.UnregisterApplication


DirectPlayLobby3.RunApplication

The DirectPlayLobby3.RunApplication method starts an application and passes to it all the information necessary to connect it to a session. This method is used by a lobby client.

object.RunApplication( _
    connection As DirectPlayLobbyConnection, _
    receiveEvent As Long) As Long

Parameters

object
Object expression that resolves to a DirectPlayLobby3 object.
connection
DirectPlayLobbyConnection interface that contains all the information necessary to specify which application to start and how to get it connected to a session instance without displaying any user dialog boxes.
receiveEvent
Handle to a synchronization event that will be set when a lobby message is received. This event can be changed later by using the DirectPlayLobby3.SetLobbyMessageEvent method.

Return Values

The method returns an ID for the application that was started. The lobby client must save this application ID for use in any calls to the DirectPlayLobby3.SendLobbyMessage and DirectPlayLobby3.ReceiveLobbyMessage methods.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_CANTCREATEPROCESS
DPERR_GENERIC
DPERR_INVALIDINTERFACE
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_OUTOFMEMORY
DPERR_UNKNOWNAPPLICATION

Remarks

This method will return after the application process has been created. The lobby client will receive a system message indicating the status of the application. If the lobby client is starting an application that will host a session, it should wait until it receives a DPLSYS_DPLAYCONNECTSUCCEEDED system message before starting the other applications that will join the session. If the application was unable to create or join a session, a DPLSYS_DPLAYCONNECTFAILED message will be generated. The lobby client will also receive a DPLSYS_CONNECTIONSETTINGSREAD system message when the application has read the connection settings and a DPLSYS_APPTERMINATED system message when the application terminates.

It is important that the lobby client not release the DirectPlayLobby3 object before it receives a DPLSYS_CONNECTIONSETTINGSREAD system message. The lobby client can either check ReceiveLobbyMessage in a loop until it is received, or supply a synchronization event.

See Also

DirectPlayLobby3.GetConnectionSettings, DirectX7.CreateEvent


DirectPlayLobby3.SendLobbyMessage

The DirectPlayLobby3.SendLobbyMessage method sends a message between the application and the lobby client.

object.SendLobbyMessage(flags As CONST_DPLMSG, _
    applicationId As Long, _
    msg As DirectPlayMessage)

Parameters

object
Object expression that resolves to a DirectPlayLobby3 object.
flags
Flags from the CONST_DPLMSG enumeration indicating the type of message being sent. The default (flags = 0 or DPLMSG_USERDEFINED) is a custom message defined by the application sending it. Another possible value is DPLMSG_STANDARD—this is a standard message defined by DirectPlay.
applicationId
Identifies which application to send a message to when called from a lobby client (that communicates with several applications). When called from an application (that communicates with only one lobby client), this parameter must be 0. This ID is obtained by using the DirectPlayLobby3.RunApplication method.
msg
DirectPlayMessage object representing the message to be sent. This object is obtained by using the DirectPlayLobby3.CreateMessage method.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_APPNOTSTARTED
DPERR_BUFFERTOOLARGE
DPERR_GENERIC
DPERR_INVALIDINTERFACE
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_OUTOFMEMORY
DPERR_TIMEOUT

See Also

DirectPlayLobby3.ReceiveLobbyMessage


DirectPlayLobby3.SetConnectionSettings

The DirectPlayLobby3.SetConnectionSettings method modifies the information needed to start and connect an application.

object.SetConnectionSettings(applicationId As Long, _
    connection As DirectPlayLobbyConnection)

Parameters

object
Object expression that resolves to a DirectPlayLobby3 object.
applicationId
When called from a lobby client (communicating with several applications), this parameter identifies which application's connection settings to set. This ID is obtained by using the DirectPlayLobby3.RunApplication method. When called from an application (communicating with only one lobby client), this parameter must be 0.
connection
DirectPlayLobbyConnection object that provides access to all the information necessary to specify which application to start and how to get it connected to a session instance without displaying any user dialog boxes.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_GENERIC
DPERR_INVALIDINTERFACE
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_OUTOFMEMORY

See Also

DirectPlayLobby3.GetConnectionSettings


DirectPlayLobby3.SetLobbyMessageEvent

The DirectPlayLobby3.SetLobbyMessageEvent method registers an event that will be set when a lobby message is received. The application must call this method if it needs to synchronize with messages. The lobby client can call this method to change the events specified in the call to the DirectPlayLobby3.RunApplication method.

object.SetLobbyMessageEvent(applicationId As Long, _
    receiveEvent As Long)

Parameters

object
Object expression that resolves to a DirectPlayLobby3 object.
applicationId
Identifies which application the event is associated with when called from a lobby client (communicating with several applications). This ID number is obtained from RunApplication. When called from an application (communicating with only one lobby client), this parameter must be 0.
receiveEvent
Handle of the event to be set when a message is received.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_GENERIC
DPERR_INVALIDINTERFACE
DPERR_INVALIDOBJECT
DPERR_INVALIDPARAMS
DPERR_OUTOFMEMORY

See Also

DirectPlayLobby3.ReceiveLobbyMessage, DirectPlayLobby3.SendLobbyMessage, DirectX7.CreateEvent


DirectPlayLobby3.UnregisterApplication

The DirectPlayLobby3.UnregisterApplication method deletes the registry entries for a DirectPlay application.

object.UnregisterApplication(GuidApplication As String)

Parameters

object
Object expression that resolves to a DirectPlayLobby3 object.
GuidApplication
Globally unique identifier (GUID) of the application to remove from the registry.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_INVALIDFLAGS
DPERR_INVALIDPARAMS
DPERR_UNKNOWNAPPLICATION

The method returns DPERR_UNKNOWNAPPLICATION if the GUID of the application could not be found in the registry.

See Also

DirectPlayLobby3.RegisterApplication, DPAPPLICATIONDESC2


DirectPlayLobby3.WaitForConnectionSettings

The DirectPlayLobby3.WaitForConnectionSettings method puts the application into wait mode, where the application waits for the connection settings. When the application is in wait mode, a lobby client that uses the DirectPlayLobby3.RunApplication method will not launch a new instance of the application, but will send the connection settings directly to the application already running in wait mode.

The application can use the DirectPlayLobby3.Connect method to connect to a session.

object.WaitForConnectionSettings(flags As CONST_DPLWAIT)

Parameters

object
Object expression that resolves to a DirectPlayLobby3 object.
flags
Flag from the CONST_DPLWAIT enumeration that puts the application into wait mode or takes it out of wait mode. By default (flags = DPLWAIT_DEFAULT, or 0), the method puts the application into wait mode. Setting flags to DPLWAIT_CANCEL takes the application out of wait mode. As soon as the connection settings are sent by the lobby client, the application will automatically be taken out of wait mode.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DPERR_INVALIDFLAGS
DPERR_UNAVAILABLE

The method returns DPERR_UNAVAILABLE if you set the flag to cancel wait mode and the application is not in wait mode.

When the lobby client uses RunApplication, DirectPlay will look for any instances of the application that are waiting for connection settings. If none are found, then a new instance of the application is launched. If a waiting application is found, it can then read the connection settings with the DirectPlayLobby3.GetConnectionSettings method and join a session using Connect.


DirectPlayLobbyConnection

The DirectPlayLobbyConnection class provides a series of methods accessing the information needed to connect an application to a session. An object of this class is returned by the DirectPlayLobby3.CreateConnectionData and DirectPlayLobby3.GetConnectionSettings methods.

The methods of the DirectPlayLobbyConnection class can be organized as follows:

Get | GetAddress
 | GetFlags
 | GetGuidSP
 | GetPlayerLongName
 | GetPlayerShortName
 | GetSessionDesc
Set | SetAddress
 | SetFlags
 | SetGuidSP
 | SetPlayerLongName
 | SetPlayerShortName
 | SetSessionDesc


DirectPlayLobbyConnection.GetAddress

The DirectPlayLobbyConnection.GetAddress method retrieves a DirectPlay address that provides access to the information that the service provider needs to connect to a session.

object.GetAddress() As DirectPlayAddress

Parameters

object
Object expression that resolves to a DirectPlayLobbyConnection object.

Return Values

The method returns a DirectPlayAddress object.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlayLobbyConnection.GetFlags

The DirectPlayLobbyConnection.GetFlags method retrieves flags, indicating how to open a session.

object.GetFlags() As Long

Parameters

object
Object expression that resolves to a DirectPlayLobbyConnection object.

Return Values

The method returns one of the flags from the CONST_DPLCONNECTIONFLAGS enumeration, indicating how to open a session.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlayLobbyConnection.GetGuidSP

The DirectPlayLobbyConnection.GetGuidSP method retrieves the globally unique identifier (GUID) of the service provider to use to connect to the session.

object.GetGuidSP() As String

Parameters

object
Object expression that resolves to a DirectPlayLobbyConnection object.

Return Values

The method returns the GUID of the service provider, in string form.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

See Also

Using GUIDs


DirectPlayLobbyConnection.GetPlayerLongName

The DirectPlayLobbyConnection.GetPlayerLongName method retrieves the formal name of the player. The application can ignore this name.

object.GetPlayerLongName() As String

Parameters

object
Object expression that resolves to a DirectPlayLobbyConnection object.

Return Values

The method returns the formal name of the player.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

See Also

DirectPlayLobbyConnection.SetPlayerLongName


DirectPlayLobbyConnection.GetPlayerShortName

The DirectPlayLobbyConnection.GetPlayerShortName method retrieves the friendly name of the player. The application can ignore this name.

object.GetPlayerShortName() As String

Parameters

object
Object expression that resolves to a DirectPlayLobbyConnection object.

Return Values

The method returns the friendly name of the player.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

See Also

DirectPlayLobbyConnection.SetPlayerShortName


DirectPlayLobbyConnection.GetSessionDesc

The DirectPlayLobbyConnection.GetSessionDesc method retrieves an object containing data that describes the session.

object.GetSessionDesc() As DirectPlaySessionData

Parameters

object
Object expression that resolves to a DirectPlayLobbyConnection object.

Return Values

The method returns a DirectPlaySessionData object.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

See Also

DirectPlay4.Open, DirectPlay4.SecureOpen, DirectPlay4.SetSessionDesc


DirectPlayLobbyConnection.SetAddress

The DirectPlayLobbyConnection.SetAddress method sets a DirectPlay address that provides access to the information that the service provider needs to connect to a session.

object.SetAddress(address As DirectPlayAddress)

Parameters

object
Object expression that resolves to a DirectPlayLobbyConnection object.
address
DirectPlayAddress object.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlayLobbyConnection.SetFlags

The DirectPlayLobbyConnection.SetFlags method sets flags indicating how to open a session

object.SetFlags(flags As CONST_DPLCONNECTIONFLAGS)

Parameters

object
Object expression that resolves to a DirectPlayLobbyConnection object.
flags
Flag from the CONST_DPLCONNECTIONFLAGS enumeration, indicating how to open a session.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlayLobbyConnection.SetGuidSP

The DirectPlayLobbyConnection.SetGuidSP method sets the globally unique identifier (GUID) of the service provider to use to connect to the session.

object.SetGuidSP(guid As String)

Parameters

object
Object expression that resolves to a DirectPlayLobbyConnection object.
guid
The GUID of the service provider. Can be one of the following string aliases:
DPSPGUID_IPX
DPSPGUID_TCPIP
DPSPGUID_SERIAL
DPSPGUID_MODEM

Error Codes

If the method fails, an error is raised and Err.Number will be set.

See Also

Using GUIDs


DirectPlayLobbyConnection.SetPlayerLongName

The DirectPlayLobbyConnection.SetPlayerLongName method sets the formal name the player should be created with. This will be the formal name of the person registered in the lobby. The application can ignore this name.

object.SetPlayerLongName(name As String)

Parameters

object
Object expression that resolves to a DirectPlayLobbyConnection object.
name
The formal name of the player to be set.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

See Also

DirectPlayLobbyConnection.SetPlayerShortName


DirectPlayLobbyConnection.SetPlayerShortName

The DirectPlayLobbyConnection.SetPlayerShortName method sets the friendly name the player should be created with. This will be the friendly name of the person registered in the lobby. The application can ignore this name.

object.SetPlayerShortName(name As String)

Parameters

object
Object expression that resolves to a DirectPlayLobbyConnection object.
name
Friendly name of the player to be set.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

See Also

DirectPlayLobbyConnection.SetPlayerLongName


DirectPlayLobbyConnection.SetSessionDesc

The DirectPlayLobbyConnection.SetSessionDesc method sets the description of the session to be created or the session to join.

object.SetSessionDesc(sessionDesc As DirectPlaySessionData)

Parameters

object
Object expression that resolves to a DirectPlayLobbyConnection object.
sessionDesc
DirectPlaySessionData object describing the session. This object is obtained by using the DirectPlay4.CreateSessionData method.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlayMessage

The DirectPlayMessage class provides methods for reading and writing message data. An application creates a DirectPlayMessage object by using the DirectPlay4.CreateMessage method. Message objects are retrieved by the DirectPlay4.Receive and DirectPlayLobby3.ReceiveLobbyMessage methods.

Messages can contain data of any type, and types can be freely mixed within a message. It is up to the application to ensure that data is read from the message in the same order as it was written.

System messages always have a Long as the first data element that identifies the message type. Once the application has determined the type of the message by reading this value, it can proceed to parse the rest of the data appropriately by using the read methods of DirectPlayMessage. See CONST_DPSYSMSGTYPES for more information on the data format for each kind of system message.

The methods of the DirectPlayMessage class may be grouped as follows:

Read data | GetMessageData
 | MoveToSecureMessage
 | MoveToTop
 | ReadByte
 | ReadDouble
 | ReadGuid
 | ReadLong
 | ReadShort
 | ReadSingle
 | ReadString
 | ReadSysChatString
 | ReadSysMsgConnection
 | ReadSysMsgData
 | ReadSysMsgSessionDesc
Write data | SetMessageData
 | WriteByte
 | WriteDouble
 | WriteGuid
 | WriteLong
 | WriteShort
 | WriteSingle
 | WriteString
Miscellaneous | Clear
 | GetMessageSize


DirectPlayMessage.Clear

The DirectPlayMessage.Clear method clears all data from the message object.

object.Clear()

Parameters

object
Object expression that resolves to a DirectPlayMessage object.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

Remarks

Reusing an existing message object by clearing it and setting new data on it is quicker than creating a new object each time the application needs to send a message.


DirectPlayMessage.GetMessageData

The DirectPlayMessage.GetMessageData method gets raw data from a message.

object.GetMessageData(userDefinedType As Any)

Parameters

object
Object expression that resolves to a DirectPlayMessage object.
userDefinedType
User-defined type to receive the message data.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

Remarks

This method should be used only for retrieving data from a message whose data has been written by using DirectPlayMessage.SetMessageData. The method retrieves the entire message, regardless of whether any part of it has already been retrieved by using one or more of the DirectPlayMessage.ReadX methods.


DirectPlayMessage.GetMessageSize

The DirectPlayMessage.GetMessageSize method retrieves the size of the message.

object.GetMessageSize() As Long

Parameters

object
Object expression that resolves to a DirectPlayMessage object.

Return Values

The message returns the size of the message in bytes.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlayMessage.MoveToSecureMessage

The DirectPlayMessage.MoveToSecureMessage moves the read pointer to the beginning of the message data in a secure message.

object.MoveToSecureMessage()

Parameters

object
Object expression that resolves to a DirectPlayMessage object.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

Remarks

A secure system message consists of a Long for the message type (DPSYS_SECUREMESSAGE), a Long for the flags, a Long for the ID of the player who originated the message, and then a pointer to the message data. The MoveToSecureMessage method moves the read pointer to the start of the data so that an application can parse it by using other methods such as DirectPlayMessage.ReadLong.

See Also

CONST_DPSYSMSGTYPES


DirectPlayMessage.MoveToTop

The DirectPlayMessage.MoveToTop method moves the read pointer to the beginning of the message data.

object.MoveToTop()

Parameters

object
Object expression that resolves to a DirectPlayMessage object.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

Remarks

Each time an element of message data is retrieved by using one of the DirectPlayMessage.ReadX methods, the read pointer is advanced. MoveToTop allows you to start reading the message again from the beginning.


DirectPlayMessage.ReadByte

The DirectPlayMessage.ReadByte method reads a Byte from the message data and advances the read pointer.

object.ReadByte() As Byte

Parameters

object
Object expression that resolves to a DirectPlayMessage object.

Return Values

The method returns a Byte from the message.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlayMessage.ReadDouble

The DirectPlayMessage.ReadDouble method reads a Double from the message data and advances the read pointer.

object.ReadDouble() As Double

Parameters

object
Object expression that resolves to a DirectPlayMessage object.

Return Values

The method returns a Double from the message.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlayMessage.ReadGuid

The DirectPlayMessage.ReadGuid method reads a GUID from the message data and advances the read pointer.

object.ReadGuid() As String

Parameters

object
Object expression that resolves to a DirectPlayMessage object.

Return Values

The method returns a GUID in string form.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

See Also

Using GUIDs


DirectPlayMessage.ReadLong

The DirectPlayMessage.ReadLong method reads a Long from the message data and advances the read pointer.

object.ReadLong() As Long

Parameters

object
Object expression that resolves to a DirectPlayMessage object.

Return Values

The method returns a Long from the message.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlayMessage.ReadShort

The DirectPlayMessage.ReadShort method reads an Integer from the message data and advances the read pointer.

object.ReadShort() As Integer

Parameters

object
Object expression that resolves to a DirectPlayMessage object.

Return Values

The method returns an Integer from the message.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlayMessage.ReadSingle

The DirectPlayMessage.ReadSingle method reads a Single from the message data and advances the read pointer.

object.ReadSingle() As Single

Parameters

object
Object expression that resolves to a DirectPlayMessage object.

Return Values

The method returns a Single from the message.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlayMessage.ReadString

The DirectPlayMessage.ReadString method reads a string from the message data and advances the read pointer.

object.ReadString() As String

Parameters

object
Object expression that resolves to a DirectPlayMessage object.

Return Values

The method returns a string from the message.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlayMessage.ReadSysChatString

The DirectPlayMessage.ReadSysChatString method reads a string from a DPSYS_CHAT message.

object.ReadSysChatString() As String

Parameters

object
Object expression that resolves to a DirectPlayMessage object.

Return Values

The method returns a string from the message.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlayMessage.ReadSysMsgConnection

The DirectPlayMessage.ReadSysMsgConnection method obtains a DirectPlayLobbyConnection object from a DPSYS_STARTSESSION message.

object.ReadSysMsgConnection() As DirectPlayLobbyConnection

Parameters

object
Object expression that resolves to a DirectPlayMessage object.

Return Values

The method returns a DirectPlayLobbyConnection object.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlayMessage.ReadSysMsgData

The DirectPlayMessage.ReadSysMsgData method obtains data from a DPSYS_CREATEPLAYERORGROUP, DPSYS_DESTROYPLAYERORGROUP, or DPSYS_SETPLAYERORGROUPDATA message.

object.ReadSysMsgData() As String

Parameters

object
Object expression that resolves to a DirectPlayMessage object.

Return Values

The method returns a string containing the message data.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

Remarks

The read pointer must be at the correct location within the message in order for this method to be called successfully. For example, when parsing a DPSYS_DESTROYPLAYERORGROUP message, you first have to call DirectPlayMessage.ReadLong three times in order to retrieve the message type, player type, and player ID. After ReadSysMsgData has been called, the read pointer advances to the next field described in the reference for the message type. (See CONST_DPSYSMSGTYPES.) In this respect the method differs from DirectPlayMessage.ReadSysChatString, DirectPlayMessage.ReadSysMsgConnection, and DirectPlayMessage.ReadSysMsgSessionDesc, which can retrieve data regardless of whether other parts of the message have been read, and which do not advance the read pointer.


DirectPlayMessage.ReadSysMsgSessionDesc

The DirectPlayMessage.ReadSysMsgSessionDesc method obtains the session description from a DPSYS_SETSESSIONDESC system message.

object.ReadSysMsgSessionDesc() As DirectPlaySessionData

Parameters

object
Object expression that resolves to a DirectPlayMessage object.

Return Values

The method returns a DirectPlaySessionData object.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlayMessage.SetMessageData

The DirectPlayMessage.SetMessageData method writes data of a user-defined type to a message.

object.SetMessageData(userDefinedType As Any, size As Long)

Parameters

object
Object expression that resolves to a DirectPlayMessage object.
userDefinedType
Type containing the message data. All members of the user defined type must be numeric types, not strings. Typically the first member of the type is a Long defining the message type.
size
Size of userDefinedType, in bytes.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

Remarks

SetMessageData can be used only to set the entire contents of a message. It must not be called more than once per message, nor can it be mixed with calls to other write methods. The data should be retrieved by using DirectPlayMessage.GetMessageData.

It is recommended that this method be employed by advanced users only. In most cases, it is better to construct message data by using the DirectPlayMessage.WriteX methods, then read back the data with the corresponding DirectPlayMessage.ReadX methods.


DirectPlayMessage.WriteByte

The DirectPlayMessage.WriteByte method writes a Byte to the message data and advances the write pointer.

object.WriteByte(val As Byte)

Parameters

object
Object expression that resolves to a DirectPlayMessage object.
val
Value to write to the message.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlayMessage.WriteDouble

The DirectPlayMessage.WriteDouble method writes a Double to the message data and advances the write pointer.

object.WriteDouble(val As Double)

Parameters

object
Object expression that resolves to a DirectPlayMessage object.
val
Value to write to the message.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlayMessage.WriteGuid

The DirectPlayMessage.WriteGUID method writes a GUID string to the message data and advances the write pointer.

object.WriteGUID(val As String)

Parameters

object
Object expression that resolves to a DirectPlayMessage object.
val
Value to write to the message.

Error Codes

If the method fails, an error is raised and Err.Number will be set.

See Also

Using GUIDs


DirectPlayMessage.WriteLong

The DirectPlayMessage.WriteLong method writes a Long to the message data and advances the write pointer.

object.WriteLong(val As Long)

Parameters

object
Object expression that resolves to a DirectPlayMessage object.
val
Value to write to the message.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlayMessage.WriteShort

The DirectPlayMessage.WriteShort method writes an Integer to the message data and advances the write pointer.

object.WriteShort(val As Integer)

Parameters

object
Object expression that resolves to a DirectPlayMessage object.
val
Value to write to the message.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlayMessage.WriteSingle

The DirectPlayMessage.WriteSingle method writes a Single to the message data and advances the write pointer.

object.WriteSingle(val As Single)

Parameters

object
Object expression that resolves to a DirectPlayMessage object.
val
Value to write to the message.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlayMessage.WriteString

The DirectPlayMessage.WriteString method writes a String to the message data and advances the write pointer.

object.WriteString(val As String)

Parameters

object
Object expression that resolves to a DirectPlayMessage object.
val
Value to write to the message.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlaySessionData

The DirectPlaySessionData class represents the descriptive data associated with a session. An object of this class is returned by the DirectPlay4.CreateSessionData method and passed to DirectPlay4.Open or DirectPlay4.SecureOpen. It is also used by various other methods to set or retrieve the session description.

The DirectPlaySessionData class has the following methods:

Get data | GetCurrentPlayers
 | GetFlags
 | GetGuidApplication
 | GetGuidInstance
 | GetMaxPlayers
 | GetSessionName
 | GetSessionPassword
 | GetUser1
 | GetUser2
 | GetUser3
 | GetUser4
Set data | SetFlags
 | SetGuidApplication
 | SetGuidInstance
 | SetMaxPlayers
 | SetSessionName
 | SetSessionPassword
 | SetUser1
 | SetUser2
 | SetUser3
 | SetUser4

See Also

DirectPlay4.GetSessionDesc, DirectPlay4.SetSessionDesc, DirectPlayLobbyConnection.GetSessionDesc, DirectPlayLobbyConnection.SetSessionDesc, DirectPlay4.GetDPEnumSessions, DirectPlayEnumSessions.GetItem


DirectPlaySessionData.GetCurrentPlayers

The DirectPlaySessionData.GetCurrentPlayers method retrieves the current number of players in the session.

object.GetCurrentPlayers() As Long

Parameters

object
Object expression that resolves to a DirectPlaySessionData object.

Return Values

The method returns the current number of players.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlaySessionData.GetFlags

The DirectPlaySessionData.GetFlags method retrieves the flags for the session.

object.GetFlags() As Long

Parameters

object
Object expression that resolves to a DirectPlaySessionData object.

Return Values

The method returns flags from the CONST_DPSESSIONFLAGS enumeration that describe the session.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlaySessionData.GetGuidApplication

The DirectPlaySessionData.GetGuidApplication method retrieves the GUID for the application that created the session.

object.GetGuidApplication() As String

Parameters

object
Object expression that resolves to a DirectPlaySessionData object.

Return Values

The method returns the GUID of the application.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlaySessionData.GetGuidInstance

The DirectPlaySessionData.GetGuidInstance method retrieves the GUID of the session instance.

object.GetGuidInstance() As String

Parameters

object
Object expression that resolves to a DirectPlaySessionData object.

Return Values

The method returns the GUID assigned by the application to the session when it was created.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlaySessionData.GetMaxPlayers

The DirectPlaySessionData.GetMaxPlayers method retrieves the greatest number of players allowed to join the session.

object.GetMaxPlayers() As Long

Parameters

object
Object expression that resolves to a DirectPlaySessionData object.

Return Values

The method returns the maximum number of players, or 0 if there is no maximum.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlaySessionData.GetSessionName

The DirectPlaySessionData.GetSessionName method retrieves the name of the session.

object.GetSessionName() As String

Parameters

object
Object expression that resolves to a DirectPlaySessionData object.

Return Values

The method returns the name of the session.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlaySessionData.GetSessionPassword

The DirectPlaySessionData.GetSessionPassword method retrieves the password of the session.

object.GetSessionPassword() As String

Parameters

object
Object expression that resolves to a DirectPlaySessionData object.

Return Values

The method returns the password required to join the session.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlaySessionData.GetUser1

See DirectPlaySessionData.GetUser(n).


DirectPlaySessionData.GetUser2

See DirectPlaySessionData.GetUser(n).


DirectPlaySessionData.GetUser3

See DirectPlaySessionData.GetUser(n).


DirectPlaySessionData.GetUser4

See DirectPlaySessionData.GetUser(n).


DirectPlaySessionData.GetUser(n)

The DirectPlaySessionData.GetUser1, DirectPlaySessionData.GetUser2, DirectPlaySessionData.GetUser3, and DirectPlaySessionData.GetUser4 methods retrieve application-defined data for the session.

object.GetUser1() As Long

Parameters

object
Object expression that resolves to a DirectPlaySessionData object.

Return Values

The methods return application-defined data.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlaySessionData.SetFlags

The DirectPlaySessionData.SetFlags method sets the flags for a session.

object.SetFlags(val As CONST_DPSESSIONFLAGS)

Parameters

object
Object expression that resolves to a DirectPlaySessionData object.
val
Flags from the CONST_DPSESSIONFLAGS enumeration describing the session.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlaySessionData.SetGuidApplication

The DirectPlaySessionData.SetGuidApplication method sets the GUID of the application in the session description.

object.SetGuidApplication(guid As String)

Parameters

object
Object expression that resolves to a DirectPlaySessionData object.
guid
GUID for the application. This member can be set to an empty string to enumerate sessions for any application.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlaySessionData.SetGuidInstance

The DirectPlaySessionData.SetGuidInstance method sets the GUID for a session instance.

object.SetGuidInstance(guid As String)

Parameters

object
Object expression that resolves to a DirectPlaySessionData object.
guid
GUID of the session.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlaySessionData.SetMaxPlayers

The DirectPlaySessionData.SetMaxPlayers method sets the greatest number of players who can join a session.

object.SetMaxPlayers(val As Long)

Parameters

object
Object expression that resolves to a DirectPlaySessionData object.
val
Maximum number of players. If 0, there is no maximum.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlaySessionData.SetSessionName

The DirectPlaySessionData.SetSessionName method sets the name of a session.

object.SetSessionName(val As String)

Parameters

object
Object expression that resolves to a DirectPlaySessionData object.
val
Name of the session.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlaySessionData.SetSessionPassword

The DirectPlaySessionData.SetSessionPassword method sets the password for a session.

object.SetSessionPassword(val As String)

Parameters

object
Object expression that resolves to a DirectPlaySessionData object.
val
Password for the session.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectPlaySessionData.SetUser1

See DirectPlaySessionData.SetUser(n).


DirectPlaySessionData.SetUser2

See DirectPlaySessionData.SetUser(n).


DirectPlaySessionData.SetUser3

See DirectPlaySessionData.SetUser(n).


DirectPlaySessionData.SetUser4

See DirectPlaySessionData.SetUser(n).


DirectPlaySessionData.SetUser(n)

The DirectPlaySessionData.SetUser1, DirectPlaySessionData.SetUser2, DirectPlaySessionData.SetUser3, and DirectPlaySessionData.SetUser4 methods set application-defined data for the session.

object.SetUser1(val As Long)

Parameters

object
Object expression that resolves to a DirectPlaySessionData object.
val
Application-defined data.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


Types

This section contains references for the following types defined for DirectPlay:

  • DPAPPLICATIONDESC2
  • DPCAPS
  • DPCREDENTIALS
  • DPSECURITYDESC


DPAPPLICATIONDESC2

The DPAPPLICATIONDESC2 type contains information about an application that is to be registered by using the DirectPlayLobby3.RegisterApplication method.

Type DPAPPLICATIONDESC2
    lFlags As Long
    strAppLauncherName As String
    strApplicationName As String
    strCommandLine As String
    strCurrentDirectory As String
    strDescription As String
    strFilename As String
    strGuid As String
    strPath As String
End Type

Members

lFlags
Not used. Must be 0.
strAppLauncherName
Name of a launcher executable. The launcher is started by the lobby, and it in turn is responsible for launching the application described in strApplicationName. The launcher must reside in the same directory as the application.
strApplicationName
Name of the application. This title should not be localized. Use the strDescription member to localize the application name.
strCommandLine
Command line arguments to be passed to the executable when launched by a lobby.
strCurrentDirectory
Path that the current directory should be set to.
strDescription
Localized description of the application. When DirectPlayLobby3.GetDPEnumLocalApplications is called, this string will be returned.
strFilename
Name of the executable to be launched. Note: The use of a stub executable should be avoided when launching from a lobby. In a lobby launch scenario, the stub should be bypassed and the main executable should be launched.
strGuid
Globally unique identifier (GUID) of the application. This should be the same as the value set by using DirectPlaySessionData.SetGuidApplication when hosting a game session.
strPath
Path where the executable is located.


DPCAPS

The DPCAPS type contains the capabilities of a DirectPlay object after a call to the DirectPlay4.GetCaps or DirectPlay4.GetPlayerCaps method. Any of these capabilities can differ, depending on whether guaranteed or nonguaranteed capabilities are requested. This type is read-only.

Type DPCAPS
    lFlags As Long
    lHeaderLength As Long
    lHundredBaud As Long
    lLatency As Long
    lMaxBufferSize As Long
    lMaxLocalPlayers As Long
    lMaxPlayers As Long
    lMaxQueueSize As Long
    lTimeout As Long
End Type

Members

lFlags
Members of the CONST_DPCAPSFLAGS enumeration that indicate the properties of the DirectPlay object. The DPCAPS_ASYNCSUPPORTED, DPCAPS_SENDTIMEOUTSUPPORTED, DPCAPS_SENDPRIORITYSUPPORTED, DPCAPS_ASYNCCANCELSUPPORTED, and DPCAPS_ASYNCCANCELALLSUPPORTED flags indicate the communications capabilities of the current session.
lHeaderLength
Size, in bytes, of the header that will be added to player messages by this DirectPlay object. The header size depends on which service provider is in use.
lHundredBaud
Bandwidth specified in multiples of 100 bits per second. For example, a value of 24 specifies 2400 bits per second.
lLatency
Estimate of latency by the service provider, in milliseconds. If this value is 0, DirectPlay cannot provide an estimate. Accuracy for some service providers rests on application-to-application testing, taking into consideration the average message size. Latency can differ, depending on whether the application uses guaranteed or nonguaranteed message delivery.
lMaxBufferSize
Maximum number of bytes that can be sent in a single packet by this service provider. Larger messages will be sent by using more than one packet.
lMaxLocalPlayers
Maximum number of local players supported in a session.
lMaxPlayers
Maximum number of local and remote players supported in a session by this DirectPlay object.
lMaxQueueSize
This member is no longer used.
lTimeout
Service provider's suggested time-out value. By default, DirectPlay will use this time-out value when waiting for replies to messages.

Remarks

Capabilities indicating which aspects of the DirectPlay4.SendEx method are supported, such as the DPCAPS_SENDPRIORITYSUPPORTED and DPCAPS_SENDTIMEOUTSUPPORTED flags in lFlags, are not available until after the session has been opened.

In order for an application to be able to use DPSEND_ASYNC on SendEx one (or both) of the following conditions must be true.

  • You specified the DPSESSION_DIRECTPLAYPROTOCOL flag when the session was created.
  • The service provider supports asynchronous messaging.

This means that modem, serial, and Internetwork Packet Exchange (IPX) service providers have guaranteed messaging available to them, but they do not have asynchronous messaging unless you explicitly set the DPSESSION_DIRECTPLAYPROTOCOL flag. The TCP/IP service provider implements asynchronous messaging when the computer has Windows Sockets 2.0 present.

If the application hosting the session has specified the DPSESSION_DIRECTPLAYPROTOCOL flag in the DirectPlaySessionData object, all the SendEx options are supported.


DPCREDENTIALS

The DPCREDENTIALS type contains the user domain, password, and name to connect to a secure server.

Type DPCREDENTIALS
    lFlags As Long
    strDomain As String
    strPassword As String
    strUsername As String
End Type

Members

lFlags
Not used. Must be 0.
strDomain, strPassword, strUsername
ANSI strings containing the user domain, password, and name.


DPSECURITYDESC

The DPSECURITYDESC type describes the security properties of a DirectPlay session instance.

Type DPSECURITYDESC
    lCAPIProviderType As Long
    lEncryptionAlgorithm As Long
    lFlags As Long
    strCAPIProvider As String
    strSSPIProvider As String
End Type

Members

lCAPIProviderType
CryptoAPI service provider type. Pass 0 to use the default type, PROV_RSA_FULL.
lEncryptionAlgorithm
Encryption algorithm to use. DirectPlay supports only stream ciphers. Pass 0 to use the default, the CALG_RC4 stream cipher.
lFlags
Not used. Must be 0.
strCAPIProvider
Unicode or ANSI string describing the CryptoAPI package to use for cryptography services. Pass NULL to use the default, the Microsoft RSA Base Cryptographic Provider 1.0.
strSSPIProvider
Unicode or ANSI string describing the Security Support Provider Interface (SSPI) package to use for authenticated logons. Pass NULL to use the default, the NTLM security provider.


Enumerations

This section contains references for the following enumerations used in DirectPlay for Visual Basic:

  • CONST_DPCAPSFLAGS
  • CONST_DPCONNECTFLAGS
  • CONST_DPENUMCONNECTIONFLAGS
  • CONST_DPENUMGROUPFLAGS
  • CONST_DPENUMPLAYERFLAGS
  • CONST_DPENUMSESSIONFLAGS
  • CONST_DPGETCAPSFLAGS
  • CONST_DPGETFLAGS
  • CONST_DPGROUPFLAGS
  • CONST_DPIDFLAGS
  • CONST_DPLAYERR
  • CONST_DPLCONNECTIONFLAGS
  • CONST_DPLMSG
  • CONST_DPLWAIT
  • CONST_DPMESSAGEQUEUEFLAGS
  • CONST_DPOPENFLAGS
  • CONST_DPPLAYERFLAGS
  • CONST_DPPLAYERTYPEFLAGS
  • CONST_DPRECEIVEFLAGS
  • CONST_DPSENDFLAGS
  • CONST_DPSESSIONFLAGS
  • CONST_DPSETFLAGS
  • CONST_DPSYSMSGTYPES


CONST_DPCAPSFLAGS

Constants of the CONST_DPCAPSFLAGS enumeration are used in the DPCAPS type to specify the capabilities of the DirectPlay object.

Enum CONST_DPCAPSFLAGS
    DPCAPS_ASYNCCANCELALLSUPPORTED = 8192 (&H2000)
    DPCAPS_ASYNCCANCELSUPPORTED =    4096 (&H1000)
    DPCAPS_ASYNCSUPPORTED =         65536 (&H10000)
    DPCAPS_ENCRYPTIONSUPPORTED =      256 (&H100)
    DPCAPS_GROUPOPTIMIZED =             8
    DPCAPS_GUARANTEEDOPTIMIZED =       32 (&H20)
    DPCAPS_GUARANTEEDSUPPORTED =       64 (&H40)
    DPCAPS_ISHOST =                     2
    DPCAPS_KEEPALIVEOPTIMIZED =        16 (&H10)
    DPCAPS_SENDPRIORITYSUPPORTED =  32768 (&H8000)
    DPCAPS_SENDTIMEOUTSUPPORTED =   16384 (&H4000)
    DPCAPS_SIGNINGSUPPORTED =         128 (&H80)
End Enum
DPCAPS_ASYNCCANCELALLSUPPORTED
Canceling all pending asynchronous messages is supported. This flag indicates that the only form of cancellation supported is the ability to cancel all unsent messages. Any attempt to cancel messages by specifying a priority range or a message ID will return DPERR_UNSUPPORTED. By contrast, the DPCAPS_ASYNCCANCELSUPPORTED flag indicates that all types of cancellation are supported. Note that capabilities indicating which aspects of SendEx are supported are not available until after the session has been opened.
DPCAPS_ASYNCCANCELSUPPORTED
Canceling asynchronous messages is supported. All types of cancellation are supported: canceling by message ID, canceling by priority range, and canceling all unsent messages. Note that capabilities indicating which aspects of SendEx are supported are not available until after the session has been opened.
DPCAPS_ASYNCSUPPORTED
Asynchronous messaging is supported. Thus, an application can use the DPSEND_ASYNC flag on SendEx. Note that capabilities indicating which aspects of SendEx are supported are not available until after the session has been opened.
DPCAPS_ENCRYPTIONSUPPORTED
Message encryption is supported by this DirectPlay object, either because the session is a secure session, or because the service provider can encrypt messages.
DPCAPS_GROUPOPTIMIZED
The service provider bound to this DirectPlay object can optimize group (multicast) messaging.
DPCAPS_GUARANTEEDOPTIMIZED
The service provider bound to this DirectPlay object supports guaranteed message delivery.
DPCAPS_GUARANTEEDSUPPORTED
The DirectPlay object supports guaranteed message delivery, either because the service provider supports it, or because DirectPlay implements it on a nonguaranteed service provider.
DPCAPS_ISHOST
The DirectPlay object created by the calling application is the session host.
DPCAPS_KEEPALIVEOPTIMIZED
The service provider can detect when the connection to the session has been lost.
DPCAPS_SENDPRIORITYSUPPORTED
The message priority set in SendEx is supported. Note that capabilities indicating which aspects of SendEx are supported are not available until after the session has been opened.
DPCAPS_SENDTIMEOUTSUPPORTED
The time-out for messages specified in SendEx is supported. This flag can be set by the service provider or by DirectPlay. Note that capabilities indicating which aspects of SendEx are supported are not available until after the session has been opened.
DPCAPS_SIGNINGSUPPORTED
Message authentication is supported by this DirectPlay object, either because it is a secure session, or because the service provider can sign messages.


CONST_DPCONNECTFLAGS

Members of the CONST_DPCONNECTFLAGS enumeration are used in the DirectPlayLobby3.Connect method to specify when the method returns.

Enum CONST_DPCONNECTFLAGS
    DPCONNECTION_DEFAULT =        0
    DPCONNECTION_RETURNSTATUS = 128 (&H80)
End Enum
DPCONNECTION_DEFAULT
The method returns after a connection has been established or the operation has timed out.
DPCONNECTION_RETURNSTATUS
The method returns immediately with the status of the connection.


CONST_DPENUMCONNECTIONFLAGS

Members of the CONST_DPENUMCONNECTIONFLAGS enumeration are used in the DirectPlay4.GetDPEnumConnections method to specify what types of connections should be enumerated.

Enum CONST_DPENUMCONNECTIONFLAGS
    DPCONNECTION_DIRECTPLAY = 1
    DPCONNECTION_DIRECTPLAYLOBBY = 2
End Enum
DPCONNECTION_DIRECTPLAY
Enumerate DirectPlay service providers to communicate in an application session.
DPCONNECTION_DIRECTPLAYLOBBY
Enumerate DirectPlay lobby providers to communicate with a lobby server.


CONST_DPENUMGROUPFLAGS

Members of the CONST_DPENUMGROUPFLAGS enumeration are used in the DirectPlay4.GetDPEnumGroups and DirectPlay4.GetDPEnumGroupsInGroup methods to specify the type of groups to be enumerated.

Enum CONST_DPENUMGROUPFLAGS
    DPENUMGROUPS_ALL =            0
    DPENUMGROUPS_HIDDEN =      4096 (&H1000)
    DPENUMGROUPS_LOCAL =          8
    DPENUMGROUPS_REMOTE =        16 (&H10)
    DPENUMGROUPS_SESSION =      128 (&H80)
    DPENUMGROUPS_SHORTCUT =    1024 (&H400)
    DPENUMGROUPS_STAGINGAREA = 2048 (&H800)
End Enum
DPENUMGROUPS_ALL
Enumerate all groups.
DPENUMGROUPS_HIDDEN
Enumerate only the currently available hidden groups in the group. Valid only for GetDPEnumGroupsInGroup.
DPENUMGROUPS_LOCAL
Enumerate groups created locally by this DirectPlay object.
DPENUMGROUPS_REMOTE
Enumerate groups created by remote DirectPlay objects.
DPENUMGROUPS_SESSION
Perform enumeration in the session identified by the sessionGuid parameter. This flag can be used only if there is no current active session, and cannot be used in lobby sessions.
DPENUMGROUPS_SHORTCUT
Enumerates groups that are shortcuts added to the group using DirectPlay4.AddGroupToGroup. (A shortcut is a link to another group.) Valid only for GetDPEnumGroupsInGroup.
DPENUMGROUPS_STAGINGAREA
Enumerates groups that are staging areas. (Staging areas are used to marshal players together in order to launch a new session.)


CONST_DPENUMPLAYERFLAGS

Members of the CONST_DPENUMPLAYERFLAGS enumeration are used in the DirectPlay4.GetDPEnumPlayers and DirectPlay4.GetDPEnumGroupPlayers methods to specify what types of players should be enumerated.

Enum CONST_DPENUMPLAYERFLAGS
    DPENUMPLAYERS_ALL =            0
    DPENUMPLAYERS_GROUP =         32 (&H20)
    DPENUMPLAYERS_LOCAL =          8
    DPENUMPLAYERS_OWNER =       8192 (&H2000)
    DPENUMPLAYERS_REMOTE =        16 (&H10)
    DPENUMPLAYERS_SERVERPLAYER = 200 (&H100)
    DPENUMPLAYERS_SESSION =      128 (&H80)
    DPENUMPLAYERS_SPECTATOR =    512 (&H200)
End Enum
DPENUMPLAYERS_ALL
All players in this session.
DPENUMPLAYERS_GROUP
Groups.
DPENUMPLAYERS_LOCAL
Players created locally by this DirectPlay object.
DPENUMPLAYERS_OWNER
Owner of the group.
DPENUMPLAYERS_REMOTE
Players created by remote DirectPlay objects.
DPENUMPLAYERS_SERVERPLAYER
Server player.
DPENUMPLAYERS_SESSION
Players for the session identified by sessionGuid. This flag can only be used if there is no current open session.
DPENUMPLAYERS_SPECTATOR
Spectator players.


CONST_DPENUMSESSIONFLAGS

Members of the CONST_DPENUMSESSIONFLAGS enumeration are used in the DirectPlay4.GetDPEnumSessions method to specify which sessions should be enumerated.

Enum CONST_DPENUMSESSIONFLAGS
    DPENUMSESSIONS_ALL =               2
    DPENUMSESSIONS_ASYNC =            16 (&H10)
    DPENUMSESSIONS_AVAILABLE =         1
    DPENUMSESSIONS_PASSWORDREQUIRED = 64 (&H40)
    DPENUMSESSIONS_RETURNSTATUS =    128 (&H80)
    DPENUMSESSIONS_STOPASYNC =        16 (&H10)
End Enum
DPENUMSESSIONS_ALL
Enumerate all active sessions, whether they are accepting new players or not. Sessions in which the player limit has been reached, new players have been disabled, or joining has been disabled will be enumerated. Password-protected sessions will not be enumerated unless the DPENUMSESSIONS_PASSWORDREQUIRED flag is also specified.
DPENUMSESSIONS_ASYNC
Enumerates all the current sessions in the session cache and returns immediately. Starts the asynchronous enumeration process if not already started. Updates to the session list continue until canceled by calling GetDPEnumSessions with the DPENUMSESSIONS_STOPASYNC flag, or by calling DirectPlay4.Open.

If this flag is not specified, the enumeration is done synchronously.

DPENUMSESSIONS_AVAILABLE
Enumerate all sessions that are accepting new players to join. Sessions that have reached their maximum number of players, have disabled new players, or have disabled joining will not be enumerated. Password-protected sessions will not be enumerated unless the DPENUMSESSIONS_PASSWORDREQUIRED flag is also specified.
DPENUMSESSIONS_PASSWORDREQUIRED
When used in combination with DPENUMSESSIONS_AVAILABLE or DPENUMSESSIONS_ALL, enables password-protected sessions to be enumerated in addition to sessions without password protection.
DPENUMSESSIONS_RETURNSTATUS
If this flag is specified, the enumeration will not display any dialog boxes showing the connection progress status. If the connection cannot be made immediately, the method will return with the DPERR_CONNECTING error. The application must keep calling GetDPEnumSessions until it succeeds or some other error code is returned.
DPENUMSESSIONS_STOPASYNC
Enumerates all the current sessions in the session cache and cancels the asynchronous enumeration process.


CONST_DPGETCAPSFLAGS

Members of the CONST_DPGETCAPSFLAGS enumeration are used to indicate DirectPlay and player capabilities. These flags are returned by the DirectPlay4.GetCaps and DirectPlay4.GetPlayerCaps methods.

Enum CONST_DPGETCAPSFLAGS
    DPGETCAPS_DEFAULT =    0
    DPGETCAPS_GUARANTEED = 1
End Enum
DPGETCAPS_DEFAULT
Capabilities for nonguaranteed messaging.
DPGETCAPS_GUARANTEED
Capabilities for guaranteed message delivery.


CONST_DPGETFLAGS

Members of the CONST_DPGETFLAGS enumeration are used to determine what data is retrieved by the DirectPlay4.GetGroupData and DirectPlay4.GetPlayerData methods.

Enum CONST_DPGETFLAGS
    DPGET_LOCAL = 1
    DPGET_REMOTE = 0
End Enum
DPGET_LOCAL
Retrieve the local data set by this application.
DPGET_REMOTE
Retrieve the current data from the remote shared data space.

See Also

CONST_DPSETFLAGS


CONST_DPGROUPFLAGS

Members of the CONST_DPGROUPFLAGS enumeration are used in the DirectPlay4.CreateGroup and DirectPlay4.CreateGroupInGroup methods to specify the type of group being created, and are returned by the DirectPlay4.GetGroupFlags method.

Enum CONST_DPGROUPFLAGS
    DPGROUP_DEFAULT =        0
    DPGROUP_HIDDEN =      4096 (&H1000)
    DPGROUP_LOCAL =          8
    DPGROUP_STAGINGAREA = 2048 (&H800)
End Enum
DPGROUP_DEFAULT
The group has none of the following characteristics.
DPGROUP_HIDDEN
The group is hidden. In a lobby session, hidden groups are available only through shortcuts created with DirectPlay4.AddGroupToGroup. This flag works much like the DPPLAYER_SPECTATOR flag for players.
DPGROUP_LOCAL
The group was created by this application. If this flag is not specified, the group is a remote group.
DPGROUP_STAGINGAREA
The group is a staging area. A staging area is used to marshal players together in order to launch a new session.


CONST_DPIDFLAGS

Members of the CONST_DPIDFLAGS enumeration are used for special player IDs.

Enum CONST_DPIDFLAGS
    DPID_ALLPLAYERS   = 0
    DPID_SERVERPLAYER = 1
    DPID_SYSMSG       = 0
    DPID_UNKNOWN     = -1 (&HFFFFFFFF)
End Enum
DPID_ALLPLAYERS
Identifies a message sent to all players.
DPID_SERVERPLAYER
Identifies the server player. This ID is assigned to a player created with the DPPLAYER_SERVERPLAYER flag in DirectPlay4.CreatePlayer.
DPID_SYSMSG
Identifies a message sent by the system.
DPID_UNKNOWN
The sender or recipient of the message is ambiguous.


CONST_DPLAYERR

The members of the CONST_DPLAYERR enumeration represent DirectPlay error codes.


CONST_DPLCONNECTIONFLAGS

The members of the CONST_DPLCONNECTIONFLAGS enumeration are used in the flags of the DirectPlayLobbyConnection object.

Enum CONST_DPLCONNECTIONFLAGS
    DPLCONNECTION_CREATESESSION = 2
    DPLCONNECTION_JOINSESSION =   1
End Enum
DPLCONNECTION_CREATESESSION
Create a new session as described in the session description.
DPLCONNECTION_JOINSESSION
Join the existing session as described in the session description.

See Also

DirectPlayLobbyConnection.GetFlags, DirectPlayLobbyConnection.SetFlags


CONST_DPLMSG

The CONST_DPLMSG enumeration is used to identify messages sent to and received from the lobby.

Enum CONST_DPLMSG
    DPLMSG_STANDARD =    2
    DPLMSG_SYSTEM =      1
    DPLMSG_USERDEFINED = 0
End Enum
DPLMSG_STANDARD
This is a DirectPlay-defined message. Processing of this type of message is optional.
DPLMSG_SYSTEM
This is a DirectPlay-generated system message used to inform the lobby of changes in the status of the application it launched.
DPLMSG_USERDEFINED
The message is defined by the application.

See Also

DirectPlayLobby3.ReceiveLobbyMessage, DirectPlayLobby3.SendLobbyMessage


CONST_DPLWAIT

The CONST_DPLWAIT enumeration is used in the DirectPlayLobby3.WaitForConnectionSettings method.

Enum CONST_DPLWAIT
    DPLWAIT_CANCEL =  1
    DPLWAIT_DEFAULT = 0
End Enum
DPLWAIT_CANCEL
The method takes the application out of wait mode.
DPLWAIT_DEFAULT
The method puts the application into wait mode.


CONST_DPMESSAGEQUEUEFLAGS

Members of the CONST_DPMESSAGEQUEUEFLAGS enumeration are used with the DirectPlay4.GetMessageQueue method.

Enum CONST_DPMESSAGEQUEUEFLAGS
    DPMESSAGEQUEUE_RECEIVE = 2
    DPMESSAGEQUEUE_SEND =    1
End Enum
DPMESSAGEQUEUE_RECEIVE
Get information about the receive queue.
DPMESSAGEQUEUE_SEND
Get information about the send queue.


CONST_DPOPENFLAGS

Members of the CONST_DOPENFLAGS enumeration are used in the DirectPlay4.Open and DirectPlay4.SecureOpen methods to specify how the session is to be opened.

Enum CONST_DOPENFLAGS
    DPOPEN_CREATE =         2
    DPOPEN_JOIN =           1
    DPOPEN_RETURNSTATUS = 128 (&H80)
End Enum
DPOPEN_CREATE
Create a new instance of an application session. The local computer will be the name server and host of the session.
DPOPEN_JOIN
Join an existing instance of an application session for the purpose of participating. The application will be able to create players and send and receive messages. Cannot be combined with DPOPEN_CREATE.
DPOPEN_RETURNSTATUS
If this flag is specified, the method will not display any dialog boxes showing the connection progress status. If the connection cannot be made immediately, the method will return with the DPERR_CONNECTING error. The application must keep calling the method until it succeeds or some other error code is returned.


CONST_DPPLAYERFLAGS

Members of the CONST_DPPLAYERFLAGS enumeration are assigned to players in the DirectPlay4.CreatePlayer method, and can be retrieved by using DirectPlay4.GetPlayerFlags.

Enum CONST_DPPLAYERFLAGS
    DPPLAYER_LOCAL          = 8
    DPPLAYER_SERVERPLAYER = 256 (&H100)
    DPPLAYER_SPECTATOR    = 512 (&H200)
End Enum
DPPLAYER_LOCAL
The player was created by this application. If this flag is not specified, the player is a remote player.
DPPLAYER_SERVERPLAYER
The player is a server player for client/server communications.
DPPLAYER_SPECTATOR
The player was created as a spectator.


CONST_DPPLAYERTYPEFLAGS

Members of the CONST_DPPLAYERTYPEFLAGS enumeration are used in the DirectPlayEnumPlayers object and in various system messages to specify whether an item pertains to a player or a group.

Enum CONST_DPPLAYERTYPEFLAGS
    DPPLAYERTYPE_GROUP =  0
    DPPLAYERTYPE_PLAYER = 1
End Enum
DPPLAYERTYPE_GROUP
The item pertains to a group.
DPPLAYERTYPE_PLAYER
The item pertains to a player.


CONST_DPRECEIVEFLAGS

Members of the CONST_DPRECEIVEFLAGS enumeration are used to specify what types of messages are to be retrieved, and how.

Enum CONST_DPRECEIVEFLAGS
    DPRECEIVE_ALL =        1
    DPRECEIVE_FROMPLAYER = 4
    DPRECEIVE_PEEK =       8
    DPRECEIVE_TOPLAYER =   2
End Enum

For the meaning of the values, see DirectPlay4.Receive.


CONST_DPSENDFLAGS

Members of the CONST_DPSENDFLAGS enumeration are used to control the manner in which messages are sent.

Enum CONST_DPSENDFLAGS
    DPSEND_ASYNC =              512 (&H200)
    DPSEND_DEFAULT =              0
    DPSEND_ENCRYPTED =           64 (&H40)
    DPSEND_GUARANTEED =           1
    DPSEND_NOSENDCOMPLETEMSG = 1024 (&H400)
    DPSEND_SIGNED =              32 (&H20)
End Enum

For the meaning of the values, see DirectPlay4.Send and DirectPlay4.SendEx.


CONST_DPSESSIONFLAGS

Members of the CONST_DPSESSIONFLAGS enumeration are used to describe the characteristics of a session.

Enum CONST_DPSESSIONFLAGS
    DPSESSION_CLIENTSERVER       = 4096 (&H1000)
    DPSESSION_DIRECTPLAYPROTOCOL = 8192 (&H2000)
    DPSESSION_JOINDISABLED         = 32 (&H20)
    DPSESSION_KEEPALIVE            = 64 (&H40)
    DPSESSION_MIGRATEHOST           = 4
    DPSESSION_MULTICASTSERVER    = 2048 (&H800)
    DPSESSION_NEWPLAYERSDISABLED    = 1
    DPSESSION_NODATAMESSAGES      = 128 (&H80)
    DPSESSION_NOMESSAGEID           = 8
    DPSESSION_NOPRESERVEORDER   = 16384 (&H4000)
    DPSESSION_OPTIMIZELATENCY   = 32768 (&H8000)
    DPSESSION_PASSWORDREQUIRED   = 1024 (&H400)
    DPSESSION_PRIVATE             = 512 (&H200)
    DPSESSION_SECURESERVER        = 256 (&H100)
End Enum
DPSESSION_CLIENTSERVER
This is a client/server session that is being hosted by an application-server process. This flag must be specified at the time the session is created. Any clients that join this session will only be able to enumerate the server player and any local players. The host of the session will see all the players. If this flag is not set, the session is a peer-to-peer session. If this flag is set, the host can only create a server player. This flag cannot be used with DPSESSION_MIGRATEHOST.
DPSESSION_DIRECTPLAYPROTOCOL
This session should use the DirectPlay guaranteed protocol instead of the one implemented by the service provider. Use this flag if message throttling is desired (and you want the performance gains it provides).
DPSESSION_JOINDISABLED
No new applications can join this session. Any call to the DirectPlay4.Open method with the DPOPEN_JOIN flag and the globally unique identifier (GUID) of this session instance will cause an error. If this flag is not specified, new remote applications can join the session until the session player limit is reached.
DPSESSION_KEEPALIVE
This session will automatically detect when remote players drop out of the game abnormally. Those players will be deleted from the session. If a temporary network outage caused the loss of the players, they will be informed by a DPSYS_SESSIONLOST system message when they return that they were dropped from the session. This flag must be specified at the time the session is created. If this flag is not specified, DirectPlay will not automatically keep the session alive if players are abnormally terminated.
DPSESSION_MIGRATEHOST
If the current host exits, another computer in the session will become the host. The players on the new host computer will receive a DPSYS_HOST system message. This flag must be specified at the time the session is created. If this flag is not specified, the host will not migrate, new computers cannot join the session, and new players cannot be created if the current host leaves. Note that the DPSESSION_MIGRATEHOST flag cannot be combined with the DPSESSION_CLIENTSERVER, DPSESSION_MULTICASTSERVER, or DPSESSION_SECURESERVER flags.
DPSESSION_MULTICASTSERVER
In a peer-to-peer session, broadcast and group messages are routed through the host that acts like a multicast server. This flag must be specified at the time the session is created. The flag is only useful if the host has a high bandwidth connection to the network. If this flag is not specified, broadcast and group messages are sent directly between peers. This flag cannot be used with DPSESSION_MIGRATEHOST.
DPSESSION_NEWPLAYERSDISABLED
New players cannot be created in the session. Any call to the DirectPlay4.CreatePlayer method by an application in the session will result in an error. Also, new applications cannot join the session. If this flag is not specified, players can be created until the session player limit is reached.
DPSESSION_NODATAMESSAGES
The session does not send system messages when remote player data, group data, or session data is changed by the DirectPlay4.SetPlayerData, DirectPlay4.SetGroupData, DirectPlay4.SetPlayerName, DirectPlay4.SetGroupName, or DirectPlay4.SetSessionDesc method. If this flag is not specified, messages will be generated that indicate that the data changed.

Note that setting this flag also suppresses the DPSYS_SETSESSIONDESC system message.

DPSESSION_NOMESSAGEID
Specifies that the session does not attach data to messages that indicate which player the message is from and to whom it is sent. Setting this flag saves message overhead if this information is not relevant. If this flag is not specified, the message ID will be added. This flag must be specified at the time the session is created.
DPSESSION_NOPRESERVEORDER
Specifies that this session does not preserve the order in which guaranteed messages are received. By default, the receive order of guaranteed messages is preserved. If the order is not needed, this flag can be used to eliminate possible delays in delivery.
DPSESSION_OPTIMIZELATENCY
Asks the service provider to optimize for latency (which turns off nagling in TCP/IP). The default is to optimize for bandwidth.
DPSESSION_PASSWORDREQUIRED
Specifies that this session is password-protected. Any applications wishing to join the session must supply the password in the DirectPlay4.Open call. This is a read-only flag. It will be set automatically by DirectPlay when the host of the session specifies a password.
DPSESSION_PRIVATE
Specifies that this is a private session. It cannot respond to enumeration requests unless the request contains a non-NULL, matching password. If this flag is not specified, the session will respond to enumeration requests.
DPSESSION_SECURESERVER
Specifies that this session is being hosted on a secure server that will require authentication credentials before it can be opened. The host must specify this flag when the session is created. It cannot be changed later through DirectPlay4.SetSessionDesc. This flag cannot be combined with the DPSESSION_MIGRATEHOST flag.

Remarks

The following flags cannot be changed once the session has started:

DPSESSION_CLIENTSERVER
DPSESSION_DIRECTPLAYPROTOCOL
DPSESSION_KEEPALIVE
DPSESSION_MIGRATEHOST
DPSESSION_MULTICASTSERVER
DPSESSION_NOMESSAGEID
DPSESSION_OPTIMIZELATENCY
DPSESSION_SECURESERVER

The following flags can be set by using DirectPlay4.SetSessionDesc, but only by the host:

DPSESSION_JOINDISABLED
DPSESSION_NEWPLAYERSDISABLED
DPSESSION_NODATAMESSAGES
DPSESSION_NOPRESERVEORDER
DPSESSION_PASSWORDREQUIRED
DPSESSION_PRIVATE


CONST_DPSETFLAGS

Members of the CONST_DPSETFLAGS enumeration are used to determine what data is set by the DirectPlay4.SetGroupData, DirectPlay4.SetGroupName, DirectPlay4.SetPlayerData, and DirectPlay4.SetPlayerName methods.

Enum CONST_DPSETFLAGS
    DPSET_GUARANTEED = 2
    DPSET_LOCAL = 1
    DPSET_REMOTE = 0
End Enum
DPSET_GUARANTEED
Propagate the data by using guaranteed messaging (if available). This flag cannot be combined with DPSET_LOCAL.
DPSET_LOCAL
This data is for local use only and will not be propagated.
DPSET_REMOTE
This data is for use by all the applications and will be propagated to all the other applications in the session. For groups, this flag can be used only on groups owned by the local session.

See Also

CONST_DPGETFLAGS


CONST_DPSYSMSGTYPES

The members of the CONST_DPSYSMSGTYPES enumeration are used to identify the different kinds of system messages and lobby messages. Every DirectPlayMessage object that represents a system or lobby message will return one of these constants from the first call to DirectPlayMessage.ReadLong. It is up to the application to determine the message type and then parse any further data by using appropriate calls to the various read methods of DirectPlayMessage.

Two lobby messages, DPLSYS_GETPROPERTY and DPLSYS_SETPROPERTY, are sent by the application rather than by the system. The application must write the type identifier and the rest of the data to the message using the appropriate write methods of DirectPlayMessage.

It is important that applications deal separately with ordinary system messages and lobby messages. Some lobby and nonlobby messages share the same value (for example, DPLSYS_SETPROPERTY and DPSYS_DESTROYPLAYERORGROUP). It would be unwise, therefore, to send all messages to a common handler without any information about whether they were lobby or nonlobby messages.

Enum CONST_DPSYSMSGTYPES
    DPLSYS_APPTERMINATED =          4
    DPLSYS_CONNECTIONSETTINGSREAD = 1
    DPLSYS_DPLAYCONNECTFAILED =     2
    DPLSYS_DPLAYCONNECTSUCCEEDED =  3
    DPLSYS_GETPROPERTY =            7
    DPLSYS_GETPROPERTYRESPONSE =    8
    DPLSYS_NEWCONNECTIONSETTINGS = 10
    DPLSYS_NEWSESSIONHOST =         9
    DPLSYS_SETPROPERTY =            5
    DPLSYS_SETPROPERTYRESPONSE  =   6
    DPSYS_ADDGROUPTOGROUP =       261 (&H105)
    DPSYS_ADDPLAYERTOGROUP =        7
    DPSYS_CHAT =                  265 (&H109)
    DPSYS_CREATEPLAYERORGROUP =     3
    DPSYS_DELETEGROUPFROMGROUP =  262 (&H106)
    DPSYS_DELETEPLAYERFROMGROUP =  33 (&H21)
    DPSYS_DESTROYPLAYERORGROUP =    5
    DPSYS_HOST =                  257 (&H101)
    DPSYS_SECUREMESSAGE =         263 (&H107)
    DPSYS_SENDCOMPLETE =          269 (&H10D)
    DPSYS_SESSIONLOST =            49 (&H31)
    DPSYS_SETGROUPOWNER =         266 (&H10A)
    DPSYS_SETPLAYERORGROUPDATA =  258 (&H102)
    DPSYS_SETPLAYERORGROUPNAME =  259 (&H103)
    DPSYS_SETSESSIONDESC =        260 (&H104)
    DPSYS_STARTSESSION =          264 (&H108)
End Enum

The following descriptions include lists of any extra data members in each message type, in the order in which they occur in the underlying structure. (For more information on the underlying C/C++ structures, see System Messages.) It is assumed that the application has already extracted the message type by using ReadLong.

If the message data consisted of a Long followed by a GUID, your application would parse the data by calling first DirectPlayMessage.ReadLong and then DirectPlayMessage.ReadGuid. In cases where the underlying structure contains a pointer to a buffer, you must use a special method such as DirectPlayMessage.ReadSysChatString in order to get the data from the buffer.

Standard Lobby Messages
DPLSYS_APPTERMINATED
The application started by DirectPlayLobby3.RunApplication has terminated.
GUID
Unique identifier of the session to which this lobby message applies.
DPLSYS_CONNECTIONSETTINGSREAD
The application started by the DirectPlayLobby3.RunApplication method has read the connection settings.
GUID
Unique identifier of the session to which this lobby message applies.
DPLSYS_DPLAYCONNECTFAILED
The application started by DirectPlayLobby3.RunApplication failed to connect to a session.
GUID
Unique identifier of the session to which this lobby message applies.
DPLSYS_DPLAYCONNECTSUCCEEDED
The application started by DirectPlayLobby3.RunApplication has created a session and is ready for other applications to join or has successfully joined a session.
GUID
Unique identifier of the session to which this lobby message applies.
DPLSYS_GETPROPERTY
Message sent by an application to the lobby to request the current value of a property.
Long
Application-generated ID to identify the request. The lobby's response will be tagged with this ID. The application can use the request ID to match responses to pending requests.
GUID
Unique identifier of the player that this property applies to (if applicable). If the property is not player-specific, this member should be set to an empty string.
GUID
Unique identifier of the property that is being requested. DirectPlay defines certain properties. The application or lobby can define its own GUIDs for additional properties. For more information, see DirectPlay Defined Properties in the C++ reference for DirectPlay.
DPLSYS_GETPROPERTYRESPONSE
Message sent by the lobby to the application in response to a DPLSYS_GETPROPERTY message.
Long
ID of the request being responded to.
GUID
Unique identifier of the player that this property applies to. If the property is not player-specific, this member will be set to an empty string. This is the same value as was given in the DPLSYS_GETPROPERTY message.
GUID
Unique identifier of the property that is being requested. This is the same value as was given in the DPLSYS_GETPROPERTY message.
Long
Return code for the get property request. Zero if the request was successful, or one of the following values otherwise:

DPERR_UNKNOWNMESSAGE

DPERR_UNAVAILABLE

Long
Size of the data, in bytes. This value is followed by a variable-size buffer that contains the property data. The property tag determines how this data should be read and interpreted. For more information, see DirectPlay Defined Properties in the C++ reference for DirectPlay.
DPLSYS_NEWCONNECTIONSETTINGS
Lobby system message. A waiting application was found when a lobby client called DirectPlayLobby3.RunApplication.The waiting application can now read the connection settings by using DirectPlayLobby3.GetConnectionSettings.
GUID
Unique identifier of the session to which this lobby message applies.
DPLSYS_NEWSESSIONHOST
Message sent by the lobby to the application instance that has become the new session host.
GUID
Unique identifier of this instance.
DPLSYS_SETPROPERTY
Message sent by an application to the lobby to set the value of a property.
Long
Application-generated ID to identify the request. The lobby's response will be tagged with this ID. The application can use the request ID to match responses to pending requests.
GUID
Unique identifier of the player that this property applies to. If the property is not player-specific, this member should be set to an empty string.
GUID
Unique identifier of the property that is being requested. DirectPlay defines certain properties. The application or lobby can define its own GUIDs for additional properties.
Long
Size of the data, in bytes. This value is followed by a variable-size buffer that contains the property data. The property tag determines how the data is organized and should be written. For example, for the DPLPROPERTY_PlayerScore property, you would call DirectPlayMessage.WriteLong once to record the number of scores, and then again for each score. For more information, see DirectPlay Defined Properties in the C++ reference for DirectPlay.
DPLSYS_SETPROPERTYRESPONSE
Message sent by the lobby to the application in response to a DPLSYS_SETPROPERTY message.
Long
ID of the request being responded to.
GUID
Unique identifier of the player that this property applies to (if applicable). If the property is not player-specific, this member will be set to an empty string. This is the same value as was given in the DPLSYS_SETPROPERTY message.
GUID
Unique identifier of the property that is being requested. This is the same value as was given in the DPLSYS_SETPROPERTY message.
Long
Return code for the set property request. Zero if the request was successful, or one of the following values otherwise:

DPERR_ACCESSDENIED

DPERR_UNKNOWNMESSAGE

Nonlobby System Messages
DPSYS_ADDGROUPTOGROUP
A group has been added to a group.
Long
ID of the group to which the group was added.
Long
ID of the group that was added to the group.
DPSYS_ADDPLAYERTOGROUP
A player has been added to a group.
Long
ID of the group to which the player was added.
Long
ID of the player that was added to the group.
DPSYS_CHAT
The message is a chat string transmitted through the lobby.
Long
Flags. Always 0.
Long
ID of the player from whom the message originated. DPID_SERVERPLAYER indicates the message originated from the server.
Long
ID of the player to whom the message was directed. If this ID is 0, then the message was sent to a group or broadcast to everyone.
Long
ID of the group to whom the message was directed. If this ID is 0 and the previous Long is also 0, then the message was broadcast to everyone.
Long
Pointer to the chat string. Read this string by using the DirectPlayMessage.ReadSysChatString method.
DPSYS_CREATEPLAYERORGROUP
A player or group was created.
Long
Flag indicating whether a player (DPPLAYERTYPE_PLAYER) or a group (DPPLAYERTYPE_GROUP) was created.
Long
ID of player or group created.
Long
Number of players in the session before this player was created.
Long (2)
Pointer to, and size of, a buffer containing local data for the group. The contents of this buffer are retrieved by using the DirectPlayMessage.ReadSysMsgData method.
Long (2)
Pointer to, and size of, a buffer containing remote data for the group. The contents of this buffer are retrieved by using ReadSysMsgData.
Long
Size of the underlying name structure, in bytes. Can be discarded.
Long
Flags for the name structure. Always 0.
String
Short name of the group.
String
Long name of the group.
Long
ID of the parent group if the group was created by a call to DirectPlay4.CreateGroupInGroup. Otherwise the value is 0.
Long
Player or group flags. Can be 0 or DPGROUP_HIDDEN (see CONST_DPGROUPFLAGS).
DPSYS_DELETEGROUPFROMGROUP
A group was removed from a group.
Long
ID of the group from which the group was removed.
Long
ID of the group that was removed.
DPSYS_DELETEPLAYERFROMGROUP
A player was removed from a group.
Long
ID of the group from which the player was removed.
Long
ID of the player that was removed.
DPSYS_DESTROYPLAYERORGROUP
A player or group was destroyed.
Long
Flag indicating whether a player (DPPLAYERTYPE_PLAYER) or a group (DPPLAYERTYPE_GROUP) was destroyed.
Long
ID of player or group that has been destroyed.
Long (2)
Pointer to, and size of, a buffer containing local data for the group. The contents of this buffer are retrieved by using the DirectPlayMessage.ReadSysMsgData method.
Long (2)
Pointer to, and size of, a buffer containing remote data for the group. The contents of this buffer are retrieved by using ReadSysMsgData.
Long
Size of the underlying name structure, in bytes. Can be discarded.
Long
Flags for the name structure. Always 0.
String
Short name of the group.
String
Long name of the group.
Long
ID of the parent group if the group being destroyed is a subgroup of the parent group—that is, the group being destroyed was created by a call to DirectPlay4.CreateGroupInGroup. Otherwise the value is 0.
Long
Player or group flags. Can contain one or more of the following values from the CONST_DPGROUPFLAGS enumeration:

DPGROUP_HIDDEN

Set when a hidden group is destroyed.

DPGROUP_STAGINGAREA

Set when a group that is a staging area is destroyed.

DPPLAYER_SERVERPLAYER

Set when the player being destroyed is a server player for client/server communications.

DPPLAYER_SPECTATOR

Set when the player destroyed is a spectator.

DPSYS_HOST
The player receiving the message is now the session host. This message contains no extra data.
DPSYS_SECUREMESSAGE
A signed or encrypted message has been received from another player.
Long
Flag indicating how the message was secured by the sender. One of the following values from the CONST_DPSENDFLAGS enumeration:

DPSEND_SIGNED

The message was signed by the sender and the signature was successfully verified.

DPSEND_ENCRYPTED

The message was encrypted by the sender and successfully decrypted.

Long
ID of the player who sent the message.

To read the decrypted message, use the DirectPlayMessage.MoveToSecureMessage method to move the read pointer to the beginning of the data buffer. Read the data by using the standard read methods of DirectPlayMessage.

DPSYS_SENDCOMPLETE
Message sent to an application to inform it of the completion status of an asynchronous send. This message is generated by default whenever an asynchronous message is sent using the DPSEND_ASYNC flag in DirectPlay4.SendEx.
Long
ID of the player who sent the message.
Long
ID of the player the message was sent to.
Long
Flags specified in SendEx when the message was sent.
Long
Priority that the message was sent at.
Long
Time-out specified when the message was sent (specified in SendEx). Zero indicates the default time-out.
Long
The context parameter supplied by the application to SendEx.
Long
Message ID returned to the application by SendEx.
Long
Result of the asynchronous message. Zero if the message was successfully sent, or one of the following error codes:

DPERR_ABORTED

The message was canceled while it was being transmitted.

DPERR_CANCELLED

The message was canceled while it was still in the send queue.

DPERR_GENERIC

The message could not be sent.

DPERR_TIMEOUT

The message timed out and was removed from the send queue.

Long
The elapsed time, in milliseconds, between the time the message was sent by the application and the time DirectPlay was able to send the message. This includes the time spent in the send queue and the time to hand the message off to the service provider. For guaranteed messages, this also includes the time to acknowledge delivery of the message.
DPSYS_SESSIONLOST
The connection to all the other players in the session was lost. After the session is lost, messages cannot be sent to remote players, but all data at the time the session was lost is still available. The application should try to recover gracefully and exit if this message is received. The message contains no extra data.
DPSYS_SETGROUPOWNER
The owner of a group has changed. Group ownership can be changed by the current owner leaving the session, by a call to DirectPlay4.SetGroupOwner, or, arbitrarily, by the lobby server in a lobby session.
Long
ID of the group whose owner changed.
Long
Player ID of the new owner of the group.
Long
Player ID of the old owner of the group.
DPSYS_SETPLAYERORGROUPDATA
DirectPlay generates this message and sends it to each player when the remote data of a player or group changes. This message will not be generated if the DPSESSION_NODATAMESSAGES flag is specified in the session description.
Long
Identifies whether the message applies to a player (DPPLAYERTYPE_PLAYER) or a group (DPPLAYERTYPE_GROUP).
Long
ID of the player or group whose data changed.
Long (2)
Pointer, and size of, a buffer containing application-specific data. The contents of this buffer are retrieved by using the DirectPlayMessage.ReadSysMsgData method.
DPSYS_SETPLAYERORGROUPNAME
DirectPlay generates this message and sends it to each local player on the computer when the name of a player or group changes. This message will not be generated if the DPSESSION_NODATAMESSAGES flag is specified in the session description.
Long
Identifies whether the message applies to a player (DPPLAYERTYPE_PLAYER) or a group (DPPLAYERTYPE_GROUP).
Long
ID of the player or group whose name changed.
Long
Size of the underlying name structure. Can be discarded.
Long
Flags. Always 0.
String
New short name of the player or group.
String
New long name of the player or group.
DPSYS_SETSESSIONDESC
Every player receives this system message when the session description changes. The new session description can be obtained by using DirectPlayMessage.ReadSysMsgSessionDesc.
DPSYS_STARTSESSION
The lobby server sends this message to each player in a group when it is time for that player to join an application session. The connection data can be retrieved by using the DirectPlayMessage.ReadSysMsgConnection method.


Error Codes

This section lists the values that can be returned by DirectPlay class methods. For a list of the error codes each method can return, see the individual method descriptions.

DirectPlay error constants are members of the CONST_DPLAYERR enumeration.

DP_OK
The request completed successfully.
DPERR_ABORTED
The operation was canceled before it could be completed.
DPERR_ACCESSDENIED
The session is full, or an incorrect password was supplied.
DPERR_ACTIVEPLAYERS
The requested operation cannot be performed because there are existing active players.
DPERR_ALREADYINITIALIZED
This object is already initialized.
DPERR_APPNOTSTARTED
The application has not been started yet.
DPERR_AUTHENTICATIONFAILED
The password or credentials supplied could not be authenticated.
DPERR_BUFFERTOOLARGE
The data buffer is too large to store.
DPERR_BUFFERTOOSMALL
The supplied buffer is not large enough to contain the requested data.
DPERR_BUSY
A message cannot be sent because the transmission medium is busy.
DPERR_CANCELFAILED
The message could not be canceled, possibly because it is a group message that has already been to sent to one or more members of the group.
DPERR_CANCELLED
The operation was canceled.
DPERR_CANNOTCREATESERVER
The server cannot be created for the new session.
DPERR_CANTADDPLAYER
The player cannot be added to the session.
DPERR_CANTCREATEGROUP
A new group cannot be created.
DPERR_CANTCREATEPLAYER
A new player cannot be created.
DPERR_CANTCREATEPROCESS
Cannot start the application.
DPERR_CANTCREATESESSION
A new session cannot be created.
DPERR_CANTLOADCAPI
No credentials were supplied and the CryptoAPI package (CAPI) to use for cryptography services cannot be loaded.
DPERR_CANTLOADSECURITYPACKAGE
The software security package cannot be loaded.
DPERR_CANTLOADSSPI
No credentials were supplied, and the Security Support Provider Interface (SSPI) that will prompt for credentials cannot be loaded.
DPERR_CAPSNOTAVAILABLEYET
The capabilities of the DirectPlay object have not been determined yet. This error will occur if the DirectPlay object is implemented on a connectivity solution that requires polling to determine available bandwidth and latency.
DPERR_CONNECTING
The method is in the process of connecting to the network. The application should keep using the method until it returns DP_OK, indicating successful completion, or until it returns a different error.
DPERR_CONNECTIONLOST
The service provider connection was reset while data was being sent.
DPERR_ENCRYPTIONFAILED
The requested information could not be digitally encrypted. Encryption is used for message privacy. This error is only relevant in a secure session.
DPERR_EXCEPTION
An exception occurred when processing the request.
DPERR_GENERIC
An undefined error condition occurred.
DPERR_INVALIDFLAGS
The flags passed to this method are invalid.
DPERR_INVALIDGROUP
The group ID is not recognized as a valid group ID for this game session.
DPERR_INVALIDINTERFACE
The interface parameter is invalid.
DPERR_INVALIDOBJECT
The DirectPlay object is invalid.
DPERR_INVALIDPARAMS
One or more of the parameters passed to the method are invalid.
DPERR_INVALIDPASSWORD
An invalid password was supplied when attempting to join a session that requires a password.
DPERR_INVALIDPLAYER
The player ID is not recognized as a valid player ID for this game session.
DPERR_INVALIDPRIORITY
The specified priority is not within the range of allowed priorities, which is inclusively 0-65535.
DPERR_LOGONDENIED
The session could not be opened because credentials are required, and either no credentials were supplied, or the credentials were invalid.
DPERR_NOCAPS
The communication link that DirectPlay is attempting to use is not capable of this function.
DPERR_NOCONNECTION
No communication link was established.
DPERR_NOINTERFACE
The interface is not supported.
DPERR_NOMESSAGES
There are no messages in the receive queue.
DPERR_NONAMESERVERFOUND
No name server (host) could be found or created. A host must exisglosate a player.
DPERR_NONEWPLAYERS
The session is not accepting any new players.
DPERR_NOPLAYERS
There are no active players in the session.
DPERR_NOSESSIONS
There are no sessions for which this method can be called.
DPERR_NOTLOBBIED
Returned by the DirectPlayLobby3.Connect method if the application was not started by using the DirectPlayLobby3.RunApplication method, or if there is no DirectPlayLobbyConnection interface currently initialized for this DirectPlayLobby object.
DPERR_NOTLOGGEDIN
An action cannot be performed because a player or client application is not logged on. Returned by the DirectPlay4.Send method when the client application tries to send a secure message without being logged on.
DPERR_OUTOFMEMORY
There is insufficient memory to perform the requested operation.
DPERR_PENDING
Not an error, this return indicates that an asynchronous send has reached the point where it is successfully queued. See SendEx for more information.
DPERR_PLAYERLOST
A player has lost the connection to the session.
DPERR_SENDTOOBIG
The message being sent by the DirectPlay4.Send method is too large.
DPERR_SESSIONLOST
The connection to the session has been lost.
DPERR_SIGNFAILED
The requested information could not be digitally signed. Digital signatures are used to establish the authenticity of messages.
DPERR_TIMEOUT
The operation could not be completed in the specified time.
DPERR_UNAVAILABLE
The requested function is not available at this time.
DPERR_UNINITIALIZED
The requested object has not been initialized.
DPERR_UNKNOWNAPPLICATION
An unknown application was specified.
DPERR_UNKNOWNMESSAGE
The message ID isn't valid. Returned from DirectPlay4.CancelMessage if the ID of the message to be canceled is invalid.
DPERR_UNSUPPORTED
The function or feature is not available in this implementation or on this service provider. Returned from DirectPlay4.SetGroupConnectionSettings if this method is called from a session that is not a lobby session. Returned from DirectPlay4.SendEx if the priority or time-out is set, and these are not supported by the service provider and DirectPlay protocol is not on. Returned from DirectPlay4.GetMessageQueue if you check the send queue and it is not supported by the service provider and DirectPlay protocol is not on.
DPERR_USERCANCEL
Can be returned in two ways. 1) The user canceled the connection process during a call to the DirectPlay4.Open method. 2) The user clicked Cancel in one of the DirectPlay service provider dialog boxes during a call to DirectPlay4.GetDPEnumSessions.


DirectPlay Tools and Samples

This section describes sample applications included with the DirectX SDK that demonstrate the use of DirectPlay, as well as tools that you can use in testing your applications. Descriptions are organized as follows:

  • DirectPlay Tools
  • DirectPlay C++ Samples
  • DirectPlay Visual Basic Samples


DirectPlay Tools

The following tools can be used for testing DirectPlay applications written in either C++ or Visual Basic:

  • DirectPlay Simulator
  • Lobby Server


DirectPlay Simulator

Description

The DirectPlay Simulator tool provides a simulated environment for testing the robustness of network applications. It can simulate low-bandwidth or high-latency connections over a high-speed local area network and can generate random or programmed message transmission failures.

Path

Executable and DLL: (SDK root)\Samples\Multimedia\DPlay\Bin

DPSimcfg.exe is used to configure the tool. The functionality of the tool is in DPSim.dll, which must be copied to the Windows system directory.

User's Guide

DPSimcfg.exe is used to configure the registry parameters used by DirectPlay Simulator and to activate or deactivate it by adding or removing the service provider registry entry. When active, the simulator can be selected from the list of service providers. It is implemented over the TCP/IP service provider.

Click the arrow buttons to cycle through the following modes of operation:

  • Drop no packets.
  • Randomly drop n% of packets. Set the percentage with the slider bar.
  • Drop 1 of every n packets. Set the value of n with the slider bar.
  • Drop packets according to a pattern. In the text box, enter a series of numbers representing the number of packets passed, the number dropped, the number passed, and so on, with each number followed by a comma or space. The pattern will repeat itself when the end of the sequence is reached.

Packet dropping can be specified not to occur until a certain period (in milliseconds) after communication starts, and it can be specified to last for a certain period ( in milliseconds). These periods are defined by entering values in the Start After and Stop After text boxes. If Stop After is zero, packet dropping will continue indefinitely.

Select the Drop Guaranteed check box in order to have guaranteed messages dropped as well.

Select the Latency option button in order to introduce latency to both sent messages and received messages. Set the latency, in milliseconds, by using the slider bars. Each latency can also have a +/- variance range, evenly distributed.

Note For fine adjustment of the slider controls, you can click on the slider controls and use the arrow keys to increase or decrease the value.

To choose a simulated bandwidth instead of latency, select the Bandwidth option button and enter a baud rate in the text boxes, or choose one by clicking on the arrow buttons.

Click Activate to make DirectPlay Simulator available as a service provider.


Lobby Server

Description

The Lobby Server application creates a lobby session and allows users on different computers to communicate by using a lobby client such as the Bellhop sample.

Path

Executable: (SDK root)\Samples\Multimedia\DPlay\Bin\LServer.exe

User's Guide

To initialize the lobby server in its default mode, select the Server menu, and choose Start. Enter a name for the lobby session. The lobby server will create several default top-level groups. Users will only be allowed to create subgroups within the top-level groups, staging areas, or shortcuts to staging areas.

For your convenience, the lobby server application also provides a test mode in which no top-level groups are automatically created. Users are free to create any group hierarchy they want, to any depth. If you want to set the lobby server into test mode, you must do so before you select Start from the Server menu. To set the lobby server into test mode, choose Test Mode from the Server menu. You can now start the lobby server in test mode by choosing Start.

If you choose Secure Mode in the Server menu before selecting Start and the lobby server is running on Windows NT 4.0 or Windows 2000, the lobby server will require clients to log in.

The lobby server will ask which service provider to use. All clients connecting to the server will need to select this same service provider. You will then be asked to provide a name for the lobby server session.


DirectPlay C++ Samples

[Visual Basic]

This section pertains only to application development in C++. See DirectPlay Visual Basic Samples.

[C++]

The following samples, provided with C++ source code, show how to use DirectPlay:

  • Bellhop Sample
  • ChatConnect Sample
  • DPLaunch Sample
  • DPSlots Sample
  • Duel Sample
  • Override Sample
  • SimpleConnect Sample
  • StagedConnect Sample


Bellhop Sample

[Visual Basic]

This topic pertains only to application development in C++. See DirectPlay Visual Basic Samples.

[C++]

Description

The Bellhop sample is a lobby client program that uses the IDirectPlay4 interface to communicate with a lobby server. The Lobby Server application must be running in order for Bellhop to work.

Bellhop can be used to test lobby support in your application.

Path

Source: (SDK root)\Samples\Multimedia\DPlay\Src\Bellhop

Executable: (SDK root)\Samples\Multimedia\DPlay\Bin\Bellhop.exe

User's Guide

After launching Bellhop, you are asked to select a lobby provider. If the Lobby Server application is running, choose Lobby Connection for DirectPlay.

You are presented with a dialog asking you to select a service provider. The sample lobby server and lobby provider are capable of operating over any network supported by DirectPlay. Select an appropriate service provider (such as TCP/IP), and choose OK.

With a TCP/IP connection, you are prompted for the address of the lobby server. You can leave this blank to try to find the address on your local network. Alternatively, you can enter the computer name or IP address. When the lobby session name is displayed, join it as either a player or spectator. (There is no practical difference, because the application treats players and spectators in the same way.)

If the lobby server is not being run in test mode, you see several doors representing groups, or rooms. Double-click on one of the doors. You see a character that represents you in the virtual gaming environment. To join another group without leaving the first, double-click the doorway you wish to enter. To leave any room, right-click on the player icon and choose Delete Player From Group. To leave one room and enter another at the same time, you can drag and drop the icon representing your player.

You see the contents only of rooms you have joined. Once you leave a room, all the doorways (subgroups) and players in that room disappear.

Bellhop provides context-sensitive menus. If you right-click on a player or group, you see the options available for that specific item. If you right-click on the background, you can choose to refresh its display. Bellhop will re-enumerate all the groups and players that are available to you.

When you want to create a subgroup or staging area in an existing room, right-click the folder. In the menu that appears, select Create Group In Group. If you choose to create a staging area, you need to select which game to play from the list box. Only applications registered with DirectPlay are shown. Any other applications that may be running on the network are ignored. In addition to selecting a game, you must choose which connection will be used to launch the game. You can optionally specify a password for the session and the maximum number of players.

If you want to join a staging area, you can right-click on its icon and select Connection Settings in the menu that appears. Bellhop shows you properties of the staging area. You can modify these settings.

To start a game from a staging area, right-click on the staging area icon and select Start Session. This will launch the application on the machines of all the people in the staging area and connect them together in a session. If you move into the staging area after the session has started, select Start Session to join the session in progress. When a session is in progress, the icon changes from a green triangle to a red and black triangle.

To change the name of local groups or players, right-click the group or player and select Set Group Name or Set Player Name. Alternatively, you can simply click on the text of the group or player name.

To send a chat message to other players in the same room, enter the text in the text box at the bottom of the screen and click Send.


ChatConnect Sample

[Visual Basic]

This topic pertains only to application development in C++. See DirectPlay Visual Basic Samples.

[C++]

Description

The ChatConnect sample is a chat program that can be launched from a lobby.

Path

Source: (SDK root)\Samples\Multimedia\DPlay\Src\ChatConnect

Executable: (SDK root)\Samples\Multimedia\DPlay\Bin\ChatConnect.exe.

User's Guide

Enter the player's name, and select a connection type or "Wait for Lobby Connection" from the list. In the Multiplayer Games dialog, start a new session by clicking Create, or else click Start Search to find active sessions, then join one by highlighting it and clicking Join. After a session has been joined or created, the chat begins immediately. Other players can join the chat at any time. The host player can leave at any time, because DirectPlay automatically migrates the host player.

Note that you can test multiple instances of the sample on a single machine by using the TCP/IP service provider.

Programming Notes

This sample shows the basics of using DirectPlay for a chat session.


DPLaunch Sample

[Visual Basic]

This topic pertains only to application development in C++. See DirectPlay Visual Basic Samples.

[C++]

Description

The DPLaunch sample is a stand-alone application that demonstrates how a DirectPlay application can be launched from an external source using the IDirectPlayLobby3 interface. It can also be be used to test the lobby support in your application.

Path

Source: (SDK root)\Samples\Multimedia\DPlay\Src\DPLaunch

Executable: (SDK root)\Samples\Multimedia\DPlay\Bin\DPLaunch.exe

User's Guide

When you run it, DPLaunch presents you with a pull-down list of all registered DirectPlay applications on your computer. Once you choose which application to start, you must also select the connection method, and specify your player name. In addition, you need to pick a session name, and specify whether you are joining an existing session or creating a new one.


DPSlots Sample

[Visual Basic]

This topic pertains only to application development in C++. See DirectPlay Visual Basic Samples.

[C++]

Description

The DPSlots sample is a client/server slot machine simulator that uses security features of DirectPlay.

The server controls all the slot machines and tracks how much money each player has. The client securely logs on to the server.

Path

Source: (SDK root)\Samples\Multimedia\DPlay\Src\DPSlots

Executable: (SDK root)\Samples\Multimedia\DPlay\Bin\DPSlots.exe

User's Guide

DPSlots is really two applications in one. When you host a session, it acts as a server. When you join a session, it acts as a client.

The server maintains a simple database of account balances for every user allowed to log on. Clients can request their current balance from the server. They can also request that the server spin the wheels and calculate the amount won or lost. The server maintains a simple text database called Slotsdb.txt that records the balance for each user. Each line of the text file contains the user account ID and a 8-character balance figure separated by a comma, as shown in the following example.

Account1,    1000
Account2,     500

You need to add lines manually to this file for each user, entering the network user names in place of "Account1" and so on.

When you join a session, DPSlots acts as a client and sends messages to the server for all operations. The client can be required to log the user onto the server using a name and password.

DPSlots can be hosted using security by clicking the Require Secure Login checkbox after choosing to host. If you leave the Security Provider text box blank, the default NTLM security package is used. If you have an alternate SSPI security package installed, it can be specified here.

Once you have a security provider, the server will host a secure session. Clients have to securely log on with a user name and a password before being allowed to join the session. All messages between the client and server are digitally signed and encrypted.

When hosting a secure server, the account ID for each user is defined by the security package being used. This account ID must be stored in the database file along with the appropriate balance. The default security package is NTLM, which uses a domain and a user name for the account ID. If, for example, you use NTLM, your domain is "GAMES", and you have two users "Bob" and "Jane", your database file would be as shown in the following example.

GAMES/Bob,    1000
GAMES/Jane,    500

Currently you can only host a secure session using NTLM on a Windows NT or Windows 2000 workstation or server.


Duel Sample

[Visual Basic]

This topic pertains only to application development in C++. See DirectPlay Visual Basic Samples.

[C++]

Description

The Duel sample is a multiplayer game that can be launched from a lobby. As well as demonstrating the use of DirectPlay, it uses DirectDraw, DirectInput, and DirectSound.

Path

Source: (SDK root)\Samples\Multimedia\DPlay\Src\Duel

Executable: (SDK root)\Samples\Multimedia\DPlay\Bin\Duel.exe

User's Guide

Press ENTER to begin. You can then choose to host a new game or join an existing game.

All players in the game are represented by a small spaceship in an asteroid field. Use the left and right arrows to turn the ship left and right. The up arrow accelerates your ship forward. The down arrow accelerates it backward. Press the spacebar to fire. To exit the game, press ESC or F12.

Although it is possible to run multiple instances of the program on a single computer by using the TCP/IP connection, only the foreground instance will be updated.

To play using TCP/IP over the Internet, users who are joining the game must enter the IP address of the machine that hosted the game. A Windows 95 or Windows 98 user can determine the local IP address by running Winipcfg.exe. In Windows 2000 the same can be done by running Ipconfig.exe. If the user is connected to both a LAN and a dial-up Internet service provider (ISP), the computer can have two IP addresses, and the correct one must be selected for that connection. Most dial-up ISPs assign a dynamic IP address that changes each time the user logs on.

The game will not work through proxies or firewalls.


Override Sample

[Visual Basic]

This topic pertains only to application development in C++. See DirectPlay Visual Basic Samples.

[C++]

Description

The Override sample is a simple demonstration of how to override the DirectPlay service provider dialogs.

Path

Source: (SDK root)\Samples\Multimedia\DPlay\Src\Override

Executable: (SDK root)\Samples\Multimedia\DPlay\Bin\Override.exe

User's Guide

When the program begins, select a service provider. Once you make your selection, the application displays a custom dialog box that it creates to collect the information needed for that service provider. If you select an unknown service provider, then the service provider's dialog cannot be overridden and the Override application simply displays the default dialog box.

Once the service provider information has been collected from the user, it must be formatted into a DirectPlay address. This can be used to initialize the service provider.

The IDirectPlay4::EnumSessions and IDirectPlay4::Open methods must be called with the dwFlags parameter set to the value DPENUMSESSIONS_RETURNSTATUS. This will suppress any status dialogs that may pop up to show to progress of the connection.


SimpleConnect Sample

[Visual Basic]

This topic pertains only to application development in C++. See DirectPlay Visual Basic Samples.

[C++]

Description

The SimpleConnect sample shows how to create and join a DirectPlay session, and how to send and receive messages.

Path

Source: (SDK root)\Samples\Multimedia\DPlay\Src\SimpleConnect

Executable: (SDK root)\Samples\Multimedia\DPlay\Bin\SimpleConnect.exe

User's Guide

Enter the player's name, and select a connection type or "Wait for Lobby Connection" from the list. In the Multiplayer Games dialog, start a new session by clicking Create, or else click Start Search to find active sessions, then join one by highlighting it and clicking Join. The "game" begins immediately, but other players can join at any time. By clicking Wave to Other Players you send a message to all other players in the session. The host player can leave at any time, because DirectPlay automatically migrates the host player.

Note that you can test multiple instances of the sample on a single machine by using the TCP/IP service provider.

Programming Notes

This sample shows the basics of using DirectPlay for a game.


StagedConnect Sample

[Visual Basic]

This topic pertains only to application development in C++. See DirectPlay Visual Basic Samples.

[C++]

Description

The StagedConnect sample is a more advanced version of the ChatConnect and SimpleConnect samples. Here the session begins in a staging area where the host can limit the number of players, reject players, and start the game. The staging area also allows players to chat or drop out before the game begins.

Path

Source: (SDK root)\Samples\Multimedia\DPlay\Src\StagedConnect

Executable: (SDK root)\Samples\Multimedia\DPlay\Bin\StagedConnect.exe

User's Guide

Enter the player's name, and select a connection type or "Wait for Lobby Connection" from the list. In the Multiplayer Games dialog, start a new session by clicking Create, or else click Start Search to find active sessions, then join one by highlighting it and clicking Join.

In the staging area, select the checkbox next to your name if you are ready to join the session. Send a chat message to other players in the staging area by typing a message in the lower text box and pressing Enter.

The host can close slots or reject a player in a slot by clicking on the button for that slot, and can start play by clicking Start Game. The game can only be started when all players are ready.

Programming Notes

The sample illustrates how a staging area can be set up within an application session rather than a lobby session.


DirectPlay Visual Basic Samples

[C++]

This section pertains only to application development in Visual Basic. See DirectPlay C++ Samples.

[Visual Basic]

The following samples, provided with Visual Basic source code, show how to use DirectPlay:

  • Chat Sample
  • Memory Sample
  • Whiteboard Sample


Chat Sample

[C++]

This topic pertains only to application development in Visual Basic. See DirectPlay C++ Samples.

[Visual Basic]

Description

The Chat sample is a simple chat client that can either be launched by a lobby client or join a lobbied session after being launched by the user.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DPlay\Src\Chat

Executable: (SDK root)\Samples\Multimedia\VBSamples\DPlay\Bin\DXVBChat.exe

User's Guide

To start the chat:

1. Run the Lobby Server on one machine. Start a normal session.

2. Run the Bellhop Sample on each client machine, and join the lobby session created by the lobby server.

3. Create a staging area for DXVBChat in Bellhop on one client. (Right-click on the Chat door and choose CreateGroupInGroup.)

4. Enter the staging area on each client by double-clicking on the triangle. Start the session on one client by right-clicking on the triangle and choosing StartSession. This runs DXVBChat on all clients in the staging area, or takes it out of wait mode.

Note that new players can join after the session has started by entering the staging area and "starting" it again.

You can run DXVBChat before starting the session, but you can't run it from the Visual Basic environment; you must execute DXVBChat.exe.

You can test multiple instances of the application on a single machine by using TCP/IP. Choose different player names in each instance of Bellhop in order to see more clearly what is going on.

Programming Notes

The InitDPlay function shows how to determine whether the application was launched by the user (and needs to wait for connection settings) or by a lobby.


Memory Sample

[C++]

This topic pertains only to application development in Visual Basic. See DirectPlay C++ Samples.

[Visual Basic]

Description

Memory is a simple network game for up to four players that demonstrates how to make a connection, create and join sessions, create players, and send and receive DirectPlay messages.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DPlay\Src\Memory

Executable: (SDK root)\Samples\Multimedia\VBSamples\DPlay\Bin\Memory.exe

User's Guide

Click the Multiplayer button in order to create or join a network session. Choose a connection type and (optionally) change the player name, then click on OK. If hosting a session, you can cancel out of any service provider dialogs.

If you choose an TCP/IP connection, you can run multiple sessions and play a game on a single computer.

In the Join or Create Game dialog box, click New to create a new game, or select one from the list and click Join. Note that the list is not automatically updated, so if you're waiting for another player to create a game, you have to click the Refresh button periodically.

If creating a game, set the maximum number of players and the name, then click Create. The Waiting for Host to Start Game dialog box appears. You can start the game as soon as at least one other player is listed.

To play the game, wait till your name is highlighted on the scoreboard, then click on any two tiles. If you get a match, you play again. The winner is the player who gets the most matches. Unmatched tiles are hidden as soon as the next player clicks on a tile.

To send a chat message to all other players, press Enter.

If the host leaves the game prematurely, another player becomes the host.

Programming Notes

The application polls for messages in Sub Main, in GlobalModule.bas. Most of the forms have some DirectPlay code as well.


Whiteboard Sample

[C++]

This topic pertains only to application development in Visual Basic. See DirectPlay C++ Samples.

[Visual Basic]

Description

The Whiteboard sample is a non-lobbied chat application that allows users to work together on a sketch board as well as exchanging text messages.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DPlay\Src\Whiteboard

Executable: (SDK root)\Samples\Multimedia\VBSamples\DPlay\Bin\Whiteboard.exe

User's Guide

One user must start a session by choosing Create Host from the Sessions menu. This session then becomes available for other players to join.

Send messages by typing in the text box at the bottom of the screen and clicking Send. Draw in the whiteboard area by dragging with the mouse. Erase by clicking Clear.

Programming Notes

Messages are retrieved in response to a timer event.


DirectSetup

This section provides information about the Microsoft® DirectSetup® component of the Microsoft® DirectX® application programming interface (API) in the Platform Software Development Kit (SDK) or the stand-alone DirectX SDK. Information is found under the following main headings:

  • About DirectSetup
  • DirectSetup Essentials
  • DirectSetup Reference
  • DirectSetup Samples


About DirectSetup

[Visual Basic]

This topic applies to applications written in C++. For information on distributing an application written in Visual Basic, see Installing DirectX for Visual Basic Applications.

[C++]

DirectSetup is a simple API that provides one-call installation of the DirectX components. This is more than a convenience—DirectX is a complex product, and installing it is an involved task. You should not attempt to install DirectX manually.

DirectSetup also provides an automated way to install the appropriate Microsoft® Windows® operating system registry information for applications that use the DirectPlayLobby object. This registry information is required for the DirectPlayLobby object to enumerate and start the application.

DirectSetup includes several API functions and structures. It also includes a prototype DirectXSetupCallbackFunction that can be defined by an application to customize the user interface during the installation process. The DirectX SDK includes a sample application that demonstrates the use of this callback function. For more information, see Dinstall Sample.


DirectSetup Essentials

This section contains general information about the DirectSetup component. The following topics are discussed:

  • Setup Overview for DirectSetup
  • Installing DirectX for Visual Basic Applications
  • Preparing the Setup Folder
  • Customizing Setup
  • Testing the Setup Program
  • Enabling AutoPlay


Setup Overview for DirectSetup

[Visual Basic]

This topic applies to applications written in C++. For information on distributing an application written in Visual Basic, see Installing DirectX for Visual Basic Applications.

[C++]

Applications and games that depend on DirectX use the DirectXSetup function to install the necessary system components into an existing Windows installation. The function optionally updates the display and audio drivers for optimal support of DirectX. Typically, you would call DirectXSetup from the program that you are using to install your own application files.

Note The DirectXSetup function overwrites system components from previous versions of DirectX. For example, if you install DirectX 7.0 on a system that already has DirectX 5.0 components, all DirectX 5.0 components are overwritten. Because all DirectX components comply with Component Object Model (COM) backward-compatibility rules, software written for DirectX 5.0 continues to function properly.

The DirectXSetup function can tell when DirectX components, display drivers, and audio drivers need to be upgraded. It can also distinguish whether or not these components can be upgraded without adversely affecting the Windows operating system. This is said to be a safe upgrade. The upgrade is safe for the operating system, not necessarily for the applications running on the computer. Some hardware-dependent applications can be negatively affected by an upgrade that is safe for Windows.

By default, the DirectXSetup function performs only safe upgrades. If the upgrade of a device driver might adversely affect the operation of Windows, the upgrade is not performed.

During the setup process, DirectSetup creates a backup copy of the system components and drivers that are replaced. These can be restored if problems occur.

When display or audio drivers are upgraded, the DirectXSetup function uses a database created by Microsoft to manage the process. The database contains information on existing drivers that are provided by Microsoft, the manufacturers of the hardware, or the vendors of the hardware. This database describes the upgrade status of each driver, based on testing done at Microsoft and other sites.

Check the value returned by DirectXSetup. If it is DSETUPERR_SUCCESS_RESTART, notify the user that changes do not take effect without a restart, and offer the choice of restarting immediately. See Dinstall.c in the Dinstall sample application for an example of how to do this.


Installing DirectX for Visual Basic Applications

[C++]

This topic applies to applications written in Visual Basic

[Visual Basic]

Although you can use the DirectSetup functions in your Visual Basic application by declaring references to the functions in your module, the recommended method is to use the Application Wizard. The following steps are used to distribute your application via compact disk.

Distributing your Visual Basic application

1. Start the Application Wizard

2. Remove DxVBLib.dll from the dependency list

3. Add all the files in the Redist folder from the DirectX SDK CD located in \Dxf\Redist\Directx7 for retail and \Dxf\Debug for debug

4. Click Finish to exit the Application Wizard

5. Overwrite Setup1.exe (created by the Application Wizard) with Setup1.exe from the support folder on the DirectX SDK CD

6. If you are using Visual Basic 5.0, use the compress utility to compress Setup1.exe to Setup1.ex_. If you are developing on Visual Basic 6.0, run the batch file created by the Application Wizard.

7. The files are now ready to be distributed via compact disk.


Preparing the Setup Folder

[Visual Basic]

This topic applies to applications written in C++. For information on distributing an application written in Visual Basic, see Installing DirectX for Visual Basic Applications.

[C++]

The DirectXSetup function takes a parameter, lpszRootPath, that points to the root directory of the installation. It can be NULL to indicate that the root path is the current directory—that is, the directory where your setup program resides.

The root directory must contain Dsetup.dll, and Dsetup32.dll. It must also have a folder named "DirectX" (not case sensitive), containing all the redistributable files and drivers. To create the proper structure on your application setup disk, copy the entire contents of the Dxf\Redist\DirectX7 folder on the DirectX SDK disk into the root path of your setup program. This folder was not copied to your development computer when you installed the SDK, so you have to get it from the original disk.


Customizing Setup

[Visual Basic]

This topic applies to applications written in C++. For information on distributing an application written in Visual Basic, see Installing DirectX for Visual Basic Applications.

[C++]

DirectSetup allows you to define a callback function for customizing the DirectX setup process. In the DirectSetup documentation, this callback function is referred to as DirectXSetupCallbackFunction, but you can give it any name that you like.

If a callback function is not provided by the setup program, the DirectXSetup function displays status and error information in a dialog box and obtains user input by calling the Microsoft® Win32® MessageBox function. If a callback is provided, the information that would have been used to create the status dialog or message box is instead passed to the callback. The callback function is called once for each DirectX component and device driver that can be installed or upgraded.

You can use the callback function to do the following:

  • Employ a custom interface. Your setup program might display messages in ways other than by using MessageBox or standard Windows dialog boxes. The callback function enables you to integrate messages for the DirectX component of your installation into your own interface.
  • Update a progress indicator.
  • Suppress the display of status and error messages. Designers of programs for novice users might want to suppress error messages and let the setup program handle errors and make upgrade choices silently. This approach requires a greater development effort for the setup program, but might be appropriate for the target audience.

The following topics help you customize your setup:

  • Creating a DirectSetup Callback Function
  • Setting the Callback Function
  • Using Upgrade Flags in the Callback Function
  • Overriding Defaults in the Callback Function


Creating a DirectSetup Callback Function

[Visual Basic]

This topic applies to applications written in C++. For information on distributing an application written in Visual Basic, see Installing DirectX for Visual Basic Applications.

[C++]

To customize the setup process, first create a callback function that conforms to the DirectXSetupCallbackFunction prototype, as in the following declaration:

DWORD WINAPI DirectXSetupCallbackFunction(
        DWORD dwReason,
        DWORD dwMsgType,
        LPSTR szMessage,
        LPSTR szName,
        void *pInfo);

In this example, adapted from the Dinstall sample application, the name of the function is the same as that of the prototype, but this is optional. The parameter names differ slightly from those in the prototype declared in the Dsetup.h header file and are used throughout the following discussion.

Parameters

The dwReason parameter indicates why the callback function has been called. The possible values are listed and explained in the reference for DirectXSetupCallbackFunction.

The dwMsgType parameter receives flags equivalent to those that DirectSetup would, by default, pass to MessageBox, such as those controlling what buttons and icon are displayed. Of special interest to you are the button flags, which you use to determine what return values are expected. If this value is 0, the event never requires user input, and DirectSetup normally displays a status message.

The szMessage parameter receives the same text that DirectSetup would otherwise pass to the status dialog box or to MessageBox.

When a driver is a candidate for upgrading, its name is passed in the szName parameter, and pInfo points to information about how the upgrade is to be handled—for example, whether DirectSetup recommends that the old driver be kept or upgraded. For more information, see Using Upgrade Flags in the Callback Function.

The way your callback function interprets the parameters is entirely up to you. Typically, you would choose which messages to display (based on dwReason) and when to present the user with alternatives, and you would modify the interface accordingly.

Return Value

The value returned by your callback function must conform to the following rules:

  • When dwMsgType is 0, the return value must be IDOK. In this case, there are no choices to be made by the user. (Your application, of course, is free to display a status message, even though no input is required.)
  • If dwMsgType is nonzero, the return value must be the same as would have been returned by MessageBox, given the equivalent choice by the user.

To determine the appropriate return value in the second case, test dwMsgType for the buttons that would normally have been put in a message box. The following example, from the GetReply function in Dinstall, shows how this is done:

/* The global g_wReply identifies the custom dialog button
   that has been selected by the user. */

switch (dwMsgType & 0x0000000F)
{
   / * There would normally have been an OK and a Cancel button.
       IDBUT1 is equivalent to the OK button. If the user did not
       choose that, it was a Cancel. */
    case MB_OKCANCEL:
        wDefaultButton = (g_wReply == IDBUT1) ? IDOK : IDCANCEL;
        break;

    / * And so on with the other button combinations. */
    case MB_OK:
        wDefaultButton = IDOK;
        break;
    case MB_RETRYCANCEL:
        wDefaultButton = (g_wReply == IDBUT1) ? IDRETRY : IDCANCEL;
        break;
    case MB_ABORTRETRYIGNORE:
        if (g_wReply == IDBUT1)
            wDefaultButton = IDABORT;
        else if (g_wReply == IDBUT2)
            wDefaultButton = IDRETRY;
        else
            wDefaultButton = IDIGNORE;
        break;
    case MB_YESNOCANCEL:
        if (g_wReply == IDBUT1)
            wDefaultButton = IDYES;
        else if (g_wReply == IDBUT2)
            wDefaultButton = IDNO;
        else
            wDefaultButton = IDCANCEL;
        break;
    case MB_YESNO:
        wDefaultButton = (g_wReply == IDBUT1) ? IDYES : IDNO;
        break;
    default:
        wDefaultButton = IDOK;
}

This routine translates button clicks from the custom interface into the equivalent button identifiers in the standard dialog box that DirectSetup would otherwise create. The wDefaultButton variable is set to the identifier of the equivalent standard dialog box button, and this value is ultimately returned from the callback function.

You do not necessarily have to give the user a choice, even when dwMsgType is nonzero. You might decide, for example, to upgrade drivers automatically even if DirectSetup would normally ask for confirmation from the user. The Dinstall sample does this when the user has asked to see only problem messages and the driver upgrade is considered safe, as follows:

case DSETUP_CB_UPGRADE_SAFE:
    switch (dwMsgType & 0x0000000F)
    {
        case MB_YESNO:
        case MB_YESNOCANCEL:
            return IDYES;
        case MB_OKCANCEL:
        case MB_OK:
        default:
            return IDOK;
    }
    break;

The callback function returns either IDYES or IDOK, depending on which button would have represented a positive choice in a dialog box asking the user whether or not the upgrade should proceed.


Setting the Callback Function

[Visual Basic]

This topic applies to applications written in C++. For information on distributing an application written in Visual Basic, see Installing DirectX for Visual Basic Applications.

[C++]

Before calling DirectXSetup, notify DirectSetup that you want to use a callback by calling the DirectXSetupSetCallback function, passing a pointer to the callback as a parameter. The following example shows how this is done:

DirectXSetupSetCallback(
        (DSETUP_CALLBACK) DirectXSetupCallbackFunction);


Using Upgrade Flags in the Callback Function

[Visual Basic]

This topic applies to applications written in C++. For information on distributing an application written in Visual Basic, see Installing DirectX for Visual Basic Applications.

[C++]

When the application-defined callback function DirectXSetupCallbackFunction is called by the DirectXSetup function, it is passed a parameter that contains the reason that the callback function was invoked. If the reason is DSETUP_CB_MSG_CHECK_DRIVER_UPGRADE, the pInfo parameter points to a DSETUP_CB_UPGRADEINFO structure containing flags that summarize the DirectXSetup function recommendations on how to perform the upgrade of DirectX components and drivers. The structure member containing the flags is called UpgradeFlags.

The flags fall into the following categories:

Primary Upgrade Flags
These flags are mutually exclusive. One of them is always present in the UpgradeFlags structure member. You can extract it by performing a bitwise AND operation with DSETUP_CB_UPGRADE_TYPE_MASK.

DSETUP_CB_UPGRADE_FORCE

DSETUP_CB_UPGRADE_KEEP

DSETUP_CB_UPGRADE_SAFE

DSETUP_CB_UPGRADE_UNKNOWN

Secondary Upgrade Flags
Any or all of these flags can be present.

DSETUP_CB_UPGRADE_CANTBACKUP

DSETUP_CB_UPGRADE_HASWARNINGS

Device Active Flag
This flag is present if the device whose driver is being upgraded is active. It can be combined with any of the others.

DSETUP_CB_UPGRADE_DEVICE_ACTIVE

Device Class Flags
These flags are mutually exclusive. One of them is always present.

DSETUP_CB_UPGRADE_DISPLAY

DSETUP_CB_UPGRADE_MEDIA

In summary: every time the Reason parameter has the value DSETUP_CB_MSG_CHECK_DRIVER_UPGRADE, the UpgradeFlags member of the structure pointed to by pInfo contains one Primary Upgrade Flag, zero or more Secondary Upgrade Flags, zero or one Device Active Flag, and one Device Class Flag.

If the UpgradeFlags member is set to DSETUP_CB_UPGRADE_KEEP, the DirectX component or device driver cannot be upgraded without causing Windows to cease functioning properly. The DirectXSetup function does not perform an upgrade on the component or driver.

A value of DSETUP_CB_UPGRADE_FORCE in UpgradeFlags means that the component or driver must be upgraded for Windows to function properly. The DirectXSetup function upgrades the driver or component. It is possible that the upgrade might adversely affect some programs on the system. When the DirectXSetup function detects this condition, the UpgradeFlags member is set to (DSETUP_CB_UPGRADE_FORCE | DSETUP_CB_UPGRADE_HAS_WARNINGS). When this occurs, the DirectXSetup function performs the upgrade but issues a warning to the user.

Components and drivers are considered safe for upgrade if they do not adversely affect the operation of Windows when they are installed. In this case, the UpgradeFlags member is set to DSETUP_CB_UPGRADE_SAFE. It is possible that the upgrade can be safe for Windows, but still cause problems for programs installed on the system. When DirectXSetup detects this condition, the UpgradeFlags member contains the value (DSETUP_CB_UPGRADE_SAFE | DSETUP_CB_UPGRADE_HAS_WARNINGS). If this condition occurs, the default action for the DirectXSetup function is not to perform the upgrade.


Overriding Defaults in the Callback Function

[Visual Basic]

This topic applies to applications written in C++. For information on distributing an application written in Visual Basic, see Installing DirectX for Visual Basic Applications.

[C++]

The application-defined function DirectXSetupCallbackFunction can override some of the default behaviors of the DirectXSetup function through its return value.

For example, the default behavior for DirectXSetup is not to install a component if the upgrade type in the structure pointed to by the pInfo parameter is set to (DSETUP_CB_UPGRADE_SAFE | DSETUP_CB_UPGRADE_HAS_WARNINGS). In this case, the MsgType parameter of the callback function is set to (MB_YESNO | MB_DEFBUTTON2). Without a callback function, DirectSetup would present the user with a dialog box whose default button was No. If the callback function does not seek user input but accepts the default, it returns IDNO. To override the default, the callback function returns IDYES. If it does override the default, the DirectXSetup function notifies the user.


Testing the Setup Program

[Visual Basic]

This topic applies to applications written in C++. For information on distributing an application written in Visual Basic, see Installing DirectX for Visual Basic Applications.

[C++]

To test the DirectSetup component of your setup program, compile a version in which the DSETUP_TESTINSTALL flag is passed to the DirectXSetup function. Set up the installation directory, as described in Preparing the Setup Folder.

Now, when you run your setup program, DirectSetup goes through the motions of installing DirectX, including calls to a callback function if you have provided one, without actually installing any components.


Enabling AutoPlay

[Visual Basic]

This topic applies to applications written in C++. For information on distributing an application written in Visual Basic, see Installing DirectX for Visual Basic Applications.

[C++]

If you are building an AutoPlay compact disk title, copy the Autorun.inf file in the root directory of the DirectX SDK compact disk to the root of your application directory. This text file contains the following information:

[autorun]
OPEN=SETUP.EXE

If your application's setup program is called Setup.exe, you do not have to make any changes to this file; otherwise, edit this file to contain the name of your setup program.


DirectSetup Reference

This section contains reference information for the API elements of Microsoft® DirectSetup®. Reference material is divided into the following categories:

  • Functions
  • Structures
  • Return Values

This reference section is mainly used when programming in C++; for Microsoft® DirectX® for Visual Basic setup information, see Installing DirectX for Visual Basic Applications.


Functions

This section contains information on the following global functions used with DirectSetup:

  • DirectXRegisterApplication
  • DirectXSetup
  • DirectXSetupCallbackFunction
  • DirectXSetupGetVersion
  • DirectXSetupSetCallback
  • DirectXUnRegisterApplication


DirectXRegisterApplication

The DirectXRegisterApplication function registers an application as one designed to work with DirectPlayLobby.

int WINAPI DirectXRegisterApplication(
  HWND hWnd,
  LPDIRECTXREGISTERAPP lpDXRegApp
);

Parameters

hWnd
Handle of the parent window. If this parameter is set to NULL, the desktop is the parent window.
lpDXRegApp
Address of the DIRECTXREGISTERAPP structure that contains the registry entries that are required for the application to function properly with DirectPlayLobby.

Return Values

If this function succeeds, it returns TRUE.

If it fails, it returns FALSE. Call the GetLastError function to get extended error information.

Remarks

The DirectXRegisterApplication function has to have both dsetup.dll and dsetup32.dll which in not installed on the system, but they are included in the SDK.

Although the DirectXRegisterApplication function inserts the registry entries needed for an application to operate with DirectPlayLobby, the recommend method to install and uninstall a lobby application is to use the IDirectPlayLobby3::RegisterApplication and IDirectPlayLobby3::UnregisterApplication. If these registry entries are added with DirectXRegisterApplication, they should be removed with DirectXUnRegisterApplication when the application is uninstalled.

Many commercial install programs remove registry entries automatically when a program is uninstalled. However, such programs do so only if they added the registry entries themselves. If the DirectPlayLobby registry entries were added by DirectXRegisterApplication, commercial install programs do not delete the registry entries when the application is uninstalled. Therefore, DirectPlayLobby registry entries that are created by DirectXRegisterApplication must be deleted by DirectXUnRegisterApplication.

Registry entries needed for DirectPlayLobby access can be created without using DirectXRegisterApplication. This, however, is not generally recommended. See Registering Lobby-Aware Applications in the Microsoft® DirectPlay® documentation.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dsetup.h.
Import Library: Use Dsetup.lib.

See Also

DirectXUnRegisterApplication


DirectXSetup

The DirectXSetup function installs one or more DirectX components.

int WINAPI DirectXSetup(
  HWND  hWnd,
  LPSTR lpszRootPath,
  DWORD dwFlags
);

Parameters

hWnd
Handle of the parent window for the setup dialog boxes.
lpszRootPath
Address of a string that contains the root path of the DirectX component files. This string must specify a full path to the directory that contains the files Dsetup.dll, and Dsetup32.dll, as well as a "DirectX" (not case sensitive) directory containing redistributable files. If this value is NULL, the current working directory is used.
dwFlags
One or more flags indicating which DirectX components should be installed. A full installation (DSETUP_DIRECTX) is recommended.
DSETUP_D3D | Obsolete. DirectX 3 programs that use this flag install all DirectX components.
DSETUP_DDRAW | Obsolete. DirectX 3 programs that use this flag install all DirectX components.
DSETUP_DDRAWDRV | Not used in DirectX 7.0.
DSETUP_DINPUT | Obsolete. DirectX 3 programs that use this flag install all DirectX components.
DSETUP_DIRECTX | Installs DirectX run-time components, as well as DirectX-compatible display and audio drivers.
DSETUP_DIRECTXSETUP | Obsolete. DirectX 3 programs that use this flag install all DirectX components.
DSETUP_DPLAY | Obsolete. DirectX 3 programs that use this flag install all DirectX components.
DSETUP_DPLAYSP | Obsolete. DirectX 3 programs that use this flag install all DirectX components.
DSETUP_DSOUND | Obsolete. DirectX 3 programs that use this flag install all DirectX components.
DSETUP_DSOUNDDRV | Not used in DirectX 7.0.
DSETUP_DXCORE | Installs DirectX run-time components. Does not install DirectX-compatible display and audio drivers.
DSETUP_TESTINSTALL | Performs a test installation. Does not install new components.
DSETUP_USEROLDERFLAG | Enables the return of –14, which means that the installed version of DirectX is newer than the version being installed.

Return Values

If this function succeeds, it returns DSETUPERR_SUCCESS, or DSETUPERR_SUCCESS_RESTART if the user must restart the system for changes to take effect.

If it fails, it returns an error value. For a list of possible return values, see Return Values.

Remarks

Before using the DirectXSetup function in your setup program, ensure that there is at least 15 MB of available disk space on the system. This is the maximum space required for DirectX to set up the appropriate files. If the system already contains the DirectX files, this space is not needed.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dsetup.h.
Import Library: Use Dsetup.lib.


DirectXSetupCallbackFunction

DirectXSetupCallbackFunction is a placeholder name for an optional callback function supplied by the setup program. If present, it is called once for each step in the setup process.

DWORD DirectXSetupCallbackFunction(
  DWORD  Reason,
  DWORD  MsgType,
  char  *szMessage,
  char  *szName,
  void  *pInfo
);

Parameters

Reason
Reason for the callback. It can be one of the following values:
DSETUP_CB_MSG_BEGIN_INSTALL
DirectXSetup is about to begin installing DirectX components and device drivers.
DSETUP_CB_MSG_BEGIN_INSTALL_DRIVERS
DirectXSetup is about to begin installing device drivers.
DSETUP_CB_MSG_BEGIN_INSTALL_RUNTIME
DirectXSetup is about to begin installing DirectX components.
DSETUP_CB_MSG_BEGIN_RESTORE_DRIVERS
DirectXSetup is about to begin restoring previous drivers.
DSETUP_CB_MSG_CANTINSTALL_BETA
A prerelease beta version of the Microsoft® Windows® 95 operating system was detected. The DirectX component or device driver cannot be installed.
DSETUP_CB_MSG_CANTINSTALL_NOTWIN32
The operating system detected is not a Windows 32-bit operating system. DirectX is not compatible with Windows 3.x.
DSETUP_CB_MSG_CANTINSTALL_NT
The DirectX component or device driver cannot be installed on versions of the Microsoft® Windows NT® operating system prior to version 4.0.
DSETUP_CB_MSG_CANTINSTALL_UNKNOWNOS
The operating system is unknown. The DirectX component or device driver cannot be installed.
DSETUP_CB_MSG_CANTINSTALL_WRONGLANGUAGE
The DirectX component or device driver is not localized to the language being used by Windows.
DSETUP_CB_MSG_CANTINSTALL_WRONGPLATFORM
The DirectX component or device driver is for another type of computer.
DSETUP_CB_MSG_CHECK_DRIVER_UPGRADE
Driver is being considered for upgrade. Verification from user is recommended.
DSETUP_CB_MSG_FILECOPYERROR
Setup of the DirectX component or device driver file has failed during the copy process.
DSETUP_CB_MSG_INTERNAL_ERROR
An internal error has occurred. Setup of the DirectX component or device driver has failed.
DSETUP_CB_MSG_NOMESSAGE
No message to be displayed. The callback function should return.
DSETUP_CB_MSG_NOTPREINSTALLEDONNT
The DirectX component or device driver cannot be installed on the version of Windows NT or Microsoft® Windows® 2000 in use.
DSETUP_CB_MSG_OUTOFDISKSPACE
Setup of the DirectX component has failed due to lack of disk space.
DSETUP_CB_MSG_PREINSTALL_NT
DirectX is already installed on the version of Windows NT/Windows 2000 in use.
DSETUP_CB_MSG_SETUP_INIT_FAILED
Setup of the DirectX component or device driver has failed.
MsgType
Flags that control the display of a message box. These flags can be passed to the MessageBox function. An exception is when MsgType is 0. In that case, the setup program can display status information but should not wait for input from the user.
szMessage
Localized character string containing error or status messages that can be displayed in a dialog box created with the MessageBox function.
szName
NULL unless the Reason parameter is DSETUP_CB_MSG_CHECK_DRIVER_UPGRADE. In that case, szName contains the name of the driver to be upgraded.
pInfo
Address of a structure containing upgrade information. When Reason is DSETUP_CB_MSG_CHECK_DRIVER_UPGRADE, the setup program is upgrading a driver and asking the user whether the upgrade should take place. In this case, pInfo points to a DSETUP_CB_UPGRADEINFO structure containing information about the upgrade.

Return Values

The return value should be the same as would be returned by the MessageBox function, with one exception. If this function returns 0, the DirectXSetup function performs the default action for upgrade of the DirectX component or driver.

Remarks

The name of DirectXSetupCallbackFunction is supplied by the setup program. The DirectXSetupSetCallback function is used to pass the address of the callback function to DirectSetup.

If MsgType is 0, the setup program can display status information, but it should not wait for user input. In this case, the function returns IDOK.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dsetup.h.
Import Library: User-defined.

See Also

MessageBox, DirectXSetupSetCallback, Customizing Setup


DirectXSetupGetVersion

The DirectXSetupGetVersion function retrieves the version number of the DirectX components that are currently installed.

INT WINAPI DirectXSetupGetVersion(
  DWORD  *pdwVersion,
  DWORD  *pdwRevision
);

Parameters

pdwVersion
Address of a variable to receive the version number. Can be NULL if the version number is not wanted.
pdwRevision
Address of a variable to receive the revision number. Can be NULL if the revision number is not wanted.

Return Values

If the function succeeds, it returns nonzero.

If it fails, it returns 0.

Remarks

The DirectXSetupGetVersion function can be used to retrieve the version and revision numbers before or after the DirectXSetup function is called. If it is called before DirectXSetup is invoked, it gives the version and revision numbers of the DirectX components that are currently installed. If it is called after DirectXSetup is called, but before the computer is restarted, it gives the version and revision numbers of the DirectX components that take effect after the computer is restarted.

The version number in the pdwVersion parameter is composed of the major version number and the minor version number. The major version number is in the 16 most significant bits of the DWORD when this function returns. The minor version number is in the 16 least significant bits of the DWORD when this function returns. The version numbers can be interpreted as follows:

DirectX version | Value pointed to by pdwVersion
DirectX 1 | 0x00040001
DirectX 2 | 0x00040002
DirectX 3 | 0x00040003
DirectX 5.0 | 0x00040005
DirectX 6.0 | 0x00040006
DirectX 7.0 | 0x00040007

There is no version 4 of DirectX.

The version number in the pdwRevision parameter is composed of the release number and the build number. The release number is in the 16 most significant bits of the DWORD when this function returns. The build number is in the 16 least significant bits of the DWORD when this function returns.

The following sample code fragment demonstrates how the information returned by DirectXSetupGetVersion can be extracted and used.

DWORD dwVersion;
DWORD dwRevision;
if (DirectXSetupGetVersion(&dwVersion, &dwRevision))
{
    printf("DirectX version is %d.%d.%d.%d\n",
           HIWORD(dwVersion), LOWORD(dwVersion),
           HIWORD(dwRevision), LOWORD(dwRevision));
}

Version and revision numbers can be concatenated into a 64-bit quantity for comparison. The version number is in the 32 most significant bits and the revision number is in the 32 least significant bits.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dsetup.h.
Import Library: Use Dsetup.lib.

See Also

DirectXSetup


DirectXSetupSetCallback

The DirectXSetupSetCallback function sets a pointer to a callback function that is periodically called by DirectXSetup. The callback function can be used for setup progress notification and to implement a custom user interface for an application's setup program. For more information, see DirectXSetupCallbackFunction. If a setup program does not provide a callback function, DirectXSetupSetCallback is not invoked.

INT WINAPI DirectXSetupSetCallback(
  DSETUP_CALLBACK  Callback
);

Parameters

Callback
Address of a callback function.

Return Values

Currently returns 0.

Remarks

To set a callback function, DirectXSetupSetCallback must be called before DirectXSetup is called.

The name of the callback function passed to DirectXSetupSetCallback is supplied by the setup program. However, it must match the prototype given in DirectXSetupCallbackFunction.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dsetup.h.
Import Library: Use Dsetup.lib.

See Also

DirectXSetupCallbackFunction, DirectXSetup


DirectXUnRegisterApplication

The DirectXUnRegisterApplication function deletes the registration of an application designed to work with DirectPlayLobby.

int WINAPI DirectXUnRegisterApplication(
  HWND   hWnd,
  LPGUID lpGUID
);

Parameters

hWnd
Handle of the parent window. Set this to NULL if the desktop is the parent window.
lpGUID
Address of a GUID that represents the DirectPlay application to be unregistered.

Return Values

If the function succeeds, the return value is TRUE, meaning that the registration is successfully deleted.

If the function fails, the return value is FALSE.

Remarks

The DirectXUnRegisterApplication function has to have both dsetup.dll and dsetup32.dll which in not installed on the system, but they are included in the SDK.

Although the DirectXRegisterApplication function inserts the registry entries needed for an application to operate with DirectPlayLobby, the recommend method to install and uninstall a lobby application is to use the IDirectPlayLobby3::RegisterApplication and IDirectPlayLobby3::UnregisterApplication. An uninstall program should only use DirectXUnRegisterApplication if it used DirectXRegisterApplication when the application was installed.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dsetup.h.
Import Library: Use Dsetup.lib.

See Also

DirectXRegisterApplication


Structures

This section contains information about the following structures used with DirectSetup:

  • DIRECTXREGISTERAPP
  • DSETUP_CB_UPGRADEINFO

Note The memory for all DirectX structures must be initialized to 0 before use. In addition, all structures that contain a dwSize member must set the member to the size of the structure, in bytes, before use. The following example from Microsoft® DirectDraw® performs these tasks on a common structure, DDCAPS:

DDCAPS ddcaps; // Cannot use this yet

ZeroMemory(&ddcaps, sizeof(ddcaps));
ddcaps.dwSize = sizeof(ddcaps);

// Now the structure can be used.
.
.


DIRECTXREGISTERAPP

The DIRECTXREGISTERAPP structure contains the registry entries needed for applications designed to work with DirectPlayLobby.

typedef struct _DIRECTXREGISTERAPP {
    DWORD  dwSize;
    DWORD  dwFlags;
    LPSTR  lpszApplicationName;
    LPGUID lpGUID;
    LPSTR  lpszFilename;
    LPSTR  lpszCommandLine;
    LPSTR  lpszPath;
    LPSTR  lpszCurrentDirectory;
} DIRECTXREGISTERAPP, *PDIRECTXREGISTERAPP, *LPDIRECTXREGISTERAPP;

Members

dwSize
Size of the structure. Must be initialized to the size of the DIRECTXREGISTERAPP structure.
dwFlags
Reserved for future use.
lpszApplicationName
Name of the application.
lpGUID
Globally unique identifier (GUID) of the application.
lpszFilename
Name of the executable file to be called.
lpszCommandLine
Command-line arguments for the executable file.
lpszPath
Path of the executable file.
lpszCurrentDirectory
Current directory. This is typically the same as lpszPath.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dsetup.h.


DSETUP_CB_UPGRADEINFO

The DSETUP_CB_UPGRADEINFO structure is passed as a parameter to the application-defined DirectXSetupCallbackFunction. It contains valid information only when the Reason parameter is DSETUP_CB_MSG_CHECK_DRIVER_UPGRADE. Callback functions can use it to get status information on the upgrade that is about to be done.

typedef struct _DSETUP_CB_UPGRADEINFO {
    DWORD UpgradeFlags;
} DSETUP_CB_UPGRADEINFO;

Members

UpgradeFlags
One or more flags indicating the status of the upgrade. The following values are defined:
DSETUP_CB_UPGRADE_CANTBACKUP
The old system components cannot be backed up. Upgrade can be performed, but the components or drivers cannot be restored later.
DSETUP_CB_UPGRADE_DEVICE_ACTIVE
The device is currently in use.
DSETUP_CB_UPGRADE_DEVICE_DISPLAY
The device driver being upgraded is for a display device.
DSETUP_CB_UPGRADE_DEVICE_MEDIA
The device driver being upgraded is for a media device.
DSETUP_CB_UPGRADE_FORCE
Windows might not function correctly if the component is not upgraded. The upgrade will be performed.
DSETUP_CB_UPGRADE_HASWARNINGS
DirectSetup can upgrade the driver for this device, but doing so might affect one or more programs on the system. The szMessage parameter contains the names of the programs that might be affected. Upgrade not recommended.
DSETUP_CB_UPGRADE_KEEP
The system might fail if this device driver is upgraded. Upgrade not allowed.
DSETUP_CB_UPGRADE_SAFE
DirectSetup can safely upgrade this device driver. Upgrade recommended. A safe upgrade will not adversely affect the operation of Windows. Some hardware-dependent programs might be adversely affected.
DSETUP_CB_UPGRADE_UNKNOWN
DirectSetup does not recognize the existing driver for this device. This value occurs frequently. Upgrading might adversely affect the use of the device. It is strongly recommended that the upgrade not be performed.

Remarks

Use the DSETUP_CB_UPGRADE_TYPE_MASK value to extract the upgrade type (FORCE, KEEP, SAFE, or UNKNOWN) from UpgradeFlags.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dsetup.h.

See Also

DirectXSetupCallbackFunction


Return Values

The DirectXSetup function can return the following values. It can also return a standard COM error.

DSETUPERR_SUCCESS
Setup was successful, and no restart is required.
DSETUPERR_SUCCESS_RESTART
Setup was successful, and a restart is required.
DSETUPERR_BADSOURCESIZE
A file's size could not be verified or was incorrect.
DSETUPERR_BADSOURCETIME
A file's date and time could not be verified or were incorrect.
DSETUPERR_BADWINDOWSVERSION
DirectX does not support the Windows version on the system.
DSETUPERR_CANTFINDDIR
The setup program could not find the working directory.
DSETUPERR_CANTFINDINF
A required .inf file could not be found.
DSETUPERR_INTERNAL
An internal error occurred.
DSETUPERR_NEWERVERSION
A later version of DirectX has already been installed. Applications can safely ignore this error because the newer version is not overwritten and is fully compatible with applications written for earlier versions.
DSETUPERR_NOCOPY
A file's version could not be verified or was incorrect.
DSETUPERR_NOTPREINSTALLEDONNT
The version of Windows NT/Windows 2000 on the system does not contain the current version of DirectX. An older version of DirectX might be present, or DirectX might be absent altogether.
DSETUPERR_OUTOFDISKSPACE
The setup program ran out of disk space during installation.
DSETUPERR_SOURCEFILENOTFOUND
One of the required source files could not be found.
DSETUPERR_UNKNOWNOS
The operating system on your system is not currently supported.
DSETUPERR_USERHITCANCEL
The Cancel button was pressed before the application was fully installed.


DirectSetup Samples

The following sample program demonstrates the use and capabilities of DirectSetup:

  • Dinstall Sample (C/C++)
  • DXVBSetup Sample (Visual Basic)

Although DirectX samples include Microsoft® Visual C++® project workspace files, you might need to verify other settings in your development environment to ensure that the samples compile properly. For more information, see Compiling DirectX Samples and Other DirectX Applications.


Dinstall Sample

[Visual Basic]

This section pertains only to application development in Visual Basic. See the DXVBSetup Sample.

[C++]

Description

Dinstall is an example of how to use DirectSetup functions to install the DirectX subsystem and DirectX drivers. It shows how to use a callback function to present messages and get user input through a custom interface, in this case a simple modeless dialog box.

Path

Source: (SDK root)\Samples\Multimedia\Dxmisc\Src\Setup

User's Guide

First copy the entire contents of the \Redist\DirectX7 folder from the DirectX SDK CD into the same folder as Dinstall.exe. In your development environment, set the working directory to this folder as well. (In Microsoft® Visual C++®, this setting is on the Debug page of the Project Settings dialog box.)

Run the program and select Start Install from the File menu. DirectSetup performs a simulated installation of DirectX (see Programming Notes) and advises you of its progress in a modeless dialog box. The Options menu allows you to change the level of messages shown. However, if you are performing only a simulated installation, you will never see problem or update messages.

Choose Get Version from the File menu. The program shows the version and revision number of DirectX currently installed on the system.

Programming Notes

The driver folders in \Redist\DirectX7\Directx\Drivers contain localized versions of Microsoft-provided DirectX drivers. You can delete any number of these folders from your working directory if you want to save disk space.

By default, the program passes DSETUP_TESTINSTALL to the DirectXSetup function. This means that no files are actually copied, nor is the registry modified. To perform a real installation, delete this flag from the call.

Dinstall employs a callback function to monitor the progress of installation and intercept messages. Depending on the user's preferred warning level, as tracked in g_fStatus, messages may be ignored or presented to the user in a modeless dialog box. If user input is required, the appropriate buttons are displayed and the GetReply function monitors the message queue until one of the buttons is pressed.


DXVBSetup Sample

[C++]

This section pertains only to application development in Visual Basic. See Dinstall Sample.

[Visual Basic]

Description

The DXVBSetup sample shows how DirectSetup can be used by a Visual Basic application.

Path

Visual Basic 5 Source: (SDK root)\Samples\Multimedia\VBSamples\Dxmisc\Src\DXVB5Setup

Visual Basic 6 Source: (SDK root)\Samples\Multimedia\VBSamples\Dxmisc\Src\DXVB6Setup

User's Guide

The setup application directory should have a subfolder called Setup containing Dsetup.dll and Dsetup32.dll. It must also have a folder named "DirectX" (not case sensitive) containing all the redistributable files and drivers. To create the proper structure on your application setup disc, you should simply copy the entire contents of the Dxf\Redist\DirectX7 folder on the DirectX SDK disc into the root path of your setup program. Note that this folder was not copied to your development machine when you installed the SDK, so you have to get it from the original disc.

Programming Notes

The driver folders in \Redist\DirectX7\Directx\Drivers contain localized versions of Microsoft-provided DirectX drivers. You can delete any number of these folders from your working directory if you want to save disk space.


DirectSound

This section provides information about the DirectSound® component of the Microsoft DirectX® application programming interface (API). Information is found under the following main headings:

  • About DirectSound
  • Why Use DirectSound?
  • DirectSound Architecture
  • DirectSound Essentials
  • DirectSound Tutorials
  • DirectSound Reference
  • DirectSound Tools and Samples


About DirectSound

The Microsoft® DirectSound® application programming interface (API) is the wave-audio component of the DirectX® API. DirectSound provides low-latency mixing, hardware acceleration, and direct access to the sound device. It provides this functionality while maintaining compatibility with existing device drivers.

DirectSound enables wave sound capture and playback. In C++, it also supports property sets, which enable application developers to take advantage of extended services offered by sound cards and their associated drivers.


Why Use DirectSound?

The overriding design goal in DirectX is speed. Like other components of DirectX, DirectSound allows you to use the hardware in the most efficient way possible while insulating you from the specific details of that hardware with a device-independent interface. Your applications will work well with the simplest audio hardware but will also take advantage of the special features of cards and drivers that have been enhanced for use with DirectSound.

Here are some other things that DirectSound makes easy:

  • Querying hardware capabilities at run time to determine the best solution for any given personal computer configuration.
  • Using property sets, when programming in C++, so that new hardware capabilities can be exploited even when they are not directly supported by DirectSound.
  • Low-latency mixing of audio streams for rapid response.
  • Implementing three dimensional (3-D) sound.
  • Capturing sound.

Despite the advantages of DirectSound, the standard waveform-audio functions in Windows® continue to be a practical solution for certain tasks. For example, an application can easily play a single sound or audio stream, such as introductory music, by using the PlaySound or waveOut functions.


DirectSound Architecture

This section introduces the components of DirectSound and explains how DirectSound works with the hardware and with other applications. The following topics are discussed:

  • Architectural Overview for DirectSound
  • Sound Data
  • Playback Overview
  • Capture Overview
  • Property Sets Overview
  • Hardware Abstraction and Emulation
  • System Integration


Architectural Overview for DirectSound

DirectSound implements a new model for playing and capturing digital sound samples and mixing sample sources. Like other elements of the DirectX API, DirectSound uses the hardware to its greatest advantage whenever possible, and it emulates hardware features in software when the feature is not present in the hardware.

[C++]

DirectSound playback is built on the IDirectSound Component Object Model (COM) interface and on other interfaces for manipulating sound buffers and 3-D effects. These interfaces are IDirectSoundBuffer, IDirectSound3DBuffer, and IDirectSound3DListener.

DirectSound capture is based on the IDirectSoundCapture and IDirectSoundCaptureBuffer COM interfaces.

Another COM interface, IKsPropertySet, provides methods that allow applications to take advantage of extended capabilities of sound cards, even those introduced in the future.

Finally, the IDirectSoundNotify interface is used to signal events when playback or capture has reached a certain point in a buffer.

For more information about COM concepts that you should understand to create applications with the DirectX APIs, see The Component Object Model.

[Visual Basic]

DirectSound playback is built on the DirectSound class and on other classes for manipulating sound buffers and 3-D effects. These classes are DirectSoundBuffer, DirectSound3DBuffer, and DirectSound3DListener.

DirectSound capture is based on the DirectSoundCapture and DirectSoundCaptureBuffer classes.

Finally, the DirectXEvent class is used in conjunction with events created through the DirectX7.CreateEvent method to signal events when playback or capture has reached a certain point in a buffer.


Sound Data

[C++]

IDirectSound and IDirectSoundCapture work with waveform audio data, which consists of digital samples of the sound at a fixed frequency. The particular format of a sound can be described by a WAVEFORMATEX structure. This structure is documented in the Multimedia Structures section of the Platform SDK documentation, but is briefly described here for convenience:

typedef struct {
    WORD  wFormatTag;
    WORD  nChannels;
    DWORD nSamplesPerSec;
    DWORD nAvgBytesPerSec;
    WORD  nBlockAlign;
    WORD  wBitsPerSample;
    WORD  cbSize;
} WAVEFORMATEX;

The wFormatTag member contains a unique identifier assigned by Microsoft Corporation. A complete list can be found in the Mmreg.h header file. The only tag valid with DirectSound is WAVE_FORMAT_PCM. This tag indicates Pulse Code Modulation (PCM), an uncompressed format in which each sample represents the amplitude of the signal at the time of sampling. DirectSoundCapture can capture data in other formats by using the Audio Compression Manager.

For information on using non-PCM data with DirectSound, see Compressed Wave Formats.

The nChannels member describes the number of channels, usually either one (mono) or two (stereo). For stereo data, the samples are interleaved. The nSamplesPerSec member describes the sampling rate, or frequency, in hertz. Typical values are 11,025, 22,050, and 44,100.

The wBitsPerSample member gives the size of each sample, generally 8 or 16 bits. The value in nBlockAlign is the number of bytes required for each complete sample, and for PCM formats is equal to (wBitsPerSample * nChannels / 8). The value in nAvgBytesPerSec is the product of nBlockAlign and nSamplesPerSec.

Finally, cbSize gives the size of any extra fields required to describe a specialized wave format. This member is always zero for PCM formats.

[Visual Basic]

DirectSound and DirectSoundCapture work with waveform audio data, which consists of digital samples of the sound at a fixed frequency. The particular format of a sound can be described by a WAVEFORMATEX type. This type is briefly described here for convenience:

Type WAVEFORMATEX
    lAvgBytesPerSec As Long
    lExtra As Long
    lSamplesPerSec As Long
    nBitsPerSample As Integer
    nBlockAlign As Integer
    nChannels As Integer
    nFormatTag As Integer
    nSize As Integer
End Type

The nFormatTag member contains a unique identifier assigned by Microsoft Corporation. A complete list can be found in the Mmreg.h header file. The only tag valid with DirectSound is WAVE_FORMAT_PCM. This tag indicates Pulse Code Modulation (PCM), an uncompressed format in which each sample represents the amplitude of the signal at the time of sampling. DirectSoundCapture can capture data in other formats by using the Audio Compression Manager.

For information on using non-PCM data with DirectSound, see Compressed Wave Formats.

The nChannels member describes the number of channels, usually either one (mono) or two (stereo). For stereo data, the samples are interleaved. The lSamplesPerSec member describes the sampling rate, or frequency, in hertz. Typical values are 11,025, 22,050, and 44,100.

The nBitsPerSample member gives the size of each sample, generally 8 or 16 bits. The value in nBlockAlign is the number of bytes required for each complete sample, and for PCM formats is equal to (nBitsPerSample * nChannels / 8). The value in lAvgBytesPerSec is the product of nBlockAlign and lSamplesPerSec.

Finally, nSize gives the size of any extra fields required to describe a specialized wave format. This member is always zero for PCM formats.


Playback Overview

The DirectSound buffer object represents a buffer containing sound data. Buffer objects are used to start, stop, and pause sound playback, as well as to set attributes such as frequency and format.

The primary sound buffer holds the audio that the listener will hear. Secondary sound buffers each contain a single sound or stream of audio. DirectSound automatically creates a primary buffer, but it is the application's responsibility to create secondary buffers. When sounds in secondary buffers are played, DirectSound mixes them in the primary buffer and sends them to the output device. Only the available processing time limits the number of buffers that DirectSound can mix.

It is your responsibility to stream data in the correct format into the secondary sound buffers. DirectSound does not include methods for parsing a sound file or a wave resource. However, there is code in the accompanying sample applications that will help you with this task. For more information, see Using Wave Files and Reading Wave Data from a Resource.

Depending on the card type, DirectSound buffers can exist in hardware as on-board RAM, wave-table memory, a direct memory access (DMA) channel, or a virtual buffer (for an I/O port based audio card). Where there is no hardware implementation of a DirectSound buffer, it is emulated in system memory.

Multiple applications can create DirectSound objects for the same sound device. When the input focus changes between applications, the audio output automatically switches from one application's streams to another's. As a result, applications do not have to repeatedly play and stop their buffers when the input focus changes.

[C++]

In order to know when a streaming buffer is ready to receive new data, or when any buffer has stopped, an application can use the IDirectSoundNotify interface to set up notification positions. When the play cursor reaches one of these positions, an event is signaled. Alternatively, an application can regularly poll the position of the play cursor.

[Visual Basic]

In order to know when a streaming buffer is ready to receive new data, or when any buffer has stopped, an application can create events using the DirectX7.CreateEvent method and then call the DirectSoundBuffer.SetNotificationPositions or the DirectSoundCaptureBuffer.SetNotificationPositions method to set up notification positions. When the play cursor reaches one of these positions, an event is signaled. Alternatively, an application can regularly poll the position of the play cursor.


Capture Overview

The DirectSoundCapture object is used to query the capabilities of sound capture devices and to create buffers for capturing audio from an input source. DirectSoundCapture allows capturing of data in PCM or compressed formats.

The DirectSoundCaptureBuffer object represents a buffer used for receiving data from the input device. Like playback buffers, this buffer is conceptually circular: when input reaches the end of the buffer, it automatically starts again at the beginning.

The methods of the DirectSoundCaptureBuffer object allow you to retrieve the properties of the buffer, start and stop audio capture, and lock portions of the memory so that you can safely retrieve data for saving to a file or for some other purpose.

[C++]

As with playback, DirectSound allows you to request notification when captured data reaches a specified position within the buffer, or when capture has stopped. This service is provided through the IDirectSoundNotify interface.

[Visual Basic]

As with playback, DirectSound allows you to request notification when captured data reaches a specified position within the buffer, or when capture has stopped. This service is provided by creating events using the DirectX7.CreateEvent method and setting the notification positions with the DirectSoundCaptureBuffer.SetNotificationPositions method.


Property Sets Overview

[Visual Basic]

This topic applies only to applications written in C++.

[C++]

Through property sets, DirectSound is able to support extended services offered by manufacturers of sound cards and their associated drivers.

Hardware vendors define new capabilities as properties and publish the specification for these properties. You, the application developer, can then use the methods of the IKsPropertySet interface to determine whether a particular set of properties is available on the target hardware and to manipulate those properties, for instance by turning special effects on and off.

Property sets allow for the unlimited extension of the capabilities of DirectSound. You use a single method, IKsPropertySet::Set, to alter the state of the device in any way specified by the manufacturer.


Hardware Abstraction and Emulation

DirectSound accesses the sound hardware through the DirectSound hardware abstraction layer (HAL), an interface that is implemented by the audio-device driver.

The DirectSound HAL provides the following functionality:

  • Acquires and releases control of the audio hardware.
  • Describes the capabilities of the audio hardware.
  • Performs the specified operation when hardware is available.
  • Causes the operation request to report failure when hardware is unavailable.

The device driver does not perform any software emulation; it simply reports the capabilities of the hardware to DirectSound and passes requests from DirectSound to the hardware. If the hardware cannot perform a requested operation, the device driver reports failure of the request and DirectSound emulates the operation.

Your application can use DirectSound as long as the DirectX run-time files are present on the user's system. If the sound hardware does not have an installed DirectSound driver, DirectSound uses its hardware emulation layer (HEL), which employs the Windows multimedia waveform-audio (waveIn and waveOut) functions. Most DirectSound features are still available through the HEL, but of course hardware acceleration is not possible. To find out whether your application is running under an emulation driver, call the IDirectSound::GetCaps method in C++ or the DirectSound.GetCaps method in Visual Basic and check for the DSCAPS_EMULDRIVER flag.

DirectSound automatically takes advantage of accelerated sound hardware, including hardware mixing and hardware sound-buffer memory. Your application need not query the hardware or program specifically to use hardware acceleration. However, for you to make the best possible use of the available hardware resources, you can query DirectSound at run time (by using the various GetCaps methods) to receive a full description of the capabilities of the sound device, and then use different routines optimized for the presence or absence of a given feature. You can also specify which sound buffers should receive hardware acceleration.


System Integration

The following illustration shows the relationships between DirectSound and other system audio components.

DirectSound and the standard Windows waveform-audio functions provide alternative paths to the waveform-audio portion of the sound hardware. A single device provides access from one path at a time. If a waveform-audio driver has allocated a device, an attempt to allocate that same device by using DirectSound will fail. Similarly, if a DirectSound driver has allocated a device, an attempt to allocate the device by using the waveform-audio driver will fail.

If two sound devices are installed in the system, your application can access each device independently through either DirectSound or the waveform-audio functions.

Note Microsoft Video for Windows currently uses the waveform-audio functions to play the audio track of an audio visual interleaved (.avi) file. Therefore, if your application is using DirectSound and you play an .avi file, the audio track will not be audible. Similarly, if you play an .avi file and attempt to create a DirectSound object, the creation function will return an error.

For now, applications can release the DirectSound object by calling IDirectSound::Release in C++ or set the DirectSound object to Nothing in Visual Basic before playing an .avi file. Applications can then re-create and reinitialize the DirectSound object and its DirectSoundBuffer objects when the video finishes playing.


DirectSound Essentials

This section gives a practical overview of how the various DirectSound interfaces are used in order to play and capture sound. The following topics are discussed:

  • DirectSound Devices
  • DirectSound Buffers
  • DirectSound in 3-D
  • DirectSound 3-D Buffers
  • DirectSound 3-D Listeners
  • DirectSoundCapture
  • DirectSound Property Sets
  • Optimizing DirectSound Performance
  • Using Wave Files
  • Reading Wave Data from a Resource
[C++]

Note Most of the examples of method calls throughout this section are given in the C language form, which accesses methods by means of a pointer to a table of pointers to functions, and requires a this pointer as the first parameter in any call. For example, a C call to the IDirectSound::GetCaps method takes this form:

lpDirectSound->lpVtbl->GetCaps(lpDirectSound, &dscaps);

The same method call in the C++ form, which treats COM interface methods just like class methods, looks like this:

lpDirectSound->GetCaps(&dscaps);

Dsound.h contains macros that expand to either the C or C++ form of the method call, depending on the environment. These macros simplify the C calls and also make it possible to develop routines that can be used in either language. For example:

IDirectSound_GetCaps(lpDirectSound, &dscaps);

[C++,Visual Basic]


DirectSound Devices

The first step in implementing DirectSound in an application is to create a DirectSound object, which represents a sound device and gives access to the IDirectSound interface in C++ or the DirectSound object in Visual Basic.

This section describes how your application can enumerate available sound devices, create the DirectSound object for a device, and use the methods of the object to set the cooperative level, retrieve the capabilities of the device, create sound buffers, set the configuration of the system's speakers, and compact hardware memory.

  • Enumeration of Sound Devices
  • Creating the DirectSound Object
  • Cooperative Levels
  • Device Capabilities
  • Speaker Configuration
  • Compacting Hardware Memory


Enumeration of Sound Devices

[C++]

For an application that is simply going to play sounds through the user's preferred playback device, you don't need to enumerate the available devices. When you create the DirectSound object with NULL as the device identifier, the interface will automatically be associated with the default device if one is present. (If no device driver is present, the call to the DirectSoundCreate function fails.)

However, if you are looking for a particular kind of device, wish to offer the user a choice of devices, or need to work with two or more devices, you must get DirectSound to enumerate the devices available on the system.

Enumeration serves three purposes:

  • Reports what hardware is available.
  • Supplies a globally unique identifier (GUID) for each device.
  • Allows you to initialize DirectSound for each device as it is enumerated, so that you can check the capabilities of the device.

To enumerate devices you must first set up a callback function that will be called each time DirectSound finds a device. You can do anything you want within this function, and you can give it any name, but you must declare it in the same form as DSEnumCallback, a prototype in this documentation. The callback function must return TRUE if enumeration is to continue, or FALSE otherwise (for instance, after finding a device with the capabilities you need).

The following callback function, extracted from Dsenum.c in the DSShow3D tool, adds information about each enumerated device to a combo box. Note that the first three parameters are supplied by the device driver. The fourth parameter is passed on from the DirectSoundEnumerate function.

BOOL CALLBACK DSEnumProc(LPGUID lpGUID,
                         LPCTSTR lpszDesc,
                         LPCTSTR lpszDrvName,
                         LPVOID lpContext )
{
    HWND   hCombo = *(HWND *)lpContext;
    LPGUID lpTemp = NULL;

    if ( lpGUID != NULL )
    {
        if (( lpTemp = malloc( sizeof(GUID))) == NULL )
        return( TRUE );

        memcpy( lpTemp, lpGUID, sizeof(GUID));
    }

    ComboBox_AddString( hCombo, lpszDesc );
    ComboBox_SetItemData( hCombo,
                ComboBox_FindString( hCombo, 0, lpszDesc ),
                lpTemp );
    return( TRUE );
}

The enumeration is set in motion when the dialog containing the combo box is initialized:

if FAILED(DirectSoundEnumerate((LPDSENUMCALLBACK)DSEnumProc,
        &hCombo))
{
    EndDialog( hDlg, TRUE );
    return( TRUE );
}

In this case the address of the combo box handle is passed into DirectSoundEnumerate, which in turn passes it to the callback function. This parameter can be any 32-bit value that you want to have access to within the callback.

[Visual Basic]

For an application that is simply going to play sounds through the user's preferred playback device, you don't need to enumerate the available devices. When you create the DirectSound object by passing an empty string as the device identifier, the object will automatically be associated with the default device if one is present. (If no device driver is present, the call to the DirectX7.DirectSoundCreate method fails.)

However, if you are looking for a particular kind of device, wish to offer the user a choice of devices, or need to work with two or more devices, you must get DirectSound to enumerate the devices available on the system.

Enumeration serves three purposes:

  • Reports what hardware is available.
  • Supplies a globally unique identifier (GUID) for each device.
  • Allows you to initialize DirectSound for each device as it is enumerated, so that you can check the capabilities of the device.

To enumerate devices you must first call the DirectX7.GetDSEnum method to create a DirectSoundEnum object. The returned DirectSoundEnum object contains a collection of DirectSound devices. You then call the DirectSoundEnum.GetCount method to determine the number of available devices. Information on each device is then obtained by calling the DirectSoundEnum.GetDescription, DirectSoundEnum.GetGuid, and DirectSoundEnum.GetName methods and passing the specified device in the collection as the index argument.


Creating the DirectSound Object

[C++]

The simplest way to create the DirectSound object is with the DirectSoundCreate function. The first parameter of this function specifies the GUID of the device to be associated with the object. You can obtain this GUID by Enumeration of Sound Devices, or you can simply pass NULL to create the object for the default device.

LPDIRECTSOUND lpds;
HRESULT hr = DirectSoundCreate(NULL, &lpds, NULL));

The function returns an error if there is no sound device or if the sound device is under the control of an application using the waveform-audio (non-DirectSound) functions. You should prepare your applications for this call to fail so that they can either continue without sound or prompt the user to close the application that is already using the sound device.

You can also create the DirectSound object by using the CoCreateInstance function, as follows:

  1. Initialize COM at the start of your application by calling CoInitialize and specifying NULL.
    if FAILED(CoInitialize(NULL))
    return FALSE;
  2. Create your DirectSound object by using CoCreateInstance and the IDirectSound::Initialize method, rather than the DirectSoundCreate function.
    LPDIRECTSOUND lpds;
dsrval = CoCreateInstance(&CLSID_DirectSound,
                          NULL,
                          CLSCTX_INPROC_SERVER,
                          &IID_IDirectSound,
                          &lpds);
if SUCCEEDED(dsrval)
    dsrval = IDirectSound_Initialize(lpds, NULL);

CLSID_DirectSound is the class identifier of the DirectSound driver object class and IID_IDirectSound is the DirectSound interface that you should use. The lpds parameter is the uninitialized object CoCreateInstance returns.

Before you use a DirectSound object created with the CoCreateInstance function, you must call the IDirectSound::Initialize method. This method takes the same driver GUID parameter that DirectSoundCreate uses (NULL in this case). After the DirectSound object is initialized, you can use and release the DirectSound object as if it had been created by using the DirectSoundCreate function.

Before you close the application, close the COM library by calling the CoUninitialize function, as follows:

CoUninitialize();
[Visual Basic]

The simplest way to create the DirectSound object is with the DirectX7.DirectSoundCreate function. The only argument of this function specifies the GUID of the device to be associated with the object. You can obtain this GUID by Enumeration of Sound Devices, or you can simply pass an empty string to create the object for the default device.

Dim m_dx As New DirectX7
Dim m_ds As DirectSound
Set m_ds = m_dx.DirectSoundCreate("")

The method generates an error if there is no sound device or if the sound device is under the control of an application using the waveform-audio (non-DirectSound) functions. You should prepare your applications for this call to fail so that they can either continue without sound or prompt the user to close the application that is already using the sound device.


Cooperative Levels

Because Windows is a multitasking environment, more than one application may be working with a device driver at any one time. Through the use of cooperative levels, DirectX makes sure that each application does not gain access to the device in the wrong way or at the wrong time. Each DirectSound application has a cooperative level that determines the extent to which it is allowed to access the device.

After creating a DirectSound object, you must set the cooperative level for the device with the IDirectSound::SetCooperativeLevel method in C++ or the DirectSound.SetCooperativeLevel method in Visual Basic before you can play sounds.

DirectSound defines four cooperative levels for sound devices: normal, priority, exclusive, and write-primary. These are represented by the values DSSCL_NORMAL, DSSCL_PRIORITY, DSSCL_EXCLUSIVE, and DSSCL_WRITEPRIMARY.

Game applications should use DSSCL_PRIORITY in almost all circumstances. This level gives the most robust behavior while allowing the application control over sampling rate and bit depth. The priority cooperative level also allows audio from other applications (such as IP telephony) to be heard along with the audio from the game. The priority and exclusive levels provide identical performance, so DSSCL_EXCLUSIVE should be used only for applications that require all other applications to be muted. For a music-authoring application, for example, it might be critical that no other audio be heard during playback.

[C++]

The following C example sets the cooperative level for the DirectSound device initialized at Creating the DirectSound Object. The hwnd parameter is the handle to the application window.

HRESULT hr = lpDirectSound->lpVtbl->SetCooperativeLevel(
        lpDirectSound, hwnd, DSSCL_PRIORITY);
[Visual Basic]

The following Visual Basic example sets the cooperative level for the DirectSound device initialized at Creating the DirectSound Object. The hwnd argument is the handle to the application window and DSSCL_PRIORITY, like all flags in the DirectX 7 for Visual Basic type library, is a constant in an enumeration.

m_ds.SetCooperativeLevel Me.hWnd, DSSCL_PRIORITY

Normal Cooperative Level

At the normal cooperative level, the application cannot set the format of the primary sound buffer, write to the primary buffer, or compact the on-board memory of the device. All applications at this cooperative level use a primary buffer format of 22 kHz, stereo sound, and 8-bit samples, so that the device can switch between applications as smoothly as possible.

Priority Cooperative Level

When using a DirectSound device with the priority cooperative level, the application has first rights to hardware resources, such as hardware mixing, and can set the format of the primary sound buffer and compact the on-board memory of the device.

Exclusive Cooperative Level

At the exclusive cooperative level, the application has all the privileges of the priority level. In addition, when the application is in the foreground, its buffers are the only ones that are audible.

Write-primary Cooperative Level

The highest cooperative level is write-primary. When using a DirectSound device with this cooperative level, your application has direct access to the primary sound buffer. In this mode, the application must write directly to the primary buffer. Secondary buffers cannot be played while this is happening.

An application must be set to the write-primary level in order to obtain direct write access to the audio samples in the primary buffer. If the application is not set to this level, then all calls to the IDirectSoundBuffer::Lock method in C++ or DirectSoundBuffer.ReadBuffer and DirectSoundBuffer.WriteBuffer in Visual Basic for the primary buffer will fail.

When your application is set to the write-primary cooperative level and gains the foreground, all secondary buffers for other applications are stopped and marked as lost. When your application in turn moves to the background, its primary buffer is marked as lost and must be restored when the application again moves to the foreground. For more information, see Buffer Management.

You cannot set the write-primary cooperative level if a DirectSound driver is not present on the user's system. To determine whether this is the case, call the IDirectSound::GetCaps method in C++ or DirectSound.GetCaps method in Visual Basic and check for the DSCAPS_EMULDRIVER flag in the DSCAPS structure.

For more information, see Access to the Primary Buffer.


Device Capabilities

DirectSound allows your application to retrieve the hardware capabilities of the sound device. Most applications will not need to do this, because DirectSound automatically takes advantage of any available hardware acceleration. However, high-performance applications can use the information to scale their sound requirements to the available hardware. For example, an application might play more sounds if hardware mixing is available than if it is not.

[C++]

After calling the DirectSoundCreate function to create a DirectSound object, your application can retrieve the capabilities of the sound device by calling the IDirectSound::GetCaps method.

The following example retrieves the capabilities of the device that was initialized in Creating the DirectSound Object.

DSCAPS dscaps;

dscaps.dwSize = sizeof(DSCAPS);
HRESULT hr = lpDirectSound->lpVtbl->GetCaps(lpDirectSound,
    &dscaps);

The DSCAPS structure receives information about the performance and resources of the sound device, including the maximum resources of each type and the resources that are currently available. Note that the dwSize member of this structure must be initialized before the method is called.

If your application scales to hardware capabilities, you should call the IDirectSound::GetCaps method between every buffer allocation to determine if there are enough resources to create the next buffer.

[Visual Basic]

After calling the DirectX7.DirectSoundCreate method to create a DirectSound object, your application can retrieve the capabilities of the sound device by calling the DirectSound.GetCaps method.

The following example retrieves the capabilities of the device that was initialized in Creating the DirectSound Object.

Dim DSCAPS As DSCAPS

m_ds.GetCaps DSCAPS

The DSCAPS type receives information about the performance and resources of the sound device, including the maximum resources of each type and the resources that are currently available.

If your application scales to hardware capabilities, you should call the DirectSound.GetCaps method between every buffer allocation to determine if there are enough resources to create the next buffer.


Speaker Configuration

DirectSound uses the speaker configuration—that is, the position of the speakers relative to the listener—to optimize 3-D effects for the user's sound system.

[C++]

In Windows 98 and Windows 2000, the speaker configuration can be set by the user in Control Panel. An application can retrieve this value by using IDirectSound::GetSpeakerConfig and override it by calling IDirectSound::SetSpeakerConfig.

[Visual Basic]

In Windows 98 and Windows 2000, the speaker configuration can be set by the user in Control Panel. An application can retrieve this value by using DirectSound.GetSpeakerConfig and override it by calling DirectSound.SetSpeakerConfig.

In Windows 95, GetSpeakerConfig simply returns a default value or the last value you set with SetSpeakerConfig.


Compacting Hardware Memory

[Visual Basic]

This topic applies only to applications written in C++.

[C++]

As long as it has at least the priority cooperative level, your application can use the IDirectSound::Compact method to move any on-board sound memory into a contiguous block to make the largest portion of free memory available.


DirectSound Buffers

This section covers the creation and management of DirectSoundBuffer objects, which are the fundamental mechanism for playing sounds. The following topics are discussed:

  • Buffer Basics
  • Static and Streaming Sound Buffers
  • Creating Secondary Buffers
  • Buffer Control Options
  • Access to the Primary Buffer
  • Playing Sounds
  • Playback Controls
  • Current Play and Write Positions
  • Play Buffer Notification
  • Mixing Sounds
  • Custom Mixers
  • Buffer Management
  • Compressed Wave Formats
[C++]

Most of the information in this section applies to 3-D sound buffers as well. For information specific to the IDirectSound3DBuffer interface, see DirectSound 3-D Buffers.

For information about capture buffers, see DirectSoundCapture.

[Visual Basic]

Most of the information in this section applies to 3-D sound buffers as well. For information specific to the DirectSound3DBuffer class, see DirectSound 3-D Buffers.

For information about capture buffers, see DirectSoundCapture.


Buffer Basics

When you initialize DirectSound in your application, it automatically creates and manages a primary sound buffer for mixing sounds and sending them to the output device.

Your application must create at least one secondary sound buffer for storing and playing individual sounds. For more information on how to do this, see Creating Secondary Buffers.

A secondary buffer can exist throughout the life of an application or it may be destroyed when no longer needed. It may contain a single sound that is to be played repeatedly, such as a sound effect in a game, or it may be filled with new data from time to time. The application can play a sound stored in a secondary buffer as a single event or as a looping sound that plays continuously. Secondary buffers can also be used to stream data, in cases where a sound file contains more data than can conveniently be stored in memory.

For more information on the different kinds of secondary buffers, see Static and Streaming Sound Buffers.

[C++]

You can create two or more secondary buffers in the same physical memory by using the IDirectSound::DuplicateSoundBuffer method. You cannot duplicate the primary sound buffer. Note that if the original buffer is in hardware memory and hardware resources are not available for the duplicate buffer, this call may fail.

[Visual Basic]

You can create two or more secondary buffers in the same physical memory by using the DirectSound.DuplicateSoundBuffer method. You cannot duplicate the primary sound buffer. Note that if the original buffer is in hardware memory and hardware resources are not available for the duplicate buffer, this call may fail.

You mix sounds from different secondary buffers simply by playing them at the same time. Any number of secondary buffers can be played at one time, up to the limits of available processing power.

The DirectSound mixer can provide as little as 20 milliseconds of latency, so there is no perceptible delay before play begins. Under these conditions, if your application plays a buffer and immediately begins a screen animation, the audio and video appear to start at the same time. However, if DirectSound must emulate hardware features in software, the mixer cannot achieve low latency and a longer delay (typically 100-150 milliseconds) occurs before the sound is reproduced.

Normally you do not have to concern yourself at all with the primary buffer; DirectSound manages it behind the scenes. However, if your application is to perform its own mixing, DirectSound will let you write directly to the primary buffer. If you do this, you cannot also use secondary buffers. For more information, see Access to the Primary Buffer.


Static and Streaming Sound Buffers

When you create a secondary sound buffer, you specify whether it is a static sound buffer or a streaming sound buffer. A static buffer contains a complete sound in memory. A streaming buffer holds only a portion of a sound, such as 3 seconds of data from a 15-second bit of voice dialog. When using a streaming sound buffer, your application must periodically write new data to the buffer.

If a sound device has on-board sound memory, DirectSound attempts to place static buffers in the hardware memory. These buffers can then take advantage of hardware mixing, and the processing system incurs little or no overhead to mix these sounds. This is particularly useful for sounds your application plays repeatedly, because the sound data must be downloaded only once to the hardware memory.

Streaming buffers are generally located in main system memory to allow efficient writing to the buffer, although you can use hardware mixing on peripheral component interconnect (PCI) machines or other fast buses.

DirectSound distinguishes between static and streaming buffers in order to optimize performance, but it does not restrict how you can use the buffer. If a streaming buffer is big enough, there is nothing to prevent you from writing an entire sound to it in one chunk. In fact, if you do not intend to use the sound more than once, it can be more efficient to use a streaming buffer because by doing so you eliminate the step of downloading the data to hardware memory.

Your application may attempt to explicitly locate buffers in hardware or software. If you attempt to create a hardware buffer and there is insufficient memory or mixing capacity, the buffer creation request fails. Many existing sound cards do not have any on-board memory or mixing capacity, so no hardware buffers can be created on these devices.

For more information, see Creating Secondary Buffers.


Creating Secondary Buffers

[C++]

To create a sound buffer, your application fills a DSBUFFERDESC structure and then passes its address to the IDirectSound::CreateSoundBuffer method. This method creates a DirectSoundBuffer object and returns a pointer to an IDirectSoundBuffer interface. Your application uses this interface to manipulate and play the buffer.

The following example illustrates how to create a basic secondary sound buffer:

BOOL AppCreateBasicBuffer(
        LPDIRECTSOUND lpDirectSound,
        LPDIRECTSOUNDBUFFER *lplpDsb)
{
    PCMWAVEFORMAT pcmwf;
    DSBUFFERDESC dsbdesc;
    HRESULT hr;
    // Set up wave format structure.
    memset(&pcmwf, 0, sizeof(PCMWAVEFORMAT));
    pcmwf.wf.wFormatTag = WAVE_FORMAT_PCM;
    pcmwf.wf.nChannels = 2;
    pcmwf.wf.nSamplesPerSec = 22050;
    pcmwf.wf.nBlockAlign = 4;
    pcmwf.wf.nAvgBytesPerSec =
        pcmwf.wf.nSamplesPerSec * pcmwf.wf.nBlockAlign;
    pcmwf.wBitsPerSample = 16;
    // Set up DSBUFFERDESC structure.
    memset(&dsbdesc, 0, sizeof(DSBUFFERDESC)); // Zero it out.
    dsbdesc.dwSize = sizeof(DSBUFFERDESC);
    // Need default controls (pan, volume, frequency).
    dsbdesc.dwFlags = DSBCAPS_CTRLPAN | DSBCAPS_CTRLVOLUME | DSBCAPS_CTRLFREQUENCY;
    // 3-second buffer.
    dsbdesc.dwBufferBytes = 3 * pcmwf.wf.nAvgBytesPerSec;
    dsbdesc.lpwfxFormat = (LPWAVEFORMATEX)&pcmwf;
    // Create buffer.
    hr = lpDirectSound->lpVtbl->CreateSoundBuffer(lpDirectSound,
        &dsbdesc, lplpDsb, NULL);
    if SUCCEEDED(hr)
    {
        // Valid interface is in *lplpDsb.
        return TRUE;
    }
    else
    {
        // Failed.
        *lplpDsb = NULL;
        return FALSE;
    }
}

Your application should create buffers for the most important sounds first, and then create buffers for other sounds in descending order of importance. DirectSound allocates hardware resources to the first buffer that can take advantage of them.

If your application must explicitly locate buffers in hardware or software, you can specify either the DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE flag in the DSBUFFERDESC structure. If the DSBCAPS_LOCHARDWARE flag is specified and there is insufficient hardware memory or mixing capacity, the buffer creation request fails.

You can ascertain the location of an existing buffer by using the IDirectSoundBuffer::GetCaps method and checking the dwFlags member of the DSBCAPS structure for either the DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE flags. One or the other is always specified.

[Visual Basic]

To create a sound buffer, your application fills a DSBUFFERDESC type and then passes it to the DirectSound.CreateSoundBuffer method. This method creates and returns a DirectSoundBuffer object. Your application uses this object to manipulate and play the buffer.

The following example illustrates how to create a basic secondary sound buffer:

Dim m_dx As New DirectX7
Dim m_ds As DirectSound

Private Sub Form_Load()
  Set m_ds = m_dx.DirectSoundCreate("")
  CreateSoundBuffer
End Sub

Public Sub CreateSoundBuffer()
  Dim m_dsb As DirectSoundBuffer
  Dim buffdesc As DSBUFFERDESC
  Dim format As WAVEFORMATEX

  ' First you must specify the wave format
  format.nFormatTag = WAVE_FORMAT_PCM
  format.nChannels = 2
  format.lSamplesPerSec = 22050
  format.nBitsPerSample = 16
  format.nBlockAlign = (format.nChannels * format.nBitsPerSample) / 8
  format.lAvgBytesPerSec = format.lSamplesPerSec * format.nBlockAlign
  format.nSize = 0

  ' Next describe the sound buffer to be created
  buffdesc.lBufferBytes = format.lAvgBytesPerSec
  buffdesc.lFlags = DSBCAPS_CTRLPAN Or DSBCAPS_CTRLVOLUME Or DSBCAPS_CTRLFREQUENCY Or DSBCAPS_STATIC

  ' Create the buffer
  Set m_dsb = m_ds.CreateSoundBuffer(buffdesc, format)
End Sub

Your application should create buffers for the most important sounds first, and then create buffers for other sounds in descending order of importance. DirectSound allocates hardware resources to the first buffer that can take advantage of them.

If your application must explicitly locate buffers in hardware or software, you can specify either the DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE flag in the DSBUFFERDESC type. If the DSBCAPS_LOCHARDWARE flag is specified and there is insufficient hardware memory or mixing capacity, the buffer creation request fails.

You can ascertain the location of an existing buffer by using the DirectSoundBuffer.GetCaps method and checking the lFlags member of the DSBCAPS type for either the DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE flags. One or the other is always specified.

When you create a sound buffer, you can indicate that a buffer is static by specifying the DSBCAPS_STATIC flag. If you do not specify this flag, the buffer is a streaming buffer. For more information, see Static and Streaming Sound Buffers.

DirectSoundBuffer objects are owned by the DirectSound object that created them. When the DirectSound object is released, all buffers created by that object also will be released and should not be referenced.


Buffer Control Options

[C++]

When creating a sound buffer, your application must specify the control options needed for that buffer. This is done with the dwFlags member of the DSBUFFERDESC structure, which can contain one or more DSBCAPS_CTRL* flags. The following controls are available:

  • 3-D properties
  • Frequency
  • Pan
  • Volume
  • Position notification

To obtain the best performance on all sound cards, your application should specify only control options it will use.

DirectSound uses the control options in determining whether hardware resources can be allocated to sound buffers. For example, a device might support hardware buffers but provide no pan control on those buffers. In this case, DirectSound would use hardware acceleration only if the DSBCAPS_CTRLPAN flag was not specified.

If your application attempts to use a control that a buffer lacks, the method call fails. For example, if you attempt to change the volume by using the IDirectSoundBuffer::SetVolume method, the method can succeed only if the DSBCAPS_CTRLVOLUME flag was specified when the buffer was created. Otherwise the method fails and returns the DSERR_CONTROLUNAVAIL error code.

[Visual Basic]

When creating a sound buffer, your application must specify the control options needed for that buffer. This is done with the lFlags member of the DSBUFFERDESC type, which can contain one or more DSBCAPS_CTRL* flags. The following controls are available:

  • 3-D properties
  • Frequency
  • Pan
  • Volume
  • Position notification

To obtain the best performance on all sound cards, your application should specify only control options it will use.

DirectSound uses the control options in determining whether hardware resources can be allocated to sound buffers. For example, a device might support hardware buffers but provide no pan control on those buffers. In this case, DirectSound would use hardware acceleration only if the DSBCAPS_CTRLPAN flag was not specified.

If your application attempts to use a control that a buffer lacks, the method call fails. For example, if you attempt to change the volume by using the DirectSoundBuffer.SetVolume method, the method can succeed only if the DSBCAPS_CTRLVOLUME flag was specified when the buffer was created. Otherwise the method fails and raises the DSERR_CONTROLUNAVAIL error value.


Access to the Primary Buffer

For applications that require specialized mixing or other effects not supported by secondary buffers, DirectSound allows direct access to the primary buffer.

When you obtain write access to a primary sound buffer, other DirectSound features become unavailable. Secondary buffers are not mixed and, consequently, hardware-accelerated mixing is unavailable.

Most applications should use secondary buffers instead of directly accessing the primary buffer. Applications can write to a secondary buffer easily because the larger buffer size provides more time to write the next block of data, thereby minimizing the risk of gaps in the audio. Even if an application has simple audio requirements, such as using one stream of audio data that does not require mixing, it will achieve better performance by using a secondary buffer to play its audio data.

You cannot specify the size of the primary buffer, and you must accept the returned size after the buffer is created. A primary buffer is typically very small, so if your application writes directly to this kind of buffer, it must write blocks of data at short intervals to prevent the previously written data from being replayed.

[C++]

You create an accessible primary buffer by specifying the DSBCAPS_PRIMARYBUFFER flag in the DSBUFFERDESC structure passed to the IDirectSound::CreateSoundBuffer method. If you want to write to the buffer, the cooperative level must be DSSCL_WRITEPRIMARY.

You cannot obtain write access to a primary buffer unless it exists in hardware. To determine whether this is the case, call the IDirectSoundBuffer::GetCaps method and check for the DSBCAPS_LOCHARDWARE flag in the dwFlags member of the DSBCAPS structure that is returned. If you attempt to lock a primary buffer that is emulated in software, the call will fail.

Primary sound buffers must be played with looping. Ensure that the DSBPLAY_LOOPING flag is set.

The following example shows how to obtain write access to the primary buffer:

BOOL AppCreateWritePrimaryBuffer(
    LPDIRECTSOUND lpDirectSound,
    LPDIRECTSOUNDBUFFER *lplpDsb,
    LPDWORD lpdwBufferSize,
    HWND hwnd)
{
    DSBUFFERDESC dsbdesc;
    DSBCAPS dsbcaps;
    HRESULT hr;
    WAVEFORMATEX wf;

    // Set up wave format structure.
    memset(&wf, 0, sizeof(WAVEFORMATEX));
    wf.wFormatTag = WAVE_FORMAT_PCM;
    wf.nChannels = 2;
    wf.nSamplesPerSec = 22050;
    wf.nBlockAlign = 4;
    wf.nAvgBytesPerSec =
        wf.nSamplesPerSec * wf.nBlockAlign;
    wf.wBitsPerSample = 16;

    // Set up DSBUFFERDESC structure.
    memset(&dsbdesc, 0, sizeof(DSBUFFERDESC));
    dsbdesc.dwSize = sizeof(DSBUFFERDESC);
    dsbdesc.dwFlags = DSBCAPS_PRIMARYBUFFER;
    // Buffer size is determined by sound hardware.
    dsbdesc.dwBufferBytes = 0;
    dsbdesc.lpwfxFormat = NULL; // Must be NULL for primary buffers.

    // Obtain write-primary cooperative level.
    hr = lpDirectSound->lpVtbl->SetCooperativeLevel(lpDirectSound,
        hwnd, DSSCL_WRITEPRIMARY);
    if SUCCEEDED(hr)
    {
        // Try to create buffer.
        hr = lpDirectSound->lpVtbl->CreateSoundBuffer(lpDirectSound,
            &dsbdesc, lplpDsb, NULL);
        if SUCCEEDED(hr)
        {
            // Set primary buffer to desired format.
            hr = (*lplpDsb)->lpVtbl->SetFormat(*lplpDsb, &wf);
            if SUCCEEDED(hr)
            {
                // If you want to know the buffer size, call GetCaps.
                    dsbcaps.dwSize = sizeof(DSBCAPS);
                (*lplpDsb)->lpVtbl->GetCaps(*lplpDsb, &dsbcaps);
                *lpdwBufferSize = dsbcaps.dwBufferBytes;
                return TRUE;
            }
        }
    }
    // Failure.
    *lplpDsb = NULL;
    *lpdwBufferSize = 0;
    return FALSE;
}

You may also create a primary buffer object without write access, by specifying a cooperative level other than DSSCL_WRITEPRIMARY. One reason for doing this would be to call the IDirectSoundBuffer::Play method for the primary buffer, in order to eliminate problems associated with frequent short periods of silence. For more information, see Playing the Primary Buffer Continuously.

See also Custom Mixers.

[Visual Basic]

You create an accessible primary buffer by specifying the DSBCAPS_PRIMARYBUFFER flag in the DSBUFFERDESC type passed to the DirectSound.CreateSoundBuffer method. If you want to write to the buffer, the cooperative level must be DSSCL_WRITEPRIMARY.

You cannot obtain write access to a primary buffer unless it exists in hardware. To determine whether this is the case, call the DirectSoundBuffer.GetCaps method and check for the DSBCAPS_LOCHARDWARE flag in the lFlags member of the DSBCAPS type that is returned. If you attempt to lock a primary buffer that is emulated in software, the call will fail.

Primary sound buffers must be played with looping. Ensure that the DSBPLAY_LOOPING flag is set.

The following example shows how to obtain write access to the primary buffer:

Dim dx As New DirectX7

Public Function AppWriteDataToBuffer() As Boolean

    On Error GoTo errOUT
    Dim sDATA() As Byte
    Dim ds As DirectSound
    Dim dsb As DirectSoundBuffer
    Dim dsbd As DSBUFFERDESC
    Dim wf As WAVEFORMATEX

    wf = WaveEx(11025, 1, 8)

    With dsbd
        .lFlags = DSBCAPS_STATIC
        .lBufferBytes = wf.lAvgBytesPerSec * 2
    End With

    Set ds = dx.DirectSoundCreate("")
    Set dsb = ds.CreateSoundBuffer(dsbd, wf)

    ReDim sDATA(wf.lAvgBytesPerSec * 2)

    'fill the buffer with zeros
    dsb.WriteBuffer 0, 0, sDATA(0), DSBLOCK_ENTIREBUFFER
    AppWriteDataToBuffer = True
    Exit Function
errOUT:
    AppWriteDataToBuffer = False
End Function

Private Function WaveEx(Hz As Long, Channels As Integer, BITS As Integer) As WAVEFORMATEX

    WaveEx.nFormatTag = WAVE_FORMAT_PCM
    WaveEx.nChannels = Channels
    WaveEx.lSamplesPerSec = Hz
    WaveEx.nBitsPerSample = BITS
    WaveEx.nBlockAlign = Channels * BITS / 8
    WaveEx.lAvgBytesPerSec = WaveEx.lSamplesPerSec * WaveEx.nBlockAlign
    WaveEx.nSize = 0

End Function

Private Sub Form_Load()
    Call AppWriteDataToBuffer
End Sub

You may also create a primary buffer object without write access, by specifying a cooperative level other than DSSCL_WRITEPRIMARY. One reason for doing this would be to call the DirectSoundBuffer.Play method for the primary buffer, in order to eliminate problems associated with frequent short periods of silence. For more information, see Playing the Primary Buffer Continuously.

See also Custom Mixers.


Playing Sounds

[C++]

Playing a sound consists of the following steps:

  1. Lock a portion of the secondary buffer using IDirectSoundBuffer::Lock. This method returns a pointer to the address where writing will begin, based on the offset from the beginning of the buffer that you pass in to the method.
  2. Write the audio data to the buffer.
  3. Unlock the buffer using IDirectSoundBuffer::Unlock.
  4. Send the sound to the primary buffer and from there to the output device using IDirectSoundBuffer::Play. If the buffer is a streaming buffer, it will continue playing in a loop as steps 1 to 3 are repeated.

Because streaming sound buffers usually play continually and are conceptually circular, DirectSound returns two write pointers when locking a sound buffer. For example, if you tried to lock 3,000 bytes beginning at the midpoint of a 4,000-byte buffer, the Lock method would return one pointer to the last 2,000 bytes of the buffer, and a second pointer to the first 1,000 bytes. The second pointer is NULL if the locked portion of the buffer does not wrap around.

[Visual Basic]

Playing a sound consists of the following steps:

  1. Create an array to hold the buffer data.
  2. Reallocate the storage buffer to match the buffer size. The formula is: dscursors.lWrite * dsbufferdesc.fxformat.nBlockAlign + 1.
  3. Read a portion of the secondary buffer using DirectSoundBuffer.ReadBuffer. This method sets the address where writing will begin, based on the offset from the beginning of the buffer that you pass in to the method. Keep in mind you have to pass the first element of the array to hold the buffer data.
  4. Write the audio data to the buffer by calling DirectSoundBuffer.WriteBuffer.
  5. Send the sound to the primary buffer and from there to the output device using DirectSoundBuffer.Play. If the buffer is a streaming buffer, it will continue playing in a loop as steps 3 and 4 are repeated.

Because streaming sound buffers usually play continually and are conceptually circular, DirectSound returns two write pointers when locking a sound buffer. For example, if you tried to lock 3,000 bytes beginning at the midpoint of a 4,000-byte buffer, the ReadBuffer method would return one pointer to the last 2,000 bytes of the buffer, and a second pointer to the first 1,000 bytes.

[C++]

Normally the buffer stops playing automatically when the end is reached. However, if the DSBPLAY_LOOPING flag was set in the dwFlags parameter to the Play method, the buffer plays repeatedly until the application calls the IDirectSoundBuffer::Stop method.

[Visual Basic]

Normally the buffer stops playing automatically when the end is reached. However, if the DSBPLAY_LOOPING flag was set in the dwFlags parameter to the Play method, the buffer plays repeatedly until the application calls the DirectSoundBuffer.Stop method.

For streaming sound buffers, your application is responsible for ensuring that each block of data is written to the buffer ahead of the current play position. (For more on the play position, see Current Play and Write Positions.) Applications should write at least 1 second ahead of the current play position to minimize the possibility of gaps in the audio output during playback.

[C++]

The following C example writes data to a sound buffer, starting at the offset into the buffer passed in dwOffset:

BOOL AppWriteDataToBuffer(
    LPDIRECTSOUNDBUFFER lpDsb,  // the DirectSound buffer
    DWORD dwOffset,             // our own write cursor
    LPBYTE lpbSoundData,        // start of our data
    DWORD dwSoundBytes)         // size of block to copy
{
    LPVOID  lpvPtr1;
    DWORD   dwBytes1;
    LPVOID  lpvPtr2;
    DWORD   dwBytes2;
    HRESULT hr;

    // Obtain memory address of write block. This will be in two parts
    // if the block wraps around.
    hr = lpDsb->lpVtbl->Lock(lpDsb, dwOffset, dwSoundBytes, &lpvPtr1,
        &dwBytes1, &lpvPtr2, &dwBytes2, 0);

    // If DSERR_BUFFERLOST is returned, restore and retry lock.
    if (DSERR_BUFFERLOST == hr)
    {
        lpDsb->lpVtbl->Restore(lpDsb);
        hr = lpDsb->lpVtbl->Lock(lpDsb, dwOffset, dwSoundBytes,
            &lpvPtr1, &dwAudio1, &lpvPtr2, &dwAudio2, 0);
    }
    if SUCCEEDED(hr)
    {
        // Write to pointers.
        CopyMemory(lpvPtr1, lpbSoundData, dwBytes1);
        if (NULL != lpvPtr2)
        {
            CopyMemory(lpvPtr2, lpbSoundData+dwBytes1, dwBytes2);
        }
        // Release the data back to DirectSound.
        hr = lpDsb->lpVtbl->Unlock(lpDsb, lpvPtr1, dwBytes1, lpvPtr2,
            dwBytes2);
        if SUCCEEDED(hr)
        {
            // Success.
            return TRUE;
        }
    }
    // Lock, Unlock, or Restore failed.
    return FALSE;
}


Playback Controls

[C++]

To retrieve and set the volume at which a buffer is played, your application can use the IDirectSoundBuffer::GetVolume and IDirectSoundBuffer::SetVolume methods. Setting the volume on the primary sound buffer changes the waveform-audio volume of the sound card.

Similarly, by calling the IDirectSoundBuffer::GetFrequency and IDirectSoundBuffer::SetFrequency methods, you can retrieve and set the frequency at which audio samples play. You cannot change the frequency of the primary buffer.

To retrieve and set the pan, you can call the IDirectSoundBuffer::GetPan and IDirectSoundBuffer::SetPan methods. You cannot change the pan of the primary buffer.

[Visual Basic]

To retrieve and set the volume at which a buffer is played, your application can use the DirectSoundBuffer.GetVolume and DirectSoundBuffer.SetVolume methods. Setting the volume on the primary sound buffer changes the waveform-audio volume of the sound card.

Similarly, by calling the DirectSoundBuffer.GetFrequency and DirectSoundBuffer.SetFrequency methods, you can retrieve and set the frequency at which audio samples play. You cannot change the frequency of the primary buffer.

To retrieve and set the pan, you can call the DirectSoundBuffer.GetPan and DirectSoundBuffer.SetPan methods. You cannot change the pan of the primary buffer.

In order to use any of these controls, you must have set the appropriate flags when creating the buffer. See Buffer Control Options.


Current Play and Write Positions

DirectSound maintains two pointers into the buffer: the current play position (sometimes called the play cursor) and the current write position (or write cursor). These positions are byte offsets into the buffer, not absolute memory addresses.

[C++]

The IDirectSoundBuffer::Play method always starts playing at the buffer's current play position. When a buffer is created, the play position is set to zero. As a sound is played, the play position moves and always points to the next byte of data to be output. When the buffer is stopped, the play position remains at the next byte of data.

[Visual Basic]

The DirectSoundBuffer.Play method always starts playing at the buffer's current play position. When a buffer is created, the play position is set to zero. As a sound is played, the play position moves and always points to the next byte of data to be output. When the buffer is stopped, the play position remains at the next byte of data.

The current write position is the point after which it is safe to write data into the buffer. The block between the current play position and the current write position is already committed to be played, and cannot be changed safely.

Visualize the buffer as a clock face, with data written to it in a clockwise direction. The play position and the write position are like two hands sweeping around the face at the same speed, the write position always keeping a little ahead of the play position. If the play position points to the 1 and the write position points to the 2, it is only safe to write data after the 2. Data between the 1 and the 2 may already have been queued for playback by DirectSound and should not be touched.

Note The write position moves with the play position, not with data written to the buffer. If you're streaming data, you are responsible for maintaining your own pointer into the buffer to indicate where the next block of data should be written.

[C++]

Also note that the dwWriteCursor parameter to the IDirectSoundBuffer::Lock method is not the current write position; it is the offset within the buffer where you actually intend to begin writing data. (If you do want to begin writing at the current write position, you specify DSBLOCK_FROMWRITECURSOR in the dwFlags parameter. In this case the dwWriteCursor parameter is ignored.)

An application can retrieve the current play and write positions by calling the IDirectSoundBuffer::GetCurrentPosition method. The IDirectSoundBuffer::SetCurrentPosition method lets you set the current play position, but the current write position cannot be changed.

To ensure that the current play position is reported as accurately as possible, you should always specify the DSBCAPS_GETCURRENTPOSITION2 flag when creating a secondary buffer. For more information, see DSBUFFERDESC.

[Visual Basic]

Also note that the start parameter to the DirectSoundBuffer.ReadBuffer method is not the current write position; it is the offset within the buffer where you actually intend to begin writing data. (If you do want to begin writing at the current write position, you specify DSBLOCK_FROMWRITECURSOR in the flags parameter. In this case the start parameter is ignored.)

An application can retrieve the current play and write positions by calling the DirectSoundBuffer.GetCurrentPosition method. The DirectSoundBuffer.SetCurrentPosition method lets you set the current play position, but the current write position cannot be changed.

To ensure that the current play position is reported as accurately as possible, you should always specify the DSBCAPS_GETCURRENTPOSITION2 flag when creating a secondary buffer. For more information, see DSBUFFERDESC.


Play Buffer Notification

[C++]

When streaming audio, you may want your application to be notified when the current play position reaches a certain point in the buffer, or when playback is stopped. With the IDirectSoundNotify::SetNotificationPositions method you can set any number of points within the buffer where events are to be signaled. You cannot do this while the buffer is playing.

First you have to obtain a pointer to the IDirectSoundNotify interface. You can do this by using the buffer object's QueryInterface method, as in the following C++ example:

// LPDIRECTSOUNDBUFFER lpDsbSecondary;
// The buffer has been initialized already.

LPDIRECTSOUNDNOTIFY lpDsNotify;  // pointer to the interface

HRESULT hr = lpDsbSecondary->QueryInterface(IID_IDirectSoundNotify,
                                            (LPVOID *)&lpDsNotify);
if SUCCEEDED(hr)
{
    // Go ahead and use lpDsNotify->SetNotificationPositions.
}

Note The IDirectSoundNotify interface is associated with the object that obtained the pointer, in this case the secondary buffer. The methods of the new interface will automatically apply to that buffer.

Sound buffers created with the DSBCAPS_CTRLPOSITIONNOTIFY flag must set a notification event. If you create a sound buffer with the NOTIFY flag, but don't actually set any notifications, the behavior is undefined. You may experience sounds being played back twice. Therefore, applications should not use DSBCAPS_CTRLPOSITIONNOTIFY unless they actually set a notification event.

When using LOC_DEFER and NOTIFY along with any voice management TERMINATEBY flag, it is possible that a sound that has notifications set, but not yet reached, may be terminated by the voice manager. In this event, the notification event will not occur.

Now create an event object with the Win32® CreateEvent function. You put the handle to this event in the hEventNotify member of a DSBPOSITIONNOTIFY structure, and in the dwOffset member of that structure you specify the offset within the buffer where you want the event to be signaled. Then you pass the address of the structure—or of an array of structures, if you want to set more than one notification position—to the IDirectSoundNotify::SetNotificationPositions method.

The following example sets a single notification position. The event will be signaled when playback stops, either because it was not looping and the end of the buffer has been reached, or because the application called the IDirectSoundBuffer::Stop method.

DSBPOSITIONNOTIFY PositionNotify;

PositionNotify.Offset = DSBPN_OFFSETSTOP;
PositionNotify.hEventNotify = hMyEvent;
// hMyEvent is the handle returned by CreateEvent()

lpDsNotify->SetNotificationPositions(1, &PositionNotify);
[Visual Basic]

When streaming audio, you may want your application to be notified when the current play position reaches a certain point in the buffer, or when playback is stopped. With the DirectSoundBuffer.SetNotificationPositions method you can set any number of points within the buffer where events are to be signaled. You cannot do this while the buffer is playing.

To set a notification event on a buffer, you must first implement a DirectXEvent object in the form that contains the code for the buffer. Then you create an event handle by calling the DirectX7.CreateEvent method and pass the event handle in the hEventNotify member of a DSBPOSITIONNOTIFY type which is a parameter of the DirectSoundBuffer.SetNotificationPositions method. When the play position reaches a notification position in the buffer, the DirectXEvent.DXCallback is called.

Note Sound buffers created with the DSBCAPS_CTRLPOSITIONNOTIFY flag must set a notification event. If you create a sound buffer with the NOTIFY flag, but don't actually set any notifications, the behavior is undefined. You may experience sounds being played back twice. Therefore, applications should not use DSBCAPS_CTRLPOSITIONNOTIFY unless they actually set a notification event.


Mixing Sounds

[C++]

It is easy to mix multiple streams with DirectSound. You simply create secondary sound buffers, obtaining an IDirectSoundBuffer interface for each sound. You then play the buffers simultaneously. DirectSound takes care of the mixing in the primary sound buffer and plays the result.

[Visual Basic]

It is easy to mix multiple streams with DirectSound. You simply create secondary sound buffers, obtaining an DirectSoundBuffer object for each sound. You then play the buffers simultaneously. DirectSound takes care of the mixing in the primary sound buffer and plays the result.

The DirectSound mixer can obtain the best results from hardware acceleration if your application correctly specifies the DSBCAPS_STATIC flag for static buffers. This flag should be specified for any static buffers that will be reused. DirectSound downloads these buffers to the sound hardware memory, where available, and consequently does not incur any processing overhead in mixing these buffers. The most important static sound buffers should be created first to give them first priority for hardware acceleration.

The DirectSound mixer produces the best sound quality if all your application's sounds use the same wave format and the hardware output format is matched to the format of the sounds. If this is done, the mixer need not perform any format conversion.

[C++]

Your application can change the hardware output format by creating a primary sound buffer and calling the IDirectSoundBuffer::SetFormat method. Note that this primary buffer is for control purposes only; creating it is not the same as obtaining write access to the primary buffer as described under Access to the Primary Buffer, and you do not need the DSSCL_WRITEPRIMARY cooperative level. However, you do need a cooperative level of DSSCL_PRIORITY or higher in order to call the SetFormat method. DirectSound will restore the hardware format to the format specified in the last call every time the application gains the input focus.

[Visual Basic]

Your application can change the hardware output format by creating a primary sound buffer and calling the DirectSoundBuffer.SetFormat method. Note that this primary buffer is for control purposes only; creating it is not the same as obtaining write access to the primary buffer as described under Access to the Primary Buffer, and you do not need the DSSCL_WRITEPRIMARY cooperative level. However, you do need a cooperative level of DSSCL_PRIORITY or higher in order to call the SetFormat method. DirectSound will restore the hardware format to the format specified in the last call every time the application gains the input focus.


Custom Mixers

Most applications will use the DirectSound mixer; it should be sufficient for almost all mixing needs and it automatically takes advantage of any available hardware acceleration. However, if an application requires some other functionality that DirectSound does not provide, it can obtain write access to the primary sound buffer and mix streams directly into it.

[C++]

To implement a custom mixer, the application must first set the DSSCL_WRITEPRIMARY cooperative level and then create a primary sound buffer. (See Access to the Primary Buffer.) It can then lock the buffer, write data to it, unlock it, and play it just like any other buffer. (See Playing Sounds.) Note however that the DSBPLAY_LOOPING flag must be specified or the IDirectSoundBuffer::Play call will fail.

The following example illustrates how an application might implement a custom mixer. The AppMixIntoPrimaryBuffer sample function would have to be called at regular intervals, frequently enough to prevent the sound device from repeating blocks of data. The CustomMixer function is an application-defined function that mixes several streams together, as specified in the application-defined AppStreamInfo structure, and writes the result to the specified pointer.

BOOL AppMixIntoPrimaryBuffer(
        LPAPPSTREAMINFO lpAppStreamInfo,
        LPDIRECTSOUNDBUFFER lpDsbPrimary,
        DWORD dwDataBytes,
        DWORD dwOldPos,
        LPDWORD lpdwNewPos)
{
    LPVOID lpvPtr1;
    DWORD dwBytes1;
    LPVOID lpvPtr2;
    DWORD dwBytes2;
    HRESULT hr;
    // Obtain write pointer.
    hr = lpDsbPrimary->lpVtbl->Lock(lpDsbPrimary,
                                    dwOldPos, dwDataBytes,
                                    &lpvPtr1, &dwBytes1,
                                    &lpvPtr2, &dwBytes2, 0);
    // If DSERR_BUFFERLOST is returned, restore and retry lock.
    if (DSERR_BUFFERLOST == hr)
    {
        lpDsbPrimary->lpVtbl->Restore(lpDsbPrimary);
        hr = lpDsbPrimary->lpVtbl->Lock(lpDsbPrimary,
                                        dwOldPos, dwDataBytes,
                                        &lpvPtr1, &dwBytes1,
                                        &lpvPtr2, &dwBytes2, 0);
    }
    if SUCCEEDED(hr)
    {
        // Mix data into the returned pointers.
        CustomMixer(lpAppStreamInfo, lpvPtr1, dwBytes1);
        *lpdwNewPos = dwOldPos + dwBytes1;
        if (NULL != lpvPtr2)
        {
            CustomMixer(lpAppStreamInfo, lpvPtr2, dwBytes2);
            *lpdwNewPos = dwBytes2; // Because it wrapped around.
        }
        // Release the data back to DirectSound.
        hr = lpDsbPrimary->lpVtbl->Unlock(lpDsbPrimary,
                                          lpvPtr1, dwBytes1,
                                          lpvPtr2, dwBytes2);
        if SUCCEEDED(hr)
        {
            return TRUE;
        }
    }
    // Lock or Unlock failed.
    return FALSE;
}
[Visual Basic]

To implement a custom mixer, the application must first set the DSSCL_WRITEPRIMARY cooperative level and then create a primary sound buffer. (See Access to the Primary Buffer.) It can then lock the buffer, write data to it, unlock it, and play it just like any other buffer. (See Playing Sounds.) Note however that the DSBPLAY_LOOPING flag must be specified or the DirectSoundBuffer.Play call will fail.


Buffer Management

[C++]

The IDirectSoundBuffer::GetCaps method retrieves the capabilities of the DirectSoundBuffer object.

Your application can use the IDirectSoundBuffer::GetStatus method to determine if the current sound buffer is playing or if it has stopped.

You can use the IDirectSoundBuffer::GetFormat method to retrieve information about the format of the sound data in the buffer. You also can use the IDirectSoundBuffer::GetFormat and IDirectSoundBuffer::SetFormat methods to retrieve and set the format of the sound data in the primary sound buffer.

Note After a secondary sound buffer is created, its format is fixed. If you need a secondary buffer that uses another format, you must create a new sound buffer with this format.

Memory for a sound buffer can be lost in certain situations: for example, when buffers are located in sound card memory and another application gains control of the hardware resources. Loss can also occur when an application with the write-primary cooperative level moves to the foreground; in this case, DirectSound makes all other sound buffers lost so that the foreground application can write directly to the primary buffer.

The DSERR_BUFFERLOST error code is returned when the IDirectSoundBuffer::Lock or IDirectSoundBuffer::Play method is called for a lost buffer. When the application that caused the loss either lowers its cooperative level from write-primary or moves to the background, other applications can attempt to reallocate the buffer memory by calling the IDirectSoundBuffer::Restore method. If successful, this method restores the buffer memory and all other settings for the buffer, such as volume and pan settings. However, a restored buffer may not contain valid sound data, so the owning application should rewrite the data to the buffer.

[Visual Basic]

The DirectSoundBuffer.GetCaps method retrieves the capabilities of the DirectSoundBuffer object.

Your application can use the DirectSoundBuffer.GetStatus method to determine if the current sound buffer is playing or if it has stopped.

You can use the DirectSoundBuffer.GetFormat method to retrieve information about the format of the sound data in the buffer. You also can use the DirectSoundBuffer.GetFormat and DirectSoundBuffer.SetFormat methods to retrieve and set the format of the sound data in the primary sound buffer.

Note After a secondary sound buffer is created, its format is fixed. If you need a secondary buffer that uses another format, you must create a new sound buffer with this format.

Memory for a sound buffer can be lost in certain situations: for example, when buffers are located in sound card memory and another application gains control of the hardware resources. Loss can also occur when an application with the write-primary cooperative level moves to the foreground; in this case, DirectSound makes all other sound buffers lost so that the foreground application can write directly to the primary buffer.

The DSERR_BUFFERLOST error code is raised when the DirectSoundBuffer.Play method is called for a lost buffer. When the application that caused the loss either lowers its cooperative level from write-primary or moves to the background, other applications can attempt to reallocate the buffer memory by calling the DirectSoundBuffer.Restore method. If successful, this method restores the buffer memory and all other settings for the buffer, such as volume and pan settings. However, a restored buffer may not contain valid sound data, so the owning application should rewrite the data to the buffer.


Compressed Wave Formats

DirectSound does not currently support compressed wave formats. Applications should use the audio compression manager (ACM) functions, provided with the Win32 APIs in the Platform SDK, to convert compressed audio to pulse-code modulation (PCM) format before writing the data to a sound buffer. In fact, by locking a pointer to the sound-buffer memory and passing this pointer to the ACM, the data can be decoded directly to the sound buffer for maximum efficiency.


DirectSound in 3-D

DirectSound enables an application to change the apparent position and orientation of a sound source or listener, and also to suggest the relative velocity of the source and listener by using Doppler shift.

The following topics cover some general aspects of 3-D sound:

  • Integration with Direct3D
  • Mono and Stereo Sources
  • Perception of Sound Positions

Information on how to use 3-D sound in an application is found in the following sections:

  • DirectSound 3-D Buffers
  • DirectSound 3-D Listeners


Integration with Direct3D

[C++]

The IDirectSound3DBuffer and IDirectSound3DListener interfaces are designed to work together with Direct3D®. The positioning information used by Direct3D to arrange objects in a virtual environment can also be used to arrange sound sources. The D3DVECTOR and D3DVALUE structures that are familiar to Direct3D programmers are also used in the IDirectSound3DBuffer and IDirectSound3DListener interfaces. The same left-handed coordinate system used by Direct3D is employed by DirectSound. (For information about coordinate systems, see 3-D Coordinate Systems, in the Direct3D overview material.)

You can use the system callback mechanism of Direct3D to simplify the implementation of 3-D sound in your application. For example, you could use the D3DRMFRAMEMOVECALLBACK application-defined function to monitor the movement of a frame in an application and change the sonic environment only when a certain condition has been reached.

[Visual Basic]

The DirectSound3DBuffer and DirectSound3DListener interfaces are designed to work together with Direct3D®. The positioning information used by Direct3D to arrange objects in a virtual environment can also be used to arrange sound sources. The D3DVECTOR type that is familiar to Direct3D programmers are also used in the DirectSound3DBuffer and DirectSound3DListener classes. The same left-handed coordinate system used by Direct3D is employed by DirectSound. (For information about coordinate systems, see 3-D Coordinate Systems, in the Direct3D overview material.)

In DirectSound, distances are normally measured in meters. If your application does not use the meter as its unit of measure for 3-D graphics, you can set a distance factor, which is a floating-point value representing meters per application-specified distance unit. For example, if your application uses feet, it could specify a DirectSound distance factor of .3048, which is the number of meters in a foot.


Mono and Stereo Sources

Stereo sound sources are not particularly useful in the 3-D sound environments of DirectSound, because DirectSound creates its own stereo output from a monaural input. If an application uses stereo sound buffers, the left and right values for each sample are averaged before the 3-D processing is applied.

Applications should supply monaural sound sources when using the 3-D capabilities of DirectSound. Although the system can convert a stereo source into mono, there is no reason to supply stereo, and the conversion step wastes time.


Perception of Sound Positions

In the real world, the perception of a sound's position in space is influenced by a number of factors, including the following:

  • Volume. The farther an object is from the listener, the quieter it sounds. This phenomenon is known as rolloff.
  • Interaural intensity difference. A sound coming from the listener's right will sound louder in the right ear than in the left. This effect is familiar to anyone who has listened to a stereo sound system.
  • Interaural time difference. A sound emitted by a source to the listener's right will arrive at the right ear slightly before it arrives at the left ear. (The duration of this offset is approximately a millisecond.)
  • Muffling. The orientation of the ears ensures that sounds coming from behind the listener are slightly muffled compared with sounds coming from in front. In addition, if a sound is coming from the right, the sound reaching the left ear will be muffled by the mass of the listener's head as well as by the orientation of the left ear.

Although these are not the only cues people use to discern the position of sound, they are the main ones, and they are the factors that have been implemented in the positioning system of DirectSound. Hardware optimized for 3-D sound can support other cues as well, such as the effect of the earlobes on the pitch and timing of sounds arriving from different directions. The mathematics behind this effect are known as the head-related transfer function.

One of the most important sound-positioning cues, however, is still the apparent visual position of the sound source. If a projectile appears as a dot in the distance and grows to the size of an intercontinental missile before it roars past the viewer's head, the listener does not need subtle acoustical cues in order to sense the position and velocity of the sound source.


DirectSound 3-D Buffers

[C++]

A 3-D sound buffer is created and managed like any other sound buffer, and all the methods of the IDirectSoundBuffer interface are available. However, in order to set 3-D parameters you need to obtain the IDirectSound3DBuffer interface for the buffer. This interface is supported only by sound buffers created with the DSBCAPS_CTRL3D flag.

This section describes how your applications can manage buffers with the IDirectSound3DBuffer interface methods. The following topics are discussed:

[Visual Basic]

A 3-D sound buffer is created and managed like any other sound buffer, and all the methods of the DirectSoundBuffer class are available. However, in order to set 3-D parameters you need to obtain the DirectSound3DBuffer object for the buffer. This interface is supported only by sound buffers created with the DSBCAPS_CTRL3D flag.

This section describes how your applications can manage buffers with the DirectSound3DBuffer class methods. The following topics are discussed:

  • Obtaining the DirectSound3DBuffer Object
  • Batch Parameters for DirectSound3DBuffer
  • Minimum and Maximum Distances
  • Processing Mode
  • Buffer Position and Velocity
  • Sound Cones


Obtaining the DirectSound3DBuffer Object

[C++]

To obtain a pointer to an IDirectSound3DBuffer interface, you must first create a secondary 3-D sound buffer. Do this by using the IDirectSound::CreateSoundBuffer method, specifying the DSBCAPS_CTRL3D flag in the dwFlags member of the DSBUFFERDESC structure. Then, use the IDirectSoundBuffer::QueryInterface method on the resulting buffer to obtain a pointer to an IDirectSound3DBuffer interface for that buffer.

The following example calls the QueryInterface method with the C++ syntax:

// LPDIRECTSOUNDBUFFER lpDsbSecondary;
// The buffer has been created with DSBCAPS_CTRL3D.
LPDIRECTSOUND3DBUFFER lpDs3dBuffer;

HRESULT hr = lpDsbSecondary->QueryInterface(IID_IDirectSound3DBuffer,
                                            (LPVOID *)&lpDs3dBuffer);
if SUCCEEDED(hr)
{
    // Set 3-D parameters of this sound.
    .
    .
    .
}
[Visual Basic]

To obtain a DirectSound3DBuffer object, you must first create a secondary 3-D sound buffer. Do this by using the DirectSound.CreateSoundBuffer method, specifying the DSBCAPS_CTRL3D flag in the lFlags member of the DSBUFFERDESC type. Then, use the DirectSoundBuffer.GetDirectSound3DBuffer method on the resulting buffer to obtain a DirectSound3DBuffer object for that buffer.

The following example shows how to create a DirectSound3DBuffer object.

' In this example, it is assumed that ds is a valid
' DirectSound object

Dim dsbd As DSBUFFERDESC
Dim dsbPrimary As DIRECTSOUNDBUFFER
Dim waveFormat As WAVEFORMATEX
Dim ds3dBuffer As DirectSound3DBuffer

' Set up the wave format
waveFormat.nSize = LenB(WAVEFORMATEX)
    waveFormat.nFormatTag = WAVE_FORMAT_PCM
    waveFormat.nChannels = 2
    waveFormat.lSamplesPerSec = 22050
    waveFormat.nBitsPerSample = 16
    waveFormat.nBlockAlign = waveFormat.nBitsPerSample / 8 * WaveFormat.nChannels
    waveFormat.lAvgBytesPerSec = waveFormat.lSamplesPerSec * waveFormat.nBlockAlign

' Create the primary buffer
dsbd.lFlags = DSBCAPS_CTRL3D Or DSBCAPS_PRIMARYBUFFER
dsbPrimary = ds.CreateSoundBuffer(dsbd, waveFormat)

' Now create the DirectSound3DListener object
ds3DBuffer = dsbPrimary.GetDirectSound3DBuffer

Note Pan control conflicts with 3-D processing. If both DSBCAPS_CTRL3D and DSBCAPS_CTRLPAN are specified when the buffer is created, DirectSound returns an error.


Batch Parameters for DirectSound3DBuffer

[C++]

Applications can retrieve or set a 3-D sound buffer's parameters individually or in batches. To set individual values, your application can use the applicable IDirectSound3DBuffer interface method. However, applications often must set or retrieve all the values at once. You can do this with the IDirectSound3DBuffer::GetAllParameters and IDirectSound3DBuffer::SetAllParameters methods.

[Visual Basic]

Applications can retrieve or set a 3-D sound buffer's parameters individually or in batches. To set individual values, your application can use the applicable DirectSound3DBuffer object method. However, applications often must set or retrieve all the values at once. You can do this with the DirectSound3DBuffer.GetAllParameters and DirectSound3DBuffer.SetAllParameters methods.


Minimum and Maximum Distances

As a listener approaches a sound source, the sound gets louder: the volume doubles when the distance is halved. Past a certain point, however, it is not reasonable for the volume to continue to increase. This is the minimum distance for the sound source.

The minimum distance is especially useful when an application must compensate for the difference in absolute volume levels of different sounds. Although a jet engine is much louder than a bee, for example, for practical reasons these sounds must be recorded at similar absolute volumes. An application might use a minimum distance of 100 meters for the jet engine and 2 centimeters for the bee. With these settings, the jet engine would be at half volume when the listener was 200 meters away, but the bee would be at half volume when the listener was 4 centimeters away.

The default minimum distance for a sound buffer, DS3D_DEFAULTMINDISTANCE, is currently defined as 1 unit. Unless you change this value, the sound will be only half as loud when it is 2 meters away from the user, a quarter as loud at 4 meters, and so on. For most sounds you will probably want to set a larger minimum distance.

The maximum distance for a sound source is the distance beyond which the sound does not get any quieter. The default maximum distance for a DirectSound 3-D buffer (DS3D_DEFAULTMAXDISTANCE) is a huge number, meaning that in most cases the attenuation will continue to be calculated even when the sound ceases to be audible. In order to avoid unnecessary processing, applications should set a reasonable maximum distance and include the DSBCAPS_MUTE3DATMAXDISTANCE flag when creating the buffer.

The maximum distance can also be used to prevent a sound from becoming inaudible. For example, if you have set the minimum distance for a sound at 100 meters, that sound might become effectively inaudible at 1,000 meters or less. By setting the maximum distance at 800 meters you would ensure that the sound always had at least one-eighth of its maximum volume regardless of the distance. In this case, of course, you would not set the DSBCAPS_MUTE3DATMAXDISTANCE flag.

The following illustration shows the concepts of minimum and maximum distance.

[C++]

An application sets and retrieves the minimum distance value by using the IDirectSound3DBuffer::SetMinDistance and IDirectSound3DBuffer::GetMinDistance methods. Similarly, it can set and retrieve the maximum distance value by using the IDirectSound3DBuffer::SetMaxDistance and IDirectSound3DBuffer::GetMaxDistance methods.

[Visual Basic]

An application sets and retrieves the minimum distance value by using the DirectSound3DBuffer.SetMinDistance and DirectSound3DBuffer.GetMinDistance methods. Similarly, it can set and retrieve the maximum distance value by using the DirectSound3DBuffer.SetMaxDistance and DirectSound3DBuffer.GetMaxDistance methods.

By default, distance values are expressed in meters. See Distance Factor.

To adjust the effect of distance on volume for all sound buffers, you can change the Rolloff Factor.


Processing Mode

Sound buffers have three processing modes: normal, head-relative, and disabled.

In normal mode, the sound source is positioned and oriented absolutely in world space. This is the default mode.

[C++]

In head-relative mode, the buffer is automatically repositioned in world space as the listener moves and turns. Values set and retrieved through methods such as IDirectSound3DBuffer::SetPosition, IDirectSound3DBuffer::SetVelocity, and IDirectSound3DBuffer::GetConeOrientation are all relative to the current position, velocity, and orientation of the listener.

In disabled mode, 3-D sound processing is disabled and the sound seems to originate from the center of the listener's head.

An application sets the mode for a 3-D sound buffer by using the IDirectSound3DBuffer::SetMode method.

[Visual Basic]

In head-relative mode, the buffer is automatically repositioned in world space as the listener moves and turns. Values set and retrieved through methods such as DirectSound3DBuffer.SetPosition, DirectSound3DBuffer.SetVelocity, and DirectSound3DBuffer.GetConeOrientation are all relative to the current position, velocity, and orientation of the listener.

In disabled mode, 3-D sound processing is disabled and the sound seems to originate from the center of the listener's head.

An application sets the mode for a 3-D sound buffer by using the DirectSound3DBuffer.SetMode method.


Buffer Position and Velocity

[C++]

An application can set and retrieve a sound source's position in 3-D space by using the IDirectSound3DBuffer::SetPosition and IDirectSound3DBuffer::GetPosition methods. A position is expressed as a vector, relative to either world space or the listener, depending on the processing mode.

To set or retrieve the velocity value that DirectSound uses to calculate Doppler-shift effects for a listener, you use the IDirectSound3DBuffer::SetVelocity and IDirectSound3DBuffer::GetVelocity methods. Velocity is measured in distance units per second—by default, meters per second.

[Visual Basic]

An application can set and retrieve a sound source's position in 3-D space by using the DirectSound3DBuffer.SetPosition and DirectSound3DBuffer.GetPosition methods. A position is expressed as a vector, relative to either world space or the listener, depending on the processing mode.

To set or retrieve the velocity value that DirectSound uses to calculate Doppler-shift effects for a listener, you use the DirectSound3DBuffer.SetVelocity and DirectSound3DBuffer.GetVelocity methods. Velocity is measured in distance units per second—by default, meters per second.

Note that velocity is completely independent of the actual position or movement of a buffer. It is entirely up to the application to set the appropriate velocity for a buffer.


Sound Cones

A sound with no orientation is a point source; the amplitude of the sound at a given distance is the same in all directions. A sound with an orientation is a sound cone.

[C++]

In DirectSound, sound cones are made up of an inside cone and an outside cone. Within the inside cone, the volume of the sound is just what it would be if there were no cone; in other words, there is no attenuation from the normal volume. (Of course, normal volume is not necessarily maximum volume. It has already been modified by the basic volume of the buffer—as set by the IDirectSoundBuffer::SetVolume method—as well as by the distance from the listener, the listener's orientation, the rolloff factor, and the buffer's minimum distance value.) Outside the outside cone, the normal volume is attenuated by a specified number of decibels, as set by the application. The angle between the inside and outside cones is a zone of transition from the inside volume to the outside volume.

[Visual Basic]

In DirectSound, sound cones are made up of an inside cone and an outside cone. Within the inside cone, the volume of the sound is just what it would be if there were no cone; in other words, there is no attenuation from the normal volume. (Of course, normal volume is not necessarily maximum volume. It has already been modified by the basic volume of the buffer—as set by the DirectSoundBuffer.SetVolume method—as well as by the distance from the listener, the listener's orientation, the rolloff factor, and the buffer's minimum distance value.) Outside the outside cone, the normal volume is attenuated by a specified number of decibels, as set by the application. The angle between the inside and outside cones is a zone of transition from the inside volume to the outside volume.

The following illustration shows the concept of sound cones.

Technically, any 3-D sound buffer in DirectSound is a sound cone, but by default a buffer behaves like an omnidirectional sound source, because the outside volume is 0 (that is, there is no attenuation), and the inside and outside cone angles are 360 degrees. Until the application changes these values, the sound will not have any apparent orientation.

Designing sound cones properly can add dramatic effects to your application. For example, you could position a sound source in the center of a room, setting its orientation toward an open door in a hallway. Then set the angle of the inside cone so that it extends to the width of the doorway, make the outside cone a bit wider, and set the outside cone volume to inaudible. A listener moving along the hallway will begin to hear the sound when near the doorway, and the sound will be loudest as the listener passes in front of the open door.

[C++]

An application sets or retrieves the angles that define sound cones by using the IDirectSound3DBuffer::SetConeAngles and IDirectSound3DBuffer::GetConeAngles methods. The outside cone angle must always be equal to or greater than the inside cone angle.

To set or retrieve the orientation of sound cones, an application can use the IDirectSound3DBuffer::SetConeOrientation and IDirectSound3DBuffer::GetConeOrientation methods.

An application sets and retrieves the outside cone volume by using the IDirectSound3DBuffer::SetConeOutsideVolume and IDirectSound3DBuffer::GetConeOutsideVolume methods. The outside cone volume is expressed in hundredths of decibels and is a negative value, because it represents attenuation from the default volume of 0.

[Visual Basic]

An application sets or retrieves the angles that define sound cones by using the DirectSound3DBuffer.SetConeAngles and DirectSound3DBuffer.GetConeAngles methods. The outside cone angle must always be equal to or greater than the inside cone angle.

To set or retrieve the orientation of sound cones, an application can use the DirectSound3DBuffer.SetConeOrientation and DirectSound3DBuffer.GetConeOrientation methods.

An application sets and retrieves the outside cone volume by using the DirectSound3DBuffer.SetConeOutsideVolume and DirectSound3DBuffer.GetConeOutsideVolume methods. The outside cone volume is expressed in hundredths of decibels and is a negative value, because it represents attenuation from the default volume of 0.


DirectSound 3-D Listeners

A sound is only a sound when it is heard. The 3-D sound effects in a DirectSound application are affected not only by the position, orientation, and velocity of the sound buffer, but also by the position, orientation, and velocity of the listener.

[C++]

The IDirectSound3DListener interface controls the listener's position, orientation, and apparent velocity in 3-D space. It also controls the general parameters of the acoustic environment, such as the amount of Doppler shift and the rate of volume attenuation over distance.

This section describes how your application can obtain a pointer to an IDirectSound3DListener interface and manage listener parameters by using interface methods. The following topics are discussed:

[Visual Basic]

The DirectSound3DListener class controls the listener's position, orientation, and apparent velocity in 3-D space. It also controls the general parameters of the acoustic environment, such as the amount of Doppler shift and the rate of volume attenuation over distance.

This section describes how your application can obtain a DirectSound3DListener object and manage listener parameters by using interface methods. The following topics are discussed:

  • Obtaining the DirectSound3DListener Object
  • Batch Parameters for DirectSound3DListener
  • Deferred Settings
  • Distance Factor
  • Listener Orientation
  • Listener Position and Velocity
  • Doppler Factor
  • Rolloff Factor


Obtaining the DirectSound3DListener Object

[C++]

To obtain a pointer to an IDirectSound3DListener interface, you must first create a primary 3-D sound buffer. Do this by using the IDirectSound::CreateSoundBuffer method, specifying the DSBCAPS_CTRL3D and DSBCAPS_PRIMARYBUFFER flags in the dwFlags member of the accompanying DSBUFFERDESC structure. Then, use the IDirectSoundBuffer::QueryInterface method on the resulting buffer to obtain a pointer to an IDirectSound3DListener interface for that buffer, as shown in the following example with C++ syntax:

/* In this example, it is assumed that lpds is a valid
   pointer to a DirectSound object */

DSBUFFERDESC        dsbd;
LPDIRECTSOUNDBUFFER lpdsbPrimary;

ZeroMemory(&dsbd, sizeof(DSBUFFERDESC));
dsbd.dwSize = sizeof(DSBUFFERDESC);
dsbd.dwFlags = DSBCAPS_CTRL3D | DSBCAPS_PRIMARYBUFFER;
if SUCCEEDED(lpds->CreateSoundBuffer(&dsbd, &lpdsbPrimary, NULL))
{
    // Get listener interface
    if FAILED(lpdsbPrimary->QueryInterface(IID_IDirectSound3DListener,
            (LPVOID *)&lp3DListener))
    {
    lpdsbPrimary->Release();
    }
}
[Visual Basic]

To obtain a DirectSound3DListener object, you must first create a primary 3-D sound buffer. Do this by using the DirectSound.CreateSoundBuffer method, specifying the DSBCAPS_CTRL3D and DSBCAPS_PRIMARYBUFFER flags in the lFlags member of the accompanying DSBUFFERDESC type. Then, use the DirectSoundBuffer.GetDirectSound3DListener method on the resulting buffer to obtain a DirectSound3DListener object for that buffer, as shown in the following example with Visual Basic syntax:

' In this example, it is assumed that ds is a valid
' DirectSound object

Dim dsbd As DSBUFFERDESC
Dim dsbPrimary As DIRECTSOUNDBUFFER
Dim waveFormat As WAVEFORMATEX
Dim ds3dListener As DirectSound3DListener

' Set up the wave format
waveFormat.nSize = LenB(WAVEFORMATEX)
    waveFormat.nFormatTag = WAVE_FORMAT_PCM
    waveFormat.nChannels = 2
    waveFormat.lSamplesPerSec = 22050
    waveFormat.nBitsPerSample = 16
    waveFormat.nBlockAlign = waveFormat.nBitsPerSample / 8 * WaveFormat.nChannels
    waveFormat.lAvgBytesPerSec = waveFormat.lSamplesPerSec * waveFormat.nBlockAlign

' Create the primary buffer
dsbd.lFlags = DSBCAPS_CTRL3D Or DSBCAPS_PRIMARYBUFFER
dsbPrimary = ds.CreateSoundBuffer(dsbd, waveFormat)

' Now create the DirectSound3DListener object
ds3DListener = dsbPrimary.GetDirectSound3DListener


Batch Parameters for DirectSound3DListener

[C++]

Applications can retrieve or set a 3-D listener object's parameters individually or in batches. To set individual values, your application can use the applicable IDirectSound3DListener interface method. However, applications often must set or retrieve all the values that describe the listener at once. An application can perform these batch parameter manipulations in a single call by using the IDirectSound3DListener::GetAllParameters and IDirectSound3DListener::SetAllParameters methods.

[Visual Basic]

Applications can retrieve or set a 3-D listener object's parameters individually or in batches. To set individual values, your application can use the applicable DirectSound3DListener object method. However, applications often must set or retrieve all the values that describe the listener at once. An application can perform these batch parameter manipulations in a single call by using the DirectSound3DListener.GetAllParameters and DirectSound3DListener.SetAllParameters methods.


Deferred Settings

[C++]

Every change to 3-D sound buffer and listener settings causes DirectSound to remix, at the expense of CPU cycles. To minimize the performance impact of changing 3-D settings, use the DS3D_DEFERRED flag in the dwApply parameter of any of the IDirectSound3DListener or IDirectSound3DBuffer methods that change 3-D settings. Then call the IDirectSound3DListener::CommitDeferredSettings method to execute all of the deferred commands at once.

[Visual Basic]

Every change to 3-D sound buffer and listener settings causes DirectSound to remix, at the expense of CPU cycles. To minimize the performance impact of changing 3-D settings, use the DS3D_DEFERRED flag in the applyFlag parameter of any of the IDirectSound3DListener or IDirectSound3DBuffer methods that change 3-D settings. Then call the DirectSound3DListener.CommitDeferredSettings method to execute all of the deferred commands at once.

Note Any deferred settings are overwritten if your application calls the same setting method with the DS3D_IMMEDIATE flag before it calls CommitDeferredSettings. For example, if you set the listener velocity to (1.0, 0.0, 0.0) with the DS3D_DEFERRED flag and then set it to (2.0, 0.0, 0.0) with the DS3D_IMMEDIATE flag, the velocity will be (2.0, 0.0, 0.0). Then, if your application calls the CommitDeferredSettings method, the velocity will not change.


Distance Factor

DirectSound uses meters as the default unit of distance measurements. If your application does not use meters, it can set a distance factor, which is the number of meters in a vector unit.

[C++]

After you have set the distance factor for a listener, use your application's own distance units in calls to any methods that apply to that listener. Suppose, for example, that the basic unit of measurement in your application is the foot. You call the IDirectSound3DListener::SetDistanceFactor method, specifying 0.3048 as the flDistanceFactor parameter. (This value is the number of meters in a foot.) From then on, you continue using feet in parameters to method calls, and they are automatically converted to meters.

You can retrieve the current distance factor set for a listener by using the IDirectSound3DListener::GetDistanceFactor method.

[Visual Basic]

After you have set the distance factor for a listener, use your application's own distance units in calls to any methods that apply to that listener. Suppose, for example, that the basic unit of measurement in your application is the foot. You call the DirectSound3DListener.SetDistanceFactor method, specifying 0.3048 as the distanceFactor parameter. (This value is the number of meters in a foot.) From then on, you continue using feet in parameters to method calls, and they are automatically converted to meters.

You can retrieve the current distance factor set for a listener by using the DirectSound3DListener.GetDistanceFactor method.

The distance factor mainly affects Doppler shift (by changing the actual velocity represented by n units per second). It does not directly affect rolloff, because the rate of attenuation over distance is based on the minimum distance in units. If you set the minimum distance for a given sound at 2 units, the volume will be halved at a distance of 4 units, whether those units are in feet, meters, or any other measure. For more information, see Minimum and Maximum Distances.


Listener Orientation

Listener orientation is defined by the relationship between two vectors that share an origin at the center of the listener's head: the top and front vectors. The top vector points straight up through the top of the head, and the front vector points forward through the listener's face at right angles to the top vector, as in the following illustration.

[C++]

An application can set and retrieve the listener's orientation by using the IDirectSound3DListener::SetOrientation and IDirectSound3DListener::GetOrientation methods. By default, the front vector is (0, 0, 1.0), and the top vector is (0, 1.0, 0).

[Visual Basic]

An application can set and retrieve the listener's orientation by using the DirectSound3DListener.SetOrientation and DirectSound3DListener.GetOrientation methods. By default, the front vector is (0, 0, 1.0), and the top vector is (0, 1.0, 0).

The two vectors must always be at right angles to one another. If necessary, DirectSound will adjust the front vector so that it is at right angles to the top vector.


Listener Position and Velocity

[C++]

An application can set and retrieve a listener's position in 3-D space by using the IDirectSound3DListener::SetPosition and IDirectSound3DListener::GetPosition methods.

To set or retrieve the velocity value that DirectSound uses to calculate Doppler-shift effects for a listener, use the IDirectSound3DListener::SetVelocity and IDirectSound3DListener::GetVelocity methods. Velocity is measured in distance units per second—by default, meters per second.

[Visual Basic]

An application can set and retrieve a listener's position in 3-D space by using the DirectSound3DListener.SetPosition and DirectSound3DListener.GetPosition methods.

To set or retrieve the velocity value that DirectSound uses to calculate Doppler-shift effects for a listener, use the DirectSound3DListener.SetVelocity and DirectSound3DListener.GetVelocity methods. Velocity is measured in distance units per second—by default, meters per second.

As with buffers, a listener's position and its velocity are completely independent. It is entirely up to the application to set an appropriate velocity for the listener.


Doppler Factor

DirectSound automatically creates Doppler shift effects for any buffer or listener that has a velocity. Effects are cumulative: if the listener and the sound buffer are both moving, the system automatically calculates the relative velocity and adjusts the Doppler effect accordingly.

In order to have realistic Doppler shift effects in your application, you must calculate the speed of any object that is moving and set the appropriate velocity for that sound source or listener. You are free to exaggerate or lessen this value in a particular case in order to create special effects. You can also globally increase or decrease Doppler shift by changing the Doppler factor.

The Doppler factor can range from DS3D_MINDOPPLERFACTOR to DS3D_MAXDOPPLERFACTOR, currently defined in Dsound.h as 0.0 and 10.0 respectively. A value of 0 means no Doppler shift is applied to a sound. Every other value represents a multiple of the real-world Doppler shift. In other words, a value of 1 (or DS3D_DEFAULTDOPPLERFACTOR) means the Doppler shift that would be experienced in the real world is applied to the sound; a value of 2 means twice the real-world Doppler shift; and so on.

[C++]

The Doppler factor can be set and retrieved by using the IDirectSound3DListener::SetDopplerFactor and IDirectSound3DListener::GetDopplerFactor methods.

[Visual Basic]

The Doppler factor can be set and retrieved by using the DirectSound3DListener.SetDopplerFactor and DirectSound3DListener.GetDopplerFactor methods.


Rolloff Factor

Rolloff is the amount of attenuation that is applied to sounds, based on the listener's distance from the sound source. DirectSound can ignore rolloff, exaggerate it, or give it the same effect as in the real world, depending on a variable called the rolloff factor.

The rolloff factor can range from DS3D_MINROLLOFFFACTOR to DS3D_MAXROLLOFFFACTOR, currently defined in Dsound.h as 0.0 and 10.0 respectively. A value of DS3D_MINROLLOFFFACTOR means no rolloff is applied to a sound. Every other value represents a multiple of the real-world rolloff. In other words, a value of 1 (DS3D_DEFAULTROLLOFFFACTOR) means the rolloff that would be experienced in the real world is applied to the sound; a value of 2 means twice the real-world rolloff, and so on.

[C++]

You set and retrieve the rolloff factor by using the IDirectSound3DListener::SetRolloffFactor and IDirectSound3DListener::GetRolloffFactor methods.

[Visual Basic]

You set and retrieve the rolloff factor by using the DirectSound3DListener.SetRolloffFactor and DirectSound3DListener.GetRolloffFactor methods.

To change the rolloff for an individual sound buffer, you can set the minimum distance for the buffer. For more information, see Minimum and Maximum Distances.


DirectSoundCapture

[C++]

DirectSoundCapture provides an interface for capturing digital audio data from an input source. To use it you must create an instance of the IDirectSoundCapture interface, then use its methods to create a single capture buffer. The actual capturing is done with the methods of the buffer object.

[Visual Basic]

DirectSoundCapture provides an interface for capturing digital audio data from an input source. To use it you must create a DirectSoundCapture object, then use its methods to create a single capture buffer. The actual capturing is done with the methods of the buffer object.

This section covers the following topics:

  • Enumeration of Capture Devices
  • Creating the DirectSoundCapture Object
  • Capture Device Capabilities
  • Creating a Capture Buffer
  • Capture Buffer Information
  • Capture Buffer Notification
  • Capturing Sounds


Enumeration of Capture Devices

[C++]

For an application that is simply going to capture sounds through the user's preferred capture device, you don't need to enumerate the available devices. When you create the DirectSoundCapture object with NULL as the device identifier, the interface will automatically be associated with the default device if one is present. (If no device driver is present, the call to the DirectSoundCaptureCreate function fails.)

[Visual Basic]

For an application that is simply going to capture sounds through the user's preferred capture device, you don't need to enumerate the available devices. When you create the DirectSoundCapture object with an empty string as the device identifier, the interface will automatically be associated with the default device if one is present. (If no device driver is present, the call to the DirectX7.DirectSoundCaptureCreate function fails.)

However, if you are looking for a particular kind of device or wish to offer the user a choice of devices, you must enumerate the devices available on the system.

Enumeration serves three purposes:

  • Reports what hardware is available.
  • Supplies a GUID for each device.
  • Allows you to initialize DirectSoundCapture for each device as it is enumerated, so that you can check the capabilities of the device.
[C++]

To enumerate devices you must first set up a callback function that will be called each time DirectSound finds a device. You can do anything you want within this function, and you can give it any name, but you must declare it in the same form as DSEnumCallback, a prototype in this documentation. The callback function must return TRUE if enumeration is to continue, or FALSE otherwise (for instance, after finding a device with the capabilities you need).

For a sample callback function, see Enumeration of Sound Devices. Note that a GUID for each device is obtained as one of the parameters to this function.

The enumeration is set in motion by using the DirectSoundCaptureEnumerate function:

DWORD pv;  // Any 32-bit value.

HRESULT hr = DirectSoundCaptureEnumerate(
        (LPDSENUMCALLBACK)DSEnumProc,
        &pv)
[Visual Basic]

To enumerate devices you must first call the DirectX7.GetDSCaptureEnum method to create a DirectSoundEnum object. The DirectSoundEnum object is filled with a collection of devices which you can then query each individual device with the DirectSoundEnum.GetCount, DirectSoundEnum.GetDescription, DirectSoundEnum.GetGuid and DirectSoundEnum.GetName methods.


Creating the DirectSoundCapture Object

[C++]

You create the DirectSoundCapture object by calling the DirectSoundCaptureCreate function, which returns a pointer to an IDirectSoundCapture COM interface.

The lpGUID parameter to DirectSoundCaptureCreate can be a GUID obtained by enumeration, or it can be NULL for the preferred capture device. In most cases you will pass NULL.

You can also use the CoCreateInstance function to create the object. The procedure is similar to that for the DirectSound object; see Creating the DirectSound Object. If you use CoCreateInstance, then the object is created for the default capture device selected by the user on the multimedia control panel.

If you want DirectSound and DirectSoundCapture objects to coexist, then you should create and initialize the DirectSound object before creating and initializing the DirectSoundCapture object.

[Visual Basic]

You create the DirectSoundCapture object by calling the DirectX7.DirectSoundCaptureCreate method, which returns a DirectSoundCapture object.

The guid parameter to DirectSoundCaptureCreate can be a GUID obtained by enumeration, or it can be an empty string for the preferred capture device. In most cases you will pass an empty string.

If you want DirectSound and DirectSoundCapture objects to coexist, then you should create the DirectSound object before creating the DirectSoundCapture object.

Some audio devices aren't configured for full duplex audio by default. If you have problems with creating and initializing both a DirectSound object and a DirectSoundCapture object, you should check your audio device to ensure that two DMA channels are enabled.


Capture Device Capabilities

[C++]

To retrieve the capabilities of a capture device, call the IDirectSoundCapture::GetCaps method. The parameter to this method is a pointer to the DSCCAPS structure. As with other such structures, you have to initialize the dwSize member before passing it.

On return, the structure contains the number of channels the device supports as well as a combination of values for supported formats, equivalent to the values in the WAVEINCAPS structure used in the Win32 waveform audio functions.

[Visual Basic]

To retrieve the capabilities of a capture device, call the DirectSoundCapture.GetCaps method. The parameter to this method is a DSCCAPS type.

On return, the type contains the number of channels the device supports as well as a combination of values for supported formats, equivalent to the values in the WAVEINCAPS structure used in the Win32 waveform audio functions.


Creating a Capture Buffer

[C++]

You create a capture buffer by calling the IDirectSoundCapture::CreateCaptureBuffer method of the DirectSoundCapture object.

One of the parameters to the method is a DSCBUFFERDESC structure that describes the characteristics of the desired buffer. The last member of this structure is a WAVEFORMATEX structure, which must be initialized with the details of the desired wave format. For more information on this structure, see Sound Data.

Note that if your application is using DirectSound as well as DirectSoundCapture, capture buffer creation can fail when the format of the capture buffer is not the same as that of the primary buffer. The reason is that some cards have only a single clock and cannot support capture and playback at two different frequencies.

The following example sets up a capture buffer that will hold 1 second of data:

/* In this example it is assumed that pDSC is a valid pointer to
   a DirectSoundCapture object. */

DSCBUFFERDESC              dscbd;
LPDIRECTSOUNDCAPTUREBUFFER pDSCB;
WAVEFORMATEX               wfx =
    {WAVE_FORMAT_PCM, 2, 44100, 176400, 4, 16, 0};
    // wFormatTag, nChannels, nSamplesPerSec, mAvgBytesPerSec,
    // nBlockAlign, wBitsPerSample, cbSize
dscbd.dwSize = sizeof(DSCBUFFERDESC);
dscbd.dwFlags = 0;
dscbd.dwBufferBytes = wfx.nAvgBytesPerSec;
dscbd.dwReserved = 0;
dscbd.lpwfxFormat = &wfx;

pDSCB = NULL;

HRESULT hr = pDSC->CreateCaptureBuffer(&dscbd,
        &pDSCB, NULL);
[Visual Basic]

You create a capture buffer by calling the DirectSoundCapture.CreateCaptureBuffer method of the DirectSoundCapture object.

One of the parameters to the method is a DSCBUFFERDESC type that describes the characteristics of the desired buffer. The fxFormat member is a WAVEFORMATEX type, which must be initialized with the details of the desired wave format. For more information on this structure, see Sound Data.

Note that if your application is using DirectSound as well as DirectSoundCapture, capture buffer creation can fail when the format of the capture buffer is not the same as that of the primary buffer. The reason is that some cards have only a single clock and cannot support capture and playback at two different frequencies.

The following example sets up a capture buffer that will hold 1 second of data:

' In this example it is assumed that DSC is a valid
' DirectSoundCapture object

Dim dscbd As DSCBUFFERDESC
Dim DSCB As DIRECTSOUNDCAPTUREBUFFER
Dim waveFormat As WAVEFORMATEX

' Set up the wave format
waveFormat.nSize = LenB(WAVEFORMATEX)
    waveFormat.nFormatTag = WAVE_FORMAT_PCM
    waveFormat.nChannels = 2
    waveFormat.lSamplesPerSec = 22050
    waveFormat.nBitsPerSample = 16
    waveFormat.nBlockAlign = waveFormat.nBitsPerSample / 8 * WaveFormat.nChannels
    waveFormat.lAvgBytesPerSec = waveFormat.lSamplesPerSec * waveFormat.nBlockAlign

' Set up the DSCBUFFERDESC
dscbd.lFlags = DSCBCAPS_DEFAULT
dscbd.lBufferBytes = waveFormat.nAvgBytesPerSec
dscbd.fxFormat = waveFormat

' Now were ready to create the capture buffer
DSCB = DSC.CreateCaptureBuffer (dscbd)


Capture Buffer Information

[C++]

Use the IDirectSoundCaptureBuffer::GetCaps method to retrieve the size of a capture buffer. Be sure to initialize the dwSize member of the DSCBCAPS structure before passing it as a parameter. You can also retrieve information about the format of the data in the buffer, as set when the buffer was created. Call the IDirectSoundCaptureBuffer::GetFormat method, which returns the format information in a WAVEFORMATEX structure. For more information on this structure, see Sound Data.

Note that your application can allow for extra format information in the WAVEFORMATEX structure by first calling the GetFormat method with NULL as the lpwfxFormat parameter. In this case the DWORD pointed to by the lpdwSizeWritten parameter will receive the size of the structure needed to receive complete format information.

To find out what a capture buffer is currently doing, call the IDirectSoundCaptureBuffer::GetStatus method. This method fills a DWORD variable with a combination of flags that indicate whether the buffer is busy capturing, and if so, whether it is looping; that is, whether the DSCBSTART_LOOPING flag was set in the last call to IDirectSoundCaptureBuffer::Start.

Finally, the IDirectSoundCaptureBuffer::GetCurrentPosition method returns the current read and capture positions within the buffer. The read position is the end of the data that has been captured into the buffer at this point. The capture position is the end of the block of data that is currently being copied from the hardware. You can safely copy data from the buffer only up to the read position.

[Visual Basic]

Use the DirectSoundCaptureBuffer.GetCaps method to retrieve information about the format of the data in the buffer, as set when the buffer was created. Call the DirectSoundCaptureBuffer.GetFormat method, which returns the format information in a WAVEFORMATEX type. For more information on this structure, see Sound Data.

To find out what a capture buffer is currently doing, call the DirectSoundCaptureBuffer.GetStatus method. This method returns with a combination of flags that indicate whether the buffer is busy capturing, and if so, whether it is looping; that is, whether the DSCBSTART_LOOPING flag was set in the last call to DirectSoundCaptureBuffer.Start.

Finally, the DirectSoundCaptureBuffer.GetCurrentPosition method returns the current read and capture positions within the buffer. The read position is the end of the data that has been captured into the buffer at this point. The capture position is the end of the block of data that is currently being copied from the hardware. You can safely copy data from the buffer only up to the read position.


Capture Buffer Notification

[C++]

You may want your application to be notified when the current read position reaches a certain point in the buffer, or when it reaches the end. The current read position is the point up to which it is safe to read data from the buffer. With the IDirectSoundNotify::SetNotificationPositions method you can set any number of points within the buffer where events are to be signaled.

First you have to obtain a pointer to the IDirectSoundNotify interface. You can do this with the capture buffer's QueryInterface method, as shown in the example under Play Buffer Notification.

Next create an event object with the Win32 CreateEvent function. You put the handle to this event in the hEventNotify member of a DSBPOSITIONNOTIFY structure, and in the dwOffset member of that structure you specify the offset within the buffer where you want the event to be signaled. Then you pass the address of the structure—or array of structures, if you want to set more than one notification position—to the IDirectSoundNotify::SetNotificationPositions method.

The following example sets up three notification positions in a one-second buffer. One event will be signaled when the read position nears the halfway point in the buffer, another will be signaled when it nears the end of the buffer, and the third will be signaled when capture stops.

#define cEvents  3

/* In this example it is assumed that the following variables have
   been properly initialized, and that wfx was included in the buffer
   description when the buffer was created.

   LPDIRECTSOUNDNOTIFY  lpDsNotify;
   WAVEFORMATEX          wfx;
*/

HANDLE             rghEvent[cEvents] = {0};
DSBPOSITIONNOTIFY  rgdsbpn[cEvents];
HRESULT            hr;
int                i;

// Create the events
for (i = 0; i < cEvents; ++i)
{
    rghEvent[i] = CreateEvent(NULL, TRUE, FALSE, NULL);
    if (NULL == rghEvent[i])
    {
        hr = GetLastError();
        goto Error;
    }
}

// Describe notifications.

rgdsbpn[0].dwOffset = (wfx.nAvgBytesPerSec/2) -1;
rgdsbpn[0].hEventNotify = rghEvent[0];

rgdsbpn[1].dwOffset = wfx.nAvgBytesPerSec - 1;
rgdsbpn[1].hEventNotify = rghEvent[1];

rgdsbpn[2].dwOffset = DSBPN_OFFSETSTOP;
rgdsbpn[2].hEventNotify = rghEvent[2];

// Create notifications.

hr = lpDsNotify->SetNotificationPositions(cEvents, rgdsbpn);
[Visual Basic]

You may want your application to be notified when the current read position reaches a certain point in the buffer, or when it reaches the end. The current read position is the point up to which it is safe to read data from the buffer. With the DirectSoundCaptureBuffer.SetNotificationPositions method you can set any number of points within the buffer where events are to be signaled.

To set a notification event on a buffer, you must first implement a DirectXEvent object in the form that contains the code for the buffer. Then you create an event handle by calling the DirectX7.CreateEvent method and pass the event handle in the hEventNotify member of a DSBPOSITIONNOTIFY type. The DSBPOSITIONNOTIFY type is then used in the DirectSoundCaptureBuffer.SetNotificationPositions method. When the play position reaches a notification position in the buffer, the DirectXEvent.DXCallback is called.


Capturing Sounds

[C++]

Capturing a sound consists of the following steps:

  1. Start the buffer by calling the IDirectSoundCaptureBuffer::Start method. Audio data from the input device begins filling the buffer from the beginning.
  2. Wait until the desired amount of data is available. For one method of determining when the capture position reaches a certain point, see Capture Buffer Notification.
  3. When sufficient data is available, lock a portion of the capture buffer by calling the IDirectSoundCaptureBuffer::Lock method.

    To make sure you are not attempting to lock a portion of memory that is about to be used for capture, you can first obtain the current read position by calling IDirectSoundCaptureBuffer::GetCurrentPosition. For an explanation of the read position, see Capture Buffer Information.

    As parameters to the Lock method, you pass the size and offset of the block of memory you want to read. The method returns a pointer to the address where the memory block begins, and the size of the block. If the block wraps around from the end of the buffer to the beginning, two pointers are returned, one for each section of the block. The second pointer is NULL if the locked portion of the buffer does not wrap around.

  4. Copy the data from the buffer, using the addresses and block sizes returned by the Lock method.
  5. Unlock the buffer with the IDirectSoundCaptureBuffer::Unlock method.
  6. Repeat steps 2 to 5 until you are ready to stop capturing data. Then call the IDirectSoundCaptureBuffer::Stop method.

Normally the buffer stops capturing automatically when the capture position reaches the end of the buffer. However, if the DSCBSTART_LOOPING flag was set in the dwFlags parameter to the IDirectSoundCaptureBuffer::Start method, the capture will continue until the application calls the IDirectSoundCaptureBuffer::Stop method.

[Visual Basic]

Capturing a sound consists of the following steps:

  1. Start the buffer by calling the DirectSoundCaptureBuffer.Start method. Audio data from the input device begins filling the buffer from the beginning.
  2. Wait until the desired amount of data is available. For one method of determining when the capture position reaches a certain point, see Capture Buffer Notification.
  3. Reallocate the storage buffer to match the buffer size. The formula is:
  4. dscursors.lWrite * dscbufferdesc.fxformat.nBlockAlign + 1.
  5. When sufficient data is available, read a portion of the capture buffer by calling the DirectSoundCaptureBuffer.ReadBuffer method.

    To make sure you are not attempting to read a portion of memory that is about to be used for capture, you can first obtain the current read position by calling DirectSoundCaptureBuffer.GetCurrentPosition. For an explanation of the read position, see Capture Buffer Information.

    As parameters to the ReadBuffer method, you pass the size and offset of the block of memory you want to read.

  6. Copy the data from the buffer, using the starting point and block size set by the ReadBuffer method by calling DirectSoundCaptureBuffer.WriteBuffer.
  7. Repeat steps 4 and 5 until you are ready to stop capturing data. Then call the DirectSoundCaptureBuffer.Stop method.

Normally the buffer stops capturing automatically when the capture position reaches the end of the buffer. However, if the DSCBSTART_LOOPING flag was set in the flags parameter to the DirectSoundCaptureBuffer.Start method, the capture will continue until the application calls the DirectSoundCaptureBuffer.Stop method.


DirectSound Property Sets

[Visual Basic]

This topic applies only to applications written in C++.

[C++]

Through the IKsPropertySet interface, DirectSound is able to support extended services offered by sound cards and their associated drivers.

Properties are arranged in sets. A GUID identifies a set, and a ULONG identifies a particular property within the set. For example, a hardware vendor might design a card capable of reverberation effects and define a property set DSPROPSETID_ReverbProps containing properties such as DSPROPERTY_REVERBPROPS_HALL and DSPROPERTY_REVERBPROPS_STADIUM.

Typically, the property identifiers are defined using a C language enumeration starting at ordinal zero.

Individual properties may also have associated parameters. The IKsPropertySet interface specification intentionally leaves these parameters undefined, allowing the designer of the property set to use them in a way most beneficial to the properties within the set being designed. The precise meaning of the parameters is defined with the definition of the properties.

To make use of extended properties on sound cards, you must first determine whether the driver supports the IKsPropertySet interface, and obtain a pointer to the interface if it is supported. You can do this by calling the QueryInterface method of an existing interface on a DirectSound3DBuffer object.

HRESULT hr = lpDirectSound3DBuffer->QueryInterface(
        IID_IKsPropertySet,
        (void**)&lpKsPropertySet));

In the example, lpDirectSound3DBuffer is a pointer to the buffer's interface and lpKsPropertySet receives the address of the IKsPropertySet interface if one is found. IID_IKsPropertySet is a GUID defined in Dsound.h.

The call will succeed only if the buffer is hardware-accelerated and the underlying driver supports property sets. If it does succeed, you can now look for a particular property using the IKsPropertySet::QuerySupport method. The value of the PropertySetId parameter is a GUID defined by the hardware vendor.

Once you've determined that support for a particular property exists, you can change the state of the property by using the IKsPropertySet::Set method and determine its present state by using the IKsPropertySet::Get method. The state of the property is set or returned in the pPropertyData parameter.

Additional property parameters may also be passed to the object in a structure pointed to by the pPropertyParams parameter to the IKsPropertySet::Set method. The exact way in which this parameter is to be used is defined in the hardware vendor's specifications for the property set, but typically it would be used to define the instance of the property set. In practice, the pPropertyParams parameter is rarely used.

Let's take a somewhat whimsical example. Suppose a sound card has the ability to play a set of songs in the voices of several famous tenors. The driver developer creates a property set, DSPROPSETID_Song, containing properties like DSPROPERTY_SONG_IRISH_EYES and DSPROPERTY_SONG_O_SOLE_MIO. The property set applies to all of the tenors, and the driver developer has specified that pPropertyParams defines the tenor instance. Now you, the application developer, want to make Caruso sing one of the songs:

/* It is assumed that the hardware vendor has also defined
   CARUSO and START in a header file. */

DWORD dwTenor = CARUSO;
BOOL  StartOrStop = START;

HRESULT hr = lpKsPropertySet->Set(
        DSPROPSETID_Song,
        DSPROPERTY_SONG_IRISH_EYES,
        &dwTenor,
        sizeof(dwTenor),
        &StartOrStop,
        sizeof(StartOrStop));


Optimizing DirectSound Performance

This section offers some miscellaneous tips for improving the performance of DirectSound. The following topics are covered:

  • Matching Buffer Formats
  • Playing the Primary Buffer Continuously
  • Using Hardware Mixing
  • Minimizing Control Changes
  • CPU Considerations for 3-D Buffers


Matching Buffer Formats

The DirectSound mixer converts the data from each secondary buffer into the format of the primary buffer. This conversion is done on the fly as data is mixed into the primary buffer, and costs CPU cycles. You can eliminate this overhead by ensuring that your secondary buffers and primary buffer have the same format. Normally this means setting the primary buffer format to the format of the wave files used for data.

Because of the way DirectSound does format conversion, you only need to match the sample rate and number of channels. It doesn't matter if there is a difference in sample size (8-bit or 16-bit).


Playing the Primary Buffer Continuously

[C++]

When there are no sounds playing, DirectSound stops the mixer engine and halts DMA (direct memory access) activity. If your application has frequent short intervals of silence, the overhead of starting and stopping the mixer each time a sound is played may be worse than the DMA overhead if you kept the mixer active. Also, some sound hardware or drivers may produce unwanted audible artifacts from frequent starting and stopping of playback. If your application is playing audio almost continuously with only short breaks of silence, you can force the mixer engine to remain active by calling the IDirectSoundBuffer::Play method for the primary buffer. The mixer will continue to run silently.

To resume the default behavior of stopping the mixer engine when there are no sounds playing, call the IDirectSoundBuffer::Stop method for the primary buffer.

[Visual Basic]

When there are no sounds playing, DirectSound stops the mixer engine and halts DMA (direct memory access) activity. If your application has frequent short intervals of silence, the overhead of starting and stopping the mixer each time a sound is played may be worse than the DMA overhead if you kept the mixer active. Also, some sound hardware or drivers may produce unwanted audible artifacts from frequent starting and stopping of playback. If your application is playing audio almost continuously with only short breaks of silence, you can force the mixer engine to remain active by calling the DirectSoundBuffer.Play method for the primary buffer. The mixer will continue to run silently.

To resume the default behavior of stopping the mixer engine when there are no sounds playing, call the DirectSoundBuffer.Stop method for the primary buffer.

For more information, see Access to the Primary Buffer


Using Hardware Mixing

[C++]

Most sound cards support some level of hardware mixing if there is a DirectSound driver for the card. The following tips will allow you to make the most of hardware mixing:

  • Use static buffers for sounds that you want to be mixed in hardware. DirectSound will attempt to use hardware mixing on static buffers.
  • Create sound buffers first for the sounds you use the most. There is a limit to the number of buffers that can be mixed by hardware.
  • At run time, use the IDirectSound::GetCaps method to determine what formats are supported by the sound-accelerator hardware and use only those formats if possible.
  • To create a static buffer, specify the DSBCAPS_STATIC flag in the dwFlags member of the DSBUFFERDESC structure when you create a secondary buffer. You can also specify the DSBCAPS_LOCHARDWARE flag to force hardware mixing for a buffer, however, if you do this and resources for hardware mixing are not available, the IDirectSound::CreateSoundBuffer method will fail.
[Visual Basic]

Most sound cards support some level of hardware mixing if there is a DirectSound driver for the card. The following tips will allow you to make the most of hardware mixing:

  • Use static buffers for sounds that you want to be mixed in hardware. DirectSound will attempt to use hardware mixing on static buffers.
  • Create sound buffers first for the sounds you use the most. There is a limit to the number of buffers that can be mixed by hardware.
  • At run time, use the DirectSound.GetCaps method to determine what formats are supported by the sound-accelerator hardware and use only those formats if possible.
  • To create a static buffer, specify the DSBCAPS_STATIC flag in the lFlags member of the DSBUFFERDESC type when you create a secondary buffer. You can also specify the DSBCAPS_LOCHARDWARE flag to force hardware mixing for a buffer, however, if you do this and resources for hardware mixing are not available, the DirectSound.CreateSoundBuffer method will fail.


Minimizing Control Changes

Performance is affected when you change the pan, volume, or frequency on a secondary buffer. To prevent interruptions in sound output, the DirectSound mixer must mix ahead from 20 to 100 or more milliseconds. Whenever you make a control change, the mixer has to flush its mix-ahead buffer and remix with the changed sound.

[C++]

It's a good idea to minimize the number of control changes you send. Try reducing the frequency of calls to routines that use the IDirectSoundBuffer::SetVolume, IDirectSoundBuffer::SetPan, and IDirectSoundBuffer::SetFrequency methods. For example, if you have a routine that moves a sound from the left to the right speaker in synchronization with animation frames, try calling the SetPan method only every second or third frame.

[Visual Basic]

It's a good idea to minimize the number of control changes you send. Try reducing the frequency of calls to routines that use the DirectSoundBuffer.SetVolume, DirectSoundBuffer.SetPan, and DirectSoundBuffer.SetFrequency methods. For example, if you have a routine that moves a sound from the left to the right speaker in synchronization with animation frames, try calling the SetPan method only every second or third frame.

Note 3-D control changes (orientation, position, velocity, Doppler factor, and so on) also cause DirectSound to remix its mix-ahead buffer. However, you can group a number of 3-D control changes together and cause only a single remix. See Deferred Settings.


CPU Considerations for 3-D Buffers

Software-emulated 3-D buffers are computationally expensive. For example, each buffer can consume about 6 percent of the processing time of a Pentium 90. You should take this into consideration when deciding when and how to use 3-D buffers in your applications.

[C++]

Use as few 3-D sounds as you can, and don't use 3-D on sounds that won't really benefit from the effect. Design your application so that it's easy to enable and disable 3-D effects on each sound. You can call the IDirectSound3DBuffer::SetMode method with the DS3DMODE_DISABLE flag to disable 3-D processing on any 3-D sound buffer.

[Visual Basic]

Use as few 3-D sounds as you can, and don't use 3-D on sounds that won't really benefit from the effect. Design your application so that it's easy to enable and disable 3-D effects on each sound. You can call the DirectSound3DBuffer.SetMode method with the DS3DMODE_DISABLE flag to disable 3-D processing on any 3-D sound buffer.

DirectSound provides a means for hardware manufacturers to provide acceleration of 3-D audio buffers. On these audio cards the host CPU consumption will not be a consideration.


Using Wave Files

[Visual Basic]

This topic applies only to applications written in C++.

[C++]

The IDirectSound and IDirectSoundCapture interfaces do not include methods for handling wave files. However, the source code for several of the sample applications includes a handy file, Wave.c, which contains functions for opening and creating a wave file, reading and writing the file headers, and streaming data to or from the file.

Wave files are in the Resource Interchange File Format (RIFF), which consists of a variable number of "chunks" containing either header information (for example, the wave format of sound samples) or data (the samples themselves). The Win32 API supplies functions for opening and closing RIFF files, seeking chunks, and so on. These functions, whose names all start with "mmio," are used by the wrapper functions in the Wave.c file.

More information about using the wrapper functions is given in the following two topics:

  • Reading from a Wave File
  • Writing to a Wave File


Reading from a Wave File

[Visual Basic]

This topic applies only to applications written in C++.

[C++]

In order to use the wrapper functions in Wavread.cpp, you must declare the following four variables:

WAVEFORMATEX  *pwfx;          // Wave format info
HMMIO         hmmio;          // File handle
MMCKINFO      mmckinfoData;   // Chunk info
MMCKINFO      mmckinfoParent; // Parent chunk info

The first step in reading a wave file is to call the WaveOpenFile function. This gets a handle to the file, verifies that it is in RIFF format, and gets information about the wave format. The parameters are the filename and the addresses of three of the variables you have declared:

if (WaveOpenFile(lpzFileName, &hmmio, &pwfx, &mmckinfoParent) != 0)
{
    // Failure
}

Note that the wrapper functions all return zero if successful.

The next step is to call the WaveStartDataRead function, causing the file pointer to descend to the data chunk. This function also fills in the MMCKINFO structure for the data chunk, so that you know how much data is available:

if (WaveStartDataRead(&hmmio, &mmckinfoData, &mmckinfoParent) != 0)
    {
    // Failure
    }

The application can now begin copying data from the file to a secondary sound buffer. Normally you don't create the sound buffer until you have obtained the size of the data chunk and the format of the wave. The following code creates a static buffer just large enough to hold all the data in the file.

/* It is assumed that lpds in a valid pointer
   to the DirectSound object. */

LPDIRECTSOUNDBUFFER  lpdsbStatic;
DSBUFFERDESC         dsbdesc;

memset(&dsbdesc, 0, sizeof(DSBUFFERDESC));
dsbdesc.dwSize = sizeof(DSBUFFERDESC);
dsbdesc.dwFlags = DSBCAPS_STATIC;
dsbdesc.dwBufferBytes = mmckinfoData.cksize;
dsbdesc.lpwfxFormat = pwfx;

if FAILED(lpds->CreateSoundBuffer(&dsbdesc, &lpdsbStatic, NULL))
{
    WaveCloseReadFile(&hmmio, &pwfx);
    return FALSE;
}

Because in this case the application is not streaming the data but simply filling a static buffer, the entire buffer is locked from the beginning. There is no wrap around, so only a single pointer and byte count are required.

LPVOID lpvAudio1;
DWORD  dwBytes1;

if FAILED(lpdsbStatic->Lock(
        0,              // Offset of lock start
        0,              // Size of lock; ignored in this case
        &lpvAudio1,     // Address of lock start
        &dwBytes1,      // Number of bytes locked
        NULL,           // Wrap around start; not used
        NULL,           // Wrap around size; not used
        DSBLOCK_ENTIREBUFFER))  // Flag
{
    // Error handling
    Close();
    .
    .
    .
}

The WaveReadFile function in Wavread.cpp copies the data from the file to the buffer pointer and returns zero if successful.

UINT cbBytesRead;

if (WaveReadFile(
        hmmio,              // file handle
        dwBytes1,           // no. of bytes to read
        (BYTE *) lpvAudio1, // destination
        &mmckinfoData,      // file chunk info
        &cbBytesRead))      // actual no. of bytes read
{
    // Handle failure on non-zero return
    WaveCloseReadFile(&hmmio, &pwfx);
    .
    .
    .
}

Finally, the application unlocks the buffer and closes the wave file:

lpdsbStatic->Unlock(lpvAudio1, dwBytes1, NULL, 0);
Close();

For a streaming buffer, you would typically call WaveReadFile at regular intervals determined by the current play position. (See Play Buffer Notification.) If the locked portion of the buffer wrapped around, of course, you would call WaveReadFile once for each segment of the lock.


Writing to a Wave File

[Visual Basic]

This topic applies only to applications written in C++.

[C++]

To prepare for writing to a wave file, the application must first declare four variables to be passed to the functions in Wavwrite.cpp:

WAVEFORMATEX  wfx;            // Wave format info
HMMIO         hmmio;          // File handle
MMCKINFO      mmckinfoData;   // Chunk info
MMCKINFO      mmckinfoParent; // Parent chunk (file) info

You must also initialize the WAVEFORMATEX structure with the format of the capture buffer.

Now you call the WaveOpenFile function, passing in the desired filename and the addresses of the global variables. The function creates the file and writes some header information. Like other functions in Wavwrite.cpp, WaveOpenFile returns zero if successful.

if (WaveOpenFile(pszFileName, &hmmio, &wfx,
        &mmckinfoData, &mmckinfoParent))
{
    // Failure
}

Next, call the WaveStartDataWrite function, which initializes the data chunk.

if (WaveStartDataWrite(&hmmio, &mmckinfoData, &mmioinfo))
{
     // Failure
}

The file is now ready to receive data. The following fragment illustrates how data might be copied from a capture buffer to a file.

/* It is assumed that the following variables contain
   valid assignments:
LPDIRECTSOUNDCAPTUREBUFFER lpdscb;    // Capture buffer
DSCBUFFERDESC    dscbDesc;            // Capture buffer description
DWORD            dwReadCursor;        // Internal cursor in buffer
DWORD            dwNumBytes;          // Bytes available
DWORD            dwTotalBytesWritten; // Running total in file
*/

LPBYTE pbInput1, pbInput2; // Pointers to data in buffer
DWORD  cbInput1, cbInput2; // Count of bytes in locked portion
UINT   BytesWritten;       // Count of bytes written to file

if FAILED(hr = lpdscb->Lock(dwReadCursor, dwNumBytes,
                      (LPVOID *)&pbInput1, &cbInput1,
                      (LPVOID *)&pbInput2, &cbInput2, 0))
{
    // Failure
}
else
{
    if (WaveWriteFile(hmmio, cbInput1, pbInput1, &mmckinfoData,
                    &dwBytesWritten, &mmioinfo))
    {
        // Failure
    }
    else dwTotalBytesWritten += BytesWritten;
    if (pbInput2 != NULL)
    {
        if (WaveWriteFile(hmmio, cbInput2, pbInput2, &mmckinfoData,
                    &BytesWritten, &mmioinfo))
        {
            // Failure
        }
        else dwTotalBytesWritten += BytesWritten;

    }
    lpdscb->Unlock(pbInput1, cbInput1, pbInput2, cbInput2);

    // Increment internal cursor, compensating for wrap around
    dwReadCursor += dwNumBytes;
    while (dwReadCursor >= dscbDesc.dwBufferBytes)
                dwMyReadCursor -= dscbDesc.dwBufferBytes;

}

When you are finished capturing data, you close the file:

WaveCloseWriteFile(&hmmio, &mmckinfoData,
        &mmckinfoParent, &mmioinfo,
        dwTotalBytesWritten / (wfx.wBitsPerSample / 8));

The WaveCloseWriteFile function calculates the total number of samples in the file and writes this number to the data chunk header.


Reading Wave Data from a Resource

[Visual Basic]

This topic applies only to applications written in C++.

[C++]

The DirectSound API does not include methods for reading a wave from a resource. However, there are helper functions in Dsutil3d.c, which you will find with the source code for the 3DMusic sample found in DirectMusic samples directory.

To store wave sounds in an executable or DLL, import your wave files as resources and give them string names. Note that Dsutil3d.c expects these resources to be of type "WAV." If you are using Microsoft® Visual C++®, imported wave files are turned into resources of type "WAVE." You must either change this nomenclature to "WAV" by editing the resource file, or else modify the assignment of c_szWAV in Dsutil3d.c so that the FindResource function is looking for "WAVE" resources.

You may also want to modify Dsutil3d.c so that the DSLoadSoundBuffer function sets only the appropriate control flags.

To create a static buffer and load the sound into it, simply pass the IDirectSound interface pointer and the name of the resource to the DSLoadSoundBuffer function. If successful, the function returns a pointer to the buffer. Here's a sample call, where lpds is the pointer to the IDirectSound interface:

#include "dsutil.h"

LPDIRECTSOUNDBUFFER  lpdsbFootstep;

lpdsbFootstep = DSLoadSoundBuffer(lpds, "FOOTSTEP");
if (lpdsbFootstep == NULL)
{
    // Failure
}


DirectSound Tutorials

This section contains a series of tutorials, each providing step-by-step instructions for implementing the basics of DirectSound in a C/C++ or Visual Basic application. The tutorials are written parallel to a set of sample files that are provided with this SDK in the \Samples\Multimedia\DSound\Tutorials directory, following their code path and providing explanations along the way. Readers are encouraged to follow along in the sample code as they move through these tutorials.

  • DirectSound C/C++ Tutorials
  • DirectSound Visual Basic Tutorials


DirectSound C/C++ Tutorials

[Visual Basic]

The information in this topic pertains only to applications written in C and C++. See DirectSound Visual Basic Tutorials.

[C++]

This section contains tutorials that provide step-by-step instructions for implementing basic DirectSound functionality.

  • Tutorial 1: Playing a Sound

    The first tutorial shows how to set up the DirectSound system, create a secondary buffer, and play data from a wave file.

  • Tutorial 2: Capturing a Sound

    The second tutorial shows how to create a DirectSoundCapture object and a capture buffer, and how to write data to a wave file.


Tutorial 1: Playing a Sound

[Visual Basic]

The information in this topic pertains only to applications written in C and C++. See DirectSound Visual Basic Tutorials.

[C++]

This tutorial shows how to create a simple DirectSound application that will play a wave file of any size.

The functions for opening, reading, and closing wave files are in Wavread.cpp, a module that is found with the DSShow3D tool application in the DirectX SDK. In order to implement the techniques shown in the tutorial, you must add Wavread.cpp and Wavread.h to your project and link to Winmm.lib. You must also add Debug.c and Debug.h from the same sample directory, or else edit the calls to the ASSERT macro in Wavread.cpp to call the standard assert function.

The method calls in this tutorial are made through the macros defined in Dsound.h, which are valid for both C and C++.

The tutorial is broken down into the following steps:

  • Step 1: Set Up DirectSound
  • Step 2: Open the Wave File
  • Step 3: Create the Secondary Buffer
  • Step 4: Set Up Play Notifications
  • Step 5: Handle the Play Notifications
  • Step 6: Stream Data from the Wave File
  • Step 7: Shut Down DirectSound


Step 1: Set Up DirectSound

[Visual Basic]

The information in this topic pertains only to applications written in C and C++. See DirectSound Visual Basic Tutorials.

[C++]

The tutorial requires the following definitions and global variables:

#define NUMEVENTS 2

LPDIRECTSOUND               lpds;
DSBUFFERDESC                dsbdesc;
LPDIRECTSOUNDBUFFER         lpdsb;
LPDIRECTSOUNDBUFFER         lpdsbPrimary;
LPDIRECTSOUNDNOTIFY         lpdsNotify;
WAVEFORMATEX                *pwfx;
HMMIO                       hmmio;
MMCKINFO                    mmckinfoData, mmckinfoParent;
DSBPOSITIONNOTIFY           rgdsbpn[NUMEVENTS];
HANDLE                      rghEvent[NUMEVENTS];

The first step is to create the DirectSound object, establish a cooperative level, and set the primary buffer format. All this is done in the InitDSound function shown in the following code.

The function takes two parameters: the main window handle and a pointer to the GUID of the sound device. In most cases you will pass NULL as the second parameter, indicating the default device, but you may obtain a GUID by device enumeration.

BOOL InitDSound(HWND hwnd, GUID *pguid)
{
   // Create DirectSound

    if FAILED(DirectSoundCreate(pguid, &lpds, NULL))
        return FALSE;

    // Set co-op level

    if FAILED(IDirectSound_SetCooperativeLevel(
            lpds, hwnd, DSSCL_PRIORITY))
        return FALSE;

You have set the priority cooperative level in order to be able to set the format of the primary buffer. If you don't change the default format, output will be in the 8-bit, 22 kHz format regardless of the format of the input. Setting the primary buffer to a higher format can do no harm, because even if the secondary buffers are in a lower format, the samples will be converted automatically by DirectSound. Note also that there's no danger of the call to IDirectSoundBuffer::SetFormat failing because the hardware doesn't support the higher format. DirectSound will simply set the closest available format.

To set the format of the primary buffer, you first describe it in the global DSBUFFERDESC structure, then pass this description to the IDirectSound::CreateSoundBuffer method.

    // Obtain primary buffer

    ZeroMemory(&dsbdesc, sizeof(DSBUFFERDESC));
    dsbdesc.dwSize = sizeof(DSBUFFERDESC);
    dsbdesc.dwFlags = DSBCAPS_PRIMARYBUFFER;
    if FAILED(lpds->CreateSoundBuffer(&dsbdesc, &lpdsbPrimary, NULL))
        return FALSE;

Once you have a primary buffer object, you describe the desired wave format and pass the description to the IDirectSoundBuffer::SetFormat method:

    // Set primary buffer format

    WAVEFORMATEX wfx;
    memset(&wfx, 0, sizeof(WAVEFORMATEX));
    wfx.wFormatTag = WAVE_FORMAT_PCM;
    wfx.nChannels = 2;
    wfx.nSamplesPerSec = 44100;
    wfx.wBitsPerSample = 16;
    wfx.nBlockAlign = wfx.wBitsPerSample / 8 * wfx.nChannels;
    wfx.nAvgBytesPerSec = wfx.nSamplesPerSec * wfx.nBlockAlign;

    hr = lpdsbPrimary->SetFormat(&wfx);

    return TRUE;
}  // InitDSound()

Next: Step 2: Open the Wave File


Step 2: Open the Wave File

[Visual Basic]

The information in this topic pertains only to applications written in C and C++. See DirectSound Visual Basic Tutorials.

[C++]

The sample program is a general-purpose wave-file reader that does not expect sound data in a particular format. That being the case, it's necessary to put off creating the secondary sound buffer until the format of the data is known.

The steps in opening the file and creating the secondary buffer are grouped in the SetupStreamBuffer function. This function first performs any necessary cleanup from the last time a sound was played:

BOOL SetupStreamBuffer(LPSTR lpzFileName)
{
    // Close any open file and release interfaces

    Close();  // Function in Wavread.cpp

    if (lpdsNotify != NULL)
    {
        lpdsNotify->Release();
        lpdsNotify = NULL;
    }

    if (lpdsb != NULL)
    {
        lpdsb->Release();
        lpdsb = NULL;
    }

The function now opens a wave file, gets the format, and advances the file pointer to the beginning of the sound data. It does this by using two functions in Wavread.cpp.

    if (WaveOpenFile(lpzFileName, &hmmio, &pwfx,
            &mmckinfoParent) != 0)
        return FALSE;
    if (WaveStartDataRead(&hmmio, &mmckinfoData,
            &mmckinfoParent) != 0)
        return FALSE;

The WaveOpenFile function initializes three of the global variables declared at the beginning of the tutorial: a file handle, a pointer to a WAVEFORMATEX structure, and the MMCKINFO structure for the parent chunk (that is, information about the file as a whole).

The file handle and chunk information are then passed to the WaveStartDataRead function, which returns information about the data chunk in mmckinfoData. You would be interested in this structure if you were creating a static buffer just big enough to accommodate all the data bytes. In this tutorial, though, you're creating a streaming buffer, so you don't need to know the size of the data chunk.

Next: Step 3: Create the Secondary Buffer


Step 3: Create the Secondary Buffer

[Visual Basic]

The information in this topic pertains only to applications written in C and C++. See DirectSound Visual Basic Tutorials.

[C++]

Still inside the SetupStreamBuffer function, you now create a secondary sound buffer in the same format as the wave file. The process is similar for that you used in Step 1 to create a primary buffer. First you describe the buffer in the global DSBUFFERDESC structure, then you pass this description to the IDirectSound::CreateSoundBuffer method.

    memset(&dsbdesc, 0, sizeof(DSBUFFERDESC));
    dsbdesc.dwSize = sizeof(DSBUFFERDESC);
    dsbdesc.dwFlags =
            DSBCAPS_GETCURRENTPOSITION2   // Always a good idea
            | DSBCAPS_GLOBALFOCUS         // Allows background playing
            | DSBCAPS_CTRLPOSITIONNOTIFY; // Needed for notification

    // The size of the buffer is arbitrary, but should be at least
    // two seconds, to keep data writes well ahead of the play
    // position.

    dsbdesc.dwBufferBytes = pwfx->nAvgBytesPerSec * 2;
    dsbdesc.lpwfxFormat = pwfx;

    if FAILED(IDirectSound_CreateSoundBuffer(
            lpds, &dsbdesc, &lpdsb, NULL))
    {
        WaveCloseReadFile(&hmmio, &pwfx);
        return FALSE;
    }

Next: Step 4: Set Up Play Notifications


Step 4: Set Up Play Notifications

[Visual Basic]

The information in this topic pertains only to applications written in C and C++. See DirectSound Visual Basic Tutorials.

[C++]

Now that you've successfully created a streaming buffer, you ask to be notified whenever the current play position reaches certain points in the buffer, so you'll know when it's time to stream more data. In the example, those positions will be set at the beginning and halfway mark of the buffer.

First you create the required number of events and store their handles in the rghEvent array:

    for (int i = 0; i < NUMEVENTS; i++)
    {
        rghEvent[i] = CreateEvent(NULL, FALSE, FALSE, NULL);
        if (NULL == rghEvent[i]) return FALSE;
    }

Next, you initialize the array of DSBPOSITIONNOTIFY structures, each of which associates a position in the buffer with an event handle:

    rgdsbpn[0].dwOffset = 0;
    rgdsbpn[0].hEventNotify = rghEvent[0];
    rgdsbpn[1].dwOffset = (dsbdesc.dwBufferBytes/2);
    rgdsbpn[1].hEventNotify = rghEvent[1];

Then you get the IDirectSoundNotify interface from the secondary buffer and pass the DSBPOSITIONNOTIFY array to the SetNotificationPositions method:

    if FAILED(IDirectSoundBuffer_QueryInterface(lpdsb,
            IID_IDirectSoundNotify, (VOID **)&lpdsNotify))
        return FALSE;

    if FAILED(IDirectSoundNotify_SetNotificationPositions(
             lpdsNotify, NUMEVENTS, rgdsbpn))
    {
        IDirectSoundNotify_Release(lpdsNotify);
        return FALSE;
    }

That completes the setup of the streaming buffer. Because you've already opened the wave file and are ready to start streaming data, you can set the buffer in motion here. You want it to continue running till the complete sound has been played, so you set the DSBPLAY_LOOPING flag.

    IDirectSoundBuffer_Play(lpdsb, 0, 0, DSBPLAY_LOOPING);

    return TRUE;
} // end of SetupStreamBuffer()

Next: Step 5: Handle the Play Notifications


Step 5: Handle the Play Notifications

[Visual Basic]

The information in this topic pertains only to applications written in C and C++. See DirectSound Visual Basic Tutorials.

[C++]

Notifications are received in the form of signaled events in the message loop within the WinMain function. The following fragment illustrates how the loop might be written in order to intercept signaled events as well as standard messages:

BOOL Done = FALSE;
while (!Done)
{
    DWORD dwEvt = MsgWaitForMultipleObjects(
            NUMEVENTS,      // How many possible events
            rghEvent,       // Location of handles
            FALSE,          // Wait for all?
            INFINITE,       // How long to wait
            QS_ALLINPUT);   // Any message is an event

    // WAIT_OBJECT_0 == 0 but is properly treated as an arbitrary
    // index value assigned to the first event, therefore we subtract
    // it from dwEvt to get the zero-based index of the event.

    dwEvt -= WAIT_OBJECT_0;

    // If the event was set by the buffer, there's input
    // to process.

    if (dwEvt < NUMEVENTS)
    {
        StreamToBuffer(dwEvt); // copy data to output stream
    }

    // If it's the last event, it's a message

    else if (dwEvt == NUMEVENTS)
    {
        while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
            if (msg.message == WM_QUIT)
            {
                Done = TRUE;
            }
            else
            {
                TranslateMessage(&msg);
                DispatchMessage(&msg);
            }
        }
    }  // end message processing
} // while (!Done)

Next: Step 6: Stream Data from the Wave File


Step 6: Stream Data from the Wave File

[Visual Basic]

The information in this topic pertains only to applications written in C and C++. See DirectSound Visual Basic Tutorials.

[C++]

The purpose of the notifications you set up and handled in the previous two steps is to alert you whenever half the data in the buffer has been played. As soon as the current play position passes the beginning or halfway point of the buffer, you write data into the segment of the buffer that has just been played. (When the buffer starts, you immediately receive a notification and write to the second half of the buffer.) Because the buffer holds 2 seconds' worth of data, your data write begins almost 1 second ahead of the current play position, which should allow ample time for the process to be completed before the play position reaches the new data.

In the WinMain function, whenever an event was signaled you passed the index of that event to the StreamToBuffer function. This index corresponds to the index of the notification position in the DSBPOSITIONNOTIFY array.

Here is the first part of the StreamToBuffer function:

BOOL StreamToBuffer(DWORD dwPos)
{
    LONG            lNumToWrite;
    DWORD           dwStartOfs;
    VOID            *lpvPtr1, *lpvPtr2;
    DWORD           dwBytes1, dwBytes2;
    UINT            cbBytesRead;
    static DWORD    dwStopNextTime = 0xFFFF;

    if (dwStopNextTime == dwPos)   // All data has been played
    {
        lpdsb->Stop();
        dwStopNextTime = 0xFFFF;
        return TRUE;
    }

    if (dwStopNextTime != 0xFFFF)  // No more to stream, but keep
                                 // playing to end of data
        return TRUE;

The dwStopNextTime variable is a flag to indicate that the end of the file has been reached; this is set later in the function. If it is nonzero, there is no more data to be streamed. If the value of dwStopNextTime equals the index of the notification being handled, then you know that the current play position has returned to where it was when the end of the file was reached; that is, the last segment of data you copied to the buffer has been played. In this case, it's time to stop the buffer so it doesn't keep playing old data.

The next part of the StreamToBuffer function determines the offset within the buffer where you will start copying the new data. Although the buffer in this tutorial has only two notification positions, the code is designed to work with any number. Remember, dwPos is the index of the notification position that has just been passed by the current play position. You are going to write to the segment of the buffer that starts at the previous notification position.

    if (dwPos == 0)
        dwStartOfs = rgdsbpn[NUMEVENTS - 1].dwOffset;
    else
        dwStartOfs = rgdsbpn[dwPos-1].dwOffset;

Now you determine the size of this segment of the buffer:

    lNumToWrite = (LONG) rgdsbpn[dwPos].dwOffset - dwStartOfs;
    if (lNumToWrite < 0) lNumToWrite += dsbdesc.dwBufferBytes;

You now have all the information you need to lock the buffer in preparation for the data write.

    IDirectSoundBuffer_Lock(lpdsb,
                     dwStartOfs,       // Offset of lock start
                     lNumToWrite,      // Number of bytes to lock
                     &lpvPtr1,         // Address of lock start
                     &dwBytes1,        // Count of bytes locked
                     &lpvPtr2,         // Address of wrap around
                     &dwBytes2,        // Count of wrap around bytes
                     0);               // Flags

In this example the lock will never wrap around, so you need to do only a single data copy from the file. You get the data by calling the WaveReadFile function in Wavread.cpp:

    WaveReadFile(hmmio,                // File handle
                 dwBytes1,             // Number of bytes to get
                 (BYTE *) lpvPtr1,     // Destination
                 &mmckinfoData,        // File chunk info
                 &cbBytesRead);        // Actual bytes read

Now determine if the end of the file has been reached. If it has, close it, write silence to the rest of this segment (because it will play all the way through before the buffer is stopped), and set the dwStopNextTime flag.

    if (cbBytesRead < dwBytes1)        // Reached end of file
    {
        WaveCloseReadFile(&hmmio, &pwfx);
        FillMemory((PBYTE)lpvPtr1 + cbBytesRead,
                dwBytes1 - cbBytesRead,
                (dsbdesc.lpwfxFormat->wBitsPerSample==8) ? 128 : 0);
        dwStopNextTime = dwPos;
    }

Finally, unlock the buffer and return to the message loop:

    IDirectSoundBuffer_Unlock(lpdsb,
            lpvPtr1, dwBytes1, lpvPtr2, dwBytes2);

    return TRUE;
} // end StreamToBuffer()

Next: Step 7: Shut Down DirectSound


Step 7: Shut Down DirectSound

[Visual Basic]

The information in this topic pertains only to applications written in C and C++. See DirectSound Visual Basic Tutorials.

[C++]

Before closing, your application needs to close any open wave file and release the DirectSoundNotify and DirectSound objects. Note that because you queried for the IDirectSoundNotify interface from a DirectSoundBuffer object, you must release the DirectSoundNotify object before releasing DirectSound. Releasing DirectSound automatically releases any existing buffers.

The following function does all the necessary cleanup:

void DSExit(void)
{
    Close();
    if (lpdsNotify)
        lpdsNotify->Release();
    if (lpds)
        lpds->Release();
}


Tutorial 2: Capturing a Sound

[Visual Basic]

The information in this topic pertains only to applications written in C and C++. See DirectSound Visual Basic Tutorials.

[C++]

This tutorial shows how to implement DirectSoundCapture to capture a sound (typically from the microphone input) and write it to a wave file.

The functions for creating, writing, and closing wave files are in Wavwrite.cpp, a module found with the CaptureSound sample application in the DirectX SDK. In order to implement the techniques shown in the tutorial, you must add Wavwrite.cpp and Wavwrite.h to your project and link to Winmm.lib. You must also add Debug.c and Debug.h from the same sample directory, or else edit the calls to the ASSERT macro in Wavwrite.cpp to call the standard assert function.

The method calls in this tutorial are made through the macros defined in Dsound.h, which are valid for both C and C++.

The tutorial is broken down into the following steps:

  • Step 1: Set Up DirectSoundCapture
  • Step 2: Set the Capture Format
  • Step 3: Create the Capture Buffer
  • Step 4: Set Up Capture Notification
  • Step 5: Create the Wave File
  • Step 6: Handle the Capture Notifications
  • Step 7: Stream Data to the Wave File
  • Step 8: Stop Capture
  • Step 9: Shut Down DirectSoundCapture


Step 1: Set Up DirectSoundCapture

[Visual Basic]

The information in this topic pertains only to applications written in C and C++. See DirectSound Visual Basic Tutorials.

[C++]

The tutorial requires the following definitions and global declarations:

#define NUMCAPTUREEVENTS 2

LPDIRECTSOUNDCAPTURE        lpdsc;
LPDIRECTSOUNDCAPTUREBUFFER  lpdscb;
LPDIRECTSOUNDNOTIFY         lpdsNotify;
DSCBUFFERDESC               dscbDesc;
HANDLE                      rghEvent[NUMCAPTUREEVENTS];
DSBPOSITIONNOTIFY           rgdscbpn[NUMCAPTUREEVENTS];
WAVEFORMATEX                wfx =
                       {WAVE_FORMAT_PCM, 1, 22050, 44100, 2, 16, 0};
HMMIO                       hmmio;
MMCKINFO                    mmckinfoData, mmckinfoParent;
MMIOINFO                    mmioinfo;
DWORD                       dwTotalBytesWritten;

It is not necessary to create a DirectSound object in order to use DirectSoundCapture. However, if your application will be playing back sound as well as recording it, you should create DirectSound first.

In this tutorial, all the initialization of the capture system takes place in a function called InitDSoundCapture, which takes no parameters. The first step is to create the DirectSoundCapture object. You associate the object with the default capture device by passing NULL as the first parameter to the DirectSoundCaptureCreate function.

BOOL InitDSoundCapture(void)
{

    if FAILED(DirectSoundCaptureCreate(NULL, &lpdsc, NULL))
        return FALSE;

Next: Step 2: Set the Capture Format


Step 2: Set the Capture Format

[Visual Basic]

The information in this topic pertains only to applications written in C and C++. See DirectSound Visual Basic Tutorials.

[C++]

After creating DirectSoundCapture, you should choose a wave format that is supported by the user's device. One way to do this is to start with the highest format and attempt to create a capture buffer in each format until the creation method succeeds. (For an example of how to step through the various formats, see Fdaudio.cpp in the Fdfilter sample program.) In this tutorial you simply check the capabilities of the device to see whether the default 16-bit format (defined in the declaration of the WAVEFORMATEX structure) is supported; if it is not, you select an 8-bit format that is supported by all devices.

The following code is within the InitDSoundCapture function:

    DSCCAPS dsccaps;

    dsccaps.dwSize = sizeof(DSCCAPS);
    if FAILED(IDirectSoundCapture_GetCaps(lpdsc, &dsccaps))
        return FALSE;

    if ((dsccaps.dwFormats & WAVE_FORMAT_2M16) == 0)
    {
        wfx.nSamplesPerSec = 11025;
        wfx.nAvgBytesPerSec = 11025;
        wfx.nBlockAlign = 1;
        wfx.wBitsPerSample = 8;
    }

Remember that if you are also using DirectSound playback in your application, you must select a capture format that is compatible with the format of the primary buffer. For more information, see the next step Step 3: Create the Capture Buffer


Step 3: Create the Capture Buffer

[Visual Basic]

The information in this topic pertains only to applications written in C and C++. See DirectSound Visual Basic Tutorials.

[C++]

Once you have ensured that the WAVEFORMATEX structure is valid for the user's device, you can go ahead and create a capture buffer in that format.

    dscbDesc.dwSize = sizeof(DSCBUFFERDESC);
    dscbDesc.dwFlags = 0;
    // Buffer will hold one second's worth of audio
    dscbDesc.dwBufferBytes = wfx.nAvgBytesPerSec;
    dscbDesc.dwReserved = 0;
    dscbDesc.lpwfxFormat = &wfx;

    if FAILED(IDirectSoundCapture_CreateCaptureBuffer(lpdsc,
            &dscbDesc, &lpdscb, NULL))
        return FALSE;

You now have a pointer to the buffer object in lpdscb.

Next: Step 4: Set Up Capture Notification


Step 4: Set Up Capture Notification

[Visual Basic]

The information in this topic pertains only to applications written in C and C++. See DirectSound Visual Basic Tutorials.

[C++]

As the final initialization step in the InitDSoundCapture function, you will set up notification positions in the capture buffer so that the application knows when it's time to stream more data to the file. In the example, these positions are set at the beginning and halfway mark of the buffer.

First you create the required number of events and store their handles in the rghEvent array:

    for (int i = 0; i < NUMCAPTUREEVENTS; i++)
    {
        rghEvent[i] = CreateEvent(NULL, FALSE, FALSE, NULL);
        if (NULL == rghEvent[i]) return FALSE;
    }

Next, you initialize the array of DSBPOSITIONNOTIFY structures, each of which associates a position in the buffer with an event handle:

    rgdscbpn[0].dwOffset = 0;
    rgdscbpn[0].hEventNotify = rghEvent[0];
    rgdscbpn[1].dwOffset = dscbDesc.dwBufferBytes/2;
    rgdscbpn[1].hEventNotify = rghEvent[1];

Finally, you get the IDirectSoundNotify interface from the capture buffer and pass the DSBPOSITIONNOTIFY array to the SetNotificationPositions method:

    if FAILED(IDirectSoundCaptureBuffer_QueryInterface(lpdscb,
            IID_IDirectSoundNotify, (VOID **)&lpdsNotify))
        return FALSE;

    if FAILED(IDirectSoundNotify_SetNotificationPositions(lpdsNotify,
            NUMCAPTUREEVENTS, rgdscbpn))
    {
        IDirectSoundNotify_Release(lpdsNotify);
        return FALSE;
    }

    return TRUE;
}  // end InitDSoundCapture()

Note that if you need to set up notifications for both a capture buffer and a secondary (output) buffer, the event handles have to be stored in the same rghEvent array. When you receive the notifications in the message loop, you can distinguish between the two types of events by the index number.

Next: Step 5: Create the Wave File


Step 5: Create the Wave File

[Visual Basic]

The information in this topic pertains only to applications written in C and C++. See DirectSound Visual Basic Tutorials.

[C++]

At this point it is presumed that you have obtained a valid filename and are ready to start saving sound data in a wave file. The process is initiated in the following function:

BOOL StartWrite(TCHAR *pszFileName)
{
    if (WaveOpenFile(pszFileName, &hmmio, &wfx,
            &mmckinfoData, &mmckinfoParent))
      return FALSE;

    if (WaveStartDataWrite(&hmmio, &mmckinfoData, &mmioinfo))
    {
        WaveCloseWriteFile(&hmmio, &mmckinfoData,
                &mmckinfoParent, &mmioinfo,
                dwTotalBytesWritten / (wfx.wBitsPerSample / 8));
        DeleteFile(pszFileName);
        return FALSE;
    }
    if FAILED(IDirectSoundCaptureBuffer_Start(lpdscb,
            DSCBSTART_LOOPING))
    {
        WaveCloseWriteFile(&hmmio, &mmckinfoData,
                &mmckinfoParent, &mmioinfo, 0);
        DeleteFile(pszFileName);
        return FALSE;
    }

    dwTotalBytesWritten = 0;

    return TRUE;
}

This function first calls the WaveOpenFile function in Wavwrite.cpp, in order to create a RIFF file and write the header for the wave format. It then calls the WaveStartDataWrite function, which advances the file pointer to the data chunk. Finally, it starts the capture buffer. In half a second your application will be notified that data is available, and you must be ready to copy it to the file.

Note also the initialization of dwTotalBytesWritten. This value is going to be needed for the data chunk header after capture is complete.

Next: Step 6: Handle the Capture Notifications


Step 6: Handle the Capture Notifications

[Visual Basic]

The information in this topic pertains only to applications written in C and C++. See DirectSound Visual Basic Tutorials.

[C++]

You receive capture notifications as events in the message loop, just as with playback notifications. Here is a sample loop:

BOOL Done = FALSE;
while (!Done)
{
    DWORD dwEvt = MsgWaitForMultipleObjects(
            NUMCAPTUREEVENTS,  // How many possible events
            rghEvent,          // Location of handles
            FALSE,             // Wait for all?
            INFINITE,          // How long to wait
            QS_ALLINPUT);      // Any message is an event

    dwEvt -= WAIT_OBJECT_0;

    // If the event was set by the buffer, there's input
    // to process.

    if (dwEvt < NUMCAPTUREEVENTS)
    {
        StreamToFile();
    }

    // If it's the last event, it's a message

    else if (dwEvt == NUMCAPTUREEVENTS)
    {
        while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
            if (msg.message == WM_QUIT)
            {
                Done = TRUE;
            }
            else
            {
                TranslateMessage(&msg);
                DispatchMessage(&msg);
            }
        }
    }  // end message processing
} // while (!Done)

As already noted, if you are receiving notifications from both a capture buffer and a secondary (output) buffer, you need to distinguish between the two types of events by the index value in dwEvt. For example, events 0 and 1 might be playback notifications, and events 2 and 3 might be capture notifications.

Next: Step 7: Stream Data to the Wave File


Step 7: Stream Data to the Wave File

[Visual Basic]

The information in this topic pertains only to applications written in C and C++. See DirectSound Visual Basic Tutorials.

[C++]

In the first tutorial you saw how to identify the segment of the buffer that was safe to write to by checking the offset of the notification position. This technique would work equally well with the capture buffer in the present tutorial, but this time you'll do things a bit differently.

In the previous step you saw how the StreamToFile function was called in response to a notification event. Unlike the StreamToBuffer function in the previous tutorial, this function does not take the event index as a parameter.

BOOL StreamToFile(void)
{
    DWORD               dwReadPos;
    DWORD               dwNumBytes;
    LPBYTE              pbInput1, pbInput2;
    DWORD               cbInput1, cbInput2;
    static DWORD        dwMyReadCursor = 0;
    UINT                dwBytesWritten;

Note the static declaration of dwMyReadCursor. This is the offset of the next byte of data you want to read; in other words, the byte just beyond the last one read on the previous pass through this function.

The first thing the function does is find the current read position. Remember, this position marks the leading edge of the data that is safe to read. It is not necessarily the same as the notification position, because it has likely advanced since the event was signaled.

    IDirectSoundCaptureBuffer_GetCurrentPosition(lpdscb,
            NULL, &dwReadPos);

The function then subtracts your internal read cursor from the current read position (after allowing for wrap around) in order to determine how many bytes of new data are available:

    if (dwReadPos < dwMyReadCursor)
            dwReadPos += dscbDesc.dwBufferBytes;
    dwNumBytes = dwReadPos - dwMyReadCursor;

You then lock the buffer and do the copy. Because the segment of data you've identified as available is not exactly demarcated by the notification positions at the beginning and midpoint of the buffer, the locked portion of the buffer might wrap around, in which case two separate copy operations are required:

    if FAILED(IDirectSoundCaptureBuffer_Lock(lpdscb,
            dwMyReadCursor, dwNumBytes,
            (LPVOID *)&pbInput1, &cbInput1,
            (LPVOID *)&pbInput2, &cbInput2, 0))
        OutputDebugString("Capture lock failure");

    else
        {
        if (WaveWriteFile(hmmio, cbInput1, pbInput1, &mmckinfoData,
                        &dwBytesWritten, &mmioinfo))
          OutputDebugString("Failure writing data to file\n");
        dwTotalBytesWritten += dwBytesWritten;

        // Wrap around
        if (pbInput2 != NULL)
        {
            if (WaveWriteFile(hmmio, cbInput2, pbInput2,
                    &mmckinfoData, &dwBytesWritten, &mmioinfo))
              OutputDebugString("Failure writing data to file\n");
            dwTotalBytesWritten += dwBytesWritten;
        }

        IDirectSoundCaptureBuffer_Unlock(lpdscb,
                pbInput1, cbInput1,
                pbInput2, cbInput2);
    }

The WaveWriteFile function returns 0 if successful and also fills dwBytesWritten with the number of bytes actually copied to the file. This value is added to the cumulative total, which will be needed when the file is closed.

Finally, update the internal read cursor, compensating for wrap around, and return to the message loop:

    dwMyReadCursor += dwNumBytes;
    if (dwMyReadCursor >= dscbDesc.dwBufferBytes)
                dwMyReadCursor -= dscbDesc.dwBufferBytes;

    return TRUE;
} // end StreamToFile()

Next: Step 8: Stop Capture


Step 8: Stop Capture

[Visual Basic]

The information in this topic pertains only to applications written in C and C++. See DirectSound Visual Basic Tutorials.

[C++]

When it's time to stop recording, call the following function:

BOOL StopWrite()
{
    IDirectSoundCaptureBuffer_Stop(lpdscb);
    StreamToFile();
    WaveCloseWriteFile(&hmmio, &mmckinfoData,
            &mmckinfoParent, &mmioinfo,
            dwTotalBytesWritten / (wfx.wBitsPerSample / 8));
    return TRUE;
}

This function stops the capture buffer, calls the StreamToFile function one more time in order to save all the data up to the current read position, and closes the file. The WaveCloseWriteFile function in Wavwrite.cpp also updates the header of the data chunk by writing the total number of samples.

Next: Step 9: Shut Down DirectSoundCapture


Step 9: Shut Down DirectSoundCapture

[Visual Basic]

The information in this topic pertains only to applications written in C and C++. See DirectSound Visual Basic Tutorials.

[C++]

Before closing the application you must shut down the capture system. This is a simple matter of releasing all the objects. You must release the IDirectSoundNotify interface before releasing the capture buffer.

void CleanupDSoundCapture(void)
{
    if (lpdsNotify)
        IDirectSoundNotify_Release(lpdsNotify);
    if (lpdscb)
        IDirectSoundCaptureBuffer_Release(lpdscb);
    if (lpdsc)
        IDirectSoundCapture_Release(lpdsc);
}


DirectSound Visual Basic Tutorials

[C++]

This section pertains only to DirectX for Visual Basic. See DirectSound C/C++ Tutorials.

[Visual Basic]

This section contains tutorials that provide step-by-step instructions for implementing basic DirectSound functionality.

  • Tutorial 1: Loading and Playing Sounds
  • Tutorial 2: Loading and Playing 3-D Sounds


Tutorial 1: Loading and Playing Sounds

[C++]

This section pertains only to DirectX for Visual Basic. See DirectSound C/C++ Tutorials.

[Visual Basic]

This tutorial demonstrates one of the most basic features of DirectSound, loading and playing a sound. This is done by loading a wave file into a buffer and playing back the buffered data.

This tutorial is divided into the following steps:

  • Step 1: Create a DirectSound Object
  • Step 2: Load a Wave File into a Buffer
  • Step 3: Play the Sound


Step 1: Create a DirectSound Object

[C++]

This section pertains only to DirectX for Visual Basic. See DirectSound C/C++ Tutorials.

[Visual Basic]

The central object to any DirectSound application is an instance of the DirectSound class. Applications use the methods of a DirectSound object to set up the sound environment and to create buffers which hold audio data.

This object is created by first creating the global DirectX7 object, which is at the core of all DirectX for Visual Basic applications, and calling the DirectX7.DirectSoundCreate method. This method returns a DirectSound object.

The following global declarations create the DirectX7 object and variables for the other necessary objects:

Dim m_dx As New DirectX7
Dim m_ds As DirectSound

In the startup code, create the DirectSound object as follows:

On Local Error Resume Next

Set m_ds = m_dx.DirectSoundCreate("")

If Err.Number <> 0 Then
    MsgBox "Unable to start DirectSound. Check to see that your sound card is properly installed"
    End
End If

Passing an empty string to the DirectSoundCreate method indicates we want the default sound device installed on the system. This method could fail if there are no installed sound devices or if DirectX is not installed. We can check the success of this method by trapping the error value generated by a failed method call. You should have error handling routines to trap and handle all errors in your application.

After creating a DirectSound object, you need to set the cooperative level of the application for the sound device. In the Tutorial 1 sample, this is done with the statement:

m_ds.SetCooperativeLevel Me.hWnd, DSSCL_PRIORITY

The first argument is the window handle to the application. The second argument sets the priority level. For information on priority levels, see the DirectSound.SetCooperativeLevel topic.

Next for Tutorial 1: Step 2: Load a Wave File into a Buffer

Next for Tutorial 2: Step 2: Load a Wave File into a 3-D Buffer


Step 2: Load a Wave File into a Buffer

[C++]

This section pertains only to DirectX for Visual Basic. See DirectSound C/C++ Tutorials.

[Visual Basic]

After creating the main DirectSound object, the next step is to create and load a wave file into a sound buffer. You describe the characteristics of a DirectSound buffer through a DSBUFFERDESC type.

The first member of a DSBUFFERDESC type is lBufferBytes which is the size of the buffer. Since we are creating a primary sound buffer, this value must be 0. The second member is one or more constants of the CONST_DSBCAPSFLAGS enumeration identifying the capabilities of the buffer.

In the Tutorial 1 sample we create a buffer which has volume changes, frequency changes, and pan changes enabled. Additionally, the DDSBCAPS_STATIC flag indicates that we want the entire file loaded into memory.

Dim bufferDesc As DSBUFFERDESC

bufferDesc.lFlags = DSBCAPS_CTRLFREQUENCY Or DSBCAPS_CTRLPAN Or DSBCAPS_CTRLVOLUME Or DSBCAPS_STATIC

The next step in creating a sound buffer is to specify the format of the wave-form audio data. This is done by setting the members of a WAVEFORMATEX type.

Dim waveFormat As WAVEFORMATEX

waveFormat.nFormatTag = WAVE_FORMAT_PCM
waveFormat.nChannels = 2
waveFormat.lSamplesPerSec = 22050
waveFormat.nBitsPerSample = 16
waveFormat.nBlockAlign = waveFormat.nBitsPerSample / 8 * waveFormat.nChannels
waveFormat.lAvgBytesPerSec = waveFormat.lSamplesPerSec * waveFormat.nBlockAlign

The final step is to create the buffer with the preceding descriptions and load a wave file into the buffer. This is done with a single call using the DirectSound.CreateSoundBufferFromFile method.

Set m_dsBuffer(i) = m_ds.CreateSoundBufferFromFile(sfile, bufferDesc, waveFormat)

Next: Step 3: Play the Sound


Step 3: Play the Sound

[C++]

This section pertains only to DirectX for Visual Basic. See DirectSound C/C++ Tutorials.

[Visual Basic]

In the Tutorial 1 sample, the sound is loaded onto a sound buffer when the user clicks the Play button. There are actually several steps before the sound is actually played.

First we set the volume and pan level to the value of the associated scroll bars. This is shown in the following two procedures:

Private Sub scrlVol_Scroll(i As Integer)
    If m_dsBuffer(i) Is Nothing Then Exit Sub
    m_dsBuffer(i).SetVolume scrlVol(i).Value
End Sub

Private Sub scrlPan_Scroll(i As Integer)
    If m_dsBuffer(i) Is Nothing Then Exit Sub
    m_dsBuffer(i).SetPan scrlPan(i).Value
End Sub

Next we determine whether the loop check box is checked:

Dim flag As Long
flag = 0
If chLoop(i).Value <> 0 Then flag = 1

If the loop box is checked, the flag variable is set to DSBPLAY_LOOPING which is equal to 1.

Finally we play the sound with the call:

m_dsBuffer(i).Play flag


Tutorial 2: Loading and Playing 3-D Sounds

[C++]

This section pertains only to DirectX for Visual Basic. See DirectSound C/C++ Tutorials.

[Visual Basic]

This tutorial expands on the concepts of the first tutorial by adding three-dimensional (3-D) sound. This is done by loading a wave file into a DS3DBUFFER which contains all information necessary to uniquely describe the location, orientation, and motion of a 3-D sound.

This tutorial also introduces the DirectSound3DListener object which describe the 3-D world parameters and position of the listener. In the Tutorial 2 application, the user interface is identical to the Tutorial 1 with the addition of a picture box control. The picture box control is used to display the position of the listener and the positions of the two 3-D sounds. Note: The first step is identical to the Tutorial 1.

  • Step 1: Create a DirectSound Object
  • Step 2: Load a Wave File into a 3-D Buffer
  • Step 3: Play the 3-D Sound


Step 2: Load a Wave File into a 3-D Buffer

[C++]

This section pertains only to DirectX for Visual Basic. See DirectSound C/C++ Tutorials.

[Visual Basic]

After creating the main DirectSound object, the next step is to create and load a wave file into a 3-D enabled sound buffer. You describe the characteristics of a DirectSound buffer through a parameter of DSBUFFERDESC type.

The first member of a DSBUFFERDESC type is lBufferBytes which is the size of the buffer. Since we are creating a primary sound buffer, this value must be 0. The second member is one or more constants of the CONST_DSBCAPSFLAGS enumeration identifying the capabilities of the buffer.

The first step is to create a primary buffer that is capable of processing 3-D sounds. This is done with the describing the wave format and specifying the DSBCAPS_CTRL3D and DSBCAPS_PRIMARYBUFFER flags:

Dim primDesc As DSBUFFERDESC, format As WAVEFORMATEX

format.nSize = LenB(WAVEFORMATEX)
format.nFormatTag = WAVE_FORMAT_PCM
format.nChannels = 2
format.lSamplesPerSec = 22050
format.nBitsPerSample = 16
format.nBlockAlign = format.nBitsPerSample / 8 * format.nChannels
format.lAvgBytesPerSec = format.lSamplesPerSec * format.nBlockAlign

primDesc.lFlags = DSBCAPS_CTRL3D Or DSBCAPS_PRIMARYBUFFER
Set m_dsPrimaryBuffer = m_ds.CreateSoundBuffer(primDesc, format)

Next we use one of the methods of the DirectSoundBuffer object, DirectSoundBuffer.GetDirectSound3DListener, to create a DirectSound3DListener object. This call would fail if we had not specified the DSBCAPS_CTRL3D flag when creating the primary sound buffer.

The DirectSound3DListener object describes a listener's position, orientation, and listening environment in 3-D space.

The next step is to load the wave form audio data into a sound buffer. Since we want to control the 3-D position of the sounds, we specify the DSBCAPS_CTRL3D flag in the buffer description:

Dim bufferDesc1 As DSBUFFERDESC
Dim waveFormat1 As WAVEFORMATEX

bufferDesc1.lFlags = (DSBCAPS_CTRL3D Or DSBCAPS_CTRLFREQUENCY Or DSBCAPS_CTRLPAN Or DSBCAPS_CTRLVOLUME) Or DSBCAPS_STATIC
Set m_dsBuffer(i) = m_ds.CreateSoundBufferFromFile(file, bufferDesc1, waveFormat1)

In the Tutorial 1 sample we create a buffer which has volume changes, frequency changes, and pan changes enabled. Additionally, the DDSBCAPS_STATIC flag indicates that we want the entire file loaded into memory.

Dim bufferDesc As DSBUFFERDESC

bufferDesc.lFlags = DSBCAPS_CTRLFREQUENCY Or DSBCAPS_CTRLPAN Or DSBCAPS_CTRLVOLUME Or DSBCAPS_STATIC

Finally, we create a DirectSound3DBuffer object to describe the position, orientation, and environment of a sound buffer in 3-D space.

Dim m_ds3dBuffer(2) As DirectSound3DBuffer
Set m_ds3dBuffer(i) = m_dsBuffer(i).GetDirectSound3DBuffer

Next: Step 3: Play the 3-D Sound


Step 3: Play the 3-D Sound

[C++]

This section pertains only to DirectX for Visual Basic. See DirectSound C/C++ Tutorials.

[Visual Basic]

When the user clicks the Play button in the Tutorial 2 sample there are several initialization steps that occur before the sound is actually played. The volume, pan and loop values are set like in Tutorial 1, but there are several additional values that are initialized because of 3-D sound processing.

The orientation of the sound projection cone for the sound buffer must be set using DirectSound3DBuffer.SetConeOrientation. In the Tutorial 2 sample, this is done in the scrlAngle_Change procedure:

Private Sub scrlAngle_Change(i As Integer)

'first we must calculate a vector of what direction
'the sound is traveling in

Dim x As Single
Dim z As Single
'we take the current angle in degrees convert to radians
'and get the cos or sin to find the direction from an angle
x = 5 * Cos(3.141 * scrlAngle(0).Value / 180)
z = 5 * Sin(3.141 * scrlAngle(0).Value / 180)

'Update the UI
DrawPositions

If m_dsBuffer(i) Is Nothing Then Exit Sub

'the zero at the end indicates we want the postion updated immediately
m_ds3dBuffer(i).SetConeOrientation x, 0, z, DS3D_IMMEDIATE

End Sub

Next we set the inside and outside angles of the sound projection cone and current cone outside volume for this sound buffer using the following calls:

m_ds3dBuffer(i).SetConeAngles DS3D_MINCONEANGLE, 100, DS3D_IMMEDIATE
m_ds3dBuffer(i).SetConeOutsideVolume -400, DS3D_IMMEDIATE

Then we sets the sound buffer's current position, in distance units:

m_ds3dBuffer(i).SetPosition m_pos(i).x / 50, 0, m_pos(i).z / 50, DS3D_IMMEDIATE

Finally the sound is played with the call:

m_dsBuffer(i).Play flag

In Tutorial 1, the user can move the position of the two sounds relative to the listener position by clicking either the left or right-mouse button and moving the triangle representing the sound. This updates the position of the sound using the DirectSound3DBuffer.SetPosition method.


DirectSound Reference

This section contains reference information for the application programming interface (API) elements provided by DirectSound in C/C++ and Visual Basic. Reference material is organized by language:

  • DirectSound C/C++ Reference
  • DirectSound Visual Basic Reference


DirectSound C/C++ Reference

This section contains reference information for the API elements that DirectSound provides. Reference material is divided into the following categories.

  • Interfaces
  • Functions
  • Callback Function
  • Structures
  • Return Values


Interfaces

This section contains references for methods of the following DirectSound interfaces:

  • IDirectSound
  • IDirectSound3DBuffer
  • IDirectSound3DListener
  • IDirectSoundBuffer
  • IDirectSoundCapture
  • IDirectSoundCaptureBuffer
  • IDirectSoundNotify
  • IKsPropertySet


IDirectSound

Applications use the methods of the IDirectSound interface to create DirectSound objects and set up the environment. This section is a reference to the methods of this interface.

The interface is obtained by using the DirectSoundCreate function.

The methods of the IDirectSound interface can be organized into the following groups:

Initialization | Initialize
 | SetCooperativeLevel
Buffer creation | CreateSoundBuffer
 | DuplicateSoundBuffer
Device capabilities | GetCaps
Memory management | Compact
Speaker configuration | GetSpeakerConfig
 | SetSpeakerConfig

The IDirectSound interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECTSOUND type is defined as a pointer to the IDirectSound interface:

typedef struct IDirectSound    *LPDIRECTSOUND;

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.


IDirectSound::Compact

The IDirectSound::Compact method moves the unused portions of on-board sound memory, if any, to a contiguous block so that the largest portion of free memory will be available.

HRESULT Compact();

Parameters

None.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED
DSERR_UNINITIALIZED

Remarks

The application's DirectSound object must have at least the DSSCL_PRIORITY cooperative level. See IDirectSound::SetCooperativeLevel.

This method will fail if any operations are in progress.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.


IDirectSound::CreateSoundBuffer

The IDirectSound::CreateSoundBuffer method creates a DirectSoundBuffer object to hold a sequence of audio samples.

HRESULT CreateSoundBuffer(
  LPCDSBUFFERDESC lpcDSBufferDesc,
  LPLPDIRECTSOUNDBUFFER lplpDirectSoundBuffer,
  IUnknown FAR * pUnkOuter
);

Parameters

lpcDSBufferDesc
Address of a DSBUFFERDESC structure that contains the description of the sound buffer to be created.
lplpDirectSoundBuffer
Address of a pointer to the new DirectSoundBuffer object, or NULL if the buffer cannot be created.
pUnkOuter
Controlling unknown of the aggregate. Its value must be NULL.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_ALLOCATED
DSERR_CONTROLUNAVAIL
DSERR_BADFORMAT
DSERR_INVALIDPARAM
DSERR_NOAGGREGATION
DSERR_OUTOFMEMORY
DSERR_UNINITIALIZED
DSERR_UNSUPPORTED

Remarks

DSBCAPS_CTRLDEFAULT has been removed to encourage use of the individual flags that DSBCAPS_CTRLDEFAULT represents. DSBCAPS_CTRLDEFAULT was previously defined as DSBCAPS_CTRLPAN | DSBCAPS_CTRLVOLUME | DSBCAPS_CTRLFREQUENCY. By specifying only the flags you need, you cut down on unnecessary resource usage.

Before it can play any sound buffers, the application must specify a cooperative level for a DirectSound object by using the IDirectSound::SetCooperativeLevel method.

The lpDSBufferDesc parameter points to a structure that describes the type of buffer desired, including format, size, and capabilities. The application must specify the needed capabilities, or they will not be available. For example, if the application creates a DirectSoundBuffer object without specifying the DSBCAPS_CTRLFREQUENCY flag, any call to IDirectSoundBuffer::SetFrequency will fail.

The DSBCAPS_STATIC flag can also be specified, in which case DirectSound stores the buffer in on-board memory, if available, to take advantage of hardware mixing. To force the buffer to use either hardware or software mixing, use the DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE flag. Additionally, you can have DirectSound assign a hardware or software resource during playing by using the DSBCAPS_LOCDEFER flag.

To find out if the buffer was created in hardware or software, call the IDirectSoundBuffer:GetCaps method and check for the DBSCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE flag in the dwFlags member of the returned DSBCAPS structure.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

DSBUFFERDESC, IDirectSound::DuplicateSoundBuffer, IDirectSound::SetCooperativeLevel, IDirectSoundBuffer, IDirectSoundBuffer::GetFormat, IDirectSoundBuffer::GetVolume, IDirectSoundBuffer::Lock, IDirectSoundBuffer::Play, IDirectSoundBuffer::SetFormat, IDirectSoundBuffer::SetFrequency


IDirectSound::DuplicateSoundBuffer

The IDirectSound::DuplicateSoundBuffer method creates a new DirectSoundBuffer object that uses the same buffer memory as the original object.

HRESULT DuplicateSoundBuffer(
  LPDIRECTSOUNDBUFFER lpDsbOriginal,
  LPLPDIRECTSOUNDBUFFER lplpDsbDuplicate
);

Parameters

lpDsbOriginal
Address of the DirectSoundBuffer object to be duplicated.
lplpDsbDuplicate
Address of a pointer to the new DirectSoundBuffer object.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_ALLOCATED
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_OUTOFMEMORY
DSERR_UNINITIALIZED

Remarks

The new object can be used just like the original.

Initially, the duplicate buffer will have the same parameters as the original buffer. However, the application can change the parameters of each buffer independently, and each can be played or stopped without affecting the other.

If data in the buffer is changed through one object, the change will be reflected in the other object because the buffer memory is shared.

The buffer memory will be released when the last object referencing it is released.

Applications cannot assume that an attempt to duplicate a sound buffer will always succeed. In particular, DirectSound will not create a software duplicate of a hardware buffer.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSound::CreateSoundBuffer


IDirectSound::GetCaps

The IDirectSound::GetCaps method retrieves the capabilities of the hardware device that is represented by the DirectSound object.

HRESULT GetCaps(
  LPDSCAPS lpDSCaps
);

Parameters

lpDSCaps
Address of the DSCAPS structure to contain the capabilities of this sound device.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_UNINITIALIZED

Remarks

Information retrieved in the DSCAPS structure describes the maximum capabilities of the sound device and those currently available, such as the number of hardware mixing channels and the amount of on-board sound memory. You can use this information to fine-tune performance and optimize resource allocation.

Because of resource-sharing requirements, the maximum capabilities in one area might be available only at the cost of another area. For example, the maximum number of hardware-mixed streaming sound buffers might be available only if there are no hardware static sound buffers.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

DirectSoundCreate


IDirectSound::GetSpeakerConfig

The IDirectSound::GetSpeakerConfig method retrieves the speaker configuration.

HRESULT GetSpeakerConfig(
  LPDWORD lpdwSpeakerConfig
);

Parameters

lpdwSpeakerConfig
Address of the speaker configuration for this DirectSound object. The speaker configuration is specified with one of the following values:
DSSPEAKER_5POINT1
The audio is played through a speaker arrangement of surround speakers with a subwoofer.
DSSPEAKER_HEADPHONE
The audio is played through headphones.
DSSPEAKER_MONO
The audio is played through a single speaker.
DSSPEAKER_QUAD
The audio is played through quadraphonic speakers.
DSSPEAKER_STEREO
The audio is played through stereo speakers (default value).
DSSPEAKER_SURROUND
The audio is played through surround speakers.
DSSPEAKER_STEREO can be combined with one of the following values:
DSSPEAKER_GEOMETRY_WIDE
The speakers are directed over an arc of 20 degrees.
DSSPEAKER_GEOMETRY_NARROW
The speakers are directed over an arc of 10 degrees.
DSSPEAKER_GEOMETRY_MIN
The speakers are directed over an arc of 5 degrees.
DSSPEAKER_GEOMETRY_MAX
The speakers are directed over an arc of 180 degrees.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_INVALIDPARAM
DSERR_UNINITIALIZED

Remarks

The value returned at lpdwSpeakerConfig may be a packed DWORD containing both configuration and geometry information. Use the DSSPEAKER_CONFIG and DSSPEAKER_GEOMETRY macros to unpack the DWORD, as in the following example:

if (DSSPEAKER_CONFIG(dwSpeakerConfig) == DSSPEAKER_STEREO)
    {
    if (DSSPEAKER_GEOMETRY(dwSpeakerConfig) ==
                      DSSPEAKER_GEOMETRY_WIDE)
       {...}
    }

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSound::SetSpeakerConfig, Speaker Configuration


IDirectSound::Initialize

The IDirectSound::Initialize method initializes the DirectSound object that was created by using the CoCreateInstance function.

HRESULT Initialize(
  LPCGUID lpcGuid
);

Parameters

lpcGuid
Address of the globally unique identifier (GUID) specifying the sound driver to which this DirectSound object binds. Pass NULL to select the primary sound driver.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_ALREADYINITIALIZED
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_NODRIVER

Remarks

This method is provided for compliance with the Component Object Model (COM) protocol. If the DirectSoundCreate function was used to create the DirectSound object, this method returns DSERR_ALREADYINITIALIZED. If IDirectSound::Initialize is not called when using CoCreateInstance to create the DirectSound object, any method called afterward returns DSERR_UNINITIALIZED.

The lLpcGuid parameter has changed from a LPGUID to a LPCGUID in DirectX 7.0.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

DirectSoundCreate


IDirectSound::SetCooperativeLevel

The IDirectSound::SetCooperativeLevel method sets the cooperative level of the application for this sound device.

HRESULT SetCooperativeLevel(
  HWND hwnd,
  DWORD dwLevel
);

Parameters

hwnd
Window handle to the application. See Remarks.
dwLevel
Requested priority level. Specify one of the following values:
DSSCL_EXCLUSIVE
Sets the application to the exclusive level. When it has the input focus, the application will be the only one audible (sounds from applications with the DSBCAPS_GLOBALFOCUS flag set will be muted). With this level, it also has all the privileges of the DSSCL_PRIORITY level. DirectSound will restore the hardware format, as specified by the most recent call to the IDirectSoundBuffer::SetFormat method, once the application gains the input focus. (Note that DirectSound will always restore the wave format no matter what priority level is set.)
DSSCL_NORMAL
Sets the application to a fully cooperative status. This level has the smoothest multitasking and resource-sharing behavior, but because it does not allow the primary buffer format to change, output is restricted to the default 8-bit format.
DSSCL_PRIORITY
Sets the application to the priority level. Applications with this cooperative level can call the IDirectSoundBuffer::SetFormat and IDirectSound::Compact methods.
DSSCL_WRITEPRIMARY
This is the highest priority level. The application has write access to the primary sound buffers. No secondary sound buffers can be played. This level cannot be set if the DirectSound driver is being emulated for the device; that is, if the IDirectSound::GetCaps method returns the DSCAPS_EMULDRIVER flag in the DSCAPS structure.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_ALLOCATED
DSERR_INVALIDPARAM
DSERR_UNINITIALIZED
DSERR_UNSUPPORTED

Remarks

The application must set the cooperative level by calling this method before its buffers can be played. The recommended cooperative level is DSSCL_PRIORITY; use other priority levels when necessary. For additional information, see Cooperative Levels.

The hwnd parameter should be the top-level application window handle. If you are also using DirectDraw, it must be the same handle passed to the IDirectDraw7::SetCooperativeLevel method.

If your application cannot easily supply a window handle, you can obtain one by using the following code:

HWND hWnd = GetForegroundWindow();
if (hWnd == NULL)
{
    hWnd = GetDesktopWindow();
}

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSound::Compact, IDirectSoundBuffer::GetFormat, IDirectSoundBuffer::GetVolume, IDirectSoundBuffer::Lock, IDirectSoundBuffer::Play, IDirectSoundBuffer::Restore, IDirectSoundBuffer::SetFormat


IDirectSound::SetSpeakerConfig

The IDirectSound::SetSpeakerConfig method specifies the speaker configuration of the DirectSound object.

HRESULT SetSpeakerConfig(
  DWORD dwSpeakerConfig
);

Parameters

dwSpeakerConfig
Speaker configuration of the specified DirectSound object. This parameter can be one of the following values:
DSSPEAKER_HEADPHONE
The speakers are headphones.
DSSPEAKER_MONO
The speakers are monaural.
DSSPEAKER_QUAD
The speakers are quadraphonic.
DSSPEAKER_STEREO
The speakers are stereo (default value).
DSSPEAKER_SURROUND
The speakers are surround sound.
DSSPEAKER_STEREO may be combined with one of the following values:
DSSPEAKER_GEOMETRY_WIDE
The speakers are directed over an arc of 20 degrees.
DSSPEAKER_GEOMETRY_NARROW
The speakers are directed over an arc of 10 degrees.
DSSPEAKER_GEOMETRY_MIN
The speakers are directed over an arc of 5 degrees.
DSSPEAKER_GEOMETRY_MAX
The speakers are directed over an arc of 180 degrees.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_INVALIDPARAM
DSERR_UNINITIALIZED

Remarks

If a geometry value is to be used, it must be packed in a DWORD along with the DSSPEAKER_STEREO flag. This can be done by using the DSSPEAKER_COMBINED macro, as in the following C++ example:

lpds->SetSpeakerConfig(DSSPEAKER_COMBINED(
    DSSPEAKER_STEREO, DSSPEAKER_GEOMETRY_WIDE));

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSound::GetSpeakerConfig, Speaker Configuration


IDirectSound3DBuffer

Applications use the methods of the IDirectSound3DBuffer interface to retrieve and set parameters that describe the position, orientation, and environment of a sound buffer in 3-D space. This section is a reference to the methods of this interface. For a conceptual overview, see DirectSound 3-D Buffers.

The IDirectSound3DBuffer is obtaining by using the IDirectSoundBuffer::QueryInterface method. For more information, see Obtaining the DirectSound3DBuffer Object.

The methods of the IDirectSound3DBuffer interface can be organized into the following groups:

Batch parameter manipulation | GetAllParameters
 | SetAllParameters
Distance | GetMaxDistance
 | GetMinDistance
 | SetMaxDistance
 | SetMinDistance
Operation mode | GetMode
 | SetMode
Position | GetPosition
 | SetPosition
Sound projection cones | GetConeAngles
 | GetConeOrientation
 | GetConeOutsideVolume
 | SetConeAngles
 | SetConeOrientation
 | SetConeOutsideVolume
Velocity | GetVelocity
 | SetVelocity

The IDirectSound3DBuffer interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECTSOUND3DBUFFER type is defined as a pointer to the IDirectSound3DBuffer interface:

typedef struct IDirectSound3DBuffer    *LPDIRECTSOUND3DBUFFER;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.


IDirectSound3DBuffer::GetAllParameters

The IDirectSound3DBuffer::GetAllParameters method retrieves information that describes the 3-D characteristics of a sound buffer at a given point in time.

HRESULT GetAllParameters(
  LPDS3DBUFFER lpDs3dBuffer
);

Parameters

lpDs3dBuffer
Address of a DS3DBUFFER structure that will contain the information describing the 3-D characteristics of the sound buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.


IDirectSound3DBuffer::GetConeAngles

The IDirectSound3DBuffer::GetConeAngles method retrieves the inside and outside angles of the sound projection cone for this sound buffer.

HRESULT GetConeAngles(
  LPDWORD lpdwInsideConeAngle,
  LPDWORD lpdwOutsideConeAngle
);

Parameters

lpdwInsideConeAngle and lpdwOutsideConeAngle
Addresses of variables that will contain the inside and outside angles of the sound projection cone, in degrees.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The minimum, maximum, and default cone angles are defined in Dsound.h as DS3D_MINCONEANGLE, DS3D_MAXCONEANGLE, and DS3D_DEFAULTCONEANGLE.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.


IDirectSound3DBuffer::GetConeOrientation

The IDirectSound3DBuffer::GetConeOrientation method retrieves the orientation of the sound projection cone for this sound buffer.

HRESULT GetConeOrientation(
  LPD3DVECTOR lpvOrientation
);

Parameters

lpvOrientation
Address of a D3DVECTOR structure that will contain the current orientation of the sound projection cone. The vector information represents the center of the sound cone.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The values returned are not necessarily the same as those set by using the IDirectSound3DBuffer::SetConeOrientation method. DirectSound adjusts orientation vectors so that they are have a magnitude of less than or equal to 1.0.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSound3DBuffer::SetConeOrientation, IDirectSound3DBuffer::SetConeAngles, IDirectSound3DBuffer::SetConeOutsideVolume


IDirectSound3DBuffer::GetConeOutsideVolume

The IDirectSound3DBuffer::GetConeOutsideVolume method retrieves the current cone outside volume for this sound buffer.

HRESULT GetConeOutsideVolume(
  LPLONG lplConeOutsideVolume
);

Parameters

lplConeOutsideVolume
Address of a variable that will contain the current cone outside volume for this buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

Volume levels are represented by attenuation. Allowable values are between DSBVOLUME_MAX (no attenuation) and DSBVOLUME_MIN (silence). The default value is DS3D_DEFAULTCONEOUTSIDEVOLUME (no attenuation). These values are defined in Dsound.h. Currently DirectSound does not support amplification.

For additional information about the concept of outside volume, see Sound Cones.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSoundBuffer::SetVolume


IDirectSound3DBuffer::GetMaxDistance

The IDirectSound3DBuffer::GetMaxDistance method retrieves the current maximum distance for this sound buffer.

HRESULT GetMaxDistance(
  LPD3DVALUE lpflMaxDistance
);

Parameters

lpflMaxDistance
Address of a variable that will contain the current maximum distance setting.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The default maximum distance, defined as DS3D_DEFAULTMAXDISTANCE, is effectively infinite.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSound3DBuffer::GetMinDistance, IDirectSound3DBuffer::SetMaxDistance


IDirectSound3DBuffer::GetMinDistance

The IDirectSound3DBuffer::GetMinDistance method retrieves the current minimum distance for this sound buffer.

HRESULT GetMinDistance(
  LPD3DVALUE lpflMinDistance
);

Parameters

lpflMinDistance
Address of a variable that will contain the current minimum distance setting.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

By default, the minimum distance value is DS3D_DEFAULTMINDISTANCE, currently defined as 1.0 (corresponding to 1.0 meter at the default distance factor of 1.0 meters per unit).

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSound3DBuffer::SetMinDistance, IDirectSound3DBuffer::GetMaxDistance


IDirectSound3DBuffer::GetMode

The IDirectSound3DBuffer::GetMode method retrieves the current operation mode for 3-D sound processing.

HRESULT GetMode(
  LPDWORD lpdwMode
);

Parameters

lpdwMode
Address of a variable that will contain the current mode setting. This value will be one of the following:
DS3DMODE_DISABLE
Processing of 3-D sound is disabled. The sound seems to originate from the center of the listener's head.
DS3DMODE_HEADRELATIVE
Sound parameters (position, velocity, and orientation) are relative to the listener's parameters. In this mode, the absolute parameters of the sound are updated automatically as the listener's parameters change, so that the relative parameters remain constant.
DS3DMODE_NORMAL
Normal processing. This is the default mode.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.


IDirectSound3DBuffer::GetPosition

The IDirectSound3DBuffer::GetPosition method retrieves the sound buffer's current position, in distance units. By default, distance units are meters, but the units can be changed by using the IDirectSound3DListener::SetDistanceFactor method.

HRESULT GetPosition(
  LPD3DVECTOR lpvPosition
);

Parameters

lpvPosition
Address of a D3DVECTOR structure that will contain the current position of the sound buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.


IDirectSound3DBuffer::GetVelocity

The IDirectSound3DBuffer::GetVelocity method retrieves the current velocity for this sound buffer. Velocity is measured in units per second. The default unit is one meter, but this can be changed by using the IDirectSound3DListener::SetDistanceFactor method.

HRESULT GetVelocity(
  LPD3DVECTOR lpvVelocity
);

Parameters

lpvVelocity
Address of a D3DVECTOR structure that will contain the sound buffer's current velocity.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

Velocity is used for Doppler effects only. It does not actually move the buffer. For additional information, see Doppler Factor.

The default unit of measurement is meters per second, but this can be changed by using the IDirectSound3DListener::SetDistanceFactor method.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSound3DBuffer::SetPosition, IDirectSound3DBuffer::SetVelocity


IDirectSound3DBuffer::SetAllParameters

The IDirectSound3DBuffer::SetAllParameters method sets all 3-D sound buffer parameters from a given DS3DBUFFER structure that describes all aspects of the sound buffer at a moment in time.

HRESULT SetAllParameters(
  LPCDS3DBUFFER lpcDs3dBuffer,
  DWORD dwApply
);

Parameters

lpcDs3dBuffer
Address of a DS3DBUFFER structure containing the information that describes the 3-D characteristics of the sound buffer.
dwApply
Value indicating when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
Settings are not applied until the application calls the IDirectSound3DListener::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.


IDirectSound3DBuffer::SetConeAngles

The IDirectSound3DBuffer::SetConeAngles method sets the inside and outside angles of the sound projection cone for this sound buffer.

HRESULT SetConeAngles(
  DWORD dwInsideConeAngle,
  DWORD dwOutsideConeAngle,
  DWORD dwApply
);

Parameters

dwInsideConeAngle and dwOutsideConeAngle
Inside and outside angles of the sound projection cone, in degrees.
dwApply
Value indicating when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
Settings are not applied until the application calls the IDirectSound3DListener::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The minimum, maximum, and default cone angles are defined in Dsound.h as DS3D_MINCONEANGLE, DS3D_MAXCONEANGLE, and DS3D_DEFAULTCONEANGLE. Each angle must be in the range of 0 degrees (no cone) to 360 degrees (the full sphere). The default value is 360.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSound3DBuffer::GetConeOutsideVolume, IDirectSound3DBuffer::SetConeOutsideVolume


IDirectSound3DBuffer::SetConeOrientation

The IDirectSound3DBuffer::SetConeOrientation method sets the orientation of the sound projection cone for this sound buffer. This method has no effect unless the cone angle and cone volume factor have also been set.

HRESULT SetConeOrientation(
  D3DVALUE x,
  D3DVALUE y,
  D3DVALUE z,
  DWORD dwApply
);

Parameters

x, y, and z
Values whose types are D3DVALUE and that represent the coordinates of the new sound cone orientation vector.
dwApply
Value indicating when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
Settings are not applied until the application calls the IDirectSound3DListener::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSound3DBuffer::SetConeAngles, IDirectSound3DBuffer::SetConeOutsideVolume


IDirectSound3DBuffer::SetConeOutsideVolume

The IDirectSound3DBuffer::SetConeOutsideVolume method sets the current cone outside volume for this sound buffer.

HRESULT SetConeOutsideVolume(
  LONG lConeOutsideVolume,
  DWORD dwApply
);

Parameters

lConeOutsideVolume
Cone outside volume for this sound buffer, in hundredths of decibels. Allowable values are between DSBVOLUME_MAX (no attenuation) and DSBVOLUME_MIN (silence). These values are defined in Dsound.h.
dwApply
Value indicating when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
Settings are not applied until the application calls the IDirectSound3DListener::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

Volume levels are represented by attenuation. Allowable values are between DSBVOLUME_MAX (no attenuation) and DSBVOLUME_MIN (silence). The default value is DS3D_DEFAULTCONEOUTSIDEVOLUME (no attenuation). These values are defined in Dsound.h. Currently DirectSound does not support amplification.

For information about the concept of cone outside volume, see Sound Cones.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSoundBuffer::SetVolume


IDirectSound3DBuffer::SetMaxDistance

The IDirectSound3DBuffer::SetMaxDistance method sets the current maximum distance value.

HRESULT SetMaxDistance(
  D3DVALUE flMaxDistance,
  DWORD dwApply
);

Parameters

flMaxDistance
New maximum distance value.
dwApply
Value indicating when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
Settings are not applied until the application calls the IDirectSound3DListener::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The default maximum distance, defined as DS3D_DEFAULTMAXDISTANCE, is effectively infinite.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSound3DBuffer::GetMaxDistance, IDirectSound3DBuffer::SetMinDistance


IDirectSound3DBuffer::SetMinDistance

The IDirectSound3DBuffer::SetMinDistance method sets the current minimum distance value.

HRESULT SetMinDistance(
  D3DVALUE flMinDistance,
  DWORD dwApply
);

Parameters

flMinDistance
New minimum distance value.
dwApply
Value indicating when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
Settings are not applied until the application calls the IDirectSound3DListener::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

By default, the minimum distance value is DS3D_DEFAULTMINDISTANCE, currently defined as 1.0 (corresponding to 1.0 meter at the default distance factor of 1.0 meters per unit).

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSound3DBuffer::SetMaxDistance


IDirectSound3DBuffer::SetMode

The IDirectSound3DBuffer::SetMode method sets the operation mode for 3-D sound processing.

HRESULT SetMode(
  DWORD dwMode,
  DWORD dwApply
);

Parameters

dwMode
Flag specifying the 3-D sound processing mode to be set:
DS3DMODE_DISABLE
Processing of 3-D sound is disabled. The sound seems to originate from the center of the listener's head.
DS3DMODE_HEADRELATIVE
Sound parameters (position, velocity, and orientation) are relative to the listener's parameters. In this mode, the absolute parameters of the sound are updated automatically as the listener's parameters change, so that the relative parameters remain constant.
DS3DMODE_NORMAL
Normal processing. This is the default mode.
dwApply
Value indicating when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
Settings are not applied until the application calls the IDirectSound3DListener::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.


IDirectSound3DBuffer::SetPosition

The IDirectSound3DBuffer::SetPosition method sets the sound buffer's current position, in distance units. By default, distance units are meters, but the units can be changed by using the IDirectSound3DListener::SetDistanceFactor method.

HRESULT SetPosition(
  D3DVALUE x,
  D3DVALUE y,
  D3DVALUE z,
  DWORD dwApply
);

Parameters

x, y, and z
Values whose types are D3DVALUE and that represent the coordinates of the new position vector. Note that DirectSound may adjust these values to prevent floating-point overflow.
dwApply
Value indicating when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
Settings are not applied until the application calls the IDirectSound3DListener::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.


IDirectSound3DBuffer::SetVelocity

The IDirectSound3DBuffer::SetVelocity method sets the sound buffer's current velocity.

HRESULT SetVelocity(
  D3DVALUE x,
  D3DVALUE y,
  D3DVALUE z,
  DWORD dwApply
);

Parameters

x, y, and z
Values whose types are D3DVALUE and that represent the coordinates of the new velocity vector. Note that DirectSound may adjust these values to prevent floating-point overflow.
dwApply
Value indicating when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
Settings are not applied until the application calls the IDirectSound3DListener::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

Velocity is used for Doppler effects only. It does not actually move the buffer. For additional information, see Doppler Factor.

The default unit of measurement is meters per second, but this can be changed by using the IDirectSound3DListener::SetDistanceFactor method.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSound3DBuffer::SetPosition, IDirectSound3DBuffer::GetVelocity


IDirectSound3DListener

Applications use the methods of the IDirectSound3DListener interface to retrieve and set parameters that describe a listener's position, orientation, and listening environment in 3-D space. This section is a reference to the methods of this interface. For a conceptual overview, see DirectSound 3-D Listeners.

The interface is obtained by using the IDirectSoundBuffer::QueryInterface method. For more information, see Obtaining the DirectSound3DListener Object.

The methods of the IDirectSound3DListener interface can be organized into the following groups:

Batch parameters | GetAllParameters
 | SetAllParameters
Deferred settings | CommitDeferredSettings
Distance factor | GetDistanceFactor
 | SetDistanceFactor
Doppler factor | GetDopplerFactor
 | SetDopplerFactor
Orientation | GetOrientation
 | SetOrientation
Position | GetPosition
 | SetPosition
Rolloff factor | GetRolloffFactor
 | SetRolloffFactor
Velocity | GetVelocity
 | SetVelocity

The IDirectSound3DListener interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECTSOUND3DLISTENER type is defined as a pointer to the IDirectSound3DListener interface:

typedef struct IDirectSound3DListener    *LPDIRECTSOUND3DLISTENER;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.


IDirectSound3DListener::CommitDeferredSettings

The IDirectSound3DListener::CommitDeferredSettings method commits any deferred settings made since the last call to this method.

HRESULT CommitDeferredSettings();

Parameters

None.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

For additional information about using deferred settings to maximize efficiency, see Deferred Settings.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.


IDirectSound3DListener::GetAllParameters

The IDirectSound3DListener::GetAllParameters method retrieves information that describes the current state of the 3-D world and listener.

HRESULT GetAllParameters(
  LPDS3DLISTENER lpListener
);

Parameters

lpListener
Address of a DS3DLISTENER structure that will contain the current state of the 3-D world and listener.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSound3DListener::SetAllParameters


IDirectSound3DListener::GetDistanceFactor

The IDirectSound3DListener::GetDistanceFactor method retrieves the current distance factor.

HRESULT GetDistanceFactor(
  LPD3DVALUE lpflDistanceFactor
);

Parameters

lpflDistanceFactor
Address of a variable whose type is D3DVALUE and that will contain the current distance factor value.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

For additional information about distance factors, see Distance Factor.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSound3DListener::SetDistanceFactor


IDirectSound3DListener::GetDopplerFactor

The IDirectSound3DListener::GetDopplerFactor method retrieves the current Doppler effect factor.

HRESULT GetDopplerFactor(
  LPD3DVALUE lpflDopplerFactor
);

Parameters

lpflDopplerFactor
Address of a variable whose type is D3DVALUE and that will contain the current Doppler factor value.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The Doppler factor has a range of DS3D_MINDOPPLERFACTOR (no Doppler effects) to DS3D_MAXDOPPLERFACTOR (as currently defined, 10 times the Doppler effects found in the real world). The default value is DS3D_DEFAULTDOPPLERFACTOR (1.0). For additional information, see Doppler Factor.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSound3DListener::SetDopplerFactor


IDirectSound3DListener::GetOrientation

The IDirectSound3DListener::GetOrientation method retrieves the listener's current orientation in vectors: a front vector and a top vector.

HRESULT GetOrientation(
  LPD3DVECTOR lpvOrientFront,
  LPD3DVECTOR lpvOrientTop
);

Parameters

lpvOrientFront
Address of a D3DVECTOR structure that will contain the listener's front orientation vector.
lpvOrientTop
Address of a D3DVECTOR structure that will contain the listener's top orientation vector.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The front vector points in the direction of the listener's nose, and the top vector points out the top of the listener's head. By default, the front vector is (0,0,1.0) and the top vector is (0,1.0,0).

The values returned are not necessarily the same as those set by using the IDirectSound3DListener::SetOrientation method. DirectSound adjusts orientation vectors so that they are at right angles and have a magnitude of less than or equal to 1.0.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSound3DListener::SetOrientation


IDirectSound3DListener::GetPosition

The IDirectSound3DListener::GetPosition method retrieves the listener's current position in distance units. By default, these units are meters, but this can be changed by calling the IDirectSound3DListener::SetDistanceFactor method.

HRESULT GetPosition(
  LPD3DVECTOR lpvPosition
);

Parameters

lpvPosition
Address of a D3DVECTOR structure that will contain the listener's position vector.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSound3DListener::SetPosition


IDirectSound3DListener::GetRolloffFactor

The IDirectSound3DListener::GetRolloffFactor method retrieves the current rolloff factor.

HRESULT GetRolloffFactor(
  LPD3DVALUE lpflRolloffFactor
);

Parameters

lpflRolloffFactor
Address of a variable whose type is D3DVALUE and that will contain the current rolloff factor value.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The rolloff factor has a range of DS3D_MINROLLOFFFACTOR (no rolloff) to DS3D_MAXROLLOFFFACTOR (as currently defined, 10 times the rolloff found in the real world). The default value is DS3D_DEFAULTROLLOFFFACTOR (1.0). For additional information, see Rolloff Factor.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSound3DListener::SetRolloffFactor


IDirectSound3DListener::GetVelocity

The IDirectSound3DListener::GetVelocity method retrieves the listener's current velocity.

HRESULT GetVelocity(
  LPD3DVECTOR lpvVelocity
);

Parameters

lpvVelocity
Address of a D3DVECTOR structure that will contain the listener's current velocity.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

Velocity is used only for Doppler effects. It does not actually move the listener. To change the listener's position, use the IDirectSound3DListener::SetPosition method. The default velocity is (0,0,0).

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSound3DListener::SetVelocity


IDirectSound3DListener::SetAllParameters

The IDirectSound3DListener::SetAllParameters method sets all 3-D listener parameters from a given DS3DLISTENER structure that describes all aspects of the 3-D listener at a moment in time.

HRESULT SetAllParameters(
  LPCDS3DLISTENER lpcListener,
  DWORD dwApply
);

Parameters

lpcListener
Address of a DS3DLISTENER structure that contains information describing all current 3-D listener parameters.
dwApply
Value indicating when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
Settings are not applied until the application calls the IDirectSound3DListener::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSound3DListener::GetAllParameters


IDirectSound3DListener::SetDistanceFactor

The IDirectSound3DListener::SetDistanceFactor method sets the current distance factor.

HRESULT SetDistanceFactor(
  D3DVALUE flDistanceFactor,
  DWORD dwApply
);

Parameters

flDistanceFactor
New distance factor.
dwApply
Value indicating when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
Settings are not applied until the application calls the IDirectSound3DListener::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

For additional information about distance factors, see Distance Factor.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSound3DListener::GetDistanceFactor


IDirectSound3DListener::SetDopplerFactor

The IDirectSound3DListener::SetDopplerFactor method sets the current Doppler effect factor.

HRESULT SetDopplerFactor(
  D3DVALUE flDopplerFactor,
  DWORD dwApply
);

Parameters

flDopplerFactor
New Doppler factor value.
dwApply
Value indicating when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
Settings are not applied until the application calls the IDirectSound3DListener::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The Doppler factor has a range of DS3D_MINDOPPLERFACTOR (no Doppler effects) to DS3D_MAXDOPPLERFACTOR (as currently defined, 10 times the Doppler effects found in the real world). The default value is DS3D_DEFAULTDOPPLERFACTOR (1.0). For additional information, see Doppler Factor.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSound3DListener::GetDopplerFactor


IDirectSound3DListener::SetOrientation

The IDirectSound3DListener::SetOrientation method sets the listener's current orientation in terms of two vectors: a front vector and a top vector.

HRESULT SetOrientation(
  D3DVALUE xFront,
  D3DVALUE yFront,
  D3DVALUE zFront,
  D3DVALUE xTop,
  D3DVALUE yTop,
  D3DVALUE zTop,
  DWORD dwApply
);

Parameters

xFront, yFront, and zFront
Values whose types are D3DVALUE and that represent the coordinates of the front orientation vector.
xTop, yTop, and zTop
Values whose types are D3DVALUE and that represent the coordinates of the top orientation vector.
dwApply
Value indicating when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
Settings are not applied until the application calls the IDirectSound3DListener::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The front vector points in the direction of the listener's nose, and the top vector points out the top of the listener's head. By default, the front vector is (0,0,1.0) and the top vector is (0,1.0,0).

The top vector must be at right angles to the front vector. If necessary, DirectSound adjusts the front vector after setting the top vector.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSound3DListener::GetOrientation


IDirectSound3DListener::SetPosition

The IDirectSound3DListener::SetPosition method sets the listener's current position, in distance units. By default, these units are meters, but this can be changed by calling the IDirectSound3DListener::SetDistanceFactor method.

HRESULT SetPosition(
  D3DVALUE x,
  D3DVALUE y,
  D3DVALUE z,
  DWORD dwApply
);

Parameters

x, y, and z
Values whose types are D3DVALUE and that represent the coordinates of the listener's new position vector. Note that DirectSound may adjust these values to prevent floating-point overflow.
dwApply
Value indicating when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
Settings are not applied until the application calls the IDirectSound3DListener::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSound3DListener::GetPosition


IDirectSound3DListener::SetRolloffFactor

The IDirectSound3DListener::SetRolloffFactor method sets the rolloff factor.

HRESULT SetRolloffFactor(
  D3DVALUE flRolloffFactor,
  DWORD dwApply
);

Parameters

flRolloffFactor
New rolloff factor.
dwApply
Value indicating when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
Settings are not applied until the application calls the IDirectSound3DListener::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The rolloff factor has a range of DS3D_MINROLLOFFFACTOR (no rolloff) to DS3D_MAXROLLOFFFACTOR (as currently defined, 10 times the rolloff found in the real world). The default value is DS3D_DEFAULTROLLOFFFACTOR (1.0). For additional information, see Rolloff Factor.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSound3DListener::GetRolloffFactor


IDirectSound3DListener::SetVelocity

The IDirectSound3DListener::SetVelocity method sets the listener's velocity.

HRESULT SetVelocity(
  D3DVALUE x,
  D3DVALUE y,
  D3DVALUE z,
  DWORD dwApply
);

Parameters

x, y, and z
Values whose types are D3DVALUE and that represent the coordinates of the listener's new velocity vector. Note that DirectSound may adjust these values to prevent floating-point overflow.
dwApply
Value indicating when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
Settings are not applied until the application calls the IDirectSound3DListener::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

Velocity is used only for Doppler effects. It does not actually move the listener. To change the listener's position, use the IDirectSound3DListener::SetPosition method. The default velocity is (0,0,0).

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSound3DListener::GetVelocity


IDirectSoundBuffer

Applications use the methods of the IDirectSoundBuffer interface to create DirectSoundBuffer objects and set up the environment.

The interface is obtained by using the IDirectSound::CreateSoundBuffer method.

The IDirectSoundBuffer methods can be organized into the following groups:

Information | GetCaps
 | GetFormat
 | GetStatus
 | SetFormat
Memory management | Initialize
 | Restore
Play management | GetCurrentPosition
 | Lock
 | Play
 | SetCurrentPosition
 | Stop
 | Unlock
Sound management | GetFrequency
 | GetPan
 | GetVolume
 | SetFrequency
 | SetPan
 | SetVolume

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECTSOUNDBUFFER type is defined as a pointer to the IDirectSoundBuffer interface:

typedef struct IDirectSoundBuffer    *LPDIRECTSOUNDBUFFER;

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.


IDirectSoundBuffer::GetCaps

The IDirectSoundBuffer::GetCaps method retrieves the capabilities of the DirectSoundBuffer object.

HRESULT GetCaps(
  LPDSBCAPS lpDSBufferCaps
);

Parameters

lpDSBufferCaps
Address of a DSBCAPS structure to contain the capabilities of this sound buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The DSBCAPS structure contains similar information to the DSBUFFERDESC structure passed to the IDirectSound::CreateSoundBuffer method, with some additional information. This additional information can include the buffer's location, either in hardware or software, and some cost measures. Examples of cost measures include the time it takes to download to a hardware buffer and the processing overhead required to mix and play the buffer when it is in the system memory.

The flags specified in the dwFlags member of the DSBCAPS structure are the same flags used by the DSBUFFERDESC structure. The only difference is that in the DSBCAPS structure, either DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE will be specified according to the location of the buffer memory. In the DSBUFFERDESC structure, these flags are optional and, depending on which flag is specified, force the buffer to be located in either hardware or software.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

DSBCAPS, DSBUFFERDESC, IDirectSoundBuffer, IDirectSound::CreateSoundBuffer


IDirectSoundBuffer::GetCurrentPosition

The IDirectSoundBuffer::GetCurrentPosition method retrieves the current position of the play and write cursors in the sound buffer.

HRESULT GetCurrentPosition(
  LPDWORD lpdwCurrentPlayCursor,
  LPDWORD lpdwCurrentWriteCursor
);

Parameters

lpdwCurrentPlayCursor
Address of a variable to contain the current play position in the DirectSoundBuffer object. This position is an offset within the sound buffer and is specified in bytes. This parameter can be NULL if the current play position is not wanted.
lpdwCurrentWriteCursor
Address of a variable to contain the current write position in the DirectSoundBuffer object. This position is an offset within the sound buffer and is specified in bytes. This parameter can be NULL if the current write position is not wanted.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The write cursor indicates the position at which it is safe to write new data to the buffer. The write cursor always leads the play cursor, typically by about 15 milliseconds' worth of audio data. For more information, see Current Play and Write Positions.

It is always safe to change data that is behind the position indicated by the lpdwCurrentPlayCursor parameter.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSoundBuffer, IDirectSoundBuffer::SetCurrentPosition


IDirectSoundBuffer::GetFormat

The IDirectSoundBuffer::GetFormat method retrieves a description of the format of the sound data in the buffer, or the buffer size needed to retrieve the format description.

HRESULT GetFormat(
  LPWAVEFORMATEX lpwfxFormat,
  DWORD dwSizeAllocated,
  LPDWORD lpdwSizeWritten
);

Parameters

lpwfxFormat
Address of the WAVEFORMATEX structure to contain a description of the sound data in the buffer. To retrieve the buffer size needed to contain the format description, specify NULL. In this case the DWORD pointed to by the lpdwSizeWritten parameter will receive the size of the structure needed to receive complete format information.
dwSizeAllocated
Size, in bytes, of the WAVEFORMATEX structure. DirectSound writes, at most, dwSizeAllocated bytes to that pointer; if the WAVEFORMATEX structure requires more memory, it is truncated.
lpdwSizeWritten
Address of a variable to contain the number of bytes written to the WAVEFORMATEX structure. This parameter can be NULL.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The WAVEFORMATEX structure can have a variable length that depends on the details of the format. Before retrieving the format description, the application should query the DirectSoundBuffer object for the size of the format by calling this method and specifying NULL for the lpwfxFormat parameter. The size of the structure will be returned in the lpdwSizeWritten parameter. The application can then allocate sufficient memory and call IDirectSoundBuffer::GetFormat again to retrieve the format description.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSoundBuffer, IDirectSoundBuffer::SetFormat


IDirectSoundBuffer::GetFrequency

The IDirectSoundBuffer::GetFrequency method retrieves the frequency, in samples per second, at which the buffer is playing.

HRESULT GetFrequency(
  LPDWORD lpdwFrequency
);

Parameters

lpdwFrequency
Address of the variable that represents the frequency at which the audio buffer is being played.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_CONTROLUNAVAIL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The frequency value will be in the range of DSBFREQUENCY_MIN to DSBFREQUENCY_MAX. These values are currently defined in Dsound.h as 100 and 100,000 respectively.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSoundBuffer, IDirectSoundBuffer::SetFrequency


IDirectSoundBuffer::GetPan

The IDirectSoundBuffer::GetPan method retrieves a variable that represents the relative volume between the left and right audio channels.

HRESULT GetPan(
  LPLONG lplPan
);

Parameters

lplPan
Address of a variable to contain the relative mix between the left and right speakers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_CONTROLUNAVAIL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The returned value is measured in hundredths of a decibel (dB), in the range of DSBPAN_LEFT to DSBPAN_RIGHT. These values are currently defined in Dsound.h as -10,000 and 10,000 respectively. The value DSBPAN_LEFT means the right channel is attenuated by 100 dB. The value DSBPAN_RIGHT means the left channel is attenuated by 100 dB. The neutral value is DSBPAN_CENTER, defined as zero. This value of 0 in the lplPan parameter means that both channels are at full volume (they are attenuated by 0 decibels). At any setting other than DSBPAN_CENTER, one of the channels is at full volume and the other is attenuated.

A pan of -2173 means that the left channel is at full volume and the right channel is attenuated by 21.73 dB. Similarly, a pan of 870 means that the left channel is attenuated by 8.7 dB and the right channel is at full volume. A pan of DSBPAN_LEFT means that the right channel is silent and the sound is all the way to the left, while a pan of DSBPAN_RIGHT means that the left channel is silent and the sound is all the way to the right.

The pan control acts cumulatively with the volume control.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSoundBuffer, IDirectSoundBuffer::GetVolume, IDirectSoundBuffer::SetPan, IDirectSoundBuffer::SetVolume


IDirectSoundBuffer::GetStatus

The IDirectSoundBuffer::GetStatus method retrieves the current status of the sound buffer.

HRESULT GetStatus(
  LPDWORD lpdwStatus
);

Parameters

lpdwStatus
Address of a variable to contain the status of the sound buffer. The status can be a combination of the following flags:
DSBSTATUS_BUFFERLOST
The buffer is lost and must be restored before it can be played or locked.
DSBSTATUS_LOOPING
The buffer is being looped. If this value is not set, the buffer will stop when it reaches the end of the sound data. Note that if this value is set, the buffer must also be playing.
DSBSTATUS_PLAYING
The buffer is playing. If this value is not set, the buffer is stopped.
DSBSTATUS_LOCSOFTWARE
The buffer is playing in software. This flag can only be set for buffers created with DSBCAPS_LOCDEFER flag set.
DSBSTATUS_LOCHARDWARE
The buffer is playing in hardware. This flag can only be set for buffers created with DSBCAPS_LOCDEFER flag set.
DSBSTATUS_TERMINATED
The buffer was prematurely terminated by the voice management logic. Note that that if this value is set, the buffer is not playing. This flag can only be set for buffers created with DSBCAPS_LOCDEFER flag set.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSoundBuffer


IDirectSoundBuffer::GetVolume

The IDirectSoundBuffer::GetVolume method retrieves the current volume for this sound buffer.

HRESULT GetVolume(
  LPLONG lplVolume
);

Parameters

lplVolume
Address of the variable to contain the volume associated with the specified DirectSound buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_CONTROLUNAVAIL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The volume is specified in hundredths of decibels (dB). Allowable values are between DSBVOLUME_MAX (no attenuation) and DSBVOLUME_MIN (silence). These values are currently defined in Dsound.h as 0 and -10,000 respectively. The value DSBVOLUME_MAX represents the original, unadjusted volume of the stream. The value DSBVOLUME_MIN indicates an audio volume attenuated by 100 dB, which, for all practical purposes, is silence. Currently DirectSound does not support amplification.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSoundBuffer, IDirectSoundBuffer::SetVolume


IDirectSoundBuffer::Initialize

The IDirectSoundBuffer::Initialize method initializes a DirectSoundBuffer object if it has not yet been initialized.

HRESULT Initialize(
  LPDIRECTSOUND lpDirectSound,
  LPCDSBUFFERDESC lpcDSBufferDesc
);

Parameters

lpDirectSound
Address of the DirectSound object associated with this DirectSoundBuffer object.
lpcDSBufferDesc
Address of a DSBUFFERDESC structure that contains the values used to initialize this sound buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values.

DSERR_INVALIDPARAM
DSERR_ALREADYINITIALIZED

Remarks

Because the IDirectSound::CreateSoundBuffer method calls IDirectSoundBuffer::Initialize internally, it is not needed for the current release of DirectSound. This method is provided for future extensibility.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

DSBUFFERDESC, IDirectSound::CreateSoundBuffer, IDirectSoundBuffer


IDirectSoundBuffer::Lock

The IDirectSoundBuffer::Lock method obtains a valid write pointer to the sound buffer's audio data.

HRESULT Lock(
  DWORD dwWriteCursor,
  DWORD dwWriteBytes,
  LPVOID lplpvAudioPtr1,
  LPDWORD lpdwAudioBytes1,
  LPVOID lplpvAudioPtr2,
  LPDWORD lpdwAudioBytes2,
  DWORD dwFlags
);

Parameters

dwWriteCursor
Offset, in bytes, from the start of the buffer to where the lock begins. This parameter is ignored if DSBLOCK_FROMWRITECURSOR is specified in the dwFlags parameter.
dwWriteBytes
Size, in bytes, of the portion of the buffer to lock. Note that the sound buffer is conceptually circular.
lplpvAudioPtr1
Address of a pointer to contain the first block of the sound buffer to be locked.
lpdwAudioBytes1
Address of a variable to contain the number of bytes pointed to by the lplpvAudioPtr1 parameter. If this value is less than the dwWriteBytes parameter, lplpvAudioPtr2 will point to a second block of sound data.
lplpvAudioPtr2
Address of a pointer to contain the second block of the sound buffer to be locked. If the value of this parameter is NULL, the lplpvAudioPtr1 parameter points to the entire locked portion of the sound buffer.
lpdwAudioBytes2
Address of a variable to contain the number of bytes pointed to by the lplpvAudioPtr2 parameter. If lplpvAudioPtr2 is NULL, this value will be 0.
dwFlags
Flags modifying the lock event. The following flags are defined:
DSBLOCK_FROMWRITECURSOR
Locks from the current write position, making a call to IDirectSoundBuffer::GetCurrentPosition unnecessary. If this flag is specified, the dwWriteCursor parameter is ignored.
DSBLOCK_ENTIREBUFFER
Locks the entire buffer. The dwWriteBytes parameter is ignored.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_BUFFERLOST
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

This method accepts an offset and a byte count, and returns two write pointers and their associated sizes. Two pointers are required because sound buffers are circular. If the locked bytes do not wrap around the end of the buffer, the second pointer, lplpvAudioBytes2, will be NULL. However, if the bytes do wrap around, then the second pointer will point to the beginning of the buffer.

If the application passes NULL for the lplpvAudioPtr2 and lpdwAudioBytes2 parameters, DirectSound will not lock the wrap-around portion of the buffer.

The application should write data to the pointers returned by the IDirectSoundBuffer::Lock method, and then call the IDirectSoundBuffer::Unlock method to release the buffer back to DirectSound. The sound buffer should not be locked for long periods of time; if it is, the play cursor will reach the locked bytes and configuration-dependent audio problems, possibly random noise, will result.

Warning This method returns a write pointer only. The application should not try to read sound data from this pointer; the data might not be valid even though the DirectSoundBuffer object contains valid sound data. For example, if the buffer is located in on-board memory, the pointer might be an address to a temporary buffer in main system memory. When IDirectSoundBuffer::Unlock is called, this temporary buffer will be transferred to the on-board memory.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSoundBuffer, IDirectSoundBuffer::GetCurrentPosition, IDirectSoundBuffer::Unlock


IDirectSoundBuffer::Play

The IDirectSoundBuffer::Play method causes the sound buffer to play from the current position.

HRESULT Play(
  DWORD dwReserved1,
  DWORD dwPriority,
  DWORD dwFlags
);

Parameters

dwReserved1
This parameter is reserved. Its value must be 0.
dwPriority
The priority for the sound. May be used by the voice manager to determine the priority of the sound when assigning hardware mixing resources. If the buffer was not created with LOC_DEFER flag, this value must be 0. The priority level is a DWORD with a range from 0 to ffffffff, with 0 being the lowest priory.
dwFlags
Flags specifying how to play the buffer. The following flag is defined:
DSBPLAY_LOOPING
Once the end of the audio buffer is reached, play restarts at the beginning of the buffer. Play continues until explicitly stopped. This flag must be set when playing primary sound buffers.
Voice Allocation flags
DSBPLAY_LOCHARDWARE
For buffers created with the DSBCAPS_LOCDEFER flag set, play this voice in a hardware buffer only. If the hardware has no available voices and no DSBPLAY_TERMINATEBY_xxx flags are set, the Play will fail. If neither DBSPLAY_LOCHARDWARE nor DBSPLAY_LOCSOFTWARE is set, the sound may be played in either software or hardware, depending on the availability of resources at the time the Play is issued. Note: This flag will only affect buffers that have been created with the DSBCAPS_LOCDEFER flag. This flag is incompatible with DSBPLAY_LOCSOFTWARE.
DSBPLAY_LOCSOFTWARE
For buffers created with the LOC_DEFER flag set, play this voice in a software buffer only. If neither DBSPLAY_LOCHARDWARE nor DBSPLAY_LOCSOFTWARE is set, the sound may be played in either software or hardware, depending on the availability of resources at the time the Play is issued. Note: This flag will only affect buffers that have been created with the DSBCAPS_LOCDEFER flag and if DSBPLAY_LOCSOFTWARE is set, no DSBPLAY_TERMINATEBY flags are allowed. This flag is incompatible with DSBPLAY_LOCHARDWARE.
Voice Management flags
DSBPLAY_TERMINATEBY_TIME
Enables hardware resource stealing. When used, it is guaranteed that the voice will play in hardware and the software HEL will not be used. If the hardware has no available voices, a currently playing buffer will be stopped to make room for the new buffer. The buffer to be prematurely terminated will be the one with the least time left to play. Note: Only buffers that have been created with the DSBCAPS_LOCDEFER flag are candidates for premature termination.
DSBPLAY_TERMINATEBY_DISTANCE
For 3-D buffers only. Enables hardware resource stealing. When used, it is guaranteed that the voice will play in hardware and the software HEL will not be used. If the hardware has no available voices, a currently playing buffer will be stopped to make room for the new buffer. The buffer to be prematurely terminated will be selected from buffers that are beyond their maximum distance, and have the buffer's DSBCAPS_ MUTE3DBYDISTANCE flag set. If there are no buffers beyond their maximum distances with MUTE3DBYDISTANCE flags set, the play will fail. Note: Only buffers that have been created with the DSBCAPS_LOCDEFER flag are candidates for premature termination.
DSBPLAY_TERMINATEBY_PRIORITY
Enables hardware resource stealing. When used, it is guaranteed that the voice will play in hardware and the software HEL will not be used. If the hardware has no available voices, a currently playing buffer will be stopped to make room for the new buffer. The buffer to be prematurely terminated will be the one with the lowest priority as set by the IDirectSoundBuffer::Play priority argument. DSBPLAY_TERMINATEBY_PRIORITY may not co-exist with DSBPLAY_TERMINATEBY_DISTANCE. Note: Only buffers that have been created with the DSBCAPS_LOCDEFER flag are candidates for premature termination.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_BUFFERLOST
DSERR_HWUNAVAIL
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

This method will cause a secondary sound buffer to be mixed into the primary buffer and sent to the sound device. If this is the first buffer to play, it will implicitly create a primary buffer and start playing that buffer; the application need not explicitly direct the primary buffer to play.

If the buffer specified in the method is already playing, the call to the method will succeed and the buffer will continue to play. However, the flags defined in the most recent call supersede flags defined in previous calls.

Primary buffers must be played with the DSBPLAY_LOOPING flag set.

This method will cause primary sound buffers to start playing to the sound device. If the application is set to the DSSCL_WRITEPRIMARY cooperative level, this will cause the audio data in the primary buffer to be sent to the sound device. However, if the application is set to any other cooperative level, this method will ensure that the primary buffer is playing even when no secondary buffers are playing; in that case, silence will be played. This can reduce processing overhead when sounds are started and stopped in sequence, because the primary buffer will be playing continuously rather than stopping and starting between secondary buffers.

Voice allocation and voice management flags apply only to buffers created with the DSBCAPS_LOCDEFER flag set. If an IDirectSoundBuffer::Play is called with a voice allocation or voice management flag set on a buffer that was not created with the DSBCAPS_LOCDEFER flag set, the call will fail DSERR_INVALIDPARAM. DSBPLAY_TERMINATEBY_TIME and DSBPLAY_TERMINATEBY_DISTANCE cannot co-exist, but either may co-exist with DSBPLAY_TERMINATEBY_PRIORITY. In this case, the TIME or DISTANCE flag is used to determine which buffer should be terminated in the event of a priority tie.

Voice management flags summary. The following chart shows the behavior if the hardware has no free voices when a new Play is issued, assuming the buffer has been created with the DSBCAPS_LOCDEFER flag set:

 | DSBPLAY_LOCHARDWARE | No DSBPLAY_LOC flag | DSBPLAY_LOCSOFTWARE
DSBPLAY_TERMINATEBY_TIME | Sound with least time left to play will be terminated and the new sound played on the released voice. | Sound with least time left to play will be terminated and the new sound played on the released voice. | New sound will be played in software.
DSBPLAY_TERMINATEBY_DISTANCE | If any sounds currently playing in hardware are beyond their "MAX_DISTANCE" setting and have the DSBCAPS_MUTE3DATMAXDISTANCE flag set, one of them will be terminated and the new sound will play in hardware. Otherwise, the Play() call with fail. | If any sounds currently playing in hardware are beyond their "MAX_DISTANCE" setting and have the DSBCAPS_MUTE3DATMAXDISTANCE flag set, one of them will be terminated and the new sound will play in hardware. Otherwise, the new sound will play in software. | New sound will be played in software.
DSBPLAY_TERMINATEBY_PRIORITY | If the new sound's priority is higher than or equal to that of any sound currently playing in hardware, one of the lowest-priority sounds will be terminated and the new sound will play in hardware. Otherwise, the Play() call with fail. | If the new sound's priority is higher than or equal to that of any sound currently playing in hardware, one of the lowest-priority sounds will be terminated and the new sound will play in hardware. Otherwise, the new sound will play in software. | New sound will be played in software.

Note Before this method can be called on any sound buffer, the application should call the IDirectSound::SetCooperativeLevel method and specify a cooperative level, typically DSSCL_NORMAL. If IDirectSound::SetCooperativeLevel has not been called, the IDirectSoundBuffer::Play method returns with DS_OK, but no sound will be produced until IDirectSound::SetCooperativeLevel is called.

DSBPLAY_LOCHARDWARE and DSBPLAY_LOCSOFTWARE may not co-exist.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSoundBuffer, IDirectSound::SetCooperativeLevel


IDirectSoundBuffer::Restore

The IDirectSoundBuffer::Restore method restores the memory allocation for a lost sound buffer for the specified DirectSoundBuffer object.

HRESULT Restore();

Parameters

None.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_BUFFERLOST
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

If the application does not have the input focus, IDirectSoundBuffer::Restore might not succeed. For example, if the application with the input focus has the DSSCL_WRITEPRIMARY cooperative level, no other application will be able to restore its buffers. Similarly, an application with the DSSCL_WRITEPRIMARY cooperative level must have the input focus to restore its primary sound buffer.

Once DirectSound restores the buffer memory, the application must rewrite the buffer with valid sound data. DirectSound cannot restore the contents of the memory, only the memory itself.

The application can receive notification that a buffer is lost when it specifies that buffer in a call to the IDirectSoundBuffer::Lock or IDirectSoundBuffer::Play method. These methods return DSERR_BUFFERLOST to indicate a lost buffer. The IDirectSoundBuffer::GetStatus method can also be used to retrieve the status of the sound buffer and test for the DSBSTATUS_BUFFERLOST flag.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSoundBuffer, IDirectSoundBuffer::Lock, IDirectSoundBuffer::Play, IDirectSoundBuffer::GetStatus


IDirectSoundBuffer::SetCurrentPosition

The IDirectSoundBuffer::SetCurrentPosition method moves the current play position for secondary sound buffers.

HRESULT SetCurrentPosition(
  DWORD dwNewPosition
);

Parameters

dwNewPosition
New position, in bytes, from the beginning of the buffer that will be used when the sound buffer is played.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

This method cannot be called on primary sound buffers.

If the buffer is playing, it will immediately move to the new position and continue. If it is not playing, it will begin from the new position the next time the IDirectSoundBuffer::Play method is called.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSoundBuffer, IDirectSoundBuffer::GetCurrentPosition, IDirectSoundBuffer::Play


IDirectSoundBuffer::SetFormat

The IDirectSoundBuffer::SetFormat method sets the format of the primary sound buffer for the application. Whenever this application has the input focus, DirectSound will set the primary buffer to the specified format.

HRESULT SetFormat(
  LPCWAVEFORMATEX lpcfxFormat
);

Parameters

lpcfxFormat
Address of a WAVEFORMATEX structure that describes the new format for the primary sound buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_BADFORMAT
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_OUTOFMEMORY
DSERR_PRIOLEVELNEEDED
DSERR_UNSUPPORTED

Remarks

If this method is called on a primary buffer that is being accessed in write-primary cooperative level, the buffer must be stopped before IDirectSoundBuffer::SetFormat is called. If this method is being called on a primary buffer for a non-write-primary level, DirectSound will implicitly stop the primary buffer, change the format, and restart the primary; the application need not do this explicitly.

This method will succeed even if the hardware does not support the requested format. DirectSound will set the buffer to the closest supported format, then mix the sound in the requested format and convert it before sending it to the primary buffer. To determine whether this is happening, an application can call the IDirectSoundBuffer::GetFormat method for the primary buffer and compare the result with the format that was requested with the SetFormat method.

A call to this method also fails if the calling application has the DSSCL_NORMAL cooperative level.

This method is not valid for secondary sound buffers. If a secondary sound buffer requires a format change, the application should create a new DirectSoundBuffer object using the new format.

DirectSound supports PCM formats; it does not currently support compressed formats.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSoundBuffer, IDirectSoundBuffer::GetFormat


IDirectSoundBuffer::SetFrequency

The IDirectSoundBuffer::SetFrequency method sets the frequency at which the audio samples are played.

HRESULT SetFrequency(
  DWORD dwFrequency
);

Parameters

dwFrequency
New frequency, in hertz (Hz), at which to play the audio samples. The value must be in the range DSBFREQUENCY_MIN to DSBFREQUENCY_MAX. These values are currently defined in Dsound.h as 100 and 100,000 respectively.

If the value is DSBFREQUENCY_ORIGINAL, the frequency is reset to the default value in the current buffer format. This format is specified in the IDirectSound::CreateSoundBuffer method.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_CONTROLUNAVAIL
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

Increasing or decreasing the frequency changes the perceived pitch of the audio data. This method does not affect the format of the buffer.

This method is not valid for primary sound buffers.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSoundBuffer, IDirectSound::CreateSoundBuffer, IDirectSoundBuffer::GetFrequency, IDirectSoundBuffer::Play, IDirectSoundBuffer::SetFormat


IDirectSoundBuffer::SetPan

The IDirectSoundBuffer::SetPan method specifies the relative volume between the left and right channels.

HRESULT SetPan(
  LONG lPan
);

Parameters

lPan
Relative volume between the left and right channels.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_CONTROLUNAVAIL
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The value in lPan is measured in hundredths of a decibel (dB), in the range of DSBPAN_LEFT to DSBPAN_RIGHT. These values are currently defined in Dsound.h as -10,000 and 10,000 respectively. The value DSBPAN_LEFT means the right channel is attenuated by 100 dB. The value DSBPAN_RIGHT means the left channel is attenuated by 100 dB. The neutral value is DSBPAN_CENTER, defined as zero. This value of 0 in the lplPan parameter means that both channels are at full volume (they are attenuated by 0 decibels). At any setting other than DSBPAN_CENTER, one of the channels is at full volume and the other is attenuated.

A pan of -2173 means that the left channel is at full volume and the right channel is attenuated by 21.73 dB. Similarly, a pan of 870 means that the left channel is attenuated by 8.7 dB and the right channel is at full volume. A pan of DSBPAN_LEFT means that the right channel is silent and the sound is all the way to the left, while a pan of DSBPAN_RIGHT means that the left channel is silent and the sound is all the way to the right.

The pan control acts cumulatively with the volume control.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSoundBuffer, IDirectSoundBuffer::GetPan, IDirectSoundBuffer::GetVolume, IDirectSoundBuffer::SetVolume


IDirectSoundBuffer::SetVolume

The IDirectSoundBuffer::SetVolume method changes the volume of a sound buffer.

HRESULT SetVolume(
  LONG lVolume
);

Parameters

lVolume
New volume requested for this sound buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_CONTROLUNAVAIL
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The volume is specified in hundredths of decibels (dB). Allowable values are between DSBVOLUME_MAX (no attenuation) and DSBVOLUME_MIN (silence). These values are currently defined in Dsound.h as 0 and -10,000 respectively. The value DSBVOLUME_MAX represents the original, unadjusted volume of the stream. The value DSBVOLUME_MIN indicates an audio volume attenuated by 100 dB, which, for all practical purposes, is silence. Currently DirectSound does not support amplification.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSoundBuffer, IDirectSoundBuffer::GetPan, IDirectSoundBuffer::GetVolume, IDirectSoundBuffer::SetPan


IDirectSoundBuffer::Stop

The IDirectSoundBuffer::Stop method causes the sound buffer to stop playing.

HRESULT Stop();

Parameters

None.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

For secondary sound buffers, IDirectSoundBuffer::Stop will set the current position of the buffer to the sample that follows the last sample played. This means that if the IDirectSoundBuffer::Play method is called on the buffer, it will continue playing where it left off.

For primary sound buffers, if an application has the DSSCL_WRITEPRIMARY level, this method will stop the buffer and reset the current position to 0 (the beginning of the buffer). This is necessary because the primary buffers on most sound cards can play only from the beginning of the buffer.

However, if IDirectSoundBuffer::Stop is called on a primary buffer and the application has a cooperative level other than DSSCL_WRITEPRIMARY, this method simply reverses the effects of IDirectSoundBuffer::Play. It configures the primary buffer to stop if no secondary buffers are playing. If other buffers are playing in this or other applications, the primary buffer will not actually stop until they are stopped. This method is useful because playing the primary buffer consumes processing overhead even if the buffer is playing sound data with the amplitude of 0 decibels.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSoundBuffer, IDirectSoundBuffer::Play


IDirectSoundBuffer::Unlock

The IDirectSoundBuffer::Unlock method releases a locked sound buffer.

HRESULT Unlock(
  LPVOID lpvAudioPtr1,
  DWORD dwAudioBytes1,
  LPVOID lpvAudioPtr2,
  DWORD dwAudioBytes2
);

Parameters

lpvAudioPtr1
Address of the value retrieved in the lplpvAudioPtr1 parameter of the IDirectSoundBuffer::Lock method.
dwAudioBytes1
Number of bytes actually written to the lpvAudioPtr1 parameter. It should not exceed the number of bytes returned by the IDirectSoundBuffer::Lock method.
lpvAudioPtr2
Address of the value retrieved in the lplpvAudioPtr2 parameter of the IDirectSoundBuffer::Lock method.
dwAudioBytes2
Number of bytes actually written to the lpvAudioPtr2 parameter. It should not exceed the number of bytes returned by the IDirectSoundBuffer::Lock method.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

An application must pass both pointers, lpvAudioPtr1 and lpvAudioPtr2, returned by the IDirectSoundBuffer::Lock method to ensure the correct pairing of IDirectSoundBuffer::Lock and IDirectSoundBuffer::Unlock. The second pointer is needed even if 0 bytes were written to the second pointer.

Applications must pass the number of bytes actually written to the two pointers in the parameters dwAudioBytes1 and dwAudioBytes2.

Make sure the sound buffer does not remain locked for long periods of time.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSoundBuffer, IDirectSoundBuffer::GetCurrentPosition, IDirectSoundBuffer::Lock


IDirectSoundCapture

The methods of the IDirectSoundCapture interface are used to create sound capture buffers.

The interface is obtained by using the DirectSoundCaptureCreate function.

This reference section gives information on the following methods of the IDirectSoundCapture interface:

Creation | CreateCaptureBuffer
 | Initialize
Capabilities | GetCaps

Like all COM interfaces, the IDirectSoundCapture interface also inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECTSOUNDCAPTURE type is defined as a pointer to the IDirectSoundCapture interface:

typedef struct IDirectSoundCapture    *LPDIRECTSOUNDCAPTURE;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.


IDirectSoundCapture::CreateCaptureBuffer

The IDirectSoundCapture::CreateCaptureBuffer method creates a capture buffer.

Unlike DirectSound, which can mix several sounds into one sound for output, DirectSoundCapture cannot do the exact opposite and extract various sounds from one input sound. For the first version, DirectSoundCapture allows only one capture buffer to exist at any given time per capture device.

HRESULT CreateCaptureBuffer(
  LPDSCBUFFERDESC lpDSCBufferDesc,
  LPLPDIRECTSOUNDCAPTUREBUFFER lplpDirectSoundCaptureBuffer,
  LPUNKNOWN pUnkOuter
);

Parameters

lpDSCBufferDesc
Pointer to a DSCBUFFERDESC structure containing values for the capture buffer being created.
lplpDirectSoundCaptureBuffer
Address of the IDirectSoundCaptureBuffer interface pointer if successful.
pUnkOuter
Controlling IUnknown of the aggregate. Its value must be NULL.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_INVALIDPARAM
DSERR_BADFORMAT
DSERR_GENERIC
DSERR_NODRIVER
DSERR_OUTOFMEMORY
DSERR_UNINITIALIZED

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.


IDirectSoundCapture::GetCaps

The IDirectSoundCapture::GetCaps method obtains the capabilities of the capture device.

HRESULT GetCaps(
  LPDSCCAPS lpDSCCaps
);

Parameters

lpDSCCaps
Pointer to a DSCCAPS structure to be filled by the capture device. When the method is called, the dwSize member must specify the size of the structure in bytes.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_INVALIDPARAM
DSERR_UNSUPPORTED
DSERR_NODRIVER
DSERR_OUTOFMEMORY
DSERR_UNINITIALIZED

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.


IDirectSoundCapture::Initialize

When CoCreateInstance is used to create a DirectSoundCapture object, the object must be initialized with the IDirectSoundCapture::Initialize method. Calling this method is not required when the DirectSoundCaptureCreate function is used to create the object.

HRESULT Initialize(
  LPCGUID lpcGuid
);

Parameters

lpcGuid
Address of the GUID specifying the sound driver to which the DirectSoundCapture object binds. Use NULL to select the primary sound driver.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_INVALIDPARAM
DSERR_NODRIVER
DSERR_OUTOFMEMORY
DSERR_ALREADYINITIALIZED

Remarks

The lpcGuid parameter has changed from a LPGUID to a LPCGUID in DirectX 7.0.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.


IDirectSoundCaptureBuffer

The methods of the IDirectSoundCaptureBuffer interface are used to manipulate sound capture buffers.

The interface is obtained by calling the IDirectSoundCapture::CreateCaptureBuffer method.

The methods of the IDirectSoundCaptureBuffer interface may be grouped as follows:

Initialization | Initialize
Information | GetCaps
 | GetCurrentPosition
 | GetFormat
 | GetStatus
Capture management | Lock
 | Start
 | Stop
 | Unlock

Like all COM interfaces, the IDirectSoundCaptureBuffer interface also inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECTSOUNDCAPTUREBUFFER type is defined as a pointer to the IDirectSoundCaptureBuffer interface:

typedef struct IDirectSoundCaptureBuffer  *LPDIRECTSOUNDCAPTUREBUFFER;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.


IDirectSoundCaptureBuffer::GetCaps

The IDirectSoundCaptureBuffer::GetCaps method returns the capabilities of the buffer.

HRESULT GetCaps(
  LPDSCBCAPS lpDSCBCaps
);

Parameters

lpDSCBCaps
Pointer to a DSCBCAPS structure to be filled by the capture buffer. On input, the dwSize member must specify the size of the structure in bytes.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_INVALIDPARAM
DSERR_UNSUPPORTED
DSERR_OUTOFMEMORY

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.


IDirectSoundCaptureBuffer::GetCurrentPosition

The IDirectSoundCaptureBuffer::GetCurrentPosition method gets the current capture and read positions in the buffer.

The capture position is ahead of the read position. These positions are not always identical due to possible buffering of captured data either on the physical device or in the host. The data after the read position up to and including the capture position is not necessarily valid data.

HRESULT GetCurrentPosition(
  LPDWORD lpdwCapturePosition,
  LPDWORD lpdwReadPosition
);

Parameters

lpdwCapturePosition
Address of a variable to receive the current capture position in the DirectSoundCaptureBuffer object. This position is an offset within the capture buffer and is specified in bytes. The value can be NULL if the caller is not interested in this position information.
lpdwReadPosition
Address of a variable to receive the current position in the DirectSoundCaptureBuffer object at which it is safe to read data. This position is an offset within the capture buffer and is specified in bytes. The value can be NULL if the caller is not interested in this position information.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_INVALIDPARAM
DSERR_NODRIVER
DSERR_OUTOFMEMORY

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.


IDirectSoundCaptureBuffer::GetFormat

The IDirectSoundCaptureBuffer::GetFormat method retrieves the current format of the capture buffer.

HRESULT GetFormat(
  LPWAVEFORMATEX lpwfxFormat,
  DWORD dwSizeAllocated,
  LPDWORD lpdwSizeWritten
);

Parameters

lpwfxFormat
Address of the WAVEFORMATEX variable to contain a description of the sound data in the capture buffer. To retrieve the buffer size needed to contain the format description, specify NULL. In this case the DWORD pointed to by the lpdwSizeWritten parameter will receive the size of the structure needed to receive complete format information.
dwSizeAllocated
Size, in bytes, of the WAVEFORMATEX structure. DirectSoundCapture writes, at most, dwSizeAllocated bytes to the structure; if the structure requires more memory, it is truncated.
lpdwSizeWritten
Address of a variable to receive the number of bytes written to the WAVEFORMATEX structure. This parameter can be NULL.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.


IDirectSoundCaptureBuffer::GetStatus

The IDirectSoundCaptureBuffer::GetStatus method retrieves the current status of the capture buffer.

HRESULT GetStatus(
  DWORD *lpdwStatus
);

Parameters

lpdwStatus
Address of a variable to contain the status of the capture buffer. The status can be set to one or more of the following:
DSCBSTATUS_CAPTURING
The buffer is currently capturing audio data.
DSCBSTATUS_LOOPING
The buffer is currently looping.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.


IDirectSoundCaptureBuffer::Initialize

The IDirectSoundCaptureBuffer::Initialize method initializes a DirectSoundCaptureBuffer object if it has not yet been initialized.

HRESULT Initialize(
  LPDIRECTSOUNDCAPTURE lpDirectSoundCapture,
  LPCDSCBUFFERDESC lpcDSCBufferDesc
);

Parameters

lpDirectSoundCapture
Address of the DirectSoundCapture object associated with this DirectSoundCaptureBuffer object.
lpcDSCBufferDesc
Address of a DSBUFFERDESC structure that contains the values used to initialize this sound buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_INVALIDPARAM
DSERR_ALREADYINITIALIZED

Remarks

Because the IDirectSoundCapture::CreateCaptureBuffer method calls the IDirectSoundCaptureBuffer::Initialize method internally, it is not needed for the current release of DirectSound. This method is provided for future extensibility.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

DSBUFFERDESC, IDirectSoundCapture::CreateCaptureBuffer


IDirectSoundCaptureBuffer::Lock

The IDirectSoundCaptureBuffer::Lock method locks the buffer. Locking the buffer returns pointers into the buffer, allowing the application to read or write audio data into that memory.

HRESULT Lock(
  DWORD dwReadCursor,
  DWORD dwReadBytes,
  LPVOID *lplpvAudioPtr1,
  LPDWORD lpdwAudioBytes1,
  LPVOID *lplpvAudioPtr2,
  LPDWORD lpdwAudioBytes2,
  DWORD dwFlags
);

Parameters

dwReadCursor
Offset, in bytes, from the start of the buffer to where the lock begins.
dwReadBytes
Size, in bytes, of the portion of the buffer to lock. Note that the capture buffer is conceptually circular.
lplpvAudioPtr1
Address of a pointer to contain the first block of the capture buffer to be locked.
lpdwAudioBytes1
Address of a variable to contain the number of bytes pointed to by the lplpvAudioPtr1 parameter. If this value is less than the dwReadBytes parameter, lplpvAudioPtr2 will point to a second block of data.
lplpvAudioPtr2
Address of a pointer to contain the second block of the capture buffer to be locked. If the value of this parameter is NULL, the lplpvAudioPtr1 parameter points to the entire locked portion of the capture buffer.
lpdwAudioBytes2
Address of a variable to contain the number of bytes pointed to by the lplpvAudioPtr2 parameter. If lplpvAudioPtr2 is NULL, this value will be 0.
dwFlags
Flags modifying the lock event. This value can be zero or the following flag:
DSCBLOCK_ENTIREBUFFER
The dwReadBytes parameter is to be ignored and the entire capture buffer is to be locked.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following values:

DSERR_INVALIDPARAM
DSERR_INVALIDCALL

Remarks

This method accepts an offset and a byte count, and returns two read pointers and their associated sizes. Two pointers are required because capture buffers are circular. If the locked bytes do not wrap around the end of the buffer, the second pointer, lplpvAudioBytes2, will be NULL. However, if the bytes do wrap around, then the second pointer will point to the beginning of the buffer.

If the application passes NULL for the lplpvAudioPtr2 and lpdwAudioBytes2 parameters, DirectSoundCapture will not lock the wrap-around portion of the buffer.

The application should read data from the pointers returned by the IDirectSoundCaptureBuffer::Lock method and then call the IDirectSoundCaptureBuffer::Unlock method to release the buffer back to DirectSoundCapture. The sound buffer should not be locked for long periods of time; if it is, the capture cursor will reach the locked bytes and configuration-dependent audio problems may result.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.


IDirectSoundCaptureBuffer::Start

The IDirectSoundCaptureBuffer::Start method puts the capture buffer into the capture state and begins capturing data into the buffer. If the capture buffer is already in the capture state then the method has no effect.

HRESULT Start(
  DWORD dwFlags
);

Parameters

dwFlags
Flags that specify the behavior for the capture buffer when capturing sound data. Flags specifying how to play the buffer. The following flag is defined:
DSCBSTART_LOOPING
Once the end of the buffer is reached, capture restarts at the beginning and continues until explicitly stopped.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_INVALIDPARAM
DSERR_NODRIVER
DSERR_OUTOFMEMORY

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.


IDirectSoundCaptureBuffer::Stop

The IDirectSoundCaptureBuffer::Stop method puts the capture buffer into the "stop" state and stops capturing data. If the capture buffer is already in the stop state then the method has no effect.

HRESULT Stop();

Parameters

None.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_NODRIVER
DSERR_OUTOFMEMORY

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.


IDirectSoundCaptureBuffer::Unlock

The IDirectSoundCaptureBuffer::Unlock method unlocks the buffer.

HRESULT Unlock(
  LPVOID lpvAudioPtr1,
  DWORD dwAudioBytes1,
  LPVOID lpvAudioPtr2,
  DWORD dwAudioBytes2
);

Parameters

lpvAudioPtr1
Address of the value retrieved in the lplpvAudioPtr1 parameter of the IDirectSoundCaptureBuffer::Lock method.
dwAudioBytes1
Number of bytes actually read from the lpvAudioPtr1 parameter. It should not exceed the number of bytes returned by the IDirectSoundCaptureBuffer::Lock method.
lpvAudioPtr2
Address of the value retrieved in the lplpvAudioPtr2 parameter of the IDirectSoundCaptureBuffer::Lock method.
dwAudioBytes2
Number of bytes actually read from the lpvAudioPtr2 parameter. It should not exceed the number of bytes returned by the IDirectSoundCaptureBuffer::Lock method.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following values:

DSERR_INVALIDPARAM
DSERR_INVALIDCALL

Remarks

An application must pass both pointers, lpvAudioPtr1 and lpvAudioPtr2, returned by the IDirectSoundCaptureBuffer::Lock method to ensure the correct pairing of IDirectSoundCaptureBuffer::Lock and IDirectSoundCaptureBuffer::Unlock. The second pointer is needed even if zero bytes were written to the second pointer.

Applications must pass the number of bytes actually written to the two pointers in the parameters dwAudioBytes1 and dwAudioBytes2.

Make sure that the capture buffer does not remain locked for long periods of time.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.


IDirectSoundNotify

The IDirectSoundNotify interface provides a mechanism for setting up notification events for a playback or capture buffer.

The interface is obtained by calling the QueryInterface method of an existing interface on a DirectSoundBuffer object. For an example, see Play Buffer Notification.

The interface has the following method:

SetNotificationPositions

Like all COM interfaces, the IDirectSoundNotify interface also inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECTSOUNDNOTIFY type is defined as a pointer to the IDirectSoundNotify interface:

typedef struct IDirectSoundNotify    *LPDIRECTSOUNDNOTIFY;

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.


IDirectSoundNotify::SetNotificationPositions

The IDirectSoundCaptureBuffer::SetNotificationPositions method sets the notification positions. During capture or playback, whenever the position reaches an offset specified in one of the DSBPOSITIONNOTIFY structures in the caller-supplied array, the associated event will be signaled. The position tracked in playback is the current play position; in capture it is the current read position.

HRESULT SetNotificationPositions(
  DWORD cPositionNotifies,
  LPCDSBPOSITIONNOTIFY lpcPositionNotifies
);

Parameters

cPositionNotifies
Number of DSBPOSITIONNOTIFY structures.
lpcPositionNotifies
Pointer to an array of DSBPOSITIONNOTIFY structures.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_INVALIDPARAM
DSERR_OUTOFMEMORY

Remarks

The value DSBPN_OFFSETSTOP can be specified in the dwOffset member to tell DirectSound to signal the associated event when the IDirectSoundBuffer::Stop or IDirectSoundCaptureBuffer::Stop method is called or when the end of the buffer has been reached and the playback is not looping. If it is used, this should be the last item in the position-notify array.

If a position-notify array has already been set, calling this function again will replace the previous position-notify array.

The buffer must be stopped when this method is called.

Note On VxD drivers, if a sound buffer is created with DSBCAPS_CTRLPOSITIONNOTIFY, this buffer will always be a software buffer. This is because the VxD driver model doesn't support the notify interface. With WDM drivers, a position notification enabled buffer may be in hardware, if hardware is available.

When using LOC_DEFER and NOTIFY along with any voice management TERMINATEBY flag, it is possible that a sound that has notifications set, but not yet reached, may be terminated by the voice manager. In this event, the notification event will not occur.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.


IKsPropertySet

The IKsPropertySet interface is part of the WDM KS (Win32® driver model kernel streaming) architecture. It allows driver to provide extended capabilities that can be used without extensions to an API. DirectSound supports this interface for accessing properties of sound drivers.

To retrieve this interface, call the QueryInterface method of any interface on a DirectSound buffer.

The IKsPropertySet interface has the following methods:

IKsPropertySet | Get
 | QuerySupport
 | Set

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.


IKsPropertySet::Get

The IKsPropertySet::Get method retrieves data for an item in a property set.

HRESULT Get(
  REFGUID rguidPropSet,
  ULONG ulId,
  LPVOID pInstanceData,
  ULONG ulInstanceLength,
  LPVOID pPropertyData,
  ULONG ulDataLength,
  ULONG * pulBytesReturned
);

Parameters

rguidPropSet
Reference to (C++) or address of (C) a GUID representing the property set to be accessed.
ulId
Item within the property set to be accessed. Items are indexed from 0 and are always the same for a given property set GUID.
pInstanceData
Instance data for the get call.
ulInstanceLength
Number of bytes pointed to by pInstanceData.
pPropertyData
Data to set for this item.
ulDataLength
Number of bytes pointed to by pPropertyData
pulBytesReturned
Address of a variable to receive the number of bytes written into pPropertyData.

Return Values

Return values are determined by the designer of the property set.

If the method succeeds, the return value may be S_OK.

If it fails, the method may return E_POINTER.

Remarks

The format of the data in both pInstanceData and pPropertyData is item-specific.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.


IKsPropertySet::QuerySupport

The IKsPropertySet::QuerySupport method determines whether a property in a property set is supported on the port or device.

HRESULT QuerySupport(
  REFGUID rguidPropSet,
  ULONG ulId,
  ULONG* pulTypeSupport
);

Parameters

rguidPropSet
Reference to (C++) or address of (C) a GUID representing the property set to be queried.
ulId
Item within the property set to be accessed. Items are indexed from 0 and are always the same for a given property set.
pulTypeSupport
Address of a variable to receive information about support for the property. If the property or property set does not exist, this is set to 0. Otherwise it may contain one or both of the following flags:
KSPROPERTY_SUPPORT_GET
The property item may be retrieved.
KSPROPERTY_SUPPORT_SET
The property item may be set.

Return Values

Return values are determined by the designer of the property set.

If the method succeeds, the return value may be S_OK. (See Remarks.)

If it fails, the method may return one of the following error values:

E_NOTIMPL (See Remarks.)
E_POINTER

Remarks

Whether it is valid to support some properties within the set but not others depends on the definition of the property set. Consult the hardware manufacturer's specification for the property set of interest.

Some implementations may return S_OK when the property is not supported, and others may return E_NOTIMPL. To be sure that a property is supported you should check both the return value of the method and the value returned in pulTypeSupport.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.


IKsPropertySet::Set

The IKsPropertySet::Set method sets the value of a property in a property set.

HRESULT Set(
  REFGUID rguidPropSet,
  ULONG ulId,
  LPVOID pInstanceData,
  ULONG ulInstanceLength,
  LPVOID pPropertyData,
  ULONG ulDataLength
);

Parameters

rguidPropSet
Reference to (C++) or address of (C) a GUID representing the property set to be accessed.
ulId
Item within the property set to be accessed. Items are indexed from 0 and are always the same for a given property set.
pInstanceData
Instance data for the set call. If there are multiple objects within the port that this operation could act on, the instance data specifies which object should be used. No standard property set items at the DirectMusic® API level use instance data; however, vendor-defined extensions are free to use it.
ulInstanceLength
Number of bytes pointed to by pInstanceData.
pPropertyData
Property data to set for this item.
ulDataLength
Number of bytes pointed to by pPropertyData.

Return Values

Return values are determined by the designer of the property set.

If the method succeeds, the return value may be S_OK.

If it fails, the method may return E_POINTER.

Remarks

The format of the data in both pInstanceData and pPropertyData is item-specific.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.


Functions

This section contains reference information for the following DirectSound and DirectSoundCapture global functions:

  • DirectSoundCaptureCreate
  • DirectSoundCaptureEnumerate
  • DirectSoundCreate
  • DirectSoundEnumerate


DirectSoundCaptureCreate

The DirectSoundCaptureCreate function creates and initializes an object that supports the IDirectSoundCapture interface.

HRESULT WINAPI DirectSoundCaptureCreate(
  LPCGUID lpcGUID,
  LPDIRECTSOUNDCAPTURE *lplpDSC,
  LPUNKNOWN pUnkOuter
);

Parameters

lpcGUID
Address of the GUID that identifies the sound capture device. The value of this parameter must be one of the GUIDs returned by DirectSoundCaptureEnumerate, or NULL for the default device.
lplpDSC
Address of a pointer to a DirectSoundCapture object created in response to this function.
pUnkOuter
Controlling unknown of the aggregate. Its value must be NULL.

Return Values

If the function succeeds, the return value is DS_OK.

If the function fails, the return value may be one of the following error values:

DSERR_ALLOCATED
DSERR_INVALIDPARAM
DSERR_NOAGGREGATION
DSERR_OUTOFMEMORY

Remarks

On sound card that do not support full duplex, this method will fail and return DSERR_ALLOCATED.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.


DirectSoundCaptureEnumerate

The DirectSoundCaptureEnumerate function enumerates the DirectSoundCapture objects installed in the system.

HRESULT WINAPI DirectSoundCaptureEnumerate(
  LPDSENUMCALLBACK lpDSEnumCallback,
  LPVOID lpContext
);

Parameters

lpDSEnumCallback
Address of the DSEnumCallback function that will be called for each DirectSoundCapture object installed in the system.
lpContext
Address of the user-defined context passed to the enumeration callback function every time that function is called.

Return Values

If the function succeeds, the return value is DS_OK.

If the function fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.


DirectSoundCreate

The DirectSoundCreate function creates and initializes an IDirectSound interface.

HRESULT WINAPI DirectSoundCreate(
  LPCGUID lpcGuid,
  LPDIRECTSOUND * ppDS,
  LPUNKNOWN  pUnkOuter
);

Parameters

lpcGuid
Address of the GUID that identifies the sound device. The value of this parameter must be one of the GUIDs returned by DirectSoundEnumerate, or NULL for the default device.
ppDS
Address of a pointer to a DirectSound object created in response to this function.
pUnkOuter
Controlling unknown of the aggregate. Its value must be NULL.

Return Values

If the function succeeds, the return value is DS_OK.

If the function fails, the return value may be one of the following error values:

DSERR_ALLOCATED
DSERR_INVALIDPARAM
DSERR_NOAGGREGATION
DSERR_NODRIVER
DSERR_OUTOFMEMORY

Remarks

The application must call the IDirectSound::SetCooperativeLevel method immediately after creating a DirectSound object.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSound::GetCaps, IDirectSound::SetCooperativeLevel


DirectSoundEnumerate

The DirectSoundEnumerate function enumerates the DirectSound drivers installed in the system.

HRESULT WINAPI DirectSoundEnumerate(
  LPDSENUMCALLBACK lpDSEnumCallback,
  LPVOID lpContext
);

Parameters

lpDSEnumCallback
Address of the DSEnumCallback function that will be called for each DirectSound object installed in the system.
lpContext
Address of the user-defined context passed to the enumeration callback function every time that function is called.

Return Values

If the function succeeds, the return value is DS_OK.

If the function fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

DSEnumCallback


Callback Function

This section contains reference information for the following DirectSound callback function.

  • DSEnumCallback


DSEnumCallback

DSEnumCallback is an application-defined callback function that enumerates the DirectSound drivers. The system calls this function in response to the application's previous call to the DirectSoundEnumerate or DirectSoundCaptureEnumerate function.

BOOL CALLBACK DSEnumCallback(
  LPGUID lpGuid,
  LPCSTR lpcstrDescription,
  LPCSTR lpcstrModule,
  LPVOID lpContext
);

Parameters

lpGuid
Address of the GUID that identifies the DirectSound driver being enumerated. This value can be passed to the DirectSoundCreate function to create a DirectSound object for that driver.
lpcstrDescription
Address of a null-terminated string that provides a textual description of the DirectSound device.
lpcstrModule
Address of a null-terminated string that specifies the module name of the DirectSound driver corresponding to this device.
lpContext
Address of application-defined data that is passed to each callback function.

Return Values

Returns TRUE to continue enumerating drivers, or FALSE to stop.

Remarks

The application can save the strings passed in the lpcstrDescription and lpcstrModule parameters by copying them to memory allocated from the heap. The memory used to pass the strings to this callback function is valid only while this callback function is running.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.
Import Library: User-defined.

See Also

DirectSoundEnumerate


Structures

This section contains reference information for the following structures used with DirectSound:

  • DS3DBUFFER
  • DS3DLISTENER
  • DSBCAPS
  • DSBPOSITIONNOTIFY
  • DSBUFFERDESC
  • DSBUFFERDESC1
  • DSCAPS
  • DSCBCAPS
  • DSCBUFFERDESC
  • DSCCAPS

Note The memory for all DirectX structures must be initialized to zero before use. In addition, all structures that contain a dwSize member must set the member to the size of the structure, in bytes, before use. The following example performs these tasks on a common structure, DSCAPS:

DSCAPS dscaps; // Can't use this yet.

ZeroMemory(&dscaps, sizeof(dscaps));
dscaps.dwSize = sizeof(dscaps);

// Now the structure can be used.
.
.


DS3DBUFFER

The DS3DBUFFER structure contains all information necessary to uniquely describe the location, orientation, and motion of a 3-D sound buffer. This structure is used with the IDirectSound3DBuffer::GetAllParameters and IDirectSound3DBuffer::SetAllParameters methods.

typedef struct {
    DWORD      dwSize;
    D3DVECTOR  vPosition;
    D3DVECTOR  vVelocity;
    DWORD      dwInsideConeAngle;
    DWORD      dwOutsideConeAngle;
    D3DVECTOR  vConeOrientation;
    LONG       lConeOutsideVolume;
    D3DVALUE   flMinDistance;
    D3DVALUE   flMaxDistance;
    DWORD      dwMode;
} DS3DBUFFER, *LPDS3DBUFFER;

typedef const DS3DBUFFER *LPCDS3DBUFFER;

Members

dwSize
Size of the structure, in bytes. This member must be initialized before the structure is used.
vPosition
A D3DVECTOR structure that describes the current position of the 3-D sound buffer.
vVelocity
A D3DVECTOR structure that describes the current velocity of the 3-D sound buffer.
dwInsideConeAngle
The angle of the inside sound projection cone.
dwOutsideConeAngle
The angle of the outside sound projection cone.
vConeOrientation
A D3DVECTOR structure that describes the current orientation of this 3-D buffer's sound projection cone.
lConeOutsideVolume
The cone outside volume.
flMinDistance
The minimum distance.
flMaxDistance
The maximum distance.
dwMode
The 3-D sound processing mode to be set.
DS3DMODE_DISABLE
3-D sound processing is disabled. The sound will appear to originate from the center of the listener's head.
DS3DMODE_HEADRELATIVE
Sound parameters (position, velocity, and orientation) are relative to the listener's parameters. In this mode, the absolute parameters of the sound are updated automatically as the listener's parameters change, so that the relative parameters remain constant.
DS3DMODE_NORMAL
Normal processing. This is the default mode.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.


DS3DLISTENER

The DS3DLISTENER structure contains all information necessary to uniquely describe the 3-D world parameters and position of the listener. This structure is used with the IDirectSound3DListener::GetAllParameters and IDirectSound3DListener::SetAllParameters methods.

typedef struct {
    DWORD      dwSize;
    D3DVECTOR  vPosition;
    D3DVECTOR  vVelocity;
    D3DVECTOR  vOrientFront;
    D3DVECTOR  vOrientTop;
    D3DVALUE   flDistanceFactor;
    D3DVALUE   flRolloffFactor;
    D3DVALUE   flDopplerFactor;
} DS3DLISTENER, *LPDS3DLISTENER;

typedef const DS3DLISTENER *LPCDS3DLISTENER;

Members

dwSize
Size of the structure, in bytes. This member must be initialized before the structure is used.
vPosition, vVelocity, vOrientFront, and vOrientTop
D3DVECTOR structures that describe the listener's position, velocity, front orientation, and top orientation, respectively.
flDistanceFactor, flRolloffFactor, and flDopplerFactor
The current distance, rolloff, and Doppler factors, respectively.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.


DSBCAPS

The DSBCAPS structure specifies the capabilities of a DirectSound buffer object, for use by the IDirectSoundBuffer::GetCaps method.

typedef struct {
    DWORD  dwSize;
    DWORD  dwFlags;
    DWORD  dwBufferBytes;
    DWORD  dwUnlockTransferRate;
    DWORD  dwPlayCpuOverhead;
} DSBCAPS, *LPDSBCAPS;

typedef const DSBCAPS *LPCDSBCAPS;

Members

dwSize
Size of the structure, in bytes. This member must be initialized before the structure is used.
dwFlags
Flags that specify buffer-object capabilities.
DSBCAPS_CTRL3D
The buffer is either a primary buffer or a secondary buffer that uses 3-D control. To create a primary buffer, the dwFlags member of the DSBUFFERDESC structure should include the DSBCAPS_PRIMARYBUFFER flag.
DSBCAPS_CTRLFREQUENCY
The buffer must have frequency control capability.
DSBCAPS_CTRLPAN
The buffer must have pan control capability.
DSBCAPS_CTRLVOLUME
The buffer must have volume control capability.
DSBCAPS_CTRLPOSITIONNOTIFY
The buffer must have position notification capability. On VxD drivers, if a sound buffer is created with DSBCAPS_CTRLPOSITIONNOTIFY, this buffer will always be a software buffer. This is because the VxD driver model doesn't support the notify interface. With WDM drivers, a position notification enabled buffer may be in hardware, if hardware is available. Calling IDirectSoundBuffer::Play with the DSBPLAY_LOCHARDWARE flag will fail when playing a buffer created with this flag set.
DSBCAPS_GETCURRENTPOSITION2
Indicates that IDirectSoundBuffer::GetCurrentPosition should use the new behavior of the play cursor. In DirectSound in DirectX 1, the play cursor was significantly ahead of the actual playing sound on emulated sound cards; it was directly behind the write cursor. Now, if the DSBCAPS_GETCURRENTPOSITION2 flag is specified, the application can get a more accurate play position. If this flag is not specified, the old behavior is preserved for compatibility. Note that this flag affects only emulated sound cards; if a DirectSound driver is present, the play cursor is accurate for DirectSound in all versions of DirectX.
DSBCAPS_GLOBALFOCUS
The buffer is a global sound buffer. With this flag set, an application using DirectSound can continue to play its buffers if the user switches focus to another application, even if the new application uses DirectSound. The one exception is if you switch focus to a DirectSound application that uses the DSSCL_EXCLUSIVE or DSSCL_WRITEPRIMARY flag for its cooperative level. In this case, the global sounds from other applications will not be audible.
DSBCAPS_LOCDEFER
The buffer can be assigned to a hardware or software resource at play time.
DSBCAPS_LOCHARDWARE
The buffer is in hardware memory and uses hardware mixing.
DSBCAPS_LOCSOFTWARE
The buffer is in software memory and uses software mixing.
DSBCAPS_MUTE3DATMAXDISTANCE
The sound is reduced to silence at the maximum distance. The buffer will stop playing when the maximum distance is exceeded, so that processor time is not wasted.
DSBCAPS_PRIMARYBUFFER
Indicates that the buffer is a primary sound buffer. If this value is not specified, a secondary sound buffer will be created.
DSBCAPS_STATIC
Indicates that the buffer will be used for static sound data. Typically, these buffers are loaded once and played many times. These buffers are candidates for hardware memory.
DSBCAPS_STICKYFOCUS
Changes the focus behavior of the sound buffer. This flag can be specified in an IDirectSound::CreateSoundBuffer call. With this flag set, an application using DirectSound can continue to play its sticky focus buffers if the user switches to another application not using DirectSound. In this situation, the application's normal buffers are muted, but the sticky focus buffers are still audible. This is useful for nongame applications, such as movie playback (DirectShow®), when the user wants to hear the soundtrack while typing in Microsoft® Excel or Microsoft Word, for example. However, if the user switches to another DirectSound application, all sound buffers, both normal and sticky focus, in the previous application are muted.
dwBufferBytes
Size of this buffer, in bytes.
dwUnlockTransferRate
Specifies the rate, in kilobytes per second, at which data is transferred to the buffer memory when IDirectSoundBuffer::Unlock is called. High-performance applications can use this value to determine the time required for IDirectSoundBuffer::Unlock to execute. For software buffers located in system memory, the rate will be very high because no processing is required. For hardware buffers, the rate might be slower because the buffer might have to be downloaded to the sound card, which might have a limited transfer rate.
dwPlayCpuOverhead
Specifies the processing overhead as a percentage of main processing cycles needed to mix this sound buffer. For hardware buffers, this member will be 0 because the mixing is performed by the sound device. For software buffers, this member depends on the buffer format and the speed of the system processor.

Remarks

The DSBCAPS structure contains information similar to that found in the DSBUFFERDESC structure passed to the IDirectSound::CreateSoundBuffer method, with some additional information. Additional information includes the location of the buffer (hardware or software) and some cost measures (such as the time to download the buffer if located in hardware, and the processing overhead to play the buffer if it is mixed in software).

Note The dwFlags member of the DSBCAPS structure contains the same flags used by the DSBUFFERDESC structure. The only difference is that in the DSBCAPS structure, either the DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE flag will be specified, according to the location of the buffer memory. In the DSBUFFERDESC structure, these flags are optional and are used to force the buffer to be located in either hardware or software.

Sound buffers created with the DSBCAPS_CTRLPOSITIONNOTIFY flag must set a notification event. If you create a sound buffer with the NOTIFY flag, but don't actually set any notifications, the behavior is undefined. You may experience sounds being played back twice. Therefore, applications should not use DSBCAPS_CTRLPOSITIONNOTIFY unless they actually set a notification event.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.

See Also

IDirectSound::CreateSoundBuffer, IDirectSoundBuffer::GetCaps


DSBPOSITIONNOTIFY

The DSBPOSITIONNOTIFY structure is used by the IDirectSoundNotify::SetNotificationPositions method.

typedef struct {
    DWORD   dwOffset;
    HANDLE  hEventNotify;
} DSBPOSITIONNOTIFY, *LPDSBPOSITIONNOTIFY;

typedef const DSBPOSITIONNOTIFY *LPCDSBPOSITIONNOTIFY;

Members

dwOffset
Offset from the beginning of the buffer where the notify event is to be triggered, or DSBPN_OFFSETSTOP.
hEventNotify
Handle to the event to be signaled when the offset has been reached.

Remarks

The DSBPN_OFFSETSTOP value in the dwOffset member causes the event to be signaled when playback or capture stops, either because the end of the buffer has been reached (and playback or capture is not looping) or because the application called the IDirectSoundBuffer::Stop or IDirectSoundCaptureBuffer::Stop method.

Note When using LOC_DEFER and NOTIFY along with any voice management TERMINATEBY flag, it is possible that a sound that has notifications set, but not yet reached, may be terminated by the voice manager. In this event, the notification event will not occur.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.


DSBUFFERDESC

The DSBUFFERDESC structure describes the necessary characteristics of a new DirectSoundBuffer object. This structure is used by the IDirectSound::CreateSoundBuffer method.

typedef struct {
    DWORD           dwSize;
    DWORD           dwFlags;
    DWORD           dwBufferBytes;
    DWORD           dwReserved;
    LPWAVEFORMATEX  lpwfxFormat;
    GUID            guid3DAlgorithm;
} DSBUFFERDESC, *LPDSBUFFERDESC;

typedef const DSBUFFERDESC *LPCDSBUFFERDESC;

Members

dwSize
Size of the structure, in bytes. This member must be initialized before the structure is used.
dwFlags
Identifies the capabilities to include when creating a new DirectSoundBuffer object. Specify one or more of the following:
DSBCAPS_CTRL3D
The buffer is either a primary buffer or a secondary buffer that uses 3-D control.
DSBCAPS_CTRLFREQUENCY
The buffer must have frequency control capability.
DSBCAPS_CTRLPAN
The buffer must have pan control capability.
DSBCAPS_CTRLPOSITIONNOTIFY
The buffer must have position notification capability. On VxD drivers, if a sound buffer is created with DSBCAPS_CTRLPOSITIONNOTIFY, this buffer will always be a software buffer. This is because the VxD driver model doesn't support the notify interface. With WDM drivers, a position notification enabled buffer may be in hardware, if hardware is available.
DSBCAPS_CTRLVOLUME
The buffer must have volume control capability.
DSBCAPS_GETCURRENTPOSITION2
Indicates that IDirectSoundBuffer::GetCurrentPosition should use the new behavior of the play cursor. In DirectSound in DirectX 1, the play cursor was significantly ahead of the actual playing sound on emulated sound cards; it was directly behind the write cursor. Now, if the DSBCAPS_GETCURRENTPOSITION2 flag is specified, the application can get a more accurate play position. If this flag is not specified, the old behavior is preserved for compatibility. Note that this flag affects only emulated sound cards; if a DirectSound driver is present, the play cursor is accurate for DirectSound in all versions of DirectX.
DSBCAPS_GLOBALFOCUS
The buffer is a global sound buffer. With this flag set, an application using DirectSound can continue to play its buffers if the user switches focus to another application, even if the new application uses DirectSound. The one exception is if you switch focus to a DirectSound application that uses the DSSCL_EXCLUSIVE or DSSCL_WRITEPRIMARY flag for its cooperative level. In this case, the global sounds from other applications will not be audible.
DSBCAPS_LOCDEFER
The buffer can be assigned to a hardware or software resource during playing. This flag must be set for buffers that will use the new voice allocation and management features of DirectX 7.0.
DSBCAPS_LOCHARDWARE
Forces the buffer to use hardware mixing, even if DSBCAPS_STATIC is not specified. If the device does not support hardware mixing or if the required hardware memory is not available, the call to the IDirectSound::CreateSoundBuffer method will fail. The application must ensure that a mixing channel will be available for this buffer; this condition is not guaranteed.
DSBCAPS_LOCSOFTWARE
Forces the buffer to be stored in software memory and use software mixing, even if DSBCAPS_STATIC is specified and hardware resources are available.
DSBCAPS_MUTE3DATMAXDISTANCE
The sound is to be reduced to silence at the maximum distance. The buffer will stop playing when the maximum distance is exceeded, so that processor time is not wasted.
DSBCAPS_PRIMARYBUFFER
Indicates that the buffer is a primary sound buffer. If this value is not specified, a secondary sound buffer will be created.
DSBCAPS_STATIC
Indicates that the buffer will be used for static sound data. Typically, these buffers are loaded once and played many times. These buffers are candidates for hardware memory.
DSBCAPS_STICKYFOCUS
Changes the focus behavior of the sound buffer. This flag can be specified in an IDirectSound::CreateSoundBuffer call. With this flag set, an application using DirectSound can continue to play its sticky focus buffers if the user switches to another application not using DirectSound. In this situation, the application's normal buffers are muted, but the sticky focus buffers are still audible. This is useful for nongame applications, such as movie playback (DirectShow), when the user wants to hear the soundtrack while typing in Microsoft Word or Microsoft Excel, for example. However, if the user switches to another DirectSound application, all sound buffers, both normal and sticky focus, in the previous application are muted.
dwBufferBytes
Size of the new buffer, in bytes. This value must be 0 when creating primary buffers. For secondary buffers, the minimum and maximum sizes allowed are specified by DSBSIZE_MIN and DSBSIZE_MAX, defined in Dsound.h.
dwReserved
This value is reserved. Do not use.
lpwfxFormat
Address of a structure specifying the waveform format for the buffer. This value must be NULL for primary buffers. The application can use IDirectSoundBuffer::SetFormat to set the format of the primary buffer.
guid3DAlgorithm
The guid3DAlgorithm member sets the 2-speaker virtualization algorithm used by the DirectSoun3D HEL. If the DSCAPS_CTRL3D flag is not set for the sound buffer, the guid3DAlgorithm parameter is ignored. These apply only to two-speaker virtualization algorithms when the speakerConfig is set to either two-speaker or headphone output. If the speakerConfig setting is other than a two speaker or headphone setting, processing will behave as if a two speaker setting was selected. If a NULL guid (GUID_NULL) is supplied, the behavior is identical to DS3DALG_DEFAULT. Note:: If DSBCAPS_CTRL3D is not set, this parameter must be GUID_NULL.

The valid algorithms that can be specified are:

DS3DALG _DEFAULT
Applies to Software Mixing Only.

The HEL is set to be the default algorithm. Currently, this will select the DS3DALG_NO_VIRTUALIZATION algorithm, which provides a CPU- efficient, but basic 3-D effect. In the future, the algorithm used when DS3DALG_DEFAULT is set may be based on the user's preference by means of a control panel setting.

AVAILABLE ON: WDM or Vxd Drivers

DS3DALG _NO_VIRTUALIZATION
Applies to Software Mixing Only.

The Direct3D API is mapped onto normal left and right stereo panning. At 90 degrees to the left, the sound is coming out of only the left speaker; at 90 degrees to the right, sound is coming out of only the right speaker. The vertical axis is ignored except for scaling of volume due to distance. Doppler shift and volume scaling are still applied, but the 3-D filtering is not performed on this buffer. This is the most efficient software implementation, but provides no virtual 3-D audio effect. When the DS3DALG_NO_VIRTUALIZATION flag is specified, Head Related Transfer Function (HRTF) processing will not be done. Note: Since DS3DALG_NO_VIRTUALIZATION uses only normal stereo panning, a buffer created with this algorithm may be accelerated by a 2-D hardware voice if no free 3-D hardware voices are available.

AVAILABLE ON: WDM or Vxd Drivers

DS3DALG_HRTF_FULL
Applies to Software Mixing Only.

The 3-D API is processed with the high quality 3-D audio algorithm. This flag applies only to the software HEL. This algorithm gives the highest quality 3-D audio effect, but uses more CPU.

AVAILABLE ON: Microsoft® Windows® 98 Second Edition and Windows 2000 that use WDM drivers. .

Note: If a sound buffer is created using one of the HRTF algorithms, and the HRTF algorithm is not available on the system (for example a non-WDM system), a partial-success code, DS_NO_VIRTUALIZATION, is returned. The sound buffer created will use the DS3DALG_NO_VIRTUALIZATION instead.

For this reason, applications should use the "SUCCEDED()" or "FAILED()" macros, rather than check explicitly for DS_OK when calling CreateSoundBuffer.

DS3DALG_HRTF_LIGHT
Applies to Software Mixing Only.

The 3-D API is processed with the efficient 3-D audio algorithm. This flag applies only to the software HEL. This algorithm gives a good 3-D audio effect, but uses less CPU than DS3DALG_HRTF_FULL.

AVAILABLE ON: Windows 98 Second Edition and Windows 2000 that use WDM drivers.

Note: If a sound buffer is created using one of the HRTF algorithms, and the HRTF algorithm is not available on the system (for example a non-WDM system), a partial-success code, DS_NO_VIRTUALIZATION, is returned. The sound buffer created will use the DS3DALG_NO_VIRTUALIZATION instead.

For this reason, applications should use the "SUCCEDED()" or "FAILED()" macros, rather than check explicitly for DS_OK when calling CreateSoundBuffer.

Remarks

DSBCAPS_CTRLDEFAULT has been removed to encourage use of the individual flags that DSBCAPS_CTRLDEFAULT represents. DSBCAPS_CTRLDEFAULT was previously defined as DSBCAPS_CTRLPAN | DSBCAPS_CTRLVOLUME | DSBCAPS_CTRLFREQUENCY. By specifying only the flags you need, you cut down on unnecessary resource usage.

The DSBCAPS_LOCHARDWARE and DSBCAPS_LOCSOFTWARE flags used in the dwFlags member are optional and mutually exclusive. DSBCAPS_LOCHARDWARE forces the buffer to reside in memory located in the sound card. DSBCAPS_LOCSOFTWARE forces the buffer to reside in main system memory, if possible.

These flags are also defined for the dwFlags member of the DSBCAPS structure, and when used there, the specified flag indicates the actual location of the DirectSoundBuffer object.

When creating a primary buffer, applications must set the dwBufferBytes member to 0; DirectSound will determine the optimal buffer size for the particular sound device in use. To determine the size of a created primary buffer, call IDirectSoundBuffer::GetCaps.

The 3-D algorithms represent selection of the software emulation layer only; that is the software algorithm that is used when no hardware is present for acceleration. In order to maximize hardware utilization, DS3DALG_NO_VIRTUALIZATION is treated as a special case. If no free 3-D hardware voices are available, the buffer is then treated as a 2-D buffer, but with 3-D API control. Specifically, when a sound buffer is created with DS3DALG_NO_VIRTUALIZATION (or the buffer is played if the buffer is created with DSBPLAY_LOCDEFER) the following procedure is followed:

If a free hardware 3-D voice is available, that 3-D hardware voice is used.

If no free hardware 3-D voices are available and a 2-D hardware voice is available, that 2-D hardware voice will be used. This is possible since the NO_VIRTUALIZATION algorithm is a simple stereo pan algorithm

If no free 2-D or 3-D hardware voices are available, the voice will be played in software using the NO_VIRTUALIZATION algorithm.

Note Sound buffers created with the DSBCAPS_CTRLPOSITIONNOTIFY flag must set a notification event. If you create a sound buffer with the NOTIFY flag, but don't actually set any notifications, the behavior is undefined. You may experience sounds being played back twice. Therefore, applications should not use DSBCAPS_CTRLPOSITIONNOTIFY unless they actually set a notification event.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.

See Also

IDirectSound::CreateSoundBuffer


DSBUFFERDESC1

The DSBUFFERDESC1 structure describes the necessary characteristics of a new DirectSoundBuffer object. This structure is used by the IDirectSound::CreateSoundBuffer method when creating DirectSound applications earlier than DirectX 7.0.

typedef struct {
    DWORD           dwSize;
    DWORD           dwFlags;
    DWORD           dwBufferBytes;
    DWORD           dwReserved;
    LPWAVEFORMATEX  lpwfxFormat;
} DSBUFFERDESC, *LPDSBUFFERDESC;

typedef const DSBUFFERDESC *LPCDSBUFFERDESC;

Members

dwSize
Size of the structure, in bytes. This member must be initialized before the structure is used.
dwFlags
Identifies the capabilities to include when creating a new DirectSoundBuffer object. Specify one or more of the following:
DSBCAPS_CTRL3D
The buffer is either a primary buffer or a secondary buffer that uses 3-D control.
DSBCAPS_CTRLFREQUENCY
The buffer must have frequency control capability.
DSBCAPS_CTRLPAN
The buffer must have pan control capability.
DSBCAPS_CTRLPOSITIONNOTIFY
The buffer must have position notification capability. On VxD drivers, if a sound buffer is created with DSBCAPS_CTRLPOSITIONNOTIFY, this buffer will always be a software buffer. This is because the VxD driver model doesn't support the notify interface. With WDM drivers, a position notification enabled buffer may be in hardware, if hardware is available. Calling IDirectSoundBuffer::Play with the DSBPLAY_LOCHARDWARE flag will fail when playing a buffer created with this flag set.
DSBCAPS_CTRLVOLUME
The buffer must have volume control capability.
DSBCAPS_GETCURRENTPOSITION2
Indicates that IDirectSoundBuffer::GetCurrentPosition should use the new behavior of the play cursor. In DirectSound in DirectX 1, the play cursor was significantly ahead of the actual playing sound on emulated sound cards; it was directly behind the write cursor. Now, if the DSBCAPS_GETCURRENTPOSITION2 flag is specified, the application can get a more accurate play position. If this flag is not specified, the old behavior is preserved for compatibility. Note that this flag affects only emulated sound cards; if a DirectSound driver is present, the play cursor is accurate for DirectSound in all versions of DirectX.
DSBCAPS_GLOBALFOCUS
The buffer is a global sound buffer. With this flag set, an application using DirectSound can continue to play its buffers if the user switches focus to another application, even if the new application uses DirectSound. The one exception is if you switch focus to a DirectSound application that uses the DSSCL_EXCLUSIVE or DSSCL_WRITEPRIMARY flag for its cooperative level. In this case, the global sounds from other applications will not be audible.
DSBCAPS_LOCHARDWARE
Forces the buffer to use hardware mixing, even if DSBCAPS_STATIC is not specified. If the device does not support hardware mixing or if the required hardware memory is not available, the call to the IDirectSound::CreateSoundBuffer method will fail. The application must ensure that a mixing channel will be available for this buffer; this condition is not guaranteed.
DSBCAPS_LOCSOFTWARE
Forces the buffer to be stored in software memory and use software mixing, even if DSBCAPS_STATIC is specified and hardware resources are available.
DSBCAPS_MUTE3DATMAXDISTANCE
The sound is to be reduced to silence at the maximum distance. The buffer will stop playing when the maximum distance is exceeded, so that processor time is not wasted.
DSBCAPS_PRIMARYBUFFER
Indicates that the buffer is a primary sound buffer. If this value is not specified, a secondary sound buffer will be created.
DSBCAPS_STATIC
Indicates that the buffer will be used for static sound data. Typically, these buffers are loaded once and played many times. These buffers are candidates for hardware memory.
DSBCAPS_STICKYFOCUS
Changes the focus behavior of the sound buffer. This flag can be specified in an IDirectSound::CreateSoundBuffer call. With this flag set, an application using DirectSound can continue to play its sticky focus buffers if the user switches to another application not using DirectSound. In this situation, the application's normal buffers are muted, but the sticky focus buffers are still audible. This is useful for nongame applications, such as movie playback (DirectShow), when the user wants to hear the soundtrack while typing in Microsoft Word or Microsoft Excel, for example. However, if the user switches to another DirectSound application, all sound buffers, both normal and sticky focus, in the previous application are muted.
dwBufferBytes
Size of the new buffer, in bytes. This value must be 0 when creating primary buffers. For secondary buffers, the minimum and maximum sizes allowed are specified by DSBSIZE_MIN and DSBSIZE_MAX, defined in Dsound.h.
dwReserved
This value is reserved. Do not use.
lpwfxFormat
Address of a structure specifying the waveform format for the buffer. This value must be NULL for primary buffers. The application can use IDirectSoundBuffer::SetFormat to set the format of the primary buffer.

Remarks

This structure should only be used for DirectX 6.1 or earlier. You should use the DSBUFFERDESC structure for DirectX 7.0 compatible applications.

The DSBCAPS_LOCHARDWARE and DSBCAPS_LOCSOFTWARE flags used in the dwFlags member are optional and mutually exclusive. DSBCAPS_LOCHARDWARE forces the buffer to reside in memory located in the sound card. DSBCAPS_LOCSOFTWARE forces the buffer to reside in main system memory, if possible.

These flags are also defined for the dwFlags member of the DSBCAPS structure, and when used there, the specified flag indicates the actual location of the DirectSoundBuffer object.

When creating a primary buffer, applications must set the dwBufferBytes member to 0; DirectSound will determine the optimal buffer size for the particular sound device in use. To determine the size of a created primary buffer, call IDirectSoundBuffer::GetCaps.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.

See Also

IDirectSound::CreateSoundBuffer


DSCAPS

The DSCAPS structure specifies the capabilities of a DirectSound device for use by the IDirectSound::GetCaps method.

typedef {
    DWORD  dwSize;
    DWORD  dwFlags;
    DWORD  dwMinSecondarySampleRate;
    DWORD  dwMaxSecondarySampleRate;
    DWORD  dwPrimaryBuffers;
    DWORD  dwMaxHwMixingAllBuffers;
    DWORD  dwMaxHwMixingStaticBuffers;
    DWORD  dwMaxHwMixingStreamingBuffers;
    DWORD  dwFreeHwMixingAllBuffers;
    DWORD  dwFreeHwMixingStaticBuffers;
    DWORD  dwFreeHwMixingStreamingBuffers;
    DWORD  dwMaxHw3DAllBuffers;
    DWORD  dwMaxHw3DStaticBuffers;
    DWORD  dwMaxHw3DStreamingBuffers;
    DWORD  dwFreeHw3DAllBuffers;
    DWORD  dwFreeHw3DStaticBuffers;
    DWORD  dwFreeHw3DStreamingBuffers;
    DWORD  dwTotalHwMemBytes;
    DWORD  dwFreeHwMemBytes;
    DWORD  dwMaxContigFreeHwMemBytes;
    DWORD  dwUnlockTransferRateHwBuffers;
    DWORD  dwPlayCpuOverheadSwBuffers;
    DWORD  dwReserved1;
    DWORD  dwReserved2;
} DSCAPS, *LPDSCAPS;

typedef const DSCAPS *LPCDSCAPS;

Members

dwSize
Size of the structure, in bytes. This member must be initialized before the structure is used.
dwFlags
Specifies device capabilities. Can be one or more of the following:
DSCAPS_CERTIFIED
This driver has been tested and certified by Microsoft.
DSCAPS_CONTINUOUSRATE
The device supports all sample rates between the dwMinSecondarySampleRate and dwMaxSecondarySampleRate member values. Typically, this means that the actual output rate will be within +/- 10 hertz (Hz) of the requested frequency.
DSCAPS_EMULDRIVER
The device does not have a DirectSound driver installed, so it is being emulated through the waveform-audio functions. Performance degradation should be expected.
DSCAPS_PRIMARY16BIT
The device supports primary sound buffers with 16-bit samples.
DSCAPS_PRIMARY8BIT
The device supports primary buffers with 8-bit samples.
DSCAPS_PRIMARYMONO
The device supports monophonic primary buffers.
DSCAPS_PRIMARYSTEREO
The device supports stereo primary buffers.
DSCAPS_SECONDARY16BIT
The device supports hardware-mixed secondary sound buffers with 16-bit samples.
DSCAPS_SECONDARY8BIT
The device supports hardware-mixed secondary buffers with 8-bit samples.
DSCAPS_SECONDARYMONO
The device supports hardware-mixed monophonic secondary buffers.
DSCAPS_SECONDARYSTEREO
The device supports hardware-mixed stereo secondary buffers.
dwMinSecondarySampleRate and dwMaxSecondarySampleRate
Minimum and maximum sample rate specifications that are supported by this device's hardware secondary sound buffers.
dwPrimaryBuffers
Number of primary buffers supported. This value will always be 1.
dwMaxHwMixingAllBuffers
Specifies the total number of buffers that can be mixed in hardware. This member can be less than the sum of dwMaxHwMixingStaticBuffers and dwMaxHwMixingStreamingBuffers. Resource tradeoffs frequently occur.
dwMaxHwMixingStaticBuffers
Specifies the maximum number of static sound buffers. See
dwMaxHwMixingStreamingBuffers
Specifies the maximum number of streaming sound buffers.
dwFreeHwMixingAllBuffers, dwFreeHwMixingStaticBuffers, and dwFreeHwMixingStreamingBuffers
Description of the free, or unallocated, hardware mixing capabilities of the device. An application can use these values to determine whether hardware resources are available for allocation to a secondary sound buffer. Also, by comparing these values to the members that specify maximum mixing capabilities, the resources that are already allocated can be determined. See Remarks.
dwMaxHw3DAllBuffers, dwMaxHw3DStaticBuffers, and dwMaxHw3DStreamingBuffers
Description of the hardware 3-D positional capabilities of the device.
dwFreeHw3DAllBuffers, dwFreeHw3DStaticBuffers, and dwFreeHw3DStreamingBuffers
Description of the free, or unallocated, hardware 3-D positional capabilities of the device. See Remarks.
dwTotalHwMemBytes
Size, in bytes, of the amount of memory on the sound card that stores static sound buffers.
dwFreeHwMemBytes
Size, in bytes, of the free memory on the sound card.
dwMaxContigFreeHwMemBytes
Size, in bytes, of the largest contiguous block of free memory on the sound card.
dwUnlockTransferRateHwBuffers
Description of the rate, in kilobytes per second, at which data can be transferred to hardware static sound buffers. This and the number of bytes transferred determines the duration of a call to the IDirectSoundBuffer::Unlock method.
dwPlayCpuOverheadSwBuffers
Description of the processing overhead, as a percentage of the central processing unit, needed to mix software buffers (those located in main system memory). This varies according to the bus type, the processor type, and the clock speed.

The unlock transfer rate for software buffers is 0 because the data need not be transferred anywhere. Similarly, the play processing overhead for hardware buffers is 0 because the mixing is done by the sound device.

dwReserved1 and dwReserved2
Reserved for future use.

Remarks

Some audio cards may be unable to report accurately the number of available or free hardware buffers. This can happen, for example, when the card can play more sounds at lower sampling rates than at higher rates. In general, a nonzero value in any of the members relating to number of free hardware buffers signifies that at least one hardware resource of the appropriate type is available.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.

See Also

IDirectSound::GetCaps


DSCBCAPS

The DSCBCAPS structure is used by the IDirectSoundCaptureBuffer::GetCaps method.

typedef struct {
    DWORD  dwSize;
    DWORD  dwFlags;
    DWORD  dwBufferBytes;
    DWORD  dwReserved;
} DSCBCAPS, *LPDSCBCAPS;

typedef const DSCBCAPS *LPCDSCBCAPS;

Members

dwSize
Size of the structure, in bytes. This member must be initialized before the structure is used.
dwFlags
Specifies device capabilities. Can be zero or the following flag:
DSCBCAPS_WAVEMAPPED
The Win32 wave mapper will be used for formats not supported by the device.
dwBufferBytes
The size, in bytes, of the capture buffer.
dwReserved
Reserved for future use.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.


DSCBUFFERDESC

The DSCBUFFERDESC structure is used by the IDirectSoundCapture::CreateCaptureBuffer method.

typedef struct {
    DWORD           dwSize;
    DWORD           dwFlags;
    DWORD           dwBufferBytes;
    DWORD           dwReserved;
    LPWAVEFORMATEX  lpwfxFormat;
} DSCBUFFERDESC, *LPDSCBUFFERDESC;

typedef const DSCBUFFERDESC *LPCDSCBUFFERDESC;

Members

dwSize
Size of the structure, in bytes. This member must be initialized before the structure is used.
dwFlags
Specifies device capabilities. Can be zero or the following flag:
DSCBCAPS_WAVEMAPPED
The Win32 wave mapper will be used for formats not supported by the device.
dwBufferBytes
Size of capture buffer to create, in bytes.
dwReserved
Reserved for future use.
lpwfxFormat
Pointer to a WAVEFORMATEX structure containing the format in which to capture the data.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.


DSCCAPS

The DSCCAPS structure is used by the IDirectSoundCapture::GetCaps method.

typedef struct {
    DWORD  dwSize;
    DWORD  dwFlags;
    DWORD  dwFormats;
    DWORD  dwChannels;
} DSCCAPS, *LPDSCCAPS;

typedef const DSCCAPS *LPCDSCCAPS;

Members

dwSize
Size of the structure, in bytes. This member must be initialized before the structure is used.
dwFlags
Specifies device capabilities. Can be 0 or the following flags:
DSCCAPS_EMULDRIVER
There is no DirectSoundCapture driver for the device, so the standard wave audio functions are being used.
DSCCAPS_CERTIFIED
The driver for the device is a certified WDM driver.
dwFormats
Standard formats that are supported. These are equivalent to the values in the WAVEINCAPS structure used in the Win32 waveform audio functions, and are reproduced here for convenience.
Value | Meaning
WAVE_FORMAT_1M08 | 11.025 kHz, mono, 8-bit
WAVE_FORMAT_1M16 | 11.025 kHz, mono, 16-bit
WAVE_FORMAT_1S08 | 11.025 kHz, stereo, 8-bit
WAVE_FORMAT_1S16 | 11.025 kHz, stereo, 16-bit
WAVE_FORMAT_2M08 | 22.05 kHz, mono, 8-bit
WAVE_FORMAT_2M16 | 22.05 kHz, mono, 16-bit
WAVE_FORMAT_2S08 | 22.05 kHz, stereo, 8-bit
WAVE_FORMAT_2S16 | 22.05 kHz, stereo, 16-bit
WAVE_FORMAT_4M08 | 44.1 kHz, mono, 8-bit
WAVE_FORMAT_4M16 | 44.1 kHz, mono, 16-bit
WAVE_FORMAT_4S08 | 44.1 kHz, stereo, 8-bit
WAVE_FORMAT_4S16 | 44.1 kHz, stereo, 16-bit

dwChannels
Number specifying the number of channels supported by the device, where 1 is mono, 2 is stereo, and so on.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in dsound.h.


Return Values

Errors are represented by negative values and cannot be combined. This table lists the values that can be returned by all IDirectSound and IDirectSoundBuffer methods. For a list of the error codes each method can return, see the individual method descriptions.

DS_OK
The request completed successfully.
DSERR_ACCESSDENIED
The request failed because access was denied.
DSERR_ALLOCATED
The request failed because resources, such as a priority level, were already in use by another caller.
DSERR_ALREADYINITIALIZED
The object is already initialized.
DSERR_BADFORMAT
The specified wave format is not supported.
DSERR_BUFFERLOST
The buffer memory has been lost and must be restored.
DSERR_CONTROLUNAVAIL
The buffer control (volume, pan, and so on) requested by the caller is not available.
DSERR_GENERIC
An undetermined error occurred inside the DirectSound subsystem.
DSERR_HWUNAVAIL
The DirectSound hardware device is unavailable.
DSERR_INVALIDCALL
This function is not valid for the current state of this object.
DSERR_INVALIDPARAM
An invalid parameter was passed to the returning function.
DSERR_NOAGGREGATION
The object does not support aggregation.
DSERR_NODRIVER
No sound driver is available for use.
DSERR_NOINTERFACE
The requested COM interface is not available.
DSERR_OTHERAPPHASPRIO
Another application has a higher priority level, preventing this call from succeeding
DSERR_OUTOFMEMORY
The DirectSound subsystem could not allocate sufficient memory to complete the caller's request.
DSERR_PRIOLEVELNEEDED
The caller does not have the priority level required for the function to succeed.
DSERR_UNINITIALIZED
The IDirectSound::Initialize method has not been called or has not been called successfully before other methods were called.
DSERR_UNSUPPORTED
The function called is not supported at this time.


DirectSound Visual Basic Reference

This section contains reference information for the API elements that DirectSound provides. Reference material is divided into the following categories.

  • Classes
  • Types
  • Enumerations
  • Error Codes


Classes

This section contains references for methods of the following DirectSound classes:

  • DirectSound
  • DirectSound3DBuffer
  • DirectSound3DListener
  • DirectSoundBuffer
  • DirectSoundCapture
  • DirectSoundCaptureBuffer
  • DirectSoundEnum
  • DirectX7


DirectSound

Applications use the methods of the DirectSound class to create DirectSound objects and set up the environment. This section is a reference to the methods of this class.

The object is obtained by using the DirectX7.DirectSoundCreate function.

The methods of the DirectSound class can be organized into the following groups:

Initialization | SetCooperativeLevel
Buffer creation | CreateSoundBuffer
 | CreateSoundBufferFromFile
 | CreateSoundBufferFromResource
 | DuplicateSoundBuffer
Device capabilities | GetCaps
Speaker configuration | GetSpeakerConfig
 | SetSpeakerConfig


DirectSound.CreateSoundBuffer

The DirectSound.CreateSoundBuffer method creates a DirectSoundBuffer object to hold a sequence of audio samples.

object.CreateSoundBuffer(bufferDesc As DSBUFFERDESC, _
    format As WAVEFORMATEX) As DirectSoundBuffer

Parameters

object
Object expression that resolves to a DirectSound object.
bufferDesc
A DSBUFFERDESC type that contains the description of the sound buffer to be created.
format
A WAVEFORMATEX type that describes the format of waveform-audio data.

Return Values

If the method succeeds, a DirectSoundBuffer object is returned.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error values:

DSERR_ALLOCATED
DSERR_BADFORMAT
DSERR_INVALIDPARAM
DSERR_NOAGGREGATION
DSERR_OUTOFMEMORY
DSERR_UNINITIALIZED
DSERR_UNSUPPORTED

Remarks

Before it can play any sound buffers, the application must specify a cooperative level for a DirectSound object by using the DirectSound.SetCooperativeLevel method.

The bufferDesc parameter points to a type that describes the type of buffer desired, including format, size, and capabilities. The application must specify the needed capabilities, or they will not be available. For example, if the application creates a DirectSoundBuffer object without specifying the DSBCAPS_CTRLFREQUENCY flag, any call to DirectSoundBuffer.SetFrequency will fail.

The DSBCAPS_STATIC flag can also be specified, in which case DirectSound stores the buffer in on-board memory, if available, to take advantage of hardware mixing. To force the buffer to use either hardware or software mixing, use the DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE flag. Additionally, you can have DirectSound assign a hardware or software resource during playing by using the DSBCAPS_LOCDEFER flag.

See Also

DSBUFFERDESC, DirectSound.DuplicateSoundBuffer, DirectSound.SetCooperativeLevel, DirectSoundBuffer, DirectSoundBuffer.GetFormat, DirectSoundBuffer.GetVolume, DirectSoundBuffer.Play, DirectSoundBuffer.SetFormat, DirectSoundBuffer.SetFrequency


DirectSound.CreateSoundBufferFromFile

The DirectSound.CreateSoundBufferFromFile method creates a DirectSoundBuffer object to hold a sequence of audio samples.

object.CreateSoundBufferFromFile(filename As String, _
    bufferDesc As DSBUFFERDESC, _
    format As WAVEFORMATEX) As DirectSoundBuffer

Parameters

object
Object expression that resolves to a DirectSound object.
filename
The filename of the wave file that is loaded into the sound buffer that is created.
bufferDesc
A DSBUFFERDESC type that contains the description of the sound buffer to be created.
format
A WAVEFORMATEX type that describes the format of waveform-audio data.

Return Values

If the method succeeds, a DirectSoundBuffer is returned.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error values:

DSERR_ALLOCATED
DSERR_BADFORMAT
DSERR_INVALIDPARAM
DSERR_NOAGGREGATION
DSERR_OUTOFMEMORY
DSERR_UNINITIALIZED
DSERR_UNSUPPORTED


DirectSound.CreateSoundBufferFromResource

The DirectSound.CreateSoundBufferFromResource method creates a DirectSoundBuffer object to hold a sequence of audio samples. The sound resource must be of type .wav.

object.CreateSoundBufferFromResource( _
    dll As String, _
    resourceName As String, _
    bufferDesc As DSBUFFERDESC, _
    format As WAVEFORMATEX) As DirectSoundBuffer

Parameters

object
Object expression that resolves to a DirectSound object.
dll
The name of the DLL that contains the resource.
resourceName
The name of the resource that is loaded in the sound buffer to be created.
bufferDesc
A DSBUFFERDESC type that contains the description of the sound buffer to be created.
format
A WAVEFORMATEX type that describes the format of waveform-audio data.

Return Values

If the method succeeds, a DirectSoundBuffer is returned.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error values:

DSERR_ALLOCATED
DSERR_BADFORMAT
DSERR_INVALIDPARAM
DSERR_NOAGGREGATION
DSERR_OUTOFMEMORY
DSERR_UNINITIALIZED
DSERR_UNSUPPORTED


DirectSound.DuplicateSoundBuffer

The DirectSound.DuplicateSoundBuffer method creates a new DirectSoundBuffer object that uses the same buffer memory as the original object.

object.DuplicateSoundBuffer( _
    original As DirectSoundBuffer) _
    As DirectSoundBuffer

Parameters

object
Object expression that resolves to a DirectSound object.
original
The DirectSoundBuffer object to be duplicated.

Return Values

If the method succeeds, a DirectSoundBuffer is returned.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error values:

DSERR_ALLOCATED
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_OUTOFMEMORY
DSERR_UNINITIALIZED

Remarks

The new object can be used just like the original.

Initially, the duplicate buffer will have the same parameters as the original buffer. However, the application can change the parameters of each buffer independently, and each can be played or stopped without affecting the other.

If data in the buffer is changed through one object, the change will be reflected in the other object because the buffer memory is shared.

The buffer memory will be released when the last object referencing it is released.

Applications cannot assume that an attempt to duplicate a sound buffer will always succeed. In particular, DirectSound will not create a software duplicate of a hardware buffer.

Note that you cannot duplicate the primary sound buffer.

See Also

DirectSound.CreateSoundBuffer, DirectSound.CreateSoundBufferFromFile, DirectSound.CreateSoundBufferFromResource


DirectSound.GetCaps

The DirectSound.GetCaps method retrieves the capabilities of the hardware device that is represented by the DirectSound object.

object.GetCaps(caps As DSCAPS)

Parameters

object
Object expression that resolves to a DirectSound object.
caps
A DSCAPS type to contain the capabilities of this sound device.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error values:

DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_UNINITIALIZED

Remarks

Information retrieved in the DSCAPS type describes the maximum capabilities of the sound device and those currently available, such as the number of hardware mixing channels and the amount of on-board sound memory. You can use this information to fine-tune performance and optimize resource allocation.

Because of resource-sharing requirements, the maximum capabilities in one area might be available only at the cost of another area. For example, the maximum number of hardware-mixed streaming sound buffers might be available only if there are no hardware static sound buffers.

See Also

DirectX7.DirectSoundCreate, DSCAPS


DirectSound.GetSpeakerConfig

The DirectSound.GetSpeakerConfig method retrieves the speaker configuration specified for this DirectSound object.

object.GetSpeakerConfig() As CONST_DSSPEAKERFLAGS

Parameters

object
Object expression that resolves to a DirectSound object.

Return Values

If the method succeeds, one or more of the following constants of the CONST_DSSPEAKERFLAGS enumeration is returned.

DSSPEAKER_HEADPHONE
The audio is played through headphones.
DSSPEAKER_MONO
The audio is played through a single speaker.
DSSPEAKER_QUAD
The audio is played through quadraphonic speakers.
DSSPEAKER_STEREO
The audio is played through stereo speakers (default value).
DSSPEAKER_SURROUND
The audio is played through surround speakers.
DSSPEAKER_STEREO may be combined with one of the following values:
DSSPEAKER_GEOMETRY_WIDE
The speakers are directed over an arc of 20 degrees.
DSSPEAKER_GEOMETRY_NARROW
The speakers are directed over an arc of 10 degrees.
DSSPEAKER_GEOMETRY_MIN
The speakers are directed over an arc of 5 degrees.
DSSPEAKER_GEOMETRY_MAX
The speakers are directed over an arc of 180 degrees.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error values:

DSERR_INVALIDPARAM
DSERR_UNINITIALIZED

Remarks

The speaker geometry is by default set to 0 which states that the speaker geometry has not been defined. The geometry must be explicitly set by using the DirectSound.SetSpeakerConfig method and passing one of the speaker geometry flags with the DSSPEAKER_STEREO flag.

See Also

DirectSound.SetSpeakerConfig


DirectSound.SetCooperativeLevel

The DirectSound.SetCooperativeLevel method sets the cooperative level of the application for this sound device.

object.SetCooperativeLevel(hwnd As Long, _
    level As CONST_DSSCLFLAGS)

Parameters

object
Object expression that resolves to a DirectSound object.
hwnd
Window handle to the application. See Remarks.
level
Requested priority level. Specify one of the following constants of the CONST_DSSCLFLAGS enumeration:
DSSCL_EXCLUSIVE
Sets the application to the exclusive level. When it has the input focus, the application will be the only one audible (sounds from applications with the DSBCAPS_GLOBALFOCUS flag set will be muted). With this level, it also has all the privileges of the DSSCL_PRIORITY level. DirectSound will restore the hardware format, as specified by the most recent call to the DirectSoundBuffer.SetFormat method, once the application gains the input focus. (Note that DirectSound will always restore the wave format no matter what priority level is set.)
DSSCL_NORMAL
Sets the application to a fully cooperative status. This level has the smoothest multitasking and resource-sharing behavior, but because it does not allow the primary buffer format to change, output is restricted to the default 8-bit format.
DSSCL_PRIORITY
Sets the application to the priority level. Applications with this cooperative level can call the DirectSoundBuffer.SetFormat method.
DSSCL_WRITEPRIMARY
This is the highest priority level. The application has write access to the primary sound buffers. No secondary sound buffers can be played. This level cannot be set if the DirectSound driver is being emulated for the device; that is, if the DirectSound.GetCaps method returns the DSCAPS_EMULDRIVER flag in the DSCAPS type.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error values:

DSERR_ALLOCATED
DSERR_INVALIDPARAM
DSERR_UNINITIALIZED
DSERR_UNSUPPORTED

Remarks

The application must set the cooperative level by calling this method before its buffers can be played. The recommended cooperative level is DSSCL_PRIORITY; use other priority levels when necessary.

The hwnd parameter should be the top-level application window handle. If you are also using DirectDraw, it must be the same handle passed to the DirectDraw7.SetCooperativeLevel method.

See Also

DirectSoundBuffer.GetFormat, DirectSoundBuffer.GetVolume, DirectSoundBuffer.Play, DirectSoundBuffer.Restore, DirectSoundBuffer.SetFormat


DirectSound.SetSpeakerConfig

The DirectSound.SetSpeakerConfig method specifies the speaker configuration of the DirectSound object.

object.SetSpeakerConfig( _
    speakerConfig As CONST_DSSPEAKERFLAGS)

Parameters

object
Object expression that resolves to a DirectSound object.
speakerConfig
Speaker configuration of the specified DirectSound object. This parameter can be one of the following constants of the CONST_DSSPEAKERFLAGS enumeration:
DSSPEAKER_HEADPHONE
The speakers are headphones.
DSSPEAKER_MONO
The speakers are monaural.
DSSPEAKER_QUAD
The speakers are quadraphonic.
DSSPEAKER_STEREO
The speakers are stereo (default value).
DSSPEAKER_SURROUND
The speakers are surround sound.
DSSPEAKER_STEREO may be combined with one of the following values:
DSSPEAKER_GEOMETRY_WIDE
The speakers are directed over an arc of 20 degrees.
DSSPEAKER_GEOMETRY_NARROW
The speakers are directed over an arc of 10 degrees.
DSSPEAKER_GEOMETRY_MIN
The speakers are directed over an arc of 5 degrees.
DSSPEAKER_GEOMETRY_MAX
The speakers are directed over an arc of 180 degrees.

Error Codes

If the method fails, an error is raised and Err.Number may be one of the following error values:

DSERR_INVALIDPARAM
DSERR_UNINITIALIZED

Remarks

The speaker geometry is by default set to 0 which states that the speaker geometry has not been defined. The geometry must be explicitly set by using the passing one of the speaker geometry flags with the DSSPEAKER_STEREO flag.

See Also

DirectSound.GetSpeakerConfig


DirectSound3DBuffer

Applications use the methods of the DirectSound3DBuffer class to retrieve and set parameters that describe the position, orientation, and environment of a sound buffer in 3-D space. This section is a reference to the methods of this class.

The DirectSound3DBuffer is obtaining by using the DirectSoundBuffer.QueryInterface method.

The methods of the DirectSound3DBuffer class can be organized into the following groups:

Batch parameter manipulation | GetAllParameters
 | SetAllParameters
Distance | GetMaxDistance
 | GetMinDistance
 | SetMaxDistance
 | SetMinDistance
Obtaining objects | GetDirectSound3DListener
 | GetDirectSoundBuffer
Operation mode | GetMode
 | SetMode
Position | GetPosition
 | SetPosition
Sound projection cones | GetConeAngles
 | GetConeOrientation
 | GetConeOutsideVolume
 | SetConeAngles
 | SetConeOrientation
 | SetConeOutsideVolume
Velocity | GetVelocity
 | SetVelocity


DirectSound3DBuffer.GetAllParameters

The DirectSound3DBuffer.GetAllParameters method retrieves information that describes the 3-D characteristics of a sound buffer at a given point in time.

object.GetAllParameters(buffer As DS3DBUFFER)

Parameters

object
Object expression that resolves to a DirectSound3DBuffer object.
buffer
A DS3DBUFFER type that will contain the information describing the 3-D characteristics of the sound buffer.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.


DirectSound3DBuffer.GetConeAngles

The DirectSound3DBuffer.GetConeAngles method retrieves the inside and outside angles of the sound projection cone for this sound buffer.

object.GetConeAngles(inCone As Long, _
    outCone As Long)

Parameters

object
Object expression that resolves to a DirectSound3DBuffer object.
inCone and outCone
Variables that will contain the inside and outside angles of the sound projection cone, in degrees.

Error Codes

If the method fails, an error is raised and Err.Number may be DSERR_INVALIDPARAM.

Remarks

The minimum, maximum, and default cone angles are defined in as DS3D_MINCONEANGLE, DS3D_MAXCONEANGLE, and DS3D_DEFAULTCONEANGLE.


DirectSound3DBuffer.GetConeOrientation

The DirectSound3DBuffer.GetConeOrientation method retrieves the orientation of the sound projection cone for this sound buffer.

object.GetConeOrientation(orientation As D3DVECTOR)

Parameters

object
Object expression that resolves to a DirectSound3DBuffer object.
orientation
A D3DVECTOR type that will contain the current orientation of the sound projection cone. The vector information represents the center of the sound cone.

Error Codes

If the method fails, an error is raised and Err.Number may be DSERR_INVALIDPARAM.

Remarks

The values returned are not necessarily the same as those set by using the DirectSound3DBuffer.SetConeOrientation method. DirectSound adjusts orientation vectors so that they have a magnitude of less than or equal to 1.0.

See Also

DirectSound3DBuffer.SetConeOrientation, DirectSound3DBuffer.SetConeAngles, DirectSound3DBuffer.SetConeOutsideVolume


DirectSound3DBuffer.GetConeOutsideVolume

The DirectSound3DBuffer.GetConeOutsideVolume method retrieves the current cone outside volume for this sound buffer.

object.GetConeOutsideVolume() As Long

Parameters

object
Object expression that resolves to a DirectSound3DBuffer object.

Error Codes

If the method fails, an error is raised and Err.Number may be DSERR_INVALIDPARAM.

Return Values

If the method succeeds, the current cone outside volume for this sound buffer is returned.

Remarks

Volume levels are represented by attenuation. Allowable values are between DSBVOLUME_MAX (no attenuation) and DSBVOLUME_MIN (silence). The default value is DS3D_DEFAULTCONEOUTSIDEVOLUME (no attenuation). Currently DirectSound does not support amplification.

For additional information about the concept of outside volume, see Sound Cones.

See Also

DirectSoundBuffer.SetVolume


DirectSound3DBuffer.GetDirectSound3DListener

The DirectSound3DBuffer.GetDirectSound3DListener method returns a DirectSound3DListener object.

object.GetDirectSound3DListener() As DirectSound3DListener

Parameters

object
Object expression that resolves to a DirectSound3DBuffer object.

Return Values

If the method succeeds, a DirectSound3DListener object is returned.

Error Codes

If the method fails, an error is raised and Err.Number may be set to E_NOINTERFACE.

Remarks

The DirectSound3DListener object may only be created from the primary sound buffer.


DirectSound3DBuffer.GetDirectSoundBuffer

The DirectSound3DBuffer.GetDirectSoundBuffer method returns a DirectSoundBuffer object.

object.GetDirectSoundBuffer() As DirectSoundBuffer

Parameters

object
Object expression that resolves to a DirectSound3DBuffer object.

Return Values

If the method succeeds, a DirectSoundBuffer object is returned.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectSound3DBuffer.GetMaxDistance

The DirectSound3DBuffer.GetMaxDistance method retrieves the current maximum distance for this sound buffer.

object.GetMaxDistance() As Single

Parameters

object
Object expression that resolves to a DirectSound3DBuffer object.

Return Values

If the method succeeds, the return value is the current maximum distance setting.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

Remarks

The default maximum distance, defined as DS3D_DEFAULTMAXDISTANCE, is effectively infinite.

See Also

DirectSound3DBuffer.GetMinDistance, DirectSound3DBuffer.SetMaxDistance


DirectSound3DBuffer.GetMinDistance

The DirectSound3DBuffer.GetMinDistance method retrieves the current minimum distance for this sound buffer.

object.GetMinDistance() As Single

Parameters

object
Object expression that resolves to a DirectSound3DBuffer object.

Return Values

If the method succeeds, the return value is the current minimum distance setting.

Error Codes

If the method fails, an error is raised and Err.Number may be DSERR_INVALIDPARAM.

Remarks

By default, the minimum distance value is DS3D_DEFAULTMINDISTANCE, currently defined as 1.0 (corresponding to 1.0 meter at the default distance factor of 1.0 meters per unit).

See Also

DirectSound3DBuffer.SetMinDistance, DirectSound3DBuffer.GetMaxDistance


DirectSound3DBuffer.GetMode

The DirectSound3DBuffer.GetMode method retrieves the current operation mode for 3-D sound processing.

object.GetMode() As CONST_DS3DMODEFLAGS

Parameters

object
Object expression that resolves to a DirectSound3DBuffer object.

Return Values

If the method succeeds, the return value contains the current mode setting. This value will be one of the following constants of the CONST_DS3DMODEFLAGS enumeration:

DS3DMODE_DISABLE
Processing of 3-D sound is disabled. The sound seems to originate from the center of the listener's head.
DS3DMODE_HEADRELATIVE
Sound parameters (position, velocity, and orientation) are relative to the listener's parameters. In this mode, the absolute parameters of the sound are updated automatically as the listener's parameters change, so that the relative parameters remain constant.
DS3DMODE_NORMAL
Normal processing. This is the default mode.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.


DirectSound3DBuffer.GetPosition

The DirectSound3DBuffer.GetPosition method retrieves the sound buffer's current position, in distance units. By default, distance units are meters, but the units can be changed by using the DirectSound3DListener.SetDistanceFactor method.

object.GetPosition(position As D3DVECTOR)

Parameters

object
Object expression that resolves to a DirectSound3DBuffer object.
position
A D3DVECTOR type that will contain the current position of the sound buffer.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.


DirectSound3DBuffer.GetVelocity

The DirectSound3DBuffer.GetVelocity method retrieves the current velocity for this sound buffer. Velocity is measured in units per second. The default unit is one meter, but this can be changed by using the DirectSound3DListener.SetDistanceFactor method.

object.GetVelocity(velocity As D3DVECTOR)

Parameters

object
Object expression that resolves to a DirectSound3DBuffer object.
velocity
A D3DVECTOR type that will contain the sound buffer's current velocity.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

Remarks

Velocity is used for Doppler effects only. It does not actually move the buffer. For additional information, see Doppler Factor.

The default unit of measurement is meters per second, but this can be changed by using the DirectSound3DListener.SetDistanceFactor method.

See Also

DirectSound3DBuffer.SetPosition, DirectSound3DBuffer.SetVelocity


DirectSound3DBuffer.SetAllParameters

The DirectSound3DBuffer.SetAllParameters method sets all 3-D sound buffer parameters from a given DS3DBUFFER type that describes all aspects of the sound buffer at a moment in time.

object.SetAllParameters(buffer As DS3DBUFFER, _
    applyFlag As CONST_DS3DAPPLYFLAGS)

Parameters

object
Object expression that resolves to a DirectSound3DBuffer object.
buffer
A DS3DBUFFER type containing the information that describes the 3-D characteristics of the sound buffer.
applyFlag
Value indicating when the setting should be applied. This value must be one of the following constants of the CONST_DS3DAPPLYFLAGS enumeration:
DS3D_DEFERRED
Settings are not applied until the application calls the DirectSound3DListener.CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.


DirectSound3DBuffer.SetConeAngles

The DirectSound3DBuffer.SetConeAngles method sets the inside and outside angles of the sound projection cone for this sound buffer.

object.SetConeAngles(inCone As Long, _
    outCone As Long, _
    applyFlag As CONST_DS3DAPPLYFLAGS)

Parameters

object
Object expression that resolves to a DirectSound3DBuffer object.
inCone and outCone
Inside and outside angles of the sound projection cone, in degrees.
applyFlag
Value indicating when the setting should be applied. This value must be one of the following constants of the CONST_DS3DAPPLYFLAGS enumeration:
DS3D_DEFERRED
Settings are not applied until the application calls the DirectSound3DListener.CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

For information on trapping errors, see the Visual Basic Error Trapping topic.

Remarks

The minimum, maximum, and default cone angles are defined as DS3D_MINCONEANGLE, DS3D_MAXCONEANGLE, and DS3D_DEFAULTCONEANGLE. Each angle must be in the range of 0 degrees (no cone) to 360 degrees (the full sphere). The default value is 360.

See Also

DirectSound3DBuffer.GetConeOutsideVolume, DirectSound3DBuffer.SetConeOutsideVolume


DirectSound3DBuffer.SetConeOrientation

The DirectSound3DBuffer.SetConeOrientation method sets the orientation of the sound projection cone for this sound buffer. This method has no effect unless the cone angle and cone volume factor have also been set.

object.SetConeOrientation( _
    x As Single, _
    y As Single, _
    z As Single, _
    applyFlag As CONST_DS3DAPPLYFLAGS)

Parameters

object
Object expression that resolves to a DirectSound3DBuffer object.
x, y, z
The coordinates of the new sound cone orientation vector.
applyFlag
One of the values of the CONST_DS3DAPPLYFLAGS enumeration indicating when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
Settings are not applied until the application calls the DirectSound3DListener.CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

See Also

DirectSound3DBuffer.SetConeAngles, DirectSound3DBuffer.SetConeOutsideVolume


DirectSound3DBuffer.SetConeOutsideVolume

The DirectSound3DBuffer.SetConeOutsideVolume method sets the current cone outside volume for this sound buffer.

object.SetConeOutsideVolume(coneOutsideVolume As Long, _
    applyFlag As CONST_DS3DAPPLYFLAGS)

Parameters

object
Object expression that resolves to a DirectSound3DBuffer object.
coneOutsideVolume
Cone outside volume for this sound buffer, in hundredths of decibels. Allowable values are between DSBVOLUME_MAX (no attenuation) and DSBVOLUME_MIN (silence).
applyFlag
Value indicating when the setting should be applied. This value must be one of the following constants of the CONST_DS3DAPPLYFLAGS enumeration:
DS3D_DEFERRED
Settings are not applied until the application calls the DirectSound3DListener.CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

Remarks

Volume levels are represented by attenuation. Allowable values are between DSBVOLUME_MAX (no attenuation) and DSBVOLUME_MIN (silence). The default value is DS3D_DEFAULTCONEOUTSIDEVOLUME (no attenuation). Currently DirectSound does not support amplification.

See Also

DirectSoundBuffer.SetVolume


DirectSound3DBuffer.SetMaxDistance

The DirectSound3DBuffer.SetMaxDistance method sets the current maximum distance value.

object.SetMaxDistance(maxDistance As Single, _
    applyFlag As CONST_DS3DAPPLYFLAGS)

Parameters

object
Object expression that resolves to a DirectSound3DBuffer object.
maxDistance
New maximum distance value.
applyFlag
Value indicating when the setting should be applied. This value must be one of the following constants of the CONST_DS3DAPPLYFLAGS enumeration:
DS3D_DEFERRED
Settings are not applied until the application calls the DirectSound3DListener.CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Error Codes

If the method fails, an error is raised and Err.Number may be DSERR_INVALIDPARAM.

Remarks

The default maximum distance, defined as DS3D_DEFAULTMAXDISTANCE, is effectively infinite.

See Also

DirectSound3DBuffer.GetMaxDistance, DirectSound3DBuffer.SetMinDistance


DirectSound3DBuffer.SetMinDistance

The DirectSound3DBuffer.SetMinDistance method sets the current minimum distance value.

object.SetMinDistance(minDistance As Single, _
    applyFlag As CONST_DS3DAPPLYFLAGS)

Parameters

object
Object expression that resolves to a DirectSound3DBuffer object.
minDistance
New minimum distance value.
applyFlag
Value indicating when the setting should be applied. This value must be one of the following constants of the CONST_DS3DAPPLYFLAGS enumeration:
DS3D_DEFERRED
Settings are not applied until the application calls the DirectSound3DListener.CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

Remarks

By default, the minimum distance value is DS3D_DEFAULTMINDISTANCE, currently defined as 1.0 (corresponding to 1.0 meter at the default distance factor of 1.0 meters per unit).

See Also

DirectSound3DBuffer.SetMaxDistance


DirectSound3DBuffer.SetMode

The DirectSound3DBuffer.SetMode method sets the operation mode for 3-D sound processing.

object.SetMode(mode As CONST_DS3DMODEFLAGS, _
    applyFlag As CONST_DS3DAPPLYFLAGS)

Parameters

object
Object expression that resolves to a DirectSound3DBuffer object.
mode
One of the following constants of the CONST_DS3DMODEFLAGS enumeration specifying the 3-D sound processing mode to be set:
DS3DMODE_DISABLE
Processing of 3-D sound is disabled. The sound seems to originate from the center of the listener's head.
DS3DMODE_HEADRELATIVE
Sound parameters (position, velocity, and orientation) are relative to the listener's parameters. In this mode, the absolute parameters of the sound are updated automatically as the listener's parameters change, so that the relative parameters remain constant.
DS3DMODE_NORMAL
Normal processing. This is the default mode.
applyFlag
Value indicating when the setting should be applied. This value must be one of the following constants of the CONST_DS3DAPPLYFLAGS enumeration:
DS3D_DEFERRED
Settings are not applied until the application calls the DirectSound3DListener.CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.


DirectSound3DBuffer.SetPosition

The DirectSound3DBuffer.SetPosition method sets the sound buffer's current position, in distance units. By default, distance units are meters, but the units can be changed by using the DirectSound3DListener.SetDistanceFactor method.

object.SetPosition(x As Single, _
    y As Single, _
    z As Single, _
    applyFlag As CONST_DS3DAPPLYFLAGS)

Parameters

object
Object expression that resolves to a DirectSound3DBuffer object.
x, y, and z
Values that represent the coordinates of the new position vector. Note that DirectSound may adjust these values to prevent floating-point overflow.
applyFlag
Value indicating when the setting should be applied. This value must be one of the following constants of the CONST_DS3DAPPLYFLAGS enumeration:
DS3D_DEFERRED
Settings are not applied until the application calls the DirectSound3DListener.CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

Remarks

Passing values greater than 10 or less than -10 may attenuate the sound beyond the threshold of audibility.


DirectSound3DBuffer.SetVelocity

The DirectSound3DBuffer.SetVelocity method sets the sound buffer's current velocity.

object.SetVelocity(x As Single, _
    y As Single, _
    z As Single, _
    applyFlag As CONST_DS3DAPPLYFLAGS)

Parameters

object
Object expression that resolves to a DirectSound3DBuffer object.
x, y, and z
Values that represent the coordinates of the new velocity vector. Note that DirectSound may adjust these values to prevent floating-point overflow.
applyFlag
Value indicating when the setting should be applied. This value must be one of the following flags of the CONST_DS3DAPPLYFLAGS enumeration:
DS3D_DEFERRED
Settings are not applied until the application calls the DirectSound3DListener.CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

Remarks

Velocity is used for Doppler effects only. It does not actually move the buffer.

The default unit of measurement is meters per second, but this can be changed by using the DirectSound3DListener.SetDistanceFactor method.

See Also

DirectSound3DBuffer.SetPosition, DirectSound3DBuffer.GetVelocity


DirectSound3DListener

Applications use the methods of the DirectSound3DListener class to retrieve and set parameters that describe a listener's position, orientation, and listening environment in 3-D space. This section is a reference to the methods of this class.

An object of this class is obtained by using the DirectSoundBuffer.GetDirectSound3DListener method.

The methods of the DirectSound3DListener class can be organized into the following groups:

Batch parameters | GetAllParameters
 | SetAllParameters
Deferred settings | CommitDeferredSettings
Distance factor | GetDistanceFactor
 | SetDistanceFactor
Doppler factor | GetDopplerFactor
 | SetDopplerFactor
Obtaining objects | GetDirectSoundBuffer
Orientation | GetOrientation
 | SetOrientation
Position | GetPosition
 | SetPosition
Rolloff factor | GetRolloffFactor
 | SetRolloffFactor
Velocity | GetVelocity
 | SetVelocity


DirectSound3DListener.CommitDeferredSettings

The DirectSound3DListener.CommitDeferredSettings method commits any deferred settings made since the last call to this method.

object.CommitDeferredSettings()

Parameters

object
Object expression that resolves to a DirectSound3DListener object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.


DirectSound3DListener.GetAllParameters

The DirectSound3DListener.GetAllParameters method retrieves information that describes the current state of the 3-D world and listener.

object.GetAllParameters(listener As DS3DLISTENER)

Parameters

object
Object expression that resolves to a DirectSound3DListener object.
listener
A DS3DLISTENER type that will contain the current state of the 3-D world and listener.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

See Also

DirectSound3DListener.SetAllParameters


DirectSound3DListener.GetDirectSoundBuffer

The DirectSound3DListener.GetDirectSoundBuffer method returns a DirectSoundBuffer object.

object.GetDirectSoundBuffer() As DirectSoundBuffer

Parameters

object
Object expression that resolves to a DirectSound3DListener object.

Return Values

If the method succeeds, a DirectSoundBuffer object is returned.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_OUTOFMEMORY.


DirectSound3DListener.GetDistanceFactor

The DirectSound3DListener.GetDistanceFactor method retrieves the current distance factor.

object.GetDistanceFactor() As Single

Parameters

object
Object expression that resolves to a DirectSound3DListener object.

Return Values

If the method succeeds, the current distance factor value is returned.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

See Also

DirectSound3DListener.SetDistanceFactor


DirectSound3DListener.GetDopplerFactor

The DirectSound3DListener.GetDopplerFactor method retrieves the current Doppler effect factor.

object.GetDopplerFactor() As Single

Parameters

object
Object expression that resolves to a DirectSound3DListener object.

Return Values

If the method succeeds, the current Doppler factor value is returned.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

Remarks

The Doppler factor has a range of DS3D_MINDOPPLERFACTOR (no Doppler effects) to DS3D_MAXDOPPLERFACTOR (as currently defined, 10 times the Doppler effects found in the real world). The default value is DS3D_DEFAULTDOPPLERFACTOR (1.0).

See Also

DirectSound3DListener.SetDopplerFactor


DirectSound3DListener.GetOrientation

The DirectSound3DListener.GetOrientation method retrieves the listener's current orientation in vectors: a front vector and a top vector.

object.GetOrientation(orientFront As D3DVECTOR, _
    orientTop As D3DVECTOR)

Parameters

object
Object expression that resolves to a DirectSound3DListener object.
orientFront
A D3DVECTOR type that will contain the listener's front orientation vector.
orientTop
A D3DVECTOR type that will contain the listener's top orientation vector.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

Remarks

The front vector points in the direction of the listener's nose, and the top vector points out the top of the listener's head. By default, the front vector is (0,0,1.0) and the top vector is (0,1.0,0).

The values returned are not necessarily the same as those set by using the DirectSound3DListener.SetOrientation method. DirectSound adjusts orientation vectors so that they are at right angles and have a magnitude of less than or equal to 1.0.

See Also

DirectSound3DListener.SetOrientation


DirectSound3DListener.GetPosition

The DirectSound3DListener.GetPosition method retrieves the listener's current position in distance units. By default, these units are meters, but this can be changed by calling the DirectSound3DListener.SetDistanceFactor method.

object.GetPosition(position As D3DVECTOR)

Parameters

object
Object expression that resolves to a DirectSound3DListener object.
position
A D3DVECTOR type that will contain the listener's position vector.

Error Codes

If the method fails, an error is raised and Err.Number may be set to the value of DSERR_INVALIDPARAM.

See Also

DirectSound3DListener.SetPosition


DirectSound3DListener.GetRolloffFactor

The DirectSound3DListener.GetRolloffFactor method retrieves the current rolloff factor.

object.GetRolloffFactor() As Single

Parameters

object
Object expression that resolves to a DirectSound3DListener object.

Return Values

If the method succeeds, the current rolloff factor value is returned.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

Remarks

The rolloff factor has a range of DS3D_MINROLLOFFFACTOR (no rolloff) to DS3D_MAXROLLOFFFACTOR (as currently defined, 10 times the rolloff found in the real world). The default value is DS3D_DEFAULTROLLOFFFACTOR (1.0). For additional information, see Rolloff Factor.

See Also

DirectSound3DListener.SetRolloffFactor


DirectSound3DListener.GetVelocity

The DirectSound3DListener.GetVelocity method retrieves the listener's current velocity.

object.GetVelocity() As D3DVECTOR

Parameters

object
Object expression that resolves to a DirectSound3DListener object.

Return Values

If the method succeeds, a D3DVECTOR type that will contain the listener's current velocity.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

Remarks

Velocity is used only for Doppler effects. It does not actually move the listener. To change the listener's position, use the DirectSound3DListener.SetPosition method. The default velocity is (0,0,0).

See Also

DirectSound3DListener.SetVelocity


DirectSound3DListener.SetAllParameters

The DirectSound3DListener.SetAllParameters method sets all 3-D listener parameters from a given DS3DLISTENER type that describes all aspects of the 3-D listener at a moment in time.

object.SetAllParameters(listener As DS3DLISTENER, _
    applyFlag As CONST_DS3DAPPLYFLAGS)

Parameters

object
Object expression that resolves to a DirectSound3DListener object.
listener
A DS3DLISTENER type that contains information describing all current 3-D listener parameters.
applyFlag
Value indicating when the setting should be applied. This value must be one of the following constants of the CONST_DS3DAPPLYFLAGS enumeration:
DS3D_DEFERRED
Settings are not applied until the application calls the DirectSound3DListener.CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

See Also

DirectSound3DListener.GetAllParameters


DirectSound3DListener.SetDistanceFactor

The DirectSound3DListener.SetDistanceFactor method sets the current distance factor.

object.SetDistanceFactor(distanceFactor As Single, _
    applyFlag As CONST_DS3DAPPLYFLAGS)

Parameters

object
Object expression that resolves to a DirectSound3DListener object.
distanceFactor
New distance factor.
applyFlag
Value indicating when the setting should be applied. This value must be one of the following flags of the CONST_DS3DAPPLYFLAGS enumeration:
DS3D_DEFERRED
Settings are not applied until the application calls the DirectSound3DListener.CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

Remarks

For additional information about distance factors, see Distance Factor.

See Also

DirectSound3DListener.GetDistanceFactor


DirectSound3DListener.SetDopplerFactor

The DirectSound3DListener.SetDopplerFactor method sets the current Doppler effect factor.

object.SetDopplerFactor(dopplerFactor As Single, _
    applyFlag As CONST_DS3DAPPLYFLAGS)

Parameters

object
Object expression that resolves to a DirectSound3DListener object.
dopplerFactor
New Doppler factor value.
applyFlag
Value indicating when the setting should be applied. This value must be one of the following constants of the CONST_DS3DAPPLYFLAGS enumeration:
DS3D_DEFERRED
Settings are not applied until the application calls the DirectSound3DListener.CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

Remarks

The Doppler factor has a range of DS3D_MINDOPPLERFACTOR (no Doppler effects) to DS3D_MAXDOPPLERFACTOR (as currently defined, 10 times the Doppler effects found in the real world). The default value is DS3D_DEFAULTDOPPLERFACTOR (1.0).

See Also

DirectSound3DListener.GetDopplerFactor


DirectSound3DListener.SetOrientation

The DirectSound3DListener.SetOrientation method sets the listener's current orientation in terms of two vectors: a front vector and a top vector.

object.SetOrientation(xFront As Single, _
    yFront As Single, _
    zFront As Single, _
    xTop As Single, _
    yTop As Single, _
    zTop As Single, _
    applyFlag As CONST_DS3DAPPLYFLAGS)

Parameters

object
Object expression that resolves to a DirectSound3DListener object.
xFront, yFront, and zFront
Values that represent the coordinates of the front orientation vector.
xTop, yTop, and zTop
Values that represent the coordinates of the top orientation vector.
applyFlag
Value indicating when the setting should be applied. This value must be one of the following constants of the CONST_DS3DAPPLYFLAGS enumeration:
DS3D_DEFERRED
Settings are not applied until the application calls the DirectSound3DListener.CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

Remarks

The front vector points in the direction of the listener's nose, and the top vector points out the top of the listener's head. By default, the front vector is (0,0,1.0) and the top vector is (0,1.0,0).

The top vector must be at right angles to the front vector. If necessary, DirectSound adjusts the front vector after setting the top vector.

See Also

DirectSound3DListener.GetOrientation


DirectSound3DListener.SetPosition

The DirectSound3DListener.SetPosition method sets the listener's current position, in distance units. By default, these units are meters, but this can be changed by calling the DirectSound3DListener.SetDistanceFactor method.

object.SetPosition(x As Single, _
    y As Single, _
    z As Single, _
    applyFlag As CONST_DS3DAPPLYFLAGS)

Parameters

object
Object expression that resolves to a DirectSound3DListener object.
x, y, and z
Values that represent the coordinates of the listener's new position vector. Note that DirectSound may adjust these values to prevent floating-point overflow.
applyFlag
Value indicating when the setting should be applied. This value must be one of the following flags of the CONST_DS3DAPPLYFLAGS enumeration:
DS3D_DEFERRED
Settings are not applied until the application calls the DirectSound3DListener.CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

See Also

DirectSound3DListener.GetPosition


DirectSound3DListener.SetRolloffFactor

The DirectSound3DListener.SetRolloffFactor method sets the rolloff factor.

object.SetRolloffFactor(rolloffFactor As Single, _
    applyFlag As CONST_DS3DAPPLYFLAGS)

Parameters

object
Object expression that resolves to a DirectSound3DListener object.
rolloffFactor
New rolloff factor.
applyFlag
Value indicating when the setting should be applied. This value must be one of the following constants of the CONST_DS3DAPPLYFLAGS enumeration:
DS3D_DEFERRED
Settings are not applied until the application calls the DirectSound3DListener.CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

Remarks

The rolloff factor has a range of DS3D_MINROLLOFFFACTOR (no rolloff) to DS3D_MAXROLLOFFFACTOR (as currently defined, 10 times the rolloff found in the real world). The default value is DS3D_DEFAULTROLLOFFFACTOR (1.0).

See Also

DirectSound3DListener.GetRolloffFactor


DirectSound3DListener.SetVelocity

The DirectSound3DListener.SetVelocity method sets the listener's velocity.

object.SetVelocity(x As Single, _
    y As Single, _
    z As Single, _
    applyFlag As CONST_DS3DAPPLYFLAGS)

Parameters

object
Object expression that resolves to a DirectSound3DListener object.
x, y, and z
Values that represent the coordinates of the listener's new velocity vector. Note that DirectSound may adjust these values to prevent floating-point overflow.
applyFlag
Value indicating when the setting should be applied. This value must be one of the following constants of the CONST_DS3DAPPLYFLAGS enumeration:
DS3D_DEFERRED
Settings are not applied until the application calls the DirectSound3DListener.CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

Remarks

Velocity is used only for Doppler effects. It does not actually move the listener. To change the listener's position, use the DirectSound3DListener.SetPosition method. The default velocity is (0,0,0).

See Also

DirectSound3DListener.GetVelocity


DirectSoundBuffer

Applications use the methods of the DirectSoundBuffer class to create DirectSoundBuffer objects and set up the environment.

The object is obtained by using the DirectSound.CreateSoundBuffer method.

The DirectSoundBuffer methods can be organized into the following groups:

Information | GetCaps
 | GetFormat
 | GetStatus
 | SetFormat
Memory management | Restore
Miscellaneous | SaveToFile
Obtaining objects | GetDirectSound3DBuffer
 | GetDirectSound3DListener
Play management | GetCurrentPosition
 | Play
 | ReadBuffer
 | SetCurrentPosition
 | SetNotificationPositions
 | Stop
 | WriteBuffer
Sound management | GetFrequency
 | GetPan
 | GetVolume
 | SetFrequency
 | SetPan
 | SetVolume


DirectSoundBuffer.GetCaps

The DirectSoundBuffer.GetCaps method retrieves the capabilities of the DirectSoundBuffer object.

object.GetCaps(caps As DSBCAPS)

Parameters

object
Object expression that resolves to a DirectSoundBuffer object.
caps
A DSBCAPS type to contain the capabilities of this sound buffer.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

Remarks

The DSBCAPS type contains similar information to the DSBUFFERDESC type passed to the DirectSound.CreateSoundBuffer method, with some additional information. This additional information can include the buffer's location, either in hardware or software, and some cost measures. Examples of cost measures include the time it takes to download to a hardware buffer and the processing overhead required to mix and play the buffer when it is in the system memory.

The flags specified in the lFlags member of the DSBCAPS type are the same flags used by the DSBUFFERDESC type. The only difference is that in the DSBCAPS type, either DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE will be specified according to the location of the buffer memory. In the DSBUFFERDESC type, these flags are optional and, depending on which flag is specified, force the buffer to be located in either hardware or software.

See Also

DSBCAPS, DSBUFFERDESC, DirectSoundBuffer, DirectSound.CreateSoundBuffer


DirectSoundBuffer.GetCurrentPosition

The DirectSoundBuffer.GetCurrentPosition method retrieves the current position of the play and write cursors in the sound buffer.

object.GetCurrentPosition(cursors As DSCURSORS)

Parameters

object
Object expression that resolves to a DirectSoundBuffer object.
cursors
A DSCURSORS type that contains the current play position and the current write position in the DirectSoundBuffer object. This position is an offset within the sound buffer and is specified in bytes.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following values:

DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The lWrite member indicates the position at which it is safe to write new data to the buffer. The write cursor always leads the play cursor, typically by about 15 milliseconds' worth of audio data.

It is always safe to change data that is behind the position indicated by the lPlay member.

See Also

DirectSoundBuffer, DirectSoundBuffer.SetCurrentPosition


DirectSoundBuffer.GetDirectSound3DBuffer

The DirectSoundBuffer.GetDirectSound3DBuffer method returns a DirectSound3DBuffer object.

object.GetDirectSound3DBuffer() As DirectSound3DBuffer

Parameters

object
Object expression that resolves to a DirectSoundBuffer object.

Return Values

If the method succeeds, a DirectSound3DBuffer object is returned.

Error Codes

If the method fails, an error is raised and Err.Number may be set to E_NOINTERFACE or DSERR_OUTOFMEMORY.


DirectSoundBuffer.GetDirectSound3DListener

The DirectSoundBuffer.GetDirectSound3DListener method returns a DirectSound3DListener object.

object.GetDirectSound3DListener() As DirectSound3DListener

Parameters

object
Object expression that resolves to a DirectSoundBuffer object.

Return Values

If the method succeeds, a DirectSound3DListener object is returned.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectSoundBuffer.GetFormat

The DirectSoundBuffer.GetFormat method retrieves a description of the format of the sound data in the buffer, or the buffer size needed to retrieve the format description.

object.GetFormat(format As WAVEFORMATEX)

Parameters

object
Object expression that resolves to a DirectSoundBuffer object.
format
A WAVEFORMATEX type to contain a description of the sound data in the buffer.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

See Also

DirectSoundBuffer, DirectSoundBuffer.SetFormat


DirectSoundBuffer.GetFrequency

The DirectSoundBuffer.GetFrequency method retrieves the frequency, in samples per second, at which the buffer is playing.

object.GetFrequency() As Long

Parameters

object
Object expression that resolves to a DirectSoundBuffer object.

Return Values

The frequency at which the audio buffer is being played.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes:

DSERR_CONTROLUNAVAIL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The frequency value will be in the range of DSBFREQUENCY_MIN to DSBFREQUENCY_MAX. These values are currently defined as 100 and 100,000 respectively.

See Also

DirectSoundBuffer, DirectSoundBuffer.SetFrequency


DirectSoundBuffer.GetPan

The DirectSoundBuffer.GetPan method retrieves a variable that represents the relative volume between the left and right audio channels.

object.GetPan() As Long

Parameters

object
Object expression that resolves to a DirectSoundBuffer object.

Return Values

The relative mix between the left and right speakers.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes:

DSERR_CONTROLUNAVAIL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The returned value is measured in hundredths of a decibel (dB), in the range of DSBPAN_LEFT to DSBPAN_RIGHT. These values are currently defined as -10,000 and 10,000 respectively. The value DSBPAN_LEFT means the right channel is attenuated by 100 dB. The value DSBPAN_RIGHT means the left channel is attenuated by 100 dB. The neutral value is DSBPAN_CENTER, defined as zero. This value of 0 for the return value means that both channels are at full volume (they are attenuated by 0 decibels). At any setting other than DSBPAN_CENTER, one of the channels is at full volume and the other is attenuated.

A pan of -2173 means that the left channel is at full volume and the right channel is attenuated by 21.73 dB. Similarly, a pan of 870 means that the left channel is attenuated by 8.7 dB and the right channel is at full volume. A pan of DSBPAN_LEFT means that the right channel is silent and the sound is all the way to the left, while a pan of DSBPAN_RIGHT means that the left channel is silent and the sound is all the way to the right.

The pan control acts cumulatively with the volume control.

See Also

DirectSoundBuffer, DirectSoundBuffer.GetVolume, DirectSoundBuffer.SetPan, DirectSoundBuffer.SetVolume


DirectSoundBuffer.GetStatus

The DirectSoundBuffer.GetStatus method retrieves the current status of the sound buffer.

object.GetStatus() As CONST_DSBSTATUSFLAGS

Parameters

object
Object expression that resolves to a DirectSoundBuffer object.

Return Values

The status of the sound buffer. The status can be a combination of the following constants of the CONST_DSBSTATUSFLAGS enumeration:

DSBSTATUS_BUFFERLOST
The buffer is lost and must be restored before it can be played or locked.
DSBSTATUS_LOOPING
The buffer is being looped. If this value is not set, the buffer will stop when it reaches the end of the sound data. Note that if this value is set, the buffer must also be playing.
DSBSTATUS_PLAYING
The buffer is playing. If this value is not set, the buffer is stopped.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.

See Also

DirectSoundBuffer


DirectSoundBuffer.GetVolume

The DirectSoundBuffer.GetVolume method retrieves the current volume for this sound buffer.

object.GetVolume() As Long

Parameters

object
Object expression that resolves to a DirectSoundBuffer object.

Return Values

The volume associated with the specified DirectSound buffer.

Error Codes

If the method fails, an error is raised and Err.Number may be set to

DSERR_CONTROLUNAVAIL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The volume is specified in hundredths of decibels (dB). Allowable values are between DSBVOLUME_MAX (no attenuation) and DSBVOLUME_MIN (silence). These values are currently defined as 0 and -10,000 respectively. The value DSBVOLUME_MAX represents the original, unadjusted volume of the stream. The value DSBVOLUME_MIN indicates an audio volume attenuated by 100 dB, which, for all practical purposes, is silence. Currently DirectSound does not support amplification.

See Also

DirectSoundBuffer, DirectSoundBuffer.SetVolume


DirectSoundBuffer.Play

The DirectSoundBuffer.Play method causes the sound buffer to play from the current position.

object.Play(flags As CONST_DSBPLAYFLAGS)

Parameters

object
Object expression that resolves to a DirectSoundBuffer object.
flags
Flags specifying how to play the buffer. The following constant is defined in the CONST_DSBPLAYFLAGS enumeration:
DSBPLAY_LOOPING
Once the end of the audio buffer is reached, play restarts at the beginning of the buffer. Play continues until explicitly stopped. This flag must be set when playing primary sound buffers.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes:

DSERR_BUFFERLOST
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

This method will cause a secondary sound buffer to be mixed into the primary buffer and sent to the sound device. If this is the first buffer to play, it will implicitly create a primary buffer and start playing that buffer; the application need not explicitly direct the primary buffer to play.

If the buffer specified in the method is already playing, the call to the method will succeed and the buffer will continue to play. However, the flags defined in the most recent call supersede flags defined in previous calls.

Primary buffers must be played with the DSBPLAY_LOOPING flag set.

This method will cause primary sound buffers to start playing to the sound device. If the application is set to the DSSCL_WRITEPRIMARY cooperative level, this will cause the audio data in the primary buffer to be sent to the sound device. However, if the application is set to any other cooperative level, this method will ensure that the primary buffer is playing even when no secondary buffers are playing; in that case, silence will be played. This can reduce processing overhead when sounds are started and stopped in sequence, because the primary buffer will be playing continuously rather than stopping and starting between secondary buffers.

Note Before this method can be called on any sound buffer, the application should call the DirectSound.SetCooperativeLevel method and specify a cooperative level, typically DSSCL_NORMAL. If DirectSound.SetCooperativeLevel has not been called, the DirectSoundBuffer.Play method returns with DS_OK, but no sound will be produced until DirectSound.SetCooperativeLevel is called.

See Also

DirectSoundBuffer, DirectSound.SetCooperativeLevel


DirectSoundBuffer.ReadBuffer

The DirectSoundBuffer.ReadBuffer method reads a segment of the sound buffer and stores the data into a variable of type Any.

object.ReadBuffer(start As Long, _
    size As Long, _
    buffer As Any, _
    flags As CONST_DSBLOCKFLAGS)

Parameters

object
Object expression that resolves to a DirectSoundBuffer object.
start
Offset, in bytes, from the start of the buffer to where the read begins. This parameter is ignored if DSBLOCK_FROMWRITECURSOR constant is specified in the flags parameter.
size
Size, in bytes, of the portion of the buffer to read. Note that the sound buffer is conceptually circular.
buffer
Variable to hold the data read. Must be the same size as the sound buffer. You must pass the first element of the array.
flags
One of the following constants of the CONST_DSBLOCKFLAGS enumeration that modifies what is read:
DSBLOCK_FROMWRITECURSOR
Read from the current write position, making a call to DirectSoundBuffer.GetCurrentPosition method unnecessary. If this flag is specified, the start parameter is ignored.
DSBLOCK_ENTIREBUFFER
Reads the entire buffer. The size parameter is ignored.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes:

DSERR_BUFFERLOST
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED


DirectSoundBuffer.Restore

The DirectSoundBuffer.Restore method restores the memory allocation for a lost sound buffer for the specified DirectSoundBuffer object.

object.Restore()

Parameters

object
Object expression that resolves to a DirectSoundBuffer object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes:

DSERR_BUFFERLOST
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

If the application does not have the input focus, DirectSoundBuffer.Restore might not succeed. For example, if the application with the input focus has the DSSCL_WRITEPRIMARY cooperative level, no other application will be able to restore its buffers. Similarly, an application with the DSSCL_WRITEPRIMARY cooperative level must have the input focus to restore its primary sound buffer.

Once DirectSound restores the buffer memory, the application must rewrite the buffer with valid sound data. DirectSound cannot restore the contents of the memory, only the memory itself.

The application can receive notification that a buffer is lost when it specifies that buffer in a call to the DirectSoundBuffer.Play method. These methods return DSERR_BUFFERLOST to indicate a lost buffer. The DirectSoundBuffer.GetStatus method can also be used to retrieve the status of the sound buffer and test for the DSBSTATUS_BUFFERLOST flag.

See Also

DirectSoundBuffer, DirectSoundBuffer.Play, DirectSoundBuffer.GetStatus


DirectSoundBuffer.SaveToFile

The DirectSoundBuffer.SaveToFile method saves the contents of the DirectSound buffer to a file.

object.SaveToFile(filename As String)

Parameters

object
Object expression that resolves to a DirectSoundBuffer object.
filename
The name of the file where the sound buffer will be saved.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error values:

DSERR_INVALIDCALL
DSERR_INVALIDPARAM


DirectSoundBuffer.SetCurrentPosition

The DirectSoundBuffer.SetCurrentPosition method moves the current play position for secondary sound buffers.

object.SetCurrentPosition(newPosition As Long)

Parameters

object
Object expression that resolves to a DirectSoundBuffer object.
newPosition
New position, in bytes, from the beginning of the buffer that will be used when the sound buffer is played.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error values:

DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

This method cannot be called on primary sound buffers.

If the buffer is playing, it will immediately move to the new position and continue. If it is not playing, it will begin from the new position the next time the DirectSoundBuffer.Play method is called.

See Also

DirectSoundBuffer, DirectSoundBuffer.GetCurrentPosition, DirectSoundBuffer.Play


DirectSoundBuffer.SetFormat

The DirectSoundBuffer.SetFormat method sets the format of the primary sound buffer for the application. Whenever this application has the input focus, DirectSound will set the primary buffer to the specified format.

object.SetFormat(format As WAVEFORMATEX)

Parameters

object
Object expression that resolves to a DirectSoundBuffer object.
format
A WAVEFORMATEX type that describes the new format for the primary sound buffer.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error values:

DSERR_BADFORMAT
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_OUTOFMEMORY
DSERR_PRIOLEVELNEEDED
DSERR_UNSUPPORTED

Remarks

If this method is called on a primary buffer that is being accessed in write-primary cooperative level, the buffer must be stopped before DirectSoundBuffer.SetFormat is called. If this method is being called on a primary buffer for a non-write-primary level, DirectSound will implicitly stop the primary buffer, change the format, and restart the primary; the application need not do this explicitly.

This method will succeed even if the hardware does not support the requested format. DirectSound will set the buffer to the closest supported format, then mix the sound in the requested format and convert it before sending it to the primary buffer. To determine whether this is happening, an application can call the DirectSoundBuffer.GetFormat method for the primary buffer and compare the result with the format that was requested with the SetFormat method.

A call to this method also fails if the calling application has the DSSCL_NORMAL cooperative level.

This method is not valid for secondary sound buffers. If a secondary sound buffer requires a format change, the application should create a new DirectSoundBuffer object using the new format.

DirectSound supports PCM formats; it does not currently support compressed formats.

See Also

DirectSoundBuffer, DirectSoundBuffer.GetFormat


DirectSoundBuffer.SetFrequency

The DirectSoundBuffer.SetFrequency method sets the frequency at which the audio samples are played.

object.SetFrequency(frequency As Long)

Parameters

object
Object expression that resolves to a DirectSoundBuffer object.
frequency
New frequency, in hertz (Hz), at which to play the audio samples. The value must be in the range DSBFREQUENCY_MIN to DSBFREQUENCY_MAX. These values are currently defined as 100 and 100,000 respectively.

If the value is DSBFREQUENCY_ORIGINAL, the frequency is reset to the default value in the current buffer format. This format is specified in the DirectSound.CreateSoundBuffer method.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error values:

DSERR_CONTROLUNAVAIL
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

Increasing or decreasing the frequency changes the perceived pitch of the audio data. This method does not affect the format of the buffer.

This method is not valid for primary sound buffers.

See Also

DirectSoundBuffer, DirectSound.CreateSoundBuffer, DirectSoundBuffer.GetFrequency, DirectSoundBuffer.Play, DirectSoundBuffer.SetFormat


DirectSoundBuffer.SetNotificationPositions

The DirectSoundBuffer.SetNotificationPositions method sets the notification positions. During playback, whenever the position reaches an offset specified in one of the DSBPOSITIONNOTIFY types in the caller-supplied array, the associated event will be signaled. The position tracked in playback is the current play position; in capture it is the current read position.

object.SetNotificationPositions(nElements As Long, _
    psa() As DSBPOSITIONNOTIFY)

Parameters

object
Object expression that resolves to a DirectSoundBuffer object.
nElements
The number of DSBPOSITIONNOTIFY types in the psa() array.
psa()
An array of DSBPOSITIONNOTIFY types.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes:

DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED


DirectSoundBuffer.SetPan

The DirectSoundBuffer.SetPan method specifies the relative volume between the left and right channels.

object.SetPan(pan As Long)

Parameters

object
Object expression that resolves to a DirectSoundBuffer object.
pan
Relative volume between the left and right channels.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error values:

DSERR_CONTROLUNAVAIL
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The value in pan is measured in hundredths of a decibel (dB), in the range of DSBPAN_LEFT to DSBPAN_RIGHT. These values are currently defined as -10,000 and 10,000 respectively. The value DSBPAN_LEFT means the right channel is attenuated by 100 dB. The value DSBPAN_RIGHT means the left channel is attenuated by 100 dB. The neutral value is DSBPAN_CENTER, defined as zero. This value of 0 in the pan parameter means that both channels are at full volume (they are attenuated by 0 decibels). At any setting other than DSBPAN_CENTER, one of the channels is at full volume and the other is attenuated.

A pan of -2173 means that the left channel is at full volume and the right channel is attenuated by 21.73 dB. Similarly, a pan of 870 means that the left channel is attenuated by 8.7 dB and the right channel is at full volume. A pan of DSBPAN_LEFT means that the right channel is silent and the sound is all the way to the left, while a pan of DSBPAN_RIGHT means that the left channel is silent and the sound is all the way to the right.

The pan control acts cumulatively with the volume control.

See Also

DirectSoundBuffer, DirectSoundBuffer.GetPan, DirectSoundBuffer.GetVolume, DirectSoundBuffer.SetVolume


DirectSoundBuffer.SetVolume

The DirectSoundBuffer.SetVolume method changes the volume of a sound buffer.

object.SetVolume(volume As Long)

Parameters

object
Object expression that resolves to a DirectSoundBuffer object.
volume
New volume requested for this sound buffer.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error values:

DSERR_CONTROLUNAVAIL
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The volume is specified in hundredths of decibels (dB). Allowable values are between DSBVOLUME_MAX (no attenuation) and DSBVOLUME_MIN (silence). These values are currently defined as 0 and -10,000 respectively. The value DSBVOLUME_MAX represents the original, unadjusted volume of the stream. The value DSBVOLUME_MIN indicates an audio volume attenuated by 100 dB, which, for all practical purposes, is silence. Currently DirectSound does not support amplification.

See Also

DirectSoundBuffer, DirectSoundBuffer.GetPan, DirectSoundBuffer.GetVolume, DirectSoundBuffer.SetPan


DirectSoundBuffer.Stop

The DirectSoundBuffer.Stop method causes the sound buffer to stop playing.

object.Stop()

Parameters

object
Object expression that resolves to a DirectSoundBuffer object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error values:

DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

For secondary sound buffers, DirectSoundBuffer.Stop will set the current position of the buffer to the sample that follows the last sample played. This means that if the DirectSoundBuffer.Play method is called on the buffer, it will continue playing where it left off.

For primary sound buffers, if an application has the DSSCL_WRITEPRIMARY level, this method will stop the buffer and reset the current position to 0 (the beginning of the buffer). This is necessary because the primary buffers on most sound cards can play only from the beginning of the buffer.

However, if DirectSoundBuffer.Stop is called on a primary buffer and the application has a cooperative level other than DSSCL_WRITEPRIMARY, this method simply reverses the effects of DirectSoundBuffer.Play. It configures the primary buffer to stop if no secondary buffers are playing. If other buffers are playing in this or other applications, the primary buffer will not actually stop until they are stopped. This method is useful because playing the primary buffer consumes processing overhead even if the buffer is playing sound data with the amplitude of 0 decibels.

See Also

DirectSoundBuffer, DirectSoundBuffer.Play


DirectSoundBuffer.WriteBuffer

The DirectSoundBuffer.WriteBuffer method writes to a segment of the sound buffer from a variable holding audio data.

object.WriteBuffer(start As Long, _
    size As Long, _
    buffer As Any, _
    flags As CONST_DSBLOCKFLAGS)

Parameters

object
Object expression that resolves to a DirectSoundBuffer object.
start
Offset, in bytes, from the start of the buffer to where the read begins. This parameter is ignored if DSBLOCK_FROMWRITECURSOR constant is specified in the flags parameter.
size
Size, in bytes, of the portion of the buffer to read. Note that the sound buffer is conceptually circular.
buffer
Variable with the data to be written to the sound buffer. Must be the same size as the sound buffer. You must pass the first element of the array.
flags
One of the following constants of the CONST_DSBLOCKFLAGS enumeration that modifies what is read:
DSBLOCK_FROMWRITECURSOR
Writes from the current write position, making a call to DirectSoundBuffer.GetCurrentPosition method unnecessary. If this flag is specified, the start parameter is ignored.
DSBLOCK_ENTIREBUFFER
Writes to the entire buffer. The size parameter is ignored.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes:

DSERR_BUFFERLOST
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED


DirectSoundCapture

The methods of the DirectSoundCapture class are used to create sound capture buffers.

An object of this class is obtained by using the DirectX7.DirectSoundCaptureCreate function.

This reference section gives information on the following methods of the DirectSoundCapture class:

Creation | CreateCaptureBuffer
Capabilities | GetCaps


DirectSoundCapture.CreateCaptureBuffer

The DirectSoundCapture.CreateCaptureBuffer method creates a capture buffer.

Unlike DirectSound, which can mix several sounds into one sound for output, DirectSoundCapture cannot do the exact opposite and extract various sounds from one input sound. For the first version, DirectSoundCapture allows only one capture buffer to exist at any given time per capture device.

object.CreateCaptureBuffer( _
    bufferDesc As DSCBUFFERDESC) _
    As DirectSoundCaptureBuffer

Parameters

object
Object expression that resolves to a DirectSoundCapture object.
bufferDesc
A DSCBUFFERDESC type containing values for the capture buffer being created.

Return Values

If the method succeeds, a DirectSoundCaptureBuffer object is returned.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error values:

DSERR_INVALIDPARAM
DSERR_BADFORMAT
DSERR_GENERIC
DSERR_NODRIVER
DSERR_OUTOFMEMORY
DSERR_UNINITIALIZED


DirectSoundCapture.GetCaps

The DirectSoundCapture.GetCaps method obtains the capabilities of the capture device.

object.GetCaps(caps As DSCCAPS)

Parameters

object
Object expression that resolves to a DirectSoundCapture object.
caps
A DSCCAPS type to be filled by the capture device. When the method is called, the lSize member must specify the size of the type in bytes.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error values:

DSERR_INVALIDPARAM
DSERR_UNSUPPORTED
DSERR_NODRIVER
DSERR_OUTOFMEMORY
DSERR_UNINITIALIZED


DirectSoundCaptureBuffer

The methods of the DirectSoundCaptureBuffer class are used to manipulate sound capture buffers.

An object of this class is obtained by calling the DirectSoundCapture.CreateCaptureBuffer method.

The methods of the DirectSoundCaptureBuffer class may be grouped as follows:

Information | GetCaps
 | GetCurrentPosition
 | GetFormat
 | GetStatus
Buffer | ReadBuffer
 | WriteBuffer
Notification | SetNotificationPositions
Capture management | Start
 | Stop


DirectSoundCaptureBuffer.GetCaps

The DirectSoundCaptureBuffer.GetCaps method returns the capabilities of the buffer.

object.GetCaps(caps As DSCBCAPS)

Parameters

object
Object expression that resolves to a DirectSoundCaptureBuffer object.
caps
A DSCBCAPS type to be filled by the capture buffer. On input, the lSize member must specify the size of the type in bytes.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error values:

DSERR_INVALIDPARAM
DSERR_UNSUPPORTED
DSERR_OUTOFMEMORY


DirectSoundCaptureBuffer.GetCurrentPosition

The DirectSoundCaptureBuffer.GetCurrentPosition method gets the current capture and read positions in the buffer.

The capture position is ahead of the read position. These positions are not always identical due to possible buffering of captured data either on the physical device or in the host. The data after the read position up to and including the capture position is not necessarily valid data.

object.GetCurrentPosition(cursors As DSCURSORS)

Parameters

object
Object expression that resolves to a DirectSoundCaptureBuffer object.
cursors
A DSCURSORS type that contains the current capture position and the current position (the lPlay and the lWrite members) in the DirectSoundCaptureBuffer object. This position is an offset within the capture buffer and is specified in bytes.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error values:

DSERR_INVALIDPARAM
DSERR_NODRIVER
DSERR_OUTOFMEMORY


DirectSoundCaptureBuffer.GetFormat

The DirectSoundCaptureBuffer.GetFormat method retrieves the current format of the capture buffer.

object.GetFormat(waveformat As WAVEFORMATEX)

Parameters

object
Object expression that resolves to a DirectSoundCaptureBuffer object.
waveformat
A WAVEFORMATEX type to contain a description of the sound data in the capture buffer. To retrieve the buffer size needed to contain the format description, specify Nothing.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.


DirectSoundCaptureBuffer.GetStatus

The DirectSoundCaptureBuffer.GetStatus method retrieves the current status of the capture buffer.

object.GetStatus() As CONST_DSCBSTATUSFLAGS

Parameters

object
Object expression that resolves to a DirectSoundCaptureBuffer object.

Return Values

If the method succeeds, the status of the capture buffer is returned. The status can be set to one or more of the following constants of the CONST_DSCBSTATUSFLAGS enumeration.

Error Codes

If the method fails, an error is raised and Err.Number may be set to DSERR_INVALIDPARAM.


DirectSoundCaptureBuffer.ReadBuffer

The DirectSoundCaptureBuffer.ReadBuffer method reads a segment of the sound capture buffer and stores the data into a variable of type Any.

object.ReadBuffer(start As Long, _
    size As Long, _
    buffer As Any, _
    flags As CONST_DSCBLOCKFLAGS)

Parameters

object
Object expression that resolves to a DirectSoundCaptureBuffer object.
start
Offset, in bytes, from the start of the buffer to where the read begins.
size
Size, in bytes, of the portion of the buffer to read. Note that the sound buffer is conceptually circular. This parameter is ignored if DSCBLOCK_ENTIREBUFFER constant is set in the flags argument.
buffer
Variable to hold the data read. Must be the same size as the sound buffer. You must pass the first element of the array.
flags
Pass the following constant of the CONST_DSCBLOCKFLAGS enumeration to modify what is read:
DSCBLOCK_ENTIREBUFFER
Reads the entire buffer. The size parameter is ignored.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes:

DSERR_BUFFERLOST
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED


DirectSoundCaptureBuffer.SetNotificationPositions

The DirectSoundCaptureBuffer.SetNotificationPositions method sets the notification positions. During capture, whenever the position reaches an offset specified in one of the DSBPOSITIONNOTIFY types in the caller-supplied array, the associated event will be signaled. The position tracked in playback is the current play position; in capture it is the current read position.

object.SetNotificationPositions(nElements As Long, _
    psa() As DSBPOSITIONNOTIFY)

Parameters

object
Object expression that resolves to a DirectSoundCaptureBuffer object.
nElements
The number of DSBPOSITIONNOTIFY types in the psa() array.
psa()
An array of DSBPOSITIONNOTIFY types.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes:

DSERR_BUFFERLOST
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED


DirectSoundCaptureBuffer.Start

The DirectSoundCaptureBuffer.Start method puts the capture buffer into the capture state and begins capturing data into the buffer. If the capture buffer is already in the capture state then the method has no effect.

object.Start(flags As CONST_DSCBSTARTFLAGS)

Parameters

object
Object expression that resolves to a DirectSoundCaptureBuffer object.
flags
Flags that specify the behavior for the capture buffer when capturing sound data. Flags specifying how to play the buffer. The following constant of the CONST_DSCBSTARTFLAGS enumeration is defined:
DSCBSTART_LOOPING
Once the end of the buffer is reached, capture restarts at the beginning and continues until explicitly stopped.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error values:

DSERR_INVALIDPARAM
DSERR_NODRIVER
DSERR_OUTOFMEMORY


DirectSoundCaptureBuffer.Stop

The DirectSoundCaptureBuffer.Stop method puts the capture buffer into the "stop" state and stops capturing data. If the capture buffer is already in the stop state then the method has no effect.

object.Stop()

Parameters

object
Object expression that resolves to a DirectSoundCaptureBuffer object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error values:

DSERR_NODRIVER
DSERR_OUTOFMEMORY


DirectSoundCaptureBuffer.WriteBuffer

The DirectSoundCaptureBuffer.WriteBuffer method writes to a segment of the sound capture buffer from a variable holding audio data.

object.WriteBuffer(start As Long, _
    size As Long, _
    buffer As Any, _
    flags As CONST_DSCBLOCKFLAGS)

Parameters

object
Object expression that resolves to a DirectSoundCaptureBuffer object.
start
Offset, in bytes, from the start of the buffer to where the read begins.
size
Size, in bytes, of the portion of the buffer to read. Note that the sound buffer is conceptually circular. This parameter is ignored if DSCBLOCK_ENTIREBUFFER constant is set in the flags argument.
buffer
Variable with the data to be written to the sound buffer. Must be the same size as the sound buffer. You must pass the first element of the array.
flags
Pass the following constant of the CONST_DSCBLOCKFLAGS enumeration to modify what is read:
DSCBLOCK_ENTIREBUFFER
Writes to the entire buffer. The size parameter is ignored.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes:

DSERR_BUFFERLOST
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED


DirectSoundEnum

This section contains reference information for the DirectSoundEnum class used in DirectSound. DirectSoundEnum enumerates the DirectSound drivers installed on the system.

This class has the following methods:

DirectSoundEnum | GetCount
 | GetDescription
 | GetGuid
 | GetName


DirectSoundEnum.GetCount

The DirectSoundEnum.GetCount method returns the number of entries in the enumeration object.

object.GetCount() As Long

Parameters

object
Object expression that resolves to a DirectSoundEnum object.

Return Values

The number of entries in the enumeration object.

Error Codes

If the method fails, an error is raised and Err.Number may be set to one of the following error codes:

DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED


DirectSoundEnum.GetDescription

The DirectSoundEnum.GetDescription method returns the driver description of the specified DirectSound device.

object.GetDescription(index As Long) As String

Parameters

object
Object expression that resolves to a DirectSoundEnum object.
index
The particular DirectSound device in the DirectSoundEnum object.

Return Values

The driver description of the DirectSound device.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectSoundEnum.GetGuid

The DirectSoundEnum.GetGuid method return the unique identifier of the specified DirectSound device.

object.GetGuid(index As Long) As String

Parameters

object
Object expression that resolves to a DirectSoundEnum object.
index
The particular DirectSound device in the DirectSoundEnum object.

Return Values

The unique identifier of the DirectSound device.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectSoundEnum.GetName

The DirectSoundEnum.GetName returns the driver name of the specified DirectSound device.

object.GetName(index As Long) As String
object
Object expression that resolves to a DirectSoundEnum object.
index
The particular DirectDraw device in the DirectDrawEnum object.

Return Values

The driver name of the DirectSound device.

Error Codes

If the method fails, an error is raised and Err.Number will be set.


DirectSound Global Methods

The DirectX7 class is the main class of a DirectX for Visual Basic application. This class has methods that are used with all of the DirectX components. The methods pertaining to DirectSound are:

  • DirectX7.DirectSoundCaptureCreate
  • DirectX7.DirectSoundCreate
  • DirectX7.GetDSCaptureEnum
  • DirectX7.GetDSEnum


Types

This section contains reference information for the following types used with DirectSound:

  • DS3DBUFFER
  • DS3DLISTENER
  • DSBCAPS
  • DSBPOSITIONNOTIFY
  • DSBUFFERDESC
  • DSCAPS
  • DSCBCAPS
  • DSCBUFFERDESC
  • DSCCAPS
  • DSCURSORS
  • DXDRIVERINFO
  • WAVEFORMATEX


DS3DBUFFER

The DS3DBUFFER type contains all information necessary to uniquely describe the location, orientation, and motion of a 3-D sound buffer. This type is used with the DirectSound3DBuffer.GetAllParameters and DirectSound3DBuffer.SetAllParameters methods.

Type DS3DBUFFER
    lConeOutsideVolume As Long
    lInsideConeAngle As Long
    lMode As CONST_DS3DMODEFLAGS
    lOutsideConeAngle As Long
    maxDistance As Single
    minDistance As Single
    vConeOrientation As D3DVECTOR
    vPosition As D3DVECTOR
    vVelocity As D3DVECTOR
End Type

Members

lConeOutsideVolume
The cone outside volume.
lInsideConeAngle
The angle of the inside sound projection cone.
lMode
The 3-D sound processing mode to be set. One of the following constants of the CONST_DS3DMODEFLAGS enumeration:
DS3DMODE_DISABLE
3-D sound processing is disabled. The sound will appear to originate from the center of the listener's head.
DS3DMODE_HEADRELATIVE
Sound parameters (position, velocity, and orientation) are relative to the listener's parameters. In this mode, the absolute parameters of the sound are updated automatically as the listener's parameters change, so that the relative parameters remain constant.
DS3DMODE_NORMAL
Normal processing. This is the default mode.
lOutsideConeAngle
The angle of the outside sound projection cone.
maxDistance
The maximum distance.
minDistance
The minimum distance.
vConeOrientation
A D3DVECTOR type that describes the current orientation of this 3-D buffer's sound projection cone.
vPosition
A D3DVECTOR type that describes the current position of the 3-D sound buffer.
vVelocity
A D3DVECTOR type that describes the current velocity of the 3-D sound buffer.


DS3DLISTENER

The DS3DLISTENER type contains all information necessary to uniquely describe the 3-D world parameters and position of the listener. This type is used with the DirectSound3DListener.GetAllParameters and DirectSound3DListener.SetAllParameters methods.

Type DS3DLISTENER
    distanceFactor As Single
    dopplerFactor As Single
    rolloffFactor As Single
    vOrientFront As D3DVECTOR
    vOrientTop As D3DVECTOR
    vPosition As D3DVECTOR
    vVelocity As D3DVECTOR
End Type

Members

distanceFactor, dopplerFactor, and rolloffFactor
The current distance, Doppler factors, and rolloff, respectively.
vOrientFront, vOrientTop, vPosition, and vVelocity
D3DVECTOR types that describe the listener's front orientation, top orientation, position, and velocity, respectively.


DSBCAPS

The DSBCAPS type specifies the capabilities of a DirectSoundBuffer object, for use by the DirectSoundBuffer.GetCaps method.

Type DSBCAPS
    lBufferBytes As Long
    lFlags As CONST_DSBCAPSFLAGS
    lPlayCpuOverhead As Long
    lUnlockTransferRate As Long
End Type

Members

lBufferBytes
Size of this buffer, in bytes.
lFlags
One of more of the following constants of the CONST_DSBCAPSFLAGS enumeration that specify buffer-object capabilities.
DSBCAPS_CTRL3D
The buffer is either a primary buffer or a secondary buffer that uses 3-D control. To create a primary buffer, the lFlags member of the DSBUFFERDESC type should include the DSBCAPS_PRIMARYBUFFER flag.
DSBCAPS_CTRLFREQUENCY
The buffer must have frequency control capability.
DSBCAPS_CTRLPAN
The buffer must have pan control capability.
DSBCAPS_CTRLVOLUME
The buffer must have volume control capability.
DSBCAPS_CTRLPOSITIONNOTIFY
The buffer must have position notification capability. On VxD drivers, if a sound buffer is created with DSBCAPS_CTRLPOSITIONNOTIFY, this buffer will always be a software buffer. This is because the VxD driver model doesn't support the notify interface. With WDM drivers, a position notification enabled buffer may be in hardware, if hardware is available.

Calling DirectSoundBuffer.Play with the DSBPLAY_LOCHARDWARE flag will fail when playing a buffer created with this flag set. Sound buffers created with the DSBCAPS_CTRLPOSITIONNOTIFY flag must set a notification event. If you create a sound buffer with the NOTIFY flag, but don't actually set any notifications, the behavior is undefined. You may experience sounds being played back twice. Therefore, applications should not use DSBCAPS_CTRLPOSITIONNOTIFY unless they actually set a notification event.

DSBCAPS_GETCURRENTPOSITION2
Indicates that DirectSoundBuffer.GetCurrentPosition should use the new behavior of the play cursor. In DirectSound in DirectX 1, the play cursor was significantly ahead of the actual playing sound on emulated sound cards; it was directly behind the write cursor. Now, if the DSBCAPS_GETCURRENTPOSITION2 flag is specified, the application can get a more accurate play position. If this flag is not specified, the old behavior is preserved for compatibility. Note that this flag affects only emulated sound cards; if a DirectSound driver is present, the play cursor is accurate for DirectSound in all versions of DirectX.
DSBCAPS_GLOBALFOCUS
The buffer is a global sound buffer. With this flag set, an application using DirectSound can continue to play its buffers if the user switches focus to another application, even if the new application uses DirectSound. The one exception is if you switch focus to a DirectSound application that uses the DSSCL_EXCLUSIVE or DSSCL_WRITEPRIMARY flag for its cooperative level. In this case, the global sounds from other applications will not be audible.
DSBCAPS_LOCHARDWARE
The buffer is in hardware memory and uses hardware mixing.
DSBCAPS_LOCSOFTWARE
The buffer is in software memory and uses software mixing.
DSBCAPS_MUTE3DATMAXDISTANCE
The sound is reduced to silence at the maximum distance. The buffer will stop playing when the maximum distance is exceeded, so that processor time is not wasted.
DSBCAPS_PRIMARYBUFFER
Indicates that the buffer is a primary sound buffer. If this value is not specified, a secondary sound buffer will be created.
DSBCAPS_STATIC
Indicates that the buffer will be used for static sound data. Typically, these buffers are loaded once and played many times. These buffers are candidates for hardware memory.
DSBCAPS_STICKYFOCUS
Changes the focus behavior of the sound buffer. This flag can be specified in a DirectSound.CreateSoundBuffer call. With this flag set, an application using DirectSound can continue to play its sticky focus buffers if the user switches to another application not using DirectSound. In this situation, the application's normal buffers are muted, but the sticky focus buffers are still audible. This is useful for nongame applications, such as movie playback (DirectShow®), when the user wants to hear the soundtrack while typing in Microsoft Word or Microsoft® Excel, for example. However, if the user switches to another DirectSound application, all sound buffers, both normal and sticky focus, in the previous application are muted.
lPlayCpuOverhead
Specifies the processing overhead as a percentage of main processing cycles needed to mix this sound buffer. For hardware buffers, this member will be 0 because the mixing is performed by the sound device. For software buffers, this member depends on the buffer format and the speed of the system processor.
lUnlockTransferRate
Specifies the rate, in kilobytes per second, at which data is transferred to the buffer memory. High-performance applications can use this value to determine the time required for DirectSoundBuffer.Unlock to execute. For software buffers located in system memory, the rate will be very high because no processing is required. For hardware buffers, the rate might be slower because the buffer might have to be downloaded to the sound card, which might have a limited transfer rate.

Remarks

The DSBCAPS type contains information similar to that found in the DSBUFFERDESC type passed to the DirectSound.CreateSoundBuffer method, with some additional information. Additional information includes the location of the buffer (hardware or software) and some cost measures (such as the time to download the buffer if located in hardware, and the processing overhead to play the buffer if it is mixed in software).

Note The lFlags member of the DSBCAPS type contains the same flags used by the DSBUFFERDESC type. The only difference is that in the DSBCAPS type, either the DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE flag will be specified, according to the location of the buffer memory. In the DSBUFFERDESC type, these flags are optional and are used to force the buffer to be located in either hardware or software.

Sound buffers created with the DSBCAPS_CTRLPOSITIONNOTIFY flag must set a notification event. If you create a sound buffer with the NOTIFY flag, but don't actually set any notifications, the behavior is undefined. You may experience sounds being played back twice. Therefore, applications should not use DSBCAPS_CTRLPOSITIONNOTIFY unless they actually set a notification event.

See Also

DirectSound.CreateSoundBuffer, DirectSoundBuffer.GetCaps


DSBPOSITIONNOTIFY

The DSBPOSITIONNOTIFY type is used by the DirectSoundBuffer.SetNotificationPositions and DirectSoundCaptureBuffer.SetNotificationPositions methods.

Type DSBPOSITIONNOTIFY
    hEventNotify As Long
    lOffset As Long
End Type

Members

hEventNotify
Handle to the event to be signaled when the offset has been reached.
lOffset
Offset from the beginning of the buffer where the notify event is to be triggered, or DSBPN_OFFSETSTOP.

Remarks

The DSBPN_OFFSETSTOP value in the lOffset member causes the event to be signaled when playback or capture stops, either because the end of the buffer has been reached (and playback or capture is not looping) or because the application called the DirectSoundBuffer.Stop or DirectSoundCaptureBuffer.Stop method.


DSBUFFERDESC

The DSBUFFERDESC type describes the necessary characteristics of a new DirectSoundBuffer object. This type is used by the DirectSound.CreateSoundBuffer method.

Type DSBUFFERDESC
    lBufferBytes As Long
    lFlags As CONST_DSBCAPSFLAGS
End Type

Members

lBufferBytes
Size of the new buffer, in bytes. This value must be 0 when creating primary buffers. For secondary buffers, the minimum and maximum sizes allowed are specified by DSBSIZE_MIN and DSBSIZE_MAX, defined in Dsound.h.
lFlags
Identifies the capabilities to include when creating a new DirectSoundBuffer object. Specify one or more of the following constants of the CONST_DSBCAPSFLAGS enumeration:
DSBCAPS_CTRL3D
The buffer is either a primary buffer or a secondary buffer that uses 3-D control.
DSBCAPS_CTRLFREQUENCY
The buffer must have frequency control capability.
DSBCAPS_CTRLPAN
The buffer must have pan control capability.
DSBCAPS_CTRLPOSITIONNOTIFY
The buffer must have position notification capability. On VxD drivers, if a sound buffer is created with DSBCAPS_CTRLPOSITIONNOTIFY, this buffer will always be a software buffer. This is because the VxD driver model doesn't support the notify interface. With WDM drivers, a position notification enabled buffer may be in hardware, if hardware is available. Calling DirectSoundBuffer.Play with the DSBPLAY_LOCHARDWARE flag will fail when playing a buffer created with this flag set.
DSBCAPS_CTRLVOLUME
The buffer must have volume control capability.
DSBCAPS_GETCURRENTPOSITION2
Indicates that DirectSoundBuffer.GetCurrentPosition should use the new behavior of the play cursor. In DirectSound in DirectX 1, the play cursor was significantly ahead of the actual playing sound on emulated sound cards; it was directly behind the write cursor. Now, if the DSBCAPS_GETCURRENTPOSITION2 flag is specified, the application can get a more accurate play position. If this flag is not specified, the old behavior is preserved for compatibility. Note that this flag affects only emulated sound cards; if a DirectSound driver is present, the play cursor is accurate for DirectSound in all versions of DirectX.
DSBCAPS_GLOBALFOCUS
The buffer is a global sound buffer. With this flag set, an application using DirectSound can continue to play its buffers if the user switches focus to another application, even if the new application uses DirectSound. The one exception is if you switch focus to a DirectSound application that uses the DSSCL_EXCLUSIVE or DSSCL_WRITEPRIMARY flag for its cooperative level. In this case, the global sounds from other applications will not be audible.
DSBCAPS_LOCDEFER
The buffer can be assigned to a hardware or software resource during playing. This flag must be set for buffers that will use the new voice allocation and management features of DirectX 7.0.
DSBCAPS_LOCHARDWARE
Forces the buffer to use hardware mixing, even if DSBCAPS_STATIC is not specified. If the device does not support hardware mixing or if the required hardware memory is not available, the call to the DirectSound.CreateSoundBuffer method will fail. The application must ensure that a mixing channel will be available for this buffer; this condition is not guaranteed.
DSBCAPS_LOCSOFTWARE
Forces the buffer to be stored in software memory and use software mixing, even if DSBCAPS_STATIC is specified and hardware resources are available.
DSBCAPS_MUTE3DATMAXDISTANCE
The sound is to be reduced to silence at the maximum distance. The buffer will stop playing when the maximum distance is exceeded, so that processor time is not wasted.
DSBCAPS_PRIMARYBUFFER
Indicates that the buffer is a primary sound buffer. If this value is not specified, a secondary sound buffer will be created.
DSBCAPS_STATIC
Indicates that the buffer will be used for static sound data. Typically, these buffers are loaded once and played many times. These buffers are candidates for hardware memory.
DSBCAPS_STICKYFOCUS
Changes the focus behavior of the sound buffer. This flag can be specified in a DirectSound.CreateSoundBuffer call. With this flag set, an application using DirectSound can continue to play its sticky focus buffers if the user switches to another application not using DirectSound. In this situation, the application's normal buffers are muted, but the sticky focus buffers are still audible. This is useful for nongame applications, such as movie playback (DirectShow), when the user wants to hear the soundtrack while typing in Microsoft Word or Microsoft Excel, for example. However, if the user switches to another DirectSound application, all sound buffers, both normal and sticky focus, in the previous application are muted.

Remarks

The DSBCAPS_LOCHARDWARE and DSBCAPS_LOCSOFTWARE flags used in the lFlags member are optional and mutually exclusive. DSBCAPS_LOCHARDWARE forces the buffer to reside in memory located in the sound card. DSBCAPS_LOCSOFTWARE forces the buffer to reside in main system memory, if possible.

These flags are also defined for the lFlags member of the DSBCAPS type, and when used there, the specified flag indicates the actual location of the DirectSoundBuffer object.

When creating a primary buffer, applications must set the lBufferBytes member to 0; DirectSound will determine the optimal buffer size for the particular sound device in use. To determine the size of a created primary buffer, call DirectSoundBuffer.GetCaps.

The actual values for 8-bit buffered data is 0 to 256 and -32,000 to 32,000 for 16-bit buffered data.

Note Sound buffers created with the DSBCAPS_CTRLPOSITIONNOTIFY flag must set a notification event. If you create a sound buffer with the NOTIFY flag, but don't actually set any notifications, the behavior is undefined. You may experience sounds being played back twice. Therefore, applications should not use DSBCAPS_CTRLPOSITIONNOTIFY unless they actually set a notification event.

See Also

DirectSound.CreateSoundBuffer


DSCAPS

The DSCAPS type specifies the capabilities of a DirectSound device for use by the DirectSound.GetCaps method.

Type DSCAPS
    lFlags As CONST_DSCAPSFLAGS
    lFreeHw3DAllBuffers As Long
    lFreeHw3DStaticBuffers As Long
    lFreeHw3DStreamingBuffers As Long
    lFreeHwMemBytes As Long
    lFreeHwMixingAllBuffers As Long
    lFreeHwMixingStaticBuffers As Long
    lFreeHwMixingStreamingBuffers As Long
    lMaxContigFreeHwMemBytes As Long
    lMaxHw3DAllBuffers As Long
    lMaxHw3DStaticBuffers As Long
    lMaxHw3DStreamingBuffers As Long
    lMaxHwMixingAllBuffers As Long
    lMaxHwMixingStaticBuffers As Long
    lMaxHwMixingStreamingBuffers As Long
    lMaxSecondarySampleRate As Long
    lMinSecondarySampleRate As Long
    lPlayCpuOverheadSwBuffers As Long
    lPrimaryBuffers As Long
    lReserved1 As Long
    lReserved2 As Long
    lTotalHwMemBytes As Long
    lUnlockTransferRateHwBuffers As Long
End Type

Members

lFlags
Specifies device capabilities. Can be one or more of the following flags of the CONST_DSCAPSFLAGS enumeration:
DSCAPS_CERTIFIED
This driver has been tested and certified by Microsoft.
DSCAPS_CONTINUOUSRATE
The device supports all sample rates between the lMinSecondarySampleRate and lMaxSecondarySampleRate member values. Typically, this means that the actual output rate will be within +/- 10 hertz (Hz) of the requested frequency.
DSCAPS_EMULDRIVER
The device does not have a DirectSound driver installed, so it is being emulated through the waveform-audio functions. Performance degradation should be expected.
DSCAPS_PRIMARY16BIT
The device supports primary sound buffers with 16-bit samples.
DSCAPS_PRIMARY8BIT
The device supports primary buffers with 8-bit samples.
DSCAPS_PRIMARYMONO
The device supports monophonic primary buffers.
DSCAPS_PRIMARYSTEREO
The device supports stereo primary buffers.
DSCAPS_SECONDARY16BIT
The device supports hardware-mixed secondary sound buffers with 16-bit samples.
DSCAPS_SECONDARY8BIT
The device supports hardware-mixed secondary buffers with 8-bit samples.
DSCAPS_SECONDARYMONO
The device supports hardware-mixed monophonic secondary buffers.
DSCAPS_SECONDARYSTEREO
The device supports hardware-mixed stereo secondary buffers.
lFreeHw3DAllBuffers, lFreeHw3DStaticBuffers, and lFreeHw3DStreamingBuffers
Description of the free, or unallocated, hardware 3-D positional capabilities of the device.
lFreeHwMemBytes
Size, in bytes, of the free memory on the sound card.
lFreeHwMixingAllBuffers, lFreeHwMixingStaticBuffers, and lFreeHwMixingStreamingBuffers
Description of the free, or unallocated, hardware mixing capabilities of the device. An application can use these values to determine whether hardware resources are available for allocation to a secondary sound buffer. Also, by comparing these values to the members that specify maximum mixing capabilities, the resources that are already allocated can be determined.
lMaxContigFreeHwMemBytes
Size, in bytes, of the largest contiguous block of free memory on the sound card.
lMaxHw3DAllBuffers, lMaxHw3DStaticBuffers, and lMaxHw3DStreamingBuffers
Description of the hardware 3-D positional capabilities of the device.
lMaxHwMixingAllBuffers
Specifies the total number of buffers that can be mixed in hardware. This member can be less than the sum of lMaxHwMixingStaticBuffers and lMaxHwMixingStreamingBuffers. Resource tradeoffs frequently occur.
lMaxHwMixingStaticBuffers
Specifies the maximum number of static sound buffers.
lMaxHwMixingStreamingBuffers
Specifies the maximum number of streaming sound buffers.
lMaxSecondarySampleRate and lMinSecondarySampleRate
Maximum and minimum sample rate specifications that are supported by this device's hardware secondary sound buffers.
lPlayCpuOverheadSwBuffers
Description of the processing overhead, as a percentage of the central processing unit, needed to mix software buffers (those located in main system memory). This varies according to the bus type, the processor type, and the clock speed.

The unlock transfer rate for software buffers is 0 because the data need not be transferred anywhere. Similarly, the play processing overhead for hardware buffers is 0 because the mixing is done by the sound device.

lPrimaryBuffers
Number of primary buffers supported. This value will always be 1.
lReserved1 and lReserved2
Reserved for future use.
lTotalHwMemBytes
Size, in bytes, of the amount of memory on the sound card that stores static sound buffers.
lUnlockTransferRateHwBuffers
Description of the rate, in kilobytes per second, at which data can be transferred to hardware static sound buffers.

See Also

DirectSound.GetCaps


DSCBCAPS

The DSCBCAPS type is used by the DirectSoundCaptureBuffer.GetCaps method.

Type DSCBCAPS
    lBufferBytes As Long
    lFlags As CONST_DSCBCAPSFLAGS
    lReserved As Long
End Type

Members

lBufferBytes
The size, in bytes, of the capture buffer.
lFlags
Specifies device capabilities. Can be zero or the following flag from the CONST_DSCBCAPSFLAGS enumeration:
DSCBCAPS_WAVEMAPPED
The Win32 wave mapper will be used for formats not supported by the device.
lReserved
Reserved for future use.


DSCBUFFERDESC

The DSCBUFFERDESC type is used by the DirectSoundCapture.CreateCaptureBuffer method.

Type DSCBUFFERDESC
    fxFormat As WAVEFORMATEX
    lBufferBytes As Long
    lFlags As CONST_DSCBCAPSFLAGS
End Type

Members

fxFormat
Pointer to a WAVEFORMATEX type containing the format in which to capture the data.
lBufferBytes
Size of capture buffer to create, in bytes.
lFlags
Specifies device capabilities. Can be zero or one of the constants of the CONST_DSCBCAPSFLAGS enumeration.


DSCCAPS

The DSCCAPS type is used by the DirectSoundCapture.GetCaps method.

Type DSCCAPS
    lChannels As Long
    lFlags As CONST_DSCCAPSFLAGS
    lFormats As CONST_WAVEFORMATFLAGS
End Type

Members

lChannels
Number specifying the number of channels supported by the device, where 1 is mono, 2 is stereo, and so on.
lFlags
Specifies device capabilities. Can be zero or one of the following members of the CONST_DSCCAPSFLAGS enumeration:
DSCCAPS_EMULDRIVER
There is no DirectSoundCapture driver for the device, so the standard wave audio functions are being used.
lFormats
Standard formats that are supported. These are equivalent to the values in the WAVEINCAPS type used in the Win32 waveform audio functions, and are reproduced here for convenience. All of the following values are constants of the CONST_WAVEFORMATFLAGS enumeration.
Value | Meaning
WAVE_FORMAT_1M08 | 11.025 kHz, mono, 8-bit
WAVE_FORMAT_1M16 | 11.025 kHz, mono, 16-bit
WAVE_FORMAT_1S08 | 11.025 kHz, stereo, 8-bit
WAVE_FORMAT_1S16 | 11.025 kHz, stereo, 16-bit
WAVE_FORMAT_2M08 | 22.05 kHz, mono, 8-bit
WAVE_FORMAT_2M16 | 22.05 kHz, mono, 16-bit
WAVE_FORMAT_2S08 | 22.05 kHz, stereo, 8-bit
WAVE_FORMAT_2S16 | 22.05 kHz, stereo, 16-bit
WAVE_FORMAT_4M08 | 44.1 kHz, mono, 8-bit
WAVE_FORMAT_4M16 | 44.1 kHz, mono, 16-bit
WAVE_FORMAT_4S08 | 44.1 kHz, stereo, 8-bit
WAVE_FORMAT_4S16 | 44.1 kHz, stereo, 16-bit


DSCURSORS

The DSCURSORS type is used by the DirectSoundBuffer.GetCurrentPosition and DirectSoundCaptureBuffer.GetCurrentPosition methods.

Type DSCURSORS
    lPlay As Long
    lWrite As Long
End Type

Members

lPlay
The current play position in the DirectSoundBuffer or DirectSoundCaptureBuffer object. This position is an offset within the sound buffer and is specified in bytes.
lWrite
The current write position in the DirectSoundBuffer or DirectSoundCaptureBuffer object. This position is an offset within the sound buffer and is specified in bytes.

See Also

DirectSound


DXDRIVERINFO

The DXDRIVERINFO type is used in the enumeration methods for DirectDraw, DirectSound and Direct3D to hold driver information.

Type DXDRIVERINFO
    strDescription As String
    strGuid As String
    strName As String
End Type

Members

strDescription
The textual description of the DirectSound device.
strGuid
The GUID that identifies the DirectSound driver being enumerated.
strName
The name of the DirectSound driver corresponding to this device.

Remarks

This type is also used in DirectDraw and Direct3D.


WAVEFORMATEX

The WAVEFORMATEX type defines the format of waveform-audio data. Only format information common to all waveform-audio data formats is included in this type. For formats that require additional information, this structure is included as the first member in another structure, along with the additional information.

Type WAVEFORMATEX
    lAvgBytesPerSec As Long
    lExtra As Long
    lSamplesPerSec As Long
    nBitsPerSample As Integer
    nBlockAlign As Integer
    nChannels As Integer
    nFormatTag As Integer
    nSize As Integer
End Type

Members

lAvgBytesPerSec
Required average data-transfer rate, in bytes per second, for the format. If nFormatTag is WAVE_FORMAT_PCM, nAvgBytesPerSec should be equal to the product of lSamplesPerSec and nBlockAlign. For non-PCM formats, this member must be computed according to the manufacturer's specification of the format tag.

Playback and record software can estimate buffer sizes by using the lAvgBytesPerSec member.

lExtra
This member is not used and should be set to 0.
lSamplesPerSec
Sample rate, in samples per second (hertz), that each channel should be played or recorded. If nFormatTag is WAVE_FORMAT_PCM, then common values for lSamplesPerSec are 8.0 kHz, 11.025 kHz, 22.05 kHz, and 44.1 kHz. For non-PCM formats, this member must be computed according to the manufacturer's specification of the format tag.
nBitsPerSample
Bits per sample for the nFormatTag format type. If nFormatTag is WAVE_FORMAT_PCM, then wBitsPerSample should be equal to 8 or 16. The actual values for 8-bit buffered data is 0 to 256 and -32,000 to 32,000 for 16-bit buffered data. For non-PCM formats, this member must be set according to the manufacturer's specification of the format tag. Note that some compression schemes cannot define a value for nBitsPerSample, so this member can be zero.
nBlockAlign
Block alignment, in bytes. The block alignment is the minimum atomic unit of data for the nFormatTag format type. If nFormatTag is WAVE_FORMAT_PCM, nBlockAlign should be equal to the product of nChannels and nBitsPerSample divided by 8 (bits per byte). For non-PCM formats, this member must be computed according to the manufacturer's specification of the format tag.

Playback and record software must process a multiple of nBlockAlign bytes of data at a time. Data written and read from a device must always start at the beginning of a block. For example, it is illegal to start playback of PCM data in the middle of a sample (that is, on a non-block-aligned boundary).

nChannels
Number of channels in the waveform-audio data. Monaural data uses one channel and stereo data uses two channels.
nFormatTag
Waveform-audio format type. Format tags are registered with Microsoft Corporation for many compression algorithms. A complete list of format tags can be found in the MMREG.H header file.
nSize
Size, in bytes, of extra format information appended to the end of the WAVEFORMATEX type. This information can be used by non-PCM formats to store extra attributes for the nFormatTag. If no extra information is required by the nFormatTag, this member must be set to zero. Note that for WAVE_FORMAT_PCM formats (and only WAVE_FORMAT_PCM formats), this member is ignored.


Enumerations

DirectSound uses enumerations to group constants to take advantage of the statement completion feature of Visual Basic. The enumerations used in DirectSound are:

  • CONST_DS3DAPPLYFLAGS
  • CONST_DS3DMODEFLAGS
  • CONST_DSBCAPSFLAGS
  • CONST_DSBLOCKFLAGS
  • CONST_DSBPLAYFLAGS
  • CONST_DSBSTATUSFLAGS
  • CONST_DSCAPSFLAGS
  • CONST_DSCBCAPSFLAGS
  • CONST_DSCBLOCKFLAGS
  • CONST_DSCBSTARTFLAGS
  • CONST_DSCBSTATUSFLAGS
  • CONST_DSCCAPSFLAGS
  • CONST_DSOUND
  • CONST_DSSCLFLAGS
  • CONST_DSSPEAKERFLAGS
  • CONST_WAVEFORMATFLAGS


CONST_DS3DAPPLYFLAGS

The CONST_DS3DAPPLYFLAGS enumeration is used as a parameter for numerous methods of the DirectSound3DBuffer and DirectSound3DListener class. The members of this enumeration are used to specify when settings should be applied to DirectSound3DBuffer and DirectSound3DListener objects.

Enum CONST_DS3DAPPLYFLAGS
    DS3D_DEFERRED  = 1
    DS3D_IMMEDIATE = 0
End Enum
DS3D_DEFERRED
Settings are not applied until the application calls the DirectSound3DListener.CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.


CONST_DS3DMODEFLAGS

The CONST_DS3DMODEFLAGS enumeration is used by the DirectSound3DBuffer.GetMode and DirectSound3DBuffer.SetMode methods to set and retrieve the current operation mode for the 3-D sound processing.

Enum CONST_DS3DMODEFLAGS
    DS3DMODE_DISABLE      = 2
    DS3DMODE_HEADRELATIVE = 1
    DS3DMODE_NORMAL       = 0
End Enum
DS3DMODE_DISABLE
Processing of 3-D sound is disabled. The sound seems to originate from the center of the listener's head.
DS3DMODE_HEADRELATIVE
Sound parameters (position, velocity, and orientation) are relative to the listener's parameters. In this mode, the absolute parameters of the sound are updated automatically as the listener's parameters change, so that the relative parameters remain constant.
DS3DMODE_NORMAL
Normal processing. This is the default mode.


CONST_DSBCAPSFLAGS

The CONST_DSBCAPSFLAGS enumeration is used in the lFlags member of the DSBCAPS and DSBUFFERDESC types to specify buffer-object capabilities.

Enum CONST_DSBCAPSFLAGS
    DSBCAPS_CTRL3D              =     16 (&H10)
    DSBCAPS_CTRLFREQUENCY       =     32 (&H20)
    DSBCAPS_CTRLPAN             =     64 (&H40)
    DSBCAPS_CTRLPOSITIONNOTIFY  =    256
    DSBCAPS_CTRLVOLUME          =    128 (&H80)
    DSBCAPS_GETCURRENTPOSITION2 =  65536 (&H10000)
    DSBCAPS_GLOBALFOCUS         =  32768 (&H8000)
    DSBCAPS_LOCHARDWARE         =      4
    DSBCAPS_LOCSOFTWARE         =      8
    DSBCAPS_MUTE3DATMAXDISTANCE = 131072 (&H20000)
    DSBCAPS_PRIMARYBUFFER       =      1
    DSBCAPS_STATIC              =      2
    DSBCAPS_STICKYFOCUS         =  16384 (&H4000)
End Enum
DSBCAPS_CTRL3D
The buffer is either a primary buffer or a secondary buffer that uses 3-D control.
DSBCAPS_CTRLFREQUENCY
The buffer must have frequency control capability.
DSBCAPS_CTRLPAN
The buffer must have pan control capability.
DSBCAPS_CTRLPOSITIONNOTIFY
The buffer must have position notification capability. On VxD drivers, if a sound buffer is created with DSBCAPS_CTRLPOSITIONNOTIFY, this buffer will always be a software buffer. This is because the VxD driver model doesn't support the notify interface. With WDM drivers, a position notification enabled buffer may be in hardware, if hardware is available. Calling DirectSoundBuffer.Play with the DSBPLAY_LOCHARDWARE flag will fail when playing a buffer created with this flag set.

Sound buffers created with the DSBCAPS_CTRLPOSITIONNOTIFY flag must set a notification event. If you create a sound buffer with the NOTIFY flag, but don't actually set any notifications, the behavior is undefined. You may experience sounds being played back twice. Therefore, applications should not use DSBCAPS_CTRLPOSITIONNOTIFY unless they actually set a notification event.

DSBCAPS_CTRLVOLUME
The buffer must have volume control capability.
DSBCAPS_GETCURRENTPOSITION2
Indicates that DirectSoundBuffer.GetCurrentPosition should use the new behavior of the play cursor. In DirectSound in DirectX 1, the play cursor was significantly ahead of the actual playing sound on emulated sound cards; it was directly behind the write cursor. Now, if the DSBCAPS_GETCURRENTPOSITION2 flag is specified, the application can get a more accurate play position. If this flag is not specified, the old behavior is preserved for compatibility. Note that this flag affects only emulated sound cards; if a DirectSound driver is present, the play cursor is accurate for DirectSound in all versions of DirectX.
DSBCAPS_GLOBALFOCUS
The buffer is a global sound buffer. With this flag set, an application using DirectSound can continue to play its buffers if the user switches focus to another application, even if the new application uses DirectSound. The one exception is if you switch focus to a DirectSound application that uses the DSSCL_EXCLUSIVE or DSSCL_WRITEPRIMARY flag for its cooperative level. In this case, the global sounds from other applications will not be audible.
DSBCAPS_LOCHARDWARE
Forces the buffer to use hardware mixing, even if DSBCAPS_STATIC is not specified. If the device does not support hardware mixing or if the required hardware memory is not available, the call to the DirectSound.CreateSoundBuffer method will fail. The application must ensure that a mixing channel will be available for this buffer; this condition is not guaranteed.
DSBCAPS_LOCSOFTWARE
Forces the buffer to be stored in software memory and use software mixing, even if DSBCAPS_STATIC is specified and hardware resources are available.
DSBCAPS_MUTE3DATMAXDISTANCE
The sound is to be reduced to silence at the maximum distance. The buffer will stop playing when the maximum distance is exceeded, so that processor time is not wasted.
DSBCAPS_PRIMARYBUFFER
Indicates that the buffer is a primary sound buffer. If this value is not specified, a secondary sound buffer will be created.
DSBCAPS_STATIC
Indicates that the buffer will be used for static sound data. Typically, these buffers are loaded once and played many times. These buffers are candidates for hardware memory.
DSBCAPS_STICKYFOCUS
Changes the focus behavior of the sound buffer. This flag can be specified in a DirectSound.CreateSoundBuffer call. With this flag set, an application using DirectSound can continue to play its sticky focus buffers if the user switches to another application not using DirectSound. In this situation, the application's normal buffers are muted, but the sticky focus buffers are still audible. This is useful for nongame applications, such as movie playback (DirectShow), when the user wants to hear the soundtrack while typing in Microsoft Word or Microsoft Excel, for example. However, if the user switches to another DirectSound application, all sound buffers, both normal and sticky focus, in the previous application are muted.


CONST_DSBLOCKFLAGS

The CONST_DSBLOCKFLAGS enumeration is used in the flags parameter of the DirectSoundBuffer.ReadBuffer method to modify what is read or written from the sound buffer.

Enum CONST_DSBLOCKFLAGS
    DSBLOCK_DEFAULT         = 0
    DSBLOCK_ENTIREBUFFER    = 2
    DSBLOCK_FROMWRITECURSOR = 1
End Enum
DSBLOCK_DEFAULT
Reads or writes from the position specified in the start parameter.
DSBLOCK_FROMWRITECURSOR
Reads or writes from the current read/write position, making a call to DirectSoundBuffer.GetCurrentPosition method unnecessary. If this flag is specified, the start parameter is ignored.
DSBLOCK_ENTIREBUFFER
Reads from or writes to the entire buffer. The size parameter is ignored.


CONST_DSBPLAYFLAGS

The CONST_DSBPLAYFLAGS enumeration is used in flags parameter of the DirectSoundBuffer.Play method to specify how to play the buffer.

Enum CONST_DSBPLAYFLAGS
    DSBPLAY_DEFAULT = 0
    DSBPLAY_LOOPING = 1
End Enum
DSBPLAY_DEFAULT
Plays from the cursor position to the end of audio buffer.
DSBPLAY_LOOPING
Once the end of the audio buffer is reached, play restarts at the beginning of the buffer. Play continues until explicitly stopped. This flag must be set when playing primary sound buffers.


CONST_DSBSTATUSFLAGS

The CONST_DSBSTATUSFLAGS enumeration is used as a return value for the DirectSoundBuffer.GetStatus method to retrieve the status of the sound buffer.

Enum CONST_DSBSTATUSFLAGS
    DSBSTATUS_BUFFERLOST = 2
    DSBSTATUS_LOOPING    = 4
    DSBSTATUS_PLAYING    = 1
End Enum
DSBSTATUS_BUFFERLOST
The buffer is lost and must be restored before it can be played or locked.
DSBSTATUS_LOOPING
The buffer is being looped. If this value is not set, the buffer will stop when it reaches the end of the sound data. Note that if this value is set, the buffer must also be playing.
DSBSTATUS_PLAYING
The buffer is playing. If this value is not set, the buffer is stopped.


CONST_DSCAPSFLAGS

The CONST_DSCAPSFLAGS enumeration is used in the lFlags member of the DSCAPS type for specific device capabilities.

Enum CONST_DSCAPSFLAGS
    DSCAPS_CERTIFIED       =   64 (&H40)
    DSCAPS_CONTINUOUSRATE  =   16 (&H10)
    DSCAPS_EMULDRIVER      =   32 (&H20)
    DSCAPS_PRIMARY16BIT    =    8
    DSCAPS_PRIMARY8BIT     =    4
    DSCAPS_PRIMARYMONO     =    1
    DSCAPS_PRIMARYSTEREO   =    2
    DSCAPS_SECONDARY16BIT  = 2048 (&H800)
    DSCAPS_SECONDARY8BIT   = 1024 (&H400)
    DSCAPS_SECONDARYMONO   =  256 (&H100)
    DSCAPS_SECONDARYSTEREO =  512 (&H200)
End Enum
DSCAPS_CERTIFIED
This driver has been tested and certified by Microsoft.
DSCAPS_CONTINUOUSRATE
The device supports all sample rates between the lMinSecondarySampleRate and lMaxSecondarySampleRate member values. Typically, this means that the actual output rate will be within +/- 10 hertz (Hz) of the requested frequency.
DSCAPS_EMULDRIVER
The device does not have a DirectSound driver installed, so it is being emulated through the waveform-audio functions. Performance degradation should be expected.
DSCAPS_PRIMARY16BIT
The device supports primary sound buffer with 16-bit samples.
DSCAPS_PRIMARY8BIT
The device supports primary buffers with 8-bit samples.
DSCAPS_PRIMARYMONO
The device supports monophonic primary buffers.
DSCAPS_PRIMARYSTEREO
The device supports stereo primary buffers.
DSCAPS_SECONDARY16BIT
The device supports hardware-mixed secondary sound buffers with 16-bit samples.
DSCAPS_SECONDARY8BIT
The device supports hardware-mixed secondary buffers with 8-bit samples.
DSCAPS_SECONDARYMONO
The device supports hardware-mixed monophonic secondary buffers.
DSCAPS_SECONDARYSTEREO
The device supports hardware-mixed stereo secondary buffers.


CONST_DSCBCAPSFLAGS

The CONST_DSCBCAPSFLAGS enumeration is used in the lFlags member of the DSCBCAPS type to specify device capabilities.

Enum CONST_DSCBCAPSFLAGS
    DSCBCAPS_DEFAULT    = 0
    DSCBCAPS_WAVEMAPPED = -2147483648 (&H80000000)
End Enum
DSCBCAPS_WAVEMAPPED
The Win32 wave mapper will be used for formats not supported by the device.


CONST_DSCBLOCKFLAGS

The CONST_DSCBLOCKFLAGS enumeration is used by the DirectSoundCaptureBuffer.ReadBuffer and DirectSoundCaptureBuffer.WriteBuffer methods to modify what is read from or written to the sound capture buffer.

Enum CONST_DSCBLOCKFLAGS
    DSCBLOCK_DEFAULT      = 0
    DSCBLOCK_ENTIREBUFFER = 1
End Enum
DSCBLOCK_ENTIREBUFFER
Reads/writes the entire buffer. The size parameter is ignored.


CONST_DSCBSTARTFLAGS

The CONST_DSCBSTARTFLAGS enumeration is used by the flags member of the DirectSoundCaptureBuffer.Start method to specify the behavior of the capture buffer when capturing sound data.

Enum CONST_DSCBSTARTFLAGS
    DSCBSTART_DEFAULT = 0
    DSCBSTART_LOOPING = 1
End Enum
DSCBSTART_LOOPING
Once the end of the buffer is reached, capture restarts at the beginning and continues until explicitly stopped.


CONST_DSCBSTATUSFLAGS

The CONST_DSCBSTATUSFLAGS enumeration is used as a return value for the DirectSoundCaptureBuffer.GetStatus method to obtain the current status of the capture buffer.

Enum CONST_DSCBSTATUSFLAGS
    DSCBSTATUS_CAPTURING = 1
    DSCBSTATUS_LOOPING   = 2
End Enum
DSCBSTATUS_CAPTURING
The capture buffer is currently capturing sound data.
DSCBSTATUS_LOOPING
The capture buffer is currently capturing sound data and the data is looping in the buffer.


CONST_DSCCAPSFLAGS

The CONST_DSCCAPSFLAGS enumeration is used in the lFlags member of the DSCCAPS type to specify DirectSound capture device capabilities.

Enum CONST_DSCCAPSFLAGS
    DSCCAPS_DEFAULT    = 0
    DSCCAPS_EMULDRIVER = 32 (&H20)
End Enum
DSCCAPS_EMULDRIVER
There is no DirectSoundCapture driver for the device, so the standard wave audio functions are being used.


CONST_DSOUND

The CONST_DSOUND enumeration is contains constants used throughout DirectSound.

Enum
    DS3D_DEFAULTCONEANGLE         = 360 (&H168)
    DS3D_DEFAULTCONEOUTSIDEVOLUME = 0
    DS3D_DEFAULTDISTANCEFACTOR    = 1
    DS3D_DEFAULTDOPPLERFACTOR     = 1
    DS3D_DEFAULTMAXDISTANCE       = 1000000000 (&H3B9ACA00)
    DS3D_DEFAULTMINDISTANCE       = 1
    DS3D_DEFAULTROLLOFFFACTOR     = 1
    DS3D_MAXCONEANGLE             = 360 (&H168)
    DS3D_MAXDISTANCEFACTOR        = 10
    DS3D_MAXDOPPLERFACTOR         = 10
    DS3D_MAXROLLOFFFACTOR         = 10
    DS3D_MINCONEANGLE             = 0
    DS3D_MINDISTANCEFACTOR        = 0
    DS3D_MINDOPPLERFACTOR         = 0
    DS3D_MINROLLOFFFACTOR         = 0
    DSBFREQUENCY_MAX              = 100000 (&H186A0)
    DSBFREQUENCY_MIN              = 100 (&H64)
    DSBFREQUENCY_ORIGINAL         = 0
    DSBPAN_CENTER                 = 0
    DSBPAN_LEFT                   = -10000 (&HFFFFD8F0)
    DSBPAN_RIGHT                  = 10000 (&H2710)
    DSBPN_OFFSETSTOP              = -1 (&HFFFFFFFF)
    DSBSIZE_MAX                   = 268435455 (&HFFFFFFF)
    DSBSIZE_MIN                   = 4
    DSBVOLUME_MAX                 = 0
    DSBVOLUME_MIN                 = -10000 (&HFFFFD8F0)
    WAVE_FORMAT_PCM               = 1
End Enum


CONST_DSSCLFLAGS

The CONST_DSSCLFLAGS enumeration is used in the level parameter of the DirectSound.SetCooperativeLevel method to specify the priority level.

Enum CONST_DSSCLFLAGS
    DSSCL_EXCLUSIVE    = 3
    DSSCL_NORMAL       = 1
    DSSCL_PRIORITY     = 2
    DSSCL_WRITEPRIMARY = 4
End Enum
DSSCL_EXCLUSIVE
Sets the application to the exclusive level. When it has the input focus, the application will be the only one audible (sounds from applications with the DSBCAPS_GLOBALFOCUS flag set will be muted). With this level, it also has all the privileges of the DSSCL_PRIORITY level. DirectSound will restore the hardware format, as specified by the most recent call to the DirectSoundBuffer.SetFormat method, once the application gains the input focus. (Note that DirectSound will always restore the wave format no matter what priority level is set.)
DSSCL_NORMAL
Sets the application to a fully cooperative status. This level has the smoothest multitasking and resource-sharing behavior, but because it does not allow the primary buffer format to change, output is restricted to the default 8-bit format.
DSSCL_PRIORITY
Sets the application to the priority level. Applications with this cooperative level can call the DirectSoundBuffer.SetFormat method.
DSSCL_WRITEPRIMARY
This is the highest priority level. The application has write access to the primary sound buffers. No secondary sound buffers can be played. This level cannot be set if the DirectSound driver is being emulated for the device; that is, if the DirectSound.GetCaps method returns the DSCAPS_EMULDRIVER flag in the DSCAPS type.


CONST_DSSPEAKERFLAGS

The CONST_DSSPEAKERFLAGS enumeration is used by the DirectSound.GetSpeakerConfig and DirectSound.SetSpeakerConfig method to specify the speaker configuration.

Enum CONST_DSSPEAKERFLAGS
    DSSPEAKER_GEOMETRY_MAX    = 180 (&HB4)
    DSSPEAKER_GEOMETRY_MIN    =   5
    DSSPEAKER_GEOMETRY_NARROW =  10
    DSSPEAKER_GEOMETRY_WIDE   =  20 (&H14)
    DSSPEAKER_HEADPHONE       =   1
    DSSPEAKER_MONO            =   2
    DSSPEAKER_QUAD            =   3
    DSSPEAKER_STEREO          =   4
    DSSPEAKER_SURROUND        =   5
End Enum

DSSPEAKER_STEREO may be combined with one of the following values:

DSSPEAKER_GEOMETRY_MAX
The speakers are directed over an arc of 180 degrees.
DSSPEAKER_GEOMETRY_MIN
The speakers are directed over an arc of 5 degrees.
DSSPEAKER_GEOMETRY_NARROW
The speakers are directed over an arc of 10 degrees.
DSSPEAKER_GEOMETRY_WIDE
The speakers are directed over an arc of 20 degrees.
DSSPEAKER_HEADPHONE
The speakers are headphones.
DSSPEAKER_MONO
The speakers are monaural.
DSSPEAKER_QUAD
The speakers are quadraphonic.
DSSPEAKER_STEREO
The speakers are stereo (default value).
DSSPEAKER_SURROUND
The speakers are surround sound.


CONST_WAVEFORMATFLAGS

The CONST_WAVEFORMATFLAGS enumeration is used in the lFormats member of the DSCCAPS type to specify the standard formats that are supported.

Enum CONST_WAVEFORMATFLAGS
    WAVE_FORMAT_1M08 =    1
    WAVE_FORMAT_1M16 =    4
    WAVE_FORMAT_1S08 =    2
    WAVE_FORMAT_1S16 =    8
    WAVE_FORMAT_2M08 =   16 (&H10)
    WAVE_FORMAT_2M16 =   64 (&H40)
    WAVE_FORMAT_2S08 =   32 (&H20)
    WAVE_FORMAT_2S16 =  128 (&H80)
    WAVE_FORMAT_4M08 =  256 (&H100)
    WAVE_FORMAT_4M16 = 1024 (&H400)
    WAVE_FORMAT_4S08 =  512 (&H200)
    WAVE_FORMAT_4S16 = 2048 (&H800)
End Enum

Value | Meaning
WAVE_FORMAT_1M08 | 11.025 kHz, mono, 8-bit
WAVE_FORMAT_1M16 | 11.025 kHz, mono, 16-bit
WAVE_FORMAT_1S08 | 11.025 kHz, stereo, 8-bit
WAVE_FORMAT_1S16 | 11.025 kHz, stereo, 16-bit
WAVE_FORMAT_2M08 | 22.05 kHz, mono, 8-bit
WAVE_FORMAT_2M16 | 22.05 kHz, mono, 16-bit
WAVE_FORMAT_2S08 | 22.05 kHz, stereo, 8-bit
WAVE_FORMAT_2S16 | 22.05 kHz, stereo, 16-bit
WAVE_FORMAT_4M08 | 44.1 kHz, mono, 8-bit
WAVE_FORMAT_4M16 | 44.1 kHz, mono, 16-bit
WAVE_FORMAT_4S08 | 44.1 kHz, stereo, 8-bit
WAVE_FORMAT_4S16 | 44.1 kHz, stereo, 16-bit


Error Codes

Errors are represented by negative values and cannot be combined. This table lists the values that can be returned by all DirectSound and DirectSoundBuffer methods. For a list of the error codes each method can return, see the individual method descriptions.

DS_OK
The request completed successfully.
DSERR_ALLOCATED
The request failed because resources, such as a priority level, were already in use by another caller.
DSERR_ALREADYINITIALIZED
The object is already initialized.
DSERR_BADFORMAT
The specified wave format is not supported.
DSERR_BUFFERLOST
The buffer memory has been lost and must be restored.
DSERR_CONTROLUNAVAIL
The control (volume, pan, and so forth) requested by the caller is not available.
DSERR_GENERIC
An undetermined error occurred inside the DirectSound subsystem.
DSERR_INVALIDCALL
This function is not valid for the current state of this object.
DSERR_INVALIDPARAM
An invalid parameter was passed to the returning function.
DSERR_NOAGGREGATION
The object does not support aggregation.
DSERR_NODRIVER
No sound driver is available for use.
DSERR_NOINTERFACE
The requested COM interface is not available.
DSERR_OTHERAPPHASPRIO
Another application has a higher priority level, preventing this call from succeeding.
DSERR_OUTOFMEMORY
The DirectSound subsystem could not allocate sufficient memory to complete the caller's request.
DSERR_PRIOLEVELNEEDED
The caller does not have the priority level required for the function to succeed.
DSERR_UNINITIALIZED
The DirectSound device has not been initialized.
DSERR_UNSUPPORTED
The function called is not supported at this time.


DirectSound Tools and Samples

This section describes sample applications included with the DirectX SDK that demonstrate the use of DirectSound. Descriptions are organized as follows:

  • DirectSound Tools
  • DirectSound C/C++ Samples
  • DirectSound Visual Basic Samples


DirectSound Tools

This section contains information on the following application that can be used to test DirectSound capabilities:

  • DSShow3D


DSShow3D

Description

DSShow3D allows you to modify the parameters of sound buffers and the 3-D listener.

Path

Executable: (SDK root)\Samples\Multimedia\DSound\Bin

User's Guide

Using Open from the File menu, you can open one or more short sound files and play them at the same time. Note that you must select Create as a 3D Buffer in the File Open dialog in order to have access to 3-D properties. To ensure that this option is set automatically in future sessions, choose Settings from the Options menu and select Open 3D as Default.

You can also load files by dragging them onto the program's icon, or from the command line using the following syntax:

DSShow3D [/PLAY [/LOOP]] [file] [file] ...

Specifying /PLAY causes any specified files to be played as they're opened. Adding /LOOP causes them to loop as well, but /LOOP without /PLAY means nothing. File names can be enclosed in quotation marks.

For each wave file that you open, DSShow3D displays a group of buffer controls in a client window. The listener settings, which apply to all 3-D buffers, are shown in a separate window.

To play the sound, click the Play button in its window. To play it continuously, press the Looped button. You can create a duplicate of the sound buffer by choosing Duplicate! from the client window's menu.

To close a buffer, choose Close from the buffer's File menu, or simply close the window.

You can change the format of the primary buffer by choosing Output Format from the Options menu in the main window. On the same menu, Settings lets you choose preferences that will take effect next time the application is started.

Changes made in the 3DListener Object Settings window do not take effect until you click the Commit button.


DirectSound C/C++ Samples

[Visual Basic]

This section pertains only to application development in C and C++. See DirectSound Visual Basic Samples.

[C++]

This section provides summaries of the applications in the DirectX SDK that are primarily intended to demonstrate the DirectSound component. The following sample programs demonstrate the use and capabilities of DirectSound:

  • AdjustSound Sample
  • CaptureSound Sample
  • EnumDevices Sample
  • FullDuplexFilter Sample
  • Play3DSound Sample
  • PlaySound Sample
  • PlayStreaming Sample
  • VoiceManagement Sample

Although DirectX samples include Microsoft® Visual C++® project workspace files, you might need to verify other settings in your development environment to ensure that the samples compile properly. For more information, see Compiling DirectX Samples and Other DirectX Applications.


AdjustSound Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectSound Visual Basic Samples.

[C++]

Description

AdjustSound illustrates how to play a wave file using a static DirectSound buffer, and how to set the focus, frequency, pan, and volume.

Path

Source: (SDK root)\Samples\Multimedia\DSound\Src\AdjustSound

Executable: (SDK root)\Samples\Multimedia\DSound\Bin\AdjustSound.exe

User's Guide

Click Sound File and load a wave file. Choose settings and click Play. You can change settings as the sound is playing.

Programming Notes

The sample shows basic techniques of using a 2-D secondary buffer.


CaptureSound Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectSound Visual Basic Samples.

[C++]

Description

The CaptureSound program demonstrates how to use DirectSound to capture sound to a wave file.

A microphone or other audio input is required.

Path

Source: (SDK root)\Samples\Multimedia\DSound\Src\CaptureSound

Executable: (SDK root)\Samples\Multimedia\DSound\Bin\CaptureSound.exe

User's Guide

Highlight a capture format and click OK. Click Sound File and either open an existing file or create a new one. Click Record to start recording, and click it again to stop.

Programming Notes

The sample shows basic techniques of capturing sound and writing to a wave file.


EnumDevices Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectSound Visual Basic Samples.

[C++]

Description

The EnumDevices program shows how to enumerate DirectSound and DirectSoundCapture devices.

Path

Source: (SDK root)\Samples\Multimedia\DSound\Src\EnumDevices

Executable: (SDK root)\Samples\Multimedia\DSound\Bin\EnumDevices.exe

User's Guide

Select playback and capture devices from the dropdown lists and click Create.

Programming Notes

The sample code demonstrates the use of the DirectSoundEnumerate, DirectSoundCreate, DirectSoundCaptureEnumerate, and DirectSoundCaptureCreate functions.


FullDuplexFilter Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectSound Visual Basic Samples.

[C++]

Description

The FullDuplexFilter program demonstrates how to use DirectSound to implement full duplex audio and a filter.

A microphone or other audio input is required.

Path

Source: (SDK root)\Samples\Multimedia\DSound\Src\FullDuplexFilter

Executable: (SDK root)\Samples\Multimedia\DSound\Bin\FullDuplexFilter.exe

User's Guide

Highlight a format for the input buffer and then one for the output buffer. Click OK.

The program then shows a dialog box where you can enable the optional filter and start capture and playback.

Programming Notes

The sample is designed primarily to show the proper sequence of steps for dealing with the sound devices installed on the system for using full-duplex audio with waveIn as an input source and DirectSound as the output device.


Play3DSound Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectSound Visual Basic Samples.

[C++]

Description

This application shows how to play a wave file with 3-D positioning using DirectSound.

Path

Source: Mssdk\Samples\Multimedia\DSound\Src\Play3DSound

Executable: Mssdk\Samples\Multimedia\DSound\Bin\Play3DSound.exe

User's Guide

Click the Sound File button to load a wave file, and select an option in the Select 3-D Algorithm dialog box. Click Play to play the sound with looping. Adjust the playback properties by using the sliders. Click Defer if you do not want changes to be applied immediately; you can adjust the frequency at which new settings are committed by using the slider beside the button. The position of the sound source in relation to the listener is displayed as a red dot on the graph. Adjust the range of the sound's movement by using the sliders below and beside the graph.

Programming Notes

The sample shows the basics of playing a sound using the 3-D features of DirectSound, and how to use IDirectSound3DListener::CommitDeferredSettings to change multiple parameters at the same time.


PlaySound Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectSound Visual Basic Samples.

[C++]

Description

This sample shows how to play a wave file using a static DirectSoundBuffer.

Path

Source: Mssdk\Samples\Multimedia\DSound\Src\PlaySound

Executable: Mssdk\Samples\Multimedia\DSound\Bin\PlaySound.exe

User's Guide

Click the Sound File button to load a wave file, and click Play to play the sound. Select Loop in order to play the sound repeatedly.

Programming Notes

Compare the PlayStreaming Sample, which uses streaming buffers.


PlayStreaming Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectSound Visual Basic Samples.

[C++]

Description

This sample shows how to play a wave file using a streaming DirectSoundBuffer.

Path

Source: (SDK root)\Samples\Multimedia\DSound\Src\PlayStreaming

Executable: (SDK root)\Samples\Multimedia\DSound\Bin\PlayStreaming.exe

User's Guide

Click the Sound File button to load a wave file, and click Play to play the sound. Select Loop in order to play the sound repeatedly.

Programming Notes

Compare the PlaySound Sample, which uses static buffers.


VoiceManagement Sample

[Visual Basic]

This topic pertains only to application development in C and C++. See DirectSound Visual Basic Samples.

[C++]

Description

This sample shows how to use the voice allocation and voice management flags when playing a DirectSound buffer.

Path

Source: (SDK root)\Samples\Multimedia\DSound\Src\VoiceManagement

Executable: (SDK root)\Samples\Multimedia\DSound\Bin\VoiceManagement.exe

User's Guide

Click the Sound File button to load a wave file. Select voice management options. (The selected options are explained in the Expected Behavior frame.) Select Loop if you want to play the sound repeatedly. Click Play to begin playing the sound.

Programming Notes

The buffer must be created using the DSBCAPS_LOCDEFER flag. Otherwise DirectSound will not be able to dynamically place the buffer in either hardware or software at run time.


DirectSound Visual Basic Samples

[C++]

This section pertains only to application development in Visual Basic. See DirectSound C/C++ Samples.

[Visual Basic]

This section provides summaries of the applications in the DirectX SDK that are primarily intended to demonstrate the DirectSound component. The following sample programs demonstrate the use and capabilities of DirectSound:

  • Capture Sample
  • Full Duplex Sample
  • Memo Sample
  • PlaySound Sample
  • SoundMix Sample
  • StreamFrom Sample
  • StreamTo Sample

See Also

DirectSound Visual Basic Tutorials


Capture Sample

[C++]

This topic pertains only to application development in Visual Basic. See DirectSound C/C++ Samples.

[Visual Basic]

Description

The Capture application shows how to capture sound from the wave input device, typically a sound card with a microphone attached.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DSound\Src\Capture

Executable: (SDK root)\Samples\Multimedia\VBSamples\DSound\Bin\Capture.exe

User's Guide

Click Record and capture up to 20 seconds of sound, then click Stop. You can play back the buffer and save it to a wave file.

Programming Notes

In order to save the sound data, the program must copy it to an output buffer so that the DirectSoundBuffer.SaveToFile method can be used.


Full Duplex Sample

[C++]

This topic pertains only to application development in Visual Basic. See DirectSound C/C++ Samples.

[Visual Basic]

Description

The Full Duplex application shows how to capture and play a sound at the same time.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DSound\Src\Fullduplex

Executable: (SDK root)\Samples\Multimedia\VBSamples\DSound\Bin\Fullduplex.exe

User's Guide

In the Select Device dialog box, choose an input and output device. Note that in order to use your sound card for simultaneous playing and recording, you may have to change the settings in Control Panel.

In the Select Formats dialog box, select an input format. Compatible output formats are then listed. Choose one of these.

In the Full Duplex window, click Run to start capture and playback.

Programming Notes

The capture and playback buffers are the same size, so the application needs to keep only a single pointer when reading from the one and copying to the other.


Memo Sample

[C++]

This topic pertains only to application development in Visual Basic. See DirectSound C/C++ Samples.

[Visual Basic]

Description

The Memo sample allows recording of voice memos to be stored in a database.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DSound\Src\Memo

Executable: None.

User's Guide

You must have Microsoft Data Access Components installed on the system in order to run this application.

Change months on the calendar by using the arrow buttons or by clicking on a gray date in the previous or next month. Double-click on a date in the current month in order to display the Current Memo dialog box for that date. Manage memos by using the buttons. Memos can be up to 30 seconds in length.

Programming Notes

The capture buffers are written to the database as raw data.


PlaySound Sample

[C++]

This topic pertains only to application development in Visual Basic. See DirectSound C/C++ Samples.

[Visual Basic]

Description

The PlaySound sample demonstrates the basics of playing a DirectSound buffer.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DSound\Src\PlaySound

Executable: (SDK root)\Samples\Multimedia\VBSamples\DSound\Bin\Vb_PlaySound.exe

User's Guide

Click Sound File and load a wave file. Select Loop Sound if you want to hear the sound continuously, then click Play. You can adjust the frequency, pan, and volume as the sound is playing.

Programming Notes

The sample shows how to create a sound buffer from a file, play the buffer, and change parameters.


SoundMix Sample

[C++]

This topic pertains only to application development in Visual Basic. See DirectSound C/C++ Samples.

[Visual Basic]

Description

The SoundMix application demonstrates how multiple DirectSound buffers can be played simultaneously, and shows how to change parameters of buffers as they are playing.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DSound\Src\SoundMix

Executable: (SDK root)\Samples\Multimedia\VBSamples\DSound\Bin\SoundMix.exe

User's Guide

Load one or more wave files by clicking on the Load buttons. Select the Loop Play check box so short sounds will repeat. Play, pause, and stop the sounds with the buttons, and change parameters by using the sliders.

Programming Notes

The application shows how sound buffers operate independently and are mixed in the primary buffer.


StreamFrom Sample

[C++]

This topic pertains only to application development in Visual Basic. See DirectSound C/C++ Samples.

[Visual Basic]

Description

The StreamFrom application demonstrates how to stream sound from a wave file, using a streaming buffer and event notifications.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DSound\Src\StreamFrom

Executable: (SDK root)\Samples\Multimedia\VBSamples\DSound\Bin\Streamfrom.exe

User's Guide

Click Load File and open a fairly large wave file.

Programming Notes

The sample creates a primary buffer object and plays it even when a file is not being played. See Playing the Primary Buffer Continuously.


StreamTo Sample

[C++]

This topic pertains only to application development in Visual Basic. See DirectSound C/C++ Samples.

[Visual Basic]

Description

The StreamTo application demonstrates how to stream sound to a capture buffer.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DSound\Src\StreamTo

Executable: (SDK root)\Samples\Multimedia\VBSamples\DSound\Bin\Streamto.exe

User's Guide

Click Start Streaming to begin capturing sounds to a buffer. When you click End Streaming, you have the opportunity to enter a file name and save the sound to a file.

Programming Notes

The capture buffer holds 2 seconds of sound. Event notification is used to trigger writing of data to a temporary file. When the user ends capture and supplies a file name, the raw data is saved in Resource Interchange File Format (RIFF) along with the wave format information.


Glossary

This section provides a glossary of technical terms used in the Microsoft® DirectX® SDK documentation.

A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z


A

alpha channel
The opacity of an image defined by an alpha value per pixel interleaved with the color components (for example, ARGB), an alpha value per pixel stored in a separate alpha surface, or a constant alpha value for the entire surface.
alpha color component
The portion of a 32-bit color that determines its opacity. In this case, the alpha value per pixel is interleaved with the color components (for example, ARGB). Less commonly, this term can also refer to an image with an alpha value per pixel stored in a separate alpha surface.
alpha constant
A level of opacity (alpha value) applied to an entire surface.
alpha edge blend
A particular use of alpha blending (and alpha channel information) to reduce aliasing by blending edges, based on pixel coverage information.
ambient
Description of a light source that illuminates everything in a scene, regardless of the orientation, position, and surface characteristics of the objects in the scene. Because it illuminates a scene with equal strength everywhere, the position and orientation of the frame that an ambient light source is attached to are inconsequential. Multiple ambient light sources are combined within a scene.
anisotropic filtering
A mipmap filtering mode that compensates for anisotropic distortion.
anisotropy
The distortion visible in the image of a 3-D object whose surface is oriented at an angle with respect to the viewing plane. The anisotropy is measured as the elongation (length divided by width) of a screen pixel that is inverse-mapped into texture space.
array object
A group of objects organized into an array. Array objects make it simpler to apply operations to the entire group. The COM interfaces that allow you to work with array objects contain the GetElement and GetSize methods. These methods retrieve a pointer to an element in the array and the size of the array, respectively.
attach
To connect multiple DirectDrawSurface objects into complex structures, such as those needed to support 3-D page flipping with z-buffers. Attachment is not bidirectional, and a surface cannot be attached to itself. Emulated surfaces (in system memory) cannot be attached to nonemulated surfaces. Unless one surface is a texture map, the two attached surfaces must be the same size.
attached
Physically connected to the system. A device may be installed but not currently attached.
attack
The period at the beginning of a force-feedback effect when the magnitude is reaching its basic or sustain level.
audio stream
Sound data, mixed or unmixed. DirectSound mixes audio streams from each secondary sound buffer that is playing and writes the result to the primary sound buffer, which supplies audio data to the sound hardware.


B

back buffer
A nonvisible surface to which bitmaps and other images can be drawn while the primary surface displays the currently visible image.
back clipping plane
The far boundary of a viewing frustum beyond which objects are not rendered. See also front clipping plane.
bank select
A MIDI controller that allows instruments to be chosen from different groups or banks, each identified by a 2-byte code.
billboard
A primitive inserted into a 3-D scene that is oriented so that one face is toward the viewer. A texture, usually an animated sprite, is applied to the billboard to give the appearance of a 3-D object in the scene.
billboarding
A 2-D technique of simulating the appearance of a 3-D object in a scene. An application inserts a primitive, typically rectangular, into the scene, oriented so that one face is toward the viewer and applies a texture or a set of textures. The texture or set of textures gives the appearance of an animated 3-D object.
blend factor
The description of how each color component is blended in texture blending.
blend mode
The algorithm used to determine how a texture is blended with the colors of the surface to which the texture is applied.
blending stage
One step in a texture cascade. A blending stage includes one texture and a set of texture-blending operations that are used when blending multiple textures.
blit
A bit block transfer.
bounds checking
The process of checking that an on-screen image is displayed within the bounds of the screen.
bump mapping
A technique for simulating the appearance of rough surfaces in 3-D scenes. Variations in depth are stored in a texture and applied to a primitive, using standard texture-blending techniques.


C

camera
A Direct3DRMFrame object used by the viewport to define the viewing position and direction. The viewport renders only what is visible along the positive z-axis of the camera frame, with the up direction in the direction of the positive y-axis.
camera space
The frame of reference in which the viewer is at the origin, looking in the direction of the positive z-direction. Objects are transformed from world space to camera space by using the view transformation.
client/server session
A DirectPlay session in which only the server stores the session's complete state, and each client has only a subset of the session's state. Each client receives only the information that is relevant to that computer from the server. When one computer changes something, it propagates the change to the server. The server then determines which clients it must inform of the change. See also peer-to-peer session.
clip list
A series of rectangles that describes the visible areas of the surface. The clip list cannot be set if a window handle is already associated with the DirectDrawClipper object.
clipper
A DirectDrawClipper object.
codec
Represents the phrase "compressor and decompressor."
collision detection
The process of determining if any pixels for two images share the same location on the screen. See also hit detection.
color key
A value indicating the color to be used for transparent or translucent effects. For example, when using a hardware blitter, all the pixels of a rectangular area are blitted, except the value that was set as the color key; this creates nonrectangular sprites on a surface.
color space
A model for representing color as three or more coordinates. Color-space models map color components onto a Cartesian coordinate system in three or more dimensions. A color space may use any of several types of color encoding and visualizing. The two most common types of color space models are RGB and YUV.
color-space conversion
A technique for converting a color in one color space to another color space. Typically, this conversion is from YUV colors from a video source to RGB for display.
color table
An array of n color values (normally RGB triples).
complex surface
The collective term for several DirectDrawSurface objects, all of which are attached to a root surface. The complex-surface structure can be destroyed only by destroying the root.
control segment
Musical segment that controls certain aspects of playback. Normally it is the primary segment, but a secondary segment can be designated as the control segment.
culling
Skipping a back face of a 3-D primitive during the rendering process.
current play position
The location in a DirectSound buffer at which a sound is being played.
current write position
The location in a DirectSound buffer at which it is safe to change data in that buffer.


D

dark light
A light source that removes illumination from a scene, created by specifying negative values for the colors of the light.
DCI
Display Control Interface. Defined by the Intel® and Microsoft® corporations, DCI is an interface that offers improved graphics performance as a result of direct video memory access.
dead zone
An area within the range of an axis within which the axis is considered to be at the center.
decal
A texture that is rendered directly, as a visual. Decals are rendered into a viewport-aligned rectangle.
destination color key
The color that (in the case of blitting) is replaced or (in the case of overlays) is covered on the destination surface.
device window
A visible application window that Microsoft® DirectDraw® uses for display. Applications can have a device window for each display device attached to a given computer. See also focus window.
directional
Description of a light source that is attached to a frame but appears to illuminate all objects with equal intensity, as if it were at an infinite distance from the objects. Directional light has orientation but no position, and it is commonly used to simulate distant light sources, such as the sun.
DirectPlay address
A data format that Microsoft® DirectPlay® uses to pass addressing information between lobby servers, applications, DirectPlay, and service providers. A DirectPlay address is a sequence of variable-length data chunks tagged with a globally unique identifier (GUID) that supplies all the address information needed by DirectPlay. Examples of address information are: the network address of a server, the network address of a player, the e-mail name of a player, and the network address of a session.
DLS
Downloadable sounds (sometimes called downloadable samples). Digital samples in software that are used by a synthesizer to create instrument timbres.


E

emissive property
The material property that determines whether a material emits light. The emissive property of a material is one of two properties that determines how the material reflects light. See also specular property.
emissive setting
See emissive property.
enable frame
The frame to which a light applies.
envelope
A set of values that defines the shape of a force-feedback effect by modifying the magnitude at the beginning (attack) and end (fade).
even field
The second field comprising a video frame in an odd/even field set. Also known as field 2.
execute buffer
A fully self-contained, independent packet of information that describes a 3-D scene. An execute buffer contains a vertex list followed by an instruction stream. The instruction stream consists of operation codes, or opcodes, and the data that is operated on by those opcodes.


F

face
A single polygon in a mesh.
fade
The period between the central, or sustain, portion of a force-feedback effect and its end.
falloff
Light attenuation between a spotlight's inner and outer cones.
field
Data for one-half of a single video frame within a video stream. Each field contains data for every other scan line. Fields are sent and received in odd field, even field order.
field polarity
Quality determining whether a field is an even field or an odd field. Odd fields are ones in which the trailing edge of the VREF does not occur during a scan line. Even fields are ones in which the trailing edge of the VREF occurs during a scan line.
flimmering
A shimmering appearance on 3-D primitives that results from a poor separation of z values when doing decaling. Some pixels from the back texture are rendered onto the front texture and vice versa.
flip
The process of swapping the addresses associated with the back and front buffers. This effectively swaps the image in the back buffer to the front buffer, thus displaying the image.
flipping chain
A series of surfaces attached to each other that can be flipped. See also flip.
flipping surface
Any piece of memory that can be flipped. See also flip.
focus window
An application window, visible or not visible, that DirectDraw uses to hook window messages. The focus window's message handler receives input messages forwarded by DirectDraw. Applications can have only one focus window. See also device window.
frame
An invisible box that provides a frame of reference for objects in a scene. Objects can be placed in a scene by specifying their spatial relationship to a relevant reference frame. Visual objects take their positions and orientations from frames.

In a movie or animation, a single image.

front buffer
The first buffer in a flipping chain. In many cases, this is the visible primary surface. In other cases (such as a flipping chain of textures) the front buffer is the surface that the 3-D engine gets the texture from, but not the primary surface; it is not displayed. In the case of flipping overlay surfaces, the front buffer is displayed, but is only a surface overlaid on the primary surface. See also primary surface.
front clipping plane
The near boundary of a viewing frustum. Any object closer to the camera than the front clipping plane is not rendered. The height of the front clipping plane defines the field of view. See also back clipping plane.


G

genlocking
The process of synchronizing one video signal with another. Because they are synchronized, the genlocked signal can be mixed with the original signal, allowing dissolves, wipes, and other transition effects.
grid
Subdivision of a beat. The number of grids per beat is part of the Microsoft® DirectMusic® time signature.
groove level
A value given to music during style playback, determining which patterns can be selected at any given time. The composer assigns a range of groove levels to each pattern.
group
A logical collection of players. DirectPlay supports groups within a session. By creating a group of players, an application can send a single message to the group, and all players in the group receive the message. A group is the means by which a network's multicast capabilities are exposed to the application.

Groups can be used to organize players in a session. A player can belong to more than one group. DirectPlay provides methods for administering groups and their membership.


H

HAL
The hardware abstraction layer. Consists of hardware and device driver mechanisms that insulate applications from device-specific implementation details. If a capability requested by an application is not implemented by the current hardware, the capability is emulated by the software.
hardware blitter
A hardware component, built into the display adapter, that performs efficient blit operations.
HEL
The hardware emulation layer. Provides software-based emulation of features that are not present in hardware.
HID
Human Interface Device. A USB class representing devices that allow a human to control a computer.
hit detection
See collision detection.
host
In DirectPlay, a virtual player whose ID is DPID_SYSMSG. The host manages system messages and messages sent to all players in a session.
HREF
Horizontal refresh. In a video stream, the HREF is active to signal that the display is to begin a new scan line. See also VREF.


I

index palette
A DirectDrawPalette object whose entries are indexes into another palette object.
IPX service provider
A service provider that uses Windows Sockets to communicate over a local area network (LAN) using the Internetwork Packet Exchange (IPX) protocol. The service provider supports only nonguaranteed messaging. A single computer can host only one DirectPlay session using IPX.
IRE scale
International Radio Engineers scale. A scale of values ranging from 0 to 100 that defines the brightness level of a broadcast video signal. The spectrum of low-to-high IRE values describes increasing brightness levels of a video signal. At 7.5 IRE brightness—the black cut-off threshold for a National Television System Committee (NTSC) signal—the electron guns of an NTSC display device are cut off and do not display images.


L

latency
A delay in response. For example, in Microsoft® DirectSound®, it is the interval between the time that a sound buffer plays and the time that the speakers actually reproduce the sound. In DirectPlay, it is the time that it takes for a packet to reach a given destination.
light map
A texture or group of textures that contain lighting information for a 3-D scene.
lobby-aware application
An application that, at a minimum, supports being launched from a lobby.
lobby client
Lobby management routines associated with the user's computer, including launching applications, updating the user interface, and communicating with the lobby server.
lobby provider
A client component (dynamic-link library) supplied by the developer of a lobby server. It implements communication functions with the lobby server, as requested by DirectPlay.
lobby server
Lobby management routines associated with a remote server. The lobby server coordinates all the information about the users who are connected to a specific application.
lobby session
A connection to a lobby server on which clients and the server have not been specifically written to interoperate.


M

Mach bands
Bands of color that are not smoothly blended across a 3-D primitive.
material
A property that determines how a surface reflects light. A material has two components: an emissive property (whether it emits light) and a specular property, whose brightness is determined by a power setting.
mesh
A set of faces, each of which is described by a simple polygon.
mipmap
Also known as MIP map (Latin: multium in parvo, translated "much in little"). A sequence of textures, each of which is a progressively lower-resolution, prefiltered representation of the same image. A higher-resolution image is used when a visible object is close to the viewer; as the object moves farther away (and gets smaller), lower-resolution images are used.
mixing
In DirectSound, the process of combining sound buffers that are playing, and writing the result to the primary sound buffer, which supplies audio data to the sound hardware. There is no limit to the number of buffers that can be mixed, except the available processing time.
Mode X
A hybrid display mode derived from the standard VGA Mode 13. This mode allows the use of up to 256 KB of display memory (rather than the 64 KB allowed by Mode 13) by using the VGA display adapter's EGA multiple video plane system.
model coordinates
Coordinates that are relative to a local origin. See also model space and world coordinates.
model space
The frame of reference (used by model coordinates) that uses vertices relative to a single 3-D model's local origin.
multipass texture blending
The repeated rendering of a 3-D primitive while blending on a texture with each pass. This technique is widely used to achieve a variety of special effects.


N

nagling
An algorithm that causes the TCP/IP service provider to buffer small data packets into larger ones before sending. Nagling prevents a TCP/IP server from transmitting many very small packets by requiring the server to wait either until it has accumulated enough small data packets to combine them into a single large packet or until it has received an acknowledgment of the prior packet. Nagling can reduce message overhead (and decrease required bandwidth), but also causes a delay before small data packets are sent (increasing latency).
normal vector
An imaginary ray extending perpendicularly from a surface that defines the face's orientation.


O

odd field
The first field comprising a video frame in an odd/even field set.
off-screen surface
A conceptually rectangular area in memory that is generally used to store bitmaps to be blitted to a back buffer before being displayed. Commonly used to store sprites.
opcode
Operation code that defines how to interpret the vertices in an execute buffer or how to change the state of the system.
overdraw
The average number of times to which a screen pixel is written.
overlay surface
A conceptually rectangular area in memory whose stored image information covers the image information of the primary surface to which it is applied. Overlays are assumed to be on top of all other screen components.
overlay z-order
Determines the order in which overlays clip each other, enabling a hardware sprite system to be implemented under DirectDraw.


P

page flipping
See flip.
palette
The set of colors used by an object or application. In DirectX, a DirectDrawPalette object.
palette index
An integer index into the palette table array that is used to select a particular color.
palettized surface
A DirectDrawSurface object that uses an attached palette to contain color information.
pan value
The relative volume, measured in hundredths of decibels, between the left and right audio channels.
parallel point
Description of a light source that illuminates objects with parallel light, but the orientation of the light is taken from the position of the parallel point light source. For example, two meshes on either side of a parallel point light source are lit on the side that faces the position of the source.
PChannel
Performance channel. A PChannel is a MIDI channel in a particular channel group on a particular port.
peer-to-peer session
A DirectPlay session in which the session's complete state is replicated on all the computers in the session. The session description data—the list of players and groups and the names and remote data associated with each session—are duplicated on every computer. When one computer changes something, it is immediately propagated to all the other computers. This is the default mode of communication for DirectPlay. See also client/server session.
perspective correction
The technique of applying a texture map to a polygon that is angled away from the camera, interpolating so that the texture is stretched onto the polygon appropriately for the apparent depth of the polygon. Direct3D supplies perspective correction automatically.
pick
To search for visuals in a scene, given a 2-D coordinate in a viewport.
PID
Physical interface device. A USB class that allows humans to feel force feedback from a computer.
pitch
The distance, in bytes, between an address that represents the beginning of a bitmap line and the beginning of the next line. Do not confuse memory pitch and memory width, since not all display memory is laid out as one linear block. For example, with rectangular memory, the pitch of the display memory could include the width of the bitmap plus part of a cache. See also width and stride.
player
A single participant in a DirectPlay session. Each player is associated with a player ID that enables messages to be exchanged among players.
player ID
A unique number that is assigned to each participant in a DirectPlay session when the participant is created. The application can exchange messages among players by using player IDs. The host is always assigned the DPID_SYSMSG player ID.
point light
A light source that radiates equally in all directions from its origin.
point list
The simplest 3-D primitive. A collection of unconnected points in 3-D space.
power
In the specular property of a material, the value that determines the sharpness of specular highlights. A value of 5 gives a metallic appearance, and higher values give a more plastic appearance.
primary sound buffer
The buffer that the user hears when a game is playing. The primary buffer is generally used to mix sound from secondary buffers, but it can be accessed directly for custom mixing or other specialized activities.
primary surface
The area in memory containing the image being displayed on the monitor. In DirectX, the primary surface is represented by the primary DirectDrawSurface object.
projection space
Frame of reference containing vertices after they are modified from their world space locations by the projection transformation. Projection space is a homogeneous cuboid space in which all vertices in a scene have x- and y-coordinates that range from –1.0 to 1.0, and a z-coordinate that ranges from 0.0 to 1.0. Projection space is sometimes referred to as post-perspective homogeneous space.
projection transformation
The application of a matrix to vertices to change them from camera space to projection space.


Q

quaternion
A fourth element added to the [x, y, z] values that define a vector. Quaternions define a 3-D axis and a rotation around that axis.


R

reference count
A control for a Component Object Model (COM) object. When an object is created, its reference count is set to 1. Every time an interface is bound to the object, its reference count is incremented; when the interface connection is destroyed, the reference count is decremented. The object is destroyed when the reference count reaches 0. All interfaces to that object are then invalid.
region
In DirectMusic, a range of notes for which a particular digital sample is used in synthesizing an instrument's timbre.
root frame
A frame in Direct3D that has no parent frame; it is at the top of a hierarchy of frames. The root frame contains the entire set of objects that make up a scene. See also scene.


S

saturation
Adjustment to the extreme value of a range when the actual value approaches the extreme. If the maximum value in a range is 1,000 and the maximum saturation point is set to 900, any value greater than 899 is adjusted to 1,000.
scene
The entire set of objects that make up a virtual environment, including visible objects, sounds, lights, and frames. In Direct3D, the entire set of objects is contained in a root frame.
screen space
Frame of reference in which coordinates are related directly to 2-D locations in the frame buffer, to be displayed on a monitor or other viewing device. Projection space coordinates are converted to screen space coordinates, using a transformation matrix created from the viewport parameters.
secondary sound buffer
A section of audio memory that stores individual sounds that are played throughout an application. The sound can be played as a single event or as a looping sound that plays repeatedly. Secondary buffers can also play sounds that are larger than available sound-buffer memory; the buffer serves as a queue that stores the portions of the sound about to be played.
secure session
A session in which all users have been authenticated against a database of known users before being allowed to join a session. In a secure session, all DirectPlay system messages are digitally signed to verify the identity of the sender. Certain system messages that carry sensitive information are encrypted. System messages that originate from one player and need to be broadcast to all the other players in the session are first sent to the server. The server then puts its signature on the message and forwards the message to all the other computers in the session. Player-to-player messages are not signed by default and are not routed through the server.
service provider
A dynamic-link library used by DirectPlay to communicate over a network. The service provider contains all the network-specific code required to send and receive messages. Online services and network operators can supply service providers to use specialized hardware, protocols, communications media, and network resources.
session
In DirectPlay, an instance of several applications on remote computers communicating with each other. Before an application can start communicating with other computers, it must be part of a session. An application can enumerate all the existing sessions on a network and join one of them, or it can create a new session and wait for other computers to join it. Once the application is part of a session, it can create a player and exchange messages with all the other players in the session.
sound buffer
A segment of memory that stores DirectSound audio data. Sound buffers can be primary or secondary, static or streaming.
source color key
A color that (in the case of blitting) is not copied to, or (in the case of overlays) not visible on, the destination.
specular property
The material property that determines how a point of light on a shiny object corresponds to the reflected light source. The specular property of a material is one of two properties that determines how a material reflects light. See also emissive property.
spotlight
A light source that emits a cone of light. Only objects within the cone are illuminated. The cone produces light of two degrees of intensity, with a central brightly lit section that acts as a point source, and a surrounding dimly lit section that merges with the surrounding deep shadow.
static sound buffer
A section of memory that contains a complete sound. These buffers are convenient because the entire sound can be written once to the buffer.
sticky focus
In DirectSound, the ability to play sound buffers when the owning application does not have the input focus. For example, a DirectSound application could continue to play a sound buffer while the user is working in another application.
streaming sound buffer
A small sound buffer that can play lengthy sounds because the application dynamically loads audio data into the buffer as it plays. For example, an application could use a buffer that can hold 3 seconds of audio data to play a 2-minute sound. A streaming buffer requires much less memory than a static buffer.
stretching
Blitting an image into a destination with different dimensions. This operation is supported directly by some hardware.
stride
Synonymous with pitch. See also width.
surface
Memory that represents visual images. This is often display memory, but it can be system memory. See also complex surface, off-screen surface, overlay surface, and primary surface.
sustain
The period during which the basic magnitude of a force-feedback effect is attained, after the attack and before the fade.
system message
In DirectPlay, a message from the player ID DPID_SYSMSG. All system messages begin with a DWORD value.


T

TCP/IP service provider
A service provider that uses Windows Sockets to communicate over the Internet or local area network (LAN), using the TCP/IP protocol. It uses User Datagram Protocol (UDP) packets for nonguaranteed messaging and TCP for guaranteed messaging. A single computer can host multiple DirectPlay sessions, using TCP/IP.
tearing
A visual artifact produced when the screen refresh rate is out of sync with an application's frame rate. The top portion of one frame is displayed at the same time as the bottom portion of another frame, with a discernible tear between the two partial images.
tessellating
Breaking an image into small square regions for processing or output.
texel
A single element in a texture. When a texture has been applied to an object, the texels rarely correspond to pixels on the screen. Applications can use texture filtering to control how the system interpolates between texels to create pixels in a scene.
texture
A rectangular array of pixels that is applied to a visual object in Direct3D.
texture blending
The technique of combining the colors of a texture with the colors of the surface to which the texture is applied.
texture coordinates
The coordinates that determine which texel in each texture is assigned to each vertex in an object.
texture filtering
The process of mapping texel colors from one or more textures onto the pixels that comprise the image of a 3-D primitive.
texture mapping
The application of a texture to an object. Because a texture is a flat image and the object is often not, the texture must be mapped to the surface of the object, using texture coordinates and wrapping flags. See also texture coordinates and wrap.
thrashing
Removing textures used in the current frame to reclaim texture memory for subsequent frames.
throttling
Restricting the number of messages to avoid sending them faster than the underlying transport can deliver them.


U

unit vector
A vector with a magnitude (length) of 1.0.
USB
Universal serial bus.


V

VBI
Vertical blanking interval. In broadcast video, a small period of time that elapses between video frames, during which a display device refreshes its display for the next frame.
velocity
In music, the speed at which a MIDI key is pressed, roughly equivalent to the dynamic level at which the note is played in some instrumental timbres.

In 3-D sound, the speed at which a sound source or listener is considered to be moving for calculating Doppler shift.

vertex
A point in 3-D space.
video frame
A single image in a video stream, comprised of one odd field and one even field. See also field.
view space
See camera space.
view transformation
The application of a matrix to a model's vertices to change its orientation from world space to view space.
viewing frustum
A 3-D volume in a scene positioned relative to the viewport's camera. Objects within the frustum are visible. For perspective viewing, the viewing frustum is the volume of an imaginary pyramid that is between the front clipping plane and the back clipping plane. For orthographic viewing, the viewing frustum is cubic.
viewport
A rectangle that defines how a 3-D scene is rendered into a 2-D window. A viewport also defines an area on a device into which objects are rendered.
VREF
Vertical refresh. In a video stream, the VREF is active to signal that the display is to begin a new screen. See also HREF.


W

width
The distance between two addresses in memory that represent the beginning of a line and the end of the line of a stored bitmap. This distance represents only the width of the bitmap in memory; it does not include any extra memory required to reach the beginning of the next line of the bitmap, such as a cache in rectangular memory.
world coordinates
Coordinates that are relative to the origin of a scene. See also model coordinates and world space.
world space
The frame of reference, used by world coordinates, that declares vertices relative to a single origin within a 3-D scene.
world transformation
The application of a matrix to a model's vertices to change its orientation from model space to world space.
wrap
The procedure used to calculate texture coordinates for a face or mesh. The basic wrapping types are flat, cylindrical, spherical, and chrome.


Z

z-buffer
A buffer that stores a depth value for each pixel in a scene. Pixels with a small z-value overwrite pixels with a large z-value.
z fighting
See flimmering.


Introduction to Direct3D Retained Mode

Welcome to Microsoft® Direct3D® Retained Mode. With Direct3D Retained Mode, you can create a three-dimensional (3-D) graphics environment on a personal computer and manipulate it in real time.

Last Updated: July 27, 1999

About Retained Mode
Provides a brief description of Direct3D Retained Mode.
Getting Started
Describes the new features in Direct3D Retained mode version 6.x, where to get started, and where to find common topics. Also provides some of the technical background you need to manipulate points in three dimensions. Includes a general discussion of coordinate systems, transformations, polygons, triangle strips and fans, vectors, vertices, and quaternions.
Technical Background
Describes some of the technical concepts you need to understand before you write programs that incorporate 3-D graphics. In this section, you will find a general discussion of coordinate systems and transformations.
Architecture
Describes Direct3D Retained Mode objects and the interfaces they support. Also provides tips on reference counting and z-buffers.
Overviews
Provides information about using some of the Direct3D Retained Mode interfaces. See the Reference for detailed information about all Retained Mode interfaces.
Tutorial
Provides a walk-through of the code in a simple Retained Mode application.
C++/COM Reference
Provides detailed information about the interface methods, nonmember functions, and callbacks with syntax, parameter descriptions, flag descriptions, and comments about use. Also describes the members of Direct3D structures, enumerated types, other defined types, and the possible error values that can be returned.
Visual Basic Reference
Provides detailed information about the interfaces, classes, methods, and callback interfaces, with syntax, parameter descriptions, and flag descriptions. It describes the members of Direct3D Retained Mode types, enumerations, other defined types, and the possible error values that can be returned.
Samples Introduction
Provides information about how to build the Direct3D Retained Mode samples in Microsoft Developer Studio™, and it provides summaries of the samples to help you determine which sample to look at.
DirectX File Format
Describes the file format of DirectX (.x) files, which provide support for reading predefined objects into applications and writing mesh information constructed by applications in real time. Also includes information about templates, examples, the binary format of the files, and the Conv3ds.exe utility, which converts 3-D models from other packages into .x files.
Glossary
Defines basic graphics terms used in Direct3D Retained Mode.

Note: The icon external link indicates that the link takes you to a URL that is outside the microsoft.com site; you can return to the Direct3D Retained Mode site by using the Back button. Most of these external links point to servers that are not under Microsoft's control. Please read Microsoft's official statement regarding other servers.


About Direct3D Retained Mode

About Retained Mode

This section describes Microsoft® Direct3D® Retained Mode, the Microsoft solution for real-time, three-dimensional (3-D) graphics on the personal computer. If you need to create a 3-D environment and manipulate it in real time, you should use the Direct3D Retained Mode API.

If you have written code before that uses 3-D graphics, many of the concepts underlying Direct3D Retained Mode will be familiar to you. If, however, you are new to 3-D programming, you should pay close attention to Direct3D Retained Mode Architecture, and you should read Technical Background. Whether you are an experienced 3-D programmer or just beginning, you should look carefully at the sample code included with this Software Development Kit; it illustrates how to put Direct3D Retained Mode to work in real-world applications.

For an introduction to programming with Direct3D Retained Mode, see Direct3D Retained Mode Tutorial.


Getting Started

This section discusses new features in Microsoft® Direct3D® Retained Mode version 6.x and where to find particular information in the documentation. It also provides articles that walk through well-commented sample code.

  • What's New in Direct3D Retained Mode?
  • Documentation Roadmap
  • Rotating an Object: The RMBegin1 Sample
  • Frame Hierarchies: The RMBegin2 Sample
  • Enumerating Devices: The RMEnum Sample


What's New in Direct3D Retained Mode?

This section discusses new features and documentation in Microsoft® Direct3D® Retained Mode version 6.0.

Microsoft Visual Basic programmers should consult the Visual Basic Reference for information on how to use Direct3D Retained Mode.

This article contains the following sections.

  • New Articles
  • New Interfaces

New Articles

Most of the Getting Started section is new and contains the following articles.

  • Documentation Roadmap outlines where to go in this documentation for information on particular topics.
  • Rotating an Object: The RMBegin1 Sample contains a walkthrough of a simple sample that rotates an object.
  • Frame Hierarchies: The RMBegin2 Sample contains a walkthrough of a simple sample that provides a sun, planet, and moon scenario with each object revolving around the other appropriate objects.
  • How to Enumerate Devices contains a walkthrough of a sample that enumerates devices.
  • Eliminating Redundant State Changes explains how to avoid setting the state to a value equal to its current value, which can help performance.

The Samples section of this documentation is new. You can reach the section through Direct3D Retained Mode Samples Introduction, which leads to the following new articles.

  • Building Samples Using Developer Studio 5.0
  • Direct3D Retained Mode Samples

Direct3D Retained Mode Overviews contains the following new articles.

  • Interface Hierarchy Chart
  • Interface Changes

New Interfaces

Microsoft® Direct3D® Retained Mode version 6.0 introduces several interfaces and a number of other interfaces that add new methods, and thereby new functionality, to old interfaces. For a complete list of the new interfaces and methods, see Interface Changes. For information about interface inheritance see the new Interface Hierarchy Chart.

This documentation covers the latest version of an interface and notes differences between versions rather than duplicating information. For example, where you would have previously found separate, but nearly identical documentation for IDirect3DRMTexture3::GetDecalSize, IDirect3DRMTexture2::GetDecalSize, and IDirect3DRMTexture::GetDecalSize you will now find that method documented under the latest version of that interface as IDirect3DRMTexture3::GetDecalSize.

The Reference contains the following new interfaces.

  • Retained Mode version 6.0 introduces a new IDirect3DRM3 interface and Direct3DRM3 object. MeshBuilder3 objects created using IDirect3DRM3 use the DirectX Immediate Mode DrawPrimitive interface. Lights created with IDirect3DRM3 take advantage of new Immediate Mode functionality and use the Immediate Mode D3DLIGHT2 structure. IDirect3DRM3 provides all the functionality of IDirect3DRM2 and IDirect3DRM. It adds a flag parameter to CreateDeviceFromSurface, allowing you to indicate that no z-buffer should be created, and adds the RegisterClient and UnregisterClient methods. IDirect3DRM3 also adds the GetOptions and SetOptions methods to set and retrieve whether left-handed or right-handed geometry should be used.

  • All objects implement the new IDirect3DRMObject2 interface. IDirect3DRMObject2, unlike the other new interfaces, does not implement all the methods of its predecessor. IDirect3DRMObject2 and IDirect3DRMObject continue to be documented separately. IDirect3DRMObject2 adds the SetClientData and GetClientData methods that work in conjunction with the new IDirect3DRM3::RegisterClient and IDirect3DRM3::UnregisterClient methods. It also adds the GetDirect3DRM and GetAge methods.

  • IDirect3DRMAnimation2 adds the AddKey, DeleteKeyByID, GetKeys, and ModifyKey methods that allow access to the keys of an animation. It also adds the GetFrame method that returns the frame of the corresponding animation.

  • The new IDirect3DRMAnimationArray interface lets you retrieve the number of animations in the array using GetSize and request the interface for an animation using GetElement.

  • IDirect3DRMAnimationSet2 adds the GetAnimations method that enables you to retrieve the constituent animations.

  • The new IDirect3DRMClippedVisual interface allows you to clip visuals against arbitrary planes before rendering. New ClippedVisual objects are created from the Direct3DRM3 object.

  • IDirect3DRMDevice3 adds the FindPreferredTextureFormat method to select a texture format based on certain criteria. IDirect3DRMDevice3 also introduces several methods that can be used to eliminate redundant state changes: GetStateChangeOptions, LightStateChange, RenderStateChange, and SetStateChangeOptions.

  • IDirect3DRMFace2 adds a SetTexture method with which you can specify textures whose height and width are not a power a two.

  • IDirect3DRMFrame3 provides methods that enable additional transformation capabilities between model- and world-space, retrieving the world 4x4 transform, setting and retrieving traversal options, and setting and retrieving whether fogging is done through vertex fog or table fog. It also provides methods for setting and retrieving material overrides. The SetOrientation method now respects scale and shear.

  • IDirect3DRMMaterial2 adds the GetAmbient and SetAmbient methods to allow finer control over material properties.

  • IDirect3DRMMeshBuilder3 adds methods to delete face, normal, and vertex objects. It also adds the Empty and Optimize methods. Other new IDirect3DRMMeshBuilder3 methods retrieve one or more normals, the number of normals, the texture topology, faces, one or more vertices, and the state (enabled or disabled) of the meshbuilder. This interface enables you to set vertices and normals and to create and retrieve new sub-meshes and parent meshes of the meshbuilder. IDirect3DRMMeshBuilder3 also enables the application to add new triangles and to implicitly create new faces by using the AddTriangles method.

  • IDirect3DRMShadow2 adds methods allowing the visual, light, plane, and option shadow parameters to be changed after creation. SetOptions allows you to set an option that eliminates visual artifacts when blended transparency is enabled.

  • IDirect3DRMTexture3 extends the Changed method by allowing you to specify the changed region of the texture. It also provides the texture management caching methods GetCacheOptions and SetCacheOptions. GetSurface, SetDownSampleCallback, and SetValidationCallback are the other new methods IDirect3DRMTexture3 provides.

  • IDirect3DRMViewport2 adds a flag parameter to Clear, indicating whether the target surface, z-buffer surface, or dirty rectangle list are cleared.


Documentation Roadmap

This article discusses where you can find information about particular topics in the Microsoft® Direct3D® Retained Mode documentation.

If you are new to Retained Mode, start by reading the Interface Overviews to get an idea of common concepts. If you are new to three-dimensional (3-D) programming in general, read Technical Background. This background will help you understand the Tutorial and Samples. Consult the Reference, and especially the Interfaces for more details about what is going on in the code as you look at the Samples and Tutorial. The Glossary provides definitions for common terms.

Advanced developers might need detailed information about the DirectX File Format.

Where Can I Find ...

The following table lists commonly used information by C++/COM programmers and where to find it.
For information about | See this topic
Error codes | Return Values
Interface inheritance | Interface Hierarchy Chart
Interface history | Interface Changes
Interfaces | Interfaces
Constants | Constants
Enumerated types | Enumerated Types
Structures | Structures
Building samples | Building Samples Using Developer Studio 5.0
Developer Studio | Building Samples Using Developer Studio 5.0
Sample code | Samples
Retained Mode objects and their associated COM interfaces | Architecture
3-D graphics concepts | Technical Background
DirectX Files | DirectX File Format

The following table lists commonly used information by Microsoft Visual Basic programmers and where to find it.
For information about | See this topic
Error codes | Error Values
Interfaces | Interfaces
Callbacks | Callback Interfaces
Enumerated types | Enumerated Types
Types | Types
3-D graphics concepts | Technical Background
DirectX Files | DirectX File Format


Rotating an Object: The RMBegin1 Sample

Creating a device, building a scene, and moving the scene are fundamental concepts in Microsoft® Direct3D® Retained Mode. The RMBegin1 sample demonstrates these concepts by creating a default device, loading a mesh from a Microsoft DirectX® file, adding color to the object and lights to the scene, and rotating the object. In the process of building the scene, the sample uses a meshbuilder, frames, lights, and a material. The sample also creates a DirectDrawClipper object, viewport and camera.

This article walks you through code from the RMBegin1 sample. The sample source code consists of one self-contained file (RMBegin1.cpp). It does not use any separate header files, except for the standard Microsoft Windows®, DirectDraw®, and Direct3D Retained Mode header files for the sake of simplicity. It also does not contain any menus, icons, or other resources.

This sample uses the Teapot.x file from the DirectX Foundation Software Development Kit (SDK) to provide the teapot image for the scene. By default when you install the SDK, the SDK's setup program sets an environment variable to point to the SDK's media directory. Teapot.x resides in that directory, allowing the application to locate the file automatically. If you have not installed the SDK and simply run RMBegin1.exe, Teapot.x must be located in the same directory as RMBegin1.exe.

This article assumes you are an experienced C or C++ programmer and are familiar with beginning Windows programming concepts, such as the message loop, creating a window, and using menus.

This article contains the following sections.

  • Dependencies
  • Global Declarations
  • Function Summaries
  • Related Topics

Dependencies

  • RMBegin1 links to DDraw.lib and D3DRM.lib.
  • RMBegin1 loads the teapot image from Teapot.x, as described in the previous section.
  • To properly initialize globally unique identifiers (GUIDs), Direct3D applications must contain the following definition at the top of their code.
    #define INITGUID
  • The sample's RMBegin1.cpp file includes the following header files.
    #include <windows.h>   // Standard Windows header file
#include <direct.h>    // DirectDraw definitions
#include <d3drmwin.h>  // Direct3D Retained Mode definitions

Global Declarations

The sample defines some constants and global variables to help organize information.

The application-defined RELEASE macro releases an object only if the object is not NULL and ensures that an object is initialized to NULL after it has been released. This practice eliminates the problem of trying to release an object that has already been released, which can cause undesired results, such as page faults.

// Macro to release an object.
#define RELEASE(x) if (x != NULL) {x->Release(); x = NULL;}

The application-defined DISPLAYMSG macro uses the Windows MessageBox function to display information to the user. Using this macro rather than direct calls to MessageBox throughout the sample code makes the code cleaner and easier to read.

// Macro to display a message box containing the given string.
#define DISPLAYMSG(x) MessageBox(NULL, x, "D3DRM Sample", MB_OK);

Global variables keep track of the key objects, such as the Direct3D Retained Mode and DirectDrawClipper objects (the DirectDrawClipper object restricts drawing to a designated area). The myglobs structure collects device, viewport, scene, and camera information, as well as information about whether the application is minimized and whether objects have been initialized.

// Global Variables
LPDIRECT3DRM3 lpD3DRM = NULL;            // Direct3DRM object
LPDIRECTDRAWCLIPPER lpDDClipper = NULL; // DirectDrawClipper object

// Global Structure
struct _myglobs {

    // Direct3DRM device.
    LPDIRECT3DRMDEVICE3 dev;

    // Direct3DRM viewport through which to view the scene.
    LPDIRECT3DRMVIEWPORT2 view;

    // Master frame in which other frames are placed.
    LPDIRECT3DRMFRAME3 scene;

    // Frame describing the users point of view.
    LPDIRECT3DRMFRAME3 camera;

    // Application is minimized.
    BOOL bMinimized;

    // All Direct3D Retained Mode objects have been initialized.
    BOOL bInitialized;

} myglobs;

Function Summaries

RMBegin1.cpp contains the following functions.

BuildScene creates the scene to be rendered. It loads a mesh from the DirectX file, adds color to the mesh, and adds lights to the scene. BuildScene also sets the position of objects and how objects should be rotated. CreateObjects, which initializes global variables and creates default devices, frames, and viewports, uses this function.

BOOL BuildScene(LPDIRECT3DRM3, LPDIRECT3DRMDEVICE3,
                LPDIRECT3DRMFRAME3, LPDIRECT3DRMFRAME3);

RenderScene draws the scene that BuildScene created. Each time WinMain uses this function, RenderScene moves the scene, giving the effect of a spinning object.

static BOOL RenderScene(void);

AddMediaPath provides a path to the textures and .x files needed by the application by searching the registry.

VOID AddMediaPath(LPDIRECT3DRM3 pD3DRM)

CreateObjects initializes the global variables and creates a default device, camera frame, scene frame, and viewport. CreateObjects uses BuildScene to create the scene to be rendered. InitApp uses CreateObjects.

BOOL CreateObjects(HWND win);

InitApp provides standard, Windows application code to create the window class and the application's window. It uses CreateObjects to initialize global objects.

static HWND InitApp(HINSTANCE, int);

WinMain provides the application's message loop. It uses InitApp to initialize the application and uses RenderScene to draw the scene.

int APIENTRY WinMain(HINSTANCE, HINSTANCE, LPSTR, int);

WindowProc handles messages for the application. It handles cases where the application is minimized or destroyed.

LRESULT CALLBACK WindowProc(HWND, UINT, WPARAM, LPARAM);

For more information about these functions, see the following topics in this article.

  • BuildScene
  • RenderScene
  • AddMediaPath
  • CreateObjects
  • InitApp
  • WinMain
  • WindowProc

BuildScene

The BuildScene function creates the scene to be rendered. All Direct3D Retained Mode applications must create a scene, but the code required depends on the scene. Applications typically create frames and lights, add visuals to the scene, and set the position of objects.

This section of this article provides code fragments from the BuildScene function and presents the steps the RMBegin1 sample performs to build the scene. This section also presents the complete source code for the RMBegin1 sample's BuildScene function. If an error occurs, the code uses goto statements to jump to the end of the function and ensure that all objects are properly released before returning from the function.

  1. Load a mesh from a DirectX file by using the IDirect3DRM3::CreateMeshBuilder and IDirect3DRMMeshBuilder3::Load methods.
        if (FAILED(lpD3DRM->CreateMeshBuilder(&meshbuilder)))
        goto generic_error;

    rval = meshbuilder->Load("teapot.x",
                              NULL, D3DRMLOAD_FROMFILE, NULL, NULL);
  2. Create a child frame within the scene by using the IDirect3DRM3::CreateFrame method.
        if (FAILED(lpD3DRM->CreateFrame(scene, &childframe)))
        goto generic_error;
  3. Add the loaded mesh into the child frame by using the IDirect3DRMFrame3::AddVisual method.
        if (FAILED(childframe->AddVisual((LPDIRECT3DRMVISUAL)meshbuilder)))
        goto generic_error;
  4. Set the camera position within the scene by using the IDirect3DRMFrame3::SetPosition method.
        rval = camera->SetPosition(scene, D3DVAL(0), D3DVAL(0), -D3DVAL(7));
  5. Set the child frame's rotation by using the IDirect3DRMFrame3::SetRotation method.
        if (FAILED(childframe->SetRotation(scene,
                                       D3DVAL(0), D3DVAL(1), D3DVAL(0),
                                       D3DVAL(0.03)))) // angle
        goto generic_error;
  6. Create a light frame that is a child of the scene by using the IDirect3DRM3::CreateFrame method.
        if (FAILED(lpD3DRM->CreateFrame(scene, &lights)))
        goto generic_error;
  7. Position the light frame within the scene by using the IDirect3DRMFrame3::SetPosition method.
        if (FAILED(lights->SetPosition(scene,
                                   D3DVAL(5), D3DVAL(0), -D3DVAL(7))))
        goto generic_error;
  8. Create a bright, parallel point light and add it to the light frame by using the IDirect3DRM3::CreateLightRGB and IDirect3DRMFrame3::AddLight methods.
        if (FAILED(lpD3DRM->CreateLightRGB(D3DRMLIGHT_PARALLELPOINT,
                                       D3DVAL(1.0), D3DVAL(0.8),
                                       D3DVAL(0.9), &light1)))
        goto generic_error;

    if (FAILED(lights->AddLight(light1)))
        goto generic_error;
  9. Create a dim, ambient light and add it to the scene, again by using using the IDirect3DRM3::CreateLightRGB and IDirect3DRMFrame3::AddLight methods.
        if (FAILED(lpD3DRM->CreateLightRGB(D3DRMLIGHT_AMBIENT,
                                       D3DVAL(0.1), D3DVAL(0.1),
                                       D3DVAL(0.1), &light2)))
        goto generic_error;

    if (FAILED(scene->AddLight(light2)))
        goto generic_error;
  10. Create a material and set the reflectiveness by using the IDirect3DRM3::CreateMaterial and IDirect3DRMMeshBuilder3::SetMaterial methods.
        if (FAILED(lpD3DRM->CreateMaterial(D3DVAL(10.0), &mat)))
        goto generic_error;

    if (FAILED(meshbuilder->SetMaterial(mat)))
        goto generic_error;
  11. Set the mesh color by using the IDirect3DRMMeshBuilder3::SetColorRGB method.
        if (FAILED(meshbuilder->SetColorRGB(D3DVAL(0.0),   // red
                                        D3DVAL(0.7),   // green
                                        D3DVAL(0.0)))) // blue
        goto generic_error;
  12. Clean up by releasing all of the objects created by this function.
        RELEASE(childframe);
    RELEASE(lights);
    RELEASE(meshbuilder);
    RELEASE(light1);
    RELEASE(light2);
    RELEASE(mat);

BuildScene Function Source Code

// Create the scene to be rendered.

BOOL BuildScene( LPDIRECT3DRM3 lpD3DRM,  LPDIRECT3DRMDEVICE3 dev,
                 LPDIRECT3DRMFRAME3 scene, LPDIRECT3DRMFRAME3 camera )
{
    LPDIRECT3DRMFRAME3 lights = NULL;
    LPDIRECT3DRMMESHBUILDER3 meshbuilder = NULL;
    LPDIRECT3DRMFRAME3 childframe = NULL;
    LPDIRECT3DRMLIGHT light1 = NULL;
    LPDIRECT3DRMLIGHT light2 = NULL;
    LPDIRECT3DRMMATERIAL2 mat = NULL;
    HRESULT rval;

    // Load a mesh from a DirectX file.
    if (FAILED(lpD3DRM->CreateMeshBuilder(&meshbuilder)))
        goto generic_error;

    rval = meshbuilder->Load("teapot.x",
                              NULL, D3DRMLOAD_FROMFILE, NULL, NULL);
    if (FAILED(rval))
    {
        DISPLAYMSG("Failed to load .x file.");
        goto ret_with_error;
    }

    // Create a child frame within the scene.
    if (FAILED(lpD3DRM->CreateFrame(scene, &childframe)))
        goto generic_error;

    // Add the loaded mesh into the child frame.
    if (FAILED(childframe->AddVisual((LPDIRECT3DRMVISUAL)meshbuilder)))
        goto generic_error;

    // Set up the camera frame's position. Objects with the same x-value and
    // y-value as the camera will appear straight ahead.
    // Negative z-values are farther away, making the object look
    // smaller as the negative numbers increase.
    rval = camera->SetPosition(scene, D3DVAL(0), D3DVAL(0), -D3DVAL(7));
    if (FAILED(rval))
    {
        DISPLAYMSG("Failed to position the camera in the frame.");
        goto ret_with_error;
    }

    // Rotate the child mesh around the y-axis (zero x-value and z-value)
    // and use a small rotational angle to rotate slowly.
    if (FAILED(childframe->SetRotation(scene,
                                       D3DVAL(0), D3DVAL(1), D3DVAL(0),
                                       D3DVAL(0.03)))) // angle
        goto generic_error;

    // Initialize the lights in the scene, creating a light frame that
    // is a child of the scene.
    if (FAILED(lpD3DRM->CreateFrame(scene, &lights)))
        goto generic_error;

    // Position the light frame within the scene. This light comes from
    // the right of the camera. It has a different x-value, but the same
    // y-value and z-value as the camera position.
    if (FAILED(lights->SetPosition(scene,
                                   D3DVAL(5), D3DVAL(0), -D3DVAL(7))))
        goto generic_error;

    // Create a bright, parallel point light and add it to the light frame.
    // Color values must be in the range 0.0 (dim) to 1.0 (bright).
    if (FAILED(lpD3DRM->CreateLightRGB(D3DRMLIGHT_PARALLELPOINT,
                                       D3DVAL(1.0), D3DVAL(0.8),
                                       D3DVAL(0.9), &light1)))
        goto generic_error;

    if (FAILED(lights->AddLight(light1)))
        goto generic_error;

    // Create a dim, ambient light and add it to the scene frame,
    // applying it to the whole scene. Ambient light comes from all
    // directions, so a bright ambient light would wash out the object.
    if (FAILED(lpD3DRM->CreateLightRGB(D3DRMLIGHT_AMBIENT,
                                       D3DVAL(0.1), D3DVAL(0.1),
                                       D3DVAL(0.1), &light2)))
        goto generic_error;

    if (FAILED(scene->AddLight(light2)))
        goto generic_error;

    // Create a material, setting the reflectiveness (5.0 is metallic,
    // higher is more plastic) on the previously loaded mesh.
    if (FAILED(lpD3DRM->CreateMaterial(D3DVAL(10.0), &mat)))
        goto generic_error;

    if (FAILED(meshbuilder->SetMaterial(mat)))
        goto generic_error;

    // Set the mesh color (bright green in this case).
    if (FAILED(meshbuilder->SetColorRGB(D3DVAL(0.0),   // red
                                        D3DVAL(0.7),   // green
                                        D3DVAL(0.0)))) // blue
        goto generic_error;

    // Clean up.
    RELEASE(childframe);
    RELEASE(lights);
    RELEASE(meshbuilder);
    RELEASE(light1);
    RELEASE(light2);
    RELEASE(mat);
    return TRUE;

generic_error:
    DISPLAYMSG("A failure occured while building the scene.");
ret_with_error:
    RELEASE(childframe);
    RELEASE(lights);
    RELEASE(meshbuilder);
    RELEASE(light1);
    RELEASE(light2);
    RELEASE(mat);
    return FALSE;
}

RenderScene

RenderScene performs the actual drawing to the screen. It draws the scene that BuildScene created by performing the following steps.

  1. Move the scene by using IDirect3DRMFrame3::Move.
  2. Clear the viewport by using IDirect3DRMViewport2::Clear.
  3. Render the scene by using IDirect3DRMViewport2::Render.
  4. Update the window by using IDirect3DRMDevice3::Update.

RenderScene Function Source Code

// Clear the viewport, render the next frame, and update the window.

static BOOL RenderScene()
{
    HRESULT rval;

    // Move the scene.
    rval = myglobs.scene->Move(D3DVAL(1.0));
    if (FAILED(rval))
    {
        DISPLAYMSG("Moving scene failed.");
        return FALSE;
    }

    // Clear the viewport.
    rval = myglobs.view->Clear();
    if (FAILED(rval))
    {
        DISPLAYMSG("Clearing viewport failed.");
        return FALSE;
    }

    // Render the scene to the viewport.
    rval = myglobs.view->Render(myglobs.scene);
    if (FAILED(rval))
    {
        DISPLAYMSG("Rendering scene failed.");
        return FALSE;
    }

    // Update the window.
    rval = myglobs.dev->Update();
    if (FAILED(rval))
    {
        DISPLAYMSG("Updating device failed.");
        return FALSE;
    }
    return TRUE;
}

AddMediaPath

AddMediaPath provides a path to the textures and .x files needed by the application. The function searches the system registry for the location of the DirectX 6 samples, prepends that location to the path of the directory containing the Retained Mode media files, and adds the whole path to the media files to the end of the current file search path.

AddMediaPath Function Source Code

// Looks in the system registry to determine the media path for the
// sample, then adds that path to the end of the current file search path.

VOID AddMediaPath(LPDIRECT3DRM3 pD3DRM)
{
    HKEY   key;
    LONG   result;
    TCHAR  strPath[512];
    DWORD  type, size = 512;

    // Open the registry
    result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\Microsoft\\DirectX",
                          0, KEY_READ, &key);
    if(ERROR_SUCCESS != result)
        return;

    // Search for the desired registry value, and close the registry
    result = RegQueryValueEx(key, "DX6SDK Samples Path", NULL, &type,
                             (BYTE*)strPath, &size);
    RegCloseKey(key);

    if(ERROR_SUCCESS != result)
        return;

    strcat(strPath, "\\D3DRM\\Media");

    pD3DRM->AddSearchPath(strPath);

    return;
}

CreateObjects

CreateObjects initializes the sample's global variables and creates objects. After initializing global variables, CreateObjects performs the steps necessary to create a device, associate it with the application's main window, and create the master scene frame, the camera frame, and the viewport as follows:

  1. Use the DirectDraw DirectDrawCreateClipper function to create a DirectDrawClipper object.
  2. Use the DirectDrawClipper's SetHWnd method to associate the application's window with the DirectDrawClipper. The DirectDrawClipper object restricts subsequent drawing to a designated area—in this case, the application window.
  3. Use the Direct3DRMCreate function to create a Direct3D Retained Mode object, then query for the IDirect3DRM3 interface.
  4. Use the Windows GetClientRect function to obtain the height and width of the application's main window.
  5. Use the Direct3D Retained Mode object's CreateDeviceFromClipper method to create a device, passing NULL to create a default device, and passing the width and height of the application's window to the method.
  6. Create the master scene frame by using IDirect3DRM3::CreateFrame.
  7. Create the camera frame by using IDirect3DRM3::CreateFrame.
  8. Create the Direct3D Retained Mode viewport by using IDirect3DRM3::CreateViewport.
  9. Use BuildScene to create the scene.

CreateObjects Function Source Code

// Initialize globals, create the device and objects.

BOOL CreateObjects(HWND win)
{
    HRESULT rval; // Return value
    RECT rc;      // Bounding rectangle for main window
    int width;    // Device's width
    int height;   // Device's height

    // Initialize the entire global variable structure to zero.
    memset(&myglobs, 0, sizeof(myglobs));

    // Create a DirectDrawClipper object and associate the window with it.
    rval = DirectDrawCreateClipper(0, &lpDDClipper, NULL);
    if (FAILED(rval))
    {
        DISPLAYMSG("Failed to create DirectDrawClipper object");
        return FALSE;
    }

    rval = lpDDClipper->SetHWnd(0, win);
    if (FAILED(rval))
    {
        DISPLAYMSG("Failed to set the window handle for the DirectDrawClipper");
        return FALSE;
    }

    // Create the Direct3DRM object.
    LPDIRECT3DRM pD3DRMTemp;
    rval = Direct3DRMCreate(&pD3DRMTemp);
    if (FAILED(rval))
     {
        DISPLAYMSG("Failed to create Direct3DRM.");
        return FALSE;
    }
    if( FAILED(pD3DRMTemp->QueryInterface(IID_IDirect3DRM3, (void **)&lpD3DRM)))
    {
        RELEASE(pD3DRMTemp);
        DISPLAYMSG("Failed query for Direct3DRM3.\n" );
        return FALSE;
    }
    RELEASE(pD3DRMTemp);

    // Create a default Direct3D Retained Mode device.
    GetClientRect(win, &rc);

    rval = lpD3DRM->CreateDeviceFromClipper(lpDDClipper,
                           NULL, // Default device
                           rc.right, rc.bottom, &myglobs.dev);
    if (FAILED(rval))
    {
        DISPLAYMSG("Failed to create the D3DRM device.");
        return FALSE;
    }

    // Create the master scene frame and the camera frame.
    rval = lpD3DRM->CreateFrame(NULL, &myglobs.scene);
    if (FAILED(rval))
    {
        DISPLAYMSG("Failed to create the master scene frame.");
        return FALSE;
    }

    rval = lpD3DRM->CreateFrame(myglobs.scene, &myglobs.camera);
    if (FAILED(rval))
    {
        DISPLAYMSG("Failed to create the camera's frame.");
        return FALSE;
    }

    // Create the Direct3D Retained Mode viewport using the device, camera frame,
    // and the device's width and height.
    width = myglobs.dev->GetWidth();
    height = myglobs.dev->GetHeight();

    rval = lpD3DRM->CreateViewport(myglobs.dev, myglobs.camera, 0, 0,
                                   width, height, &myglobs.view);
    if (FAILED(rval))
    {
        myglobs.bInitialized = FALSE;
        RELEASE(myglobs.dev);
        return FALSE;
    }

    // Add the media path so textures and .x files can be found
    AddMediaPath( lpD3DRM );

    // Create the scene to be rendered.
    if (!BuildScene(lpD3DRM, myglobs.dev, myglobs.scene,
                    myglobs.camera))
        return FALSE;

    // Globals are initialized.
    myglobs.bInitialized = TRUE;

    return TRUE;
}

InitApp

The InitApp function creates the main window class and the main window, as is typical of Windows applications. The only Direct3D Retained Mode–related call in InitApp is the call to CreateObjects.

InitApp Function Source Code

// Create the main window and initialize objects.

static HWND InitApp(HINSTANCE this_inst, int cmdshow)
{
    HWND win;     // Main window handle
    WNDCLASS wc;  // Window class

    // Set up and register the window class.
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = WindowProc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = sizeof(DWORD);
    wc.hInstance = this_inst;
    wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
    wc.lpszMenuName = NULL;
    wc.lpszClassName = "D3DRM Example";
    if (!RegisterClass(&wc))
        return FALSE;

    // Create the window.
    win = CreateWindow(
            "D3DRM Example",                   // class
            "RMBegin1: Direct3DRM Sample One", // caption
            WS_OVERLAPPEDWINDOW,               // style
            CW_USEDEFAULT,                     // init. x pos
            CW_USEDEFAULT,                     // init. y pos
            350,                               // init. x size
            300,                               // init. y size
            NULL,                              // parent window
            NULL,                              // menu handle
            this_inst,                         // program handle
            NULL);                             // create parms

    if (!win)
        return FALSE;

    // Initialize global variables and create the Direct3D Retained
    // Mode objects.
    if (!CreateObjects(win))
        return FALSE;

    // Display the window.
    ShowWindow(win, cmdshow);
    UpdateWindow(win);

    return win;
}

WinMain

WinMain provides the main message loop for the application. As long as the global variables are initialized and the application is not minimized, WinMain uses RenderScene to draw the scene to the screen.

WinMain Function Source Code

// Initialize the application, process messages, and render the scene.

int APIENTRY WinMain (HINSTANCE this_inst,
                      HINSTANCE prev_inst,
                      LPSTR cmdline,
                      int cmdshow)
{
    HWND    hwnd;
    MSG     msg;
    prev_inst;
    cmdline;

    // Create the window and initialize objects.
    if (!(hwnd = InitApp(this_inst, cmdshow)))
        return 1;

    while (TRUE)
    {
        // Monitor the message queue and process messages. PeekMessage
        // returns control to the application immediately so that the
        // application can both process messages and continue rendering.
        // If the message is WM_QUIT, break out of this function
        // because the application is terminating.
        if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
            if (msg.message == WM_QUIT)
                break;
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }

        // If the application is not minimized and the Direct3D Retained
        // Mode objects are initialized, render.
        if (!myglobs.bMinimized && myglobs.bInitialized)
        {
            // Render one frame of the scene. If rendering fails, post
            // the WM_DESTROY message, enabling the application to
            // free resources before terminating the application.
            if (!RenderScene())
            {
                DISPLAYMSG("Rendering failed. Aborting execution.");
                PostMessage(NULL, WM_DESTROY, 0, 0);
                break;
            }

        // Yield to other applications if this application is
        // not currently rendering.
        } else
              WaitMessage();

    }
    return msg.wParam;
}

WindowProc

WindowProc handles messages for the main application window. WindowProc sets a flag so that the application stops rendering while minimized. This function also releases objects when the application shuts down.

WindowProc Function Source Code

// Handle messages for the main window.

LRESULT CALLBACK WindowProc(HWND win,
                            UINT msg,
                            WPARAM wparam,
                            LPARAM lparam)
{
    switch (msg)
    {
        case WM_SIZE:
            // Handle minimizing of the window. If the application was
            // minimized, set a flag so that rendering will stop while
            // minimized. Otherwise, continue rendering.
            if (SIZE_MINIMIZED == wparam)
                myglobs.bMinimized = TRUE;
            else
                myglobs.bMinimized = FALSE;
            break;

        case WM_DESTROY:
            // Clear the bInitialized flag, free objects, and post the
            // WM_QUIT message to terminate the application. Be sure to
            // free the viewport before freeing the device, or a general
            // protection fault might occur.
            myglobs.bInitialized = FALSE;
            RELEASE(myglobs.view);
            RELEASE(myglobs.dev);
            RELEASE(lpD3DRM);
            RELEASE(lpDDClipper);
            PostQuitMessage(0);
            break;

        default:
            return DefWindowProc(win, msg, wparam, lparam);
    }
    return 0L;
}

Related Topics

Now that you are familiar with the basics of creating objects and putting something on the screen using Direct3D Retained Mode, the code in the Direct3D Retained Mode samples should be easier to understand. Nearly all of these samples use the helper code provided by RMMain to create a device and render a scene. They each provide their own BuildScene function to create unique scenes.

As a next step, you can look at the RMBegin2 sample, which extends the functionality provided by RMBegin1. You could also look at some of the Direct3D Retained Mode samples, such as Egg or Globe, that provide functionality similar to RMBegin1.

For information about another common task in Direct3D Retained Mode, see Enumerating Devices: The RMEnum Sample, which provides a walkthrough of the RMEnum sample code. RMEnum focuses on how to enumerate devices.

For brief summaries of all of the Retained Mode samples, see Samples.


Frame Hierarchies: The RMBegin2 Sample

Creating a device, building a scene, and moving the scene are fundamental concepts in Microsoft® Direct3D® Retained Mode. The RMBegin2 sample builds on these concepts, which were introduced by the RMBegin1 sample. This article walks you through code from the RMBegin2 sample.

Similar to RMBegin1, RMBegin2 demonstrates creating a default device, loading meshes from Microsoft DirectX® files, adding color to the objects and lights to the scene, and rotating the objects. RMBegin2 builds a more complex scene than RMBegin1, scales the objects, and uses a hierarchy of frames. In the process of building the scene, the sample uses three meshbuilders, several frames, and several lights. The sample also creates a DirectDrawClipper object, viewport and camera. RMBegin2 also adds new functionality by resizing the scene when the application window is resized and by handling the WM_ACTIVATE and WM_PAINT messages.

RMBegin2 provides a hierarchy of frames with three spheres (representing a sun, planet, and moon) revolving around their respective parent frames.

The source code for the RMBegin2 sample consists of one self-contained file (RMBegin2.cpp). For simplicity, this sample doesn't use any separate header files, except for the standard Microsoft Windows®, DirectDraw®, and Direct3D Retained Mode header files. It also does not contain any menus, icons, or other resources.

This sample uses the Sphere0.x, Sphere1.x, and Sphere2.x files from the DirectX Foundation Software Development Kit (SDK) to provide the moon, planet, and sun images for the scene. By default when you install the SDK, the SDK's setup program sets an environment variable to point to the SDK's media directory. These three DirectX (.x) files reside in that directory, allowing the application to locate the file automatically. If you have not installed the SDK and simply run RMBegin2.exe, these DirectX files must be located in the same directory as RMBegin2.exe.

This article assumes you are an experienced C or C++ programmer and are familiar with beginning Windows programming concepts, such as the message loop, creating a window, and using menus.

This article contains the following sections.

  • Dependencies
  • Global Declarations
  • Function Summaries
  • Related Topics

Dependencies

  • RMBegin2 links to DDraw.lib and D3DRM.lib.
  • RMBegin2 loads the sphere images from Sphere0.x, Sphere1.x, and Sphere2.x, as described in the previous section.
  • To properly initialize globally unique identifiers (GUIDs), Direct3D applications must contain the following definition at the top of their code.
    #define INITGUID
  • The sample's RMBegin2.cpp file includes the following header files.
    #include <windows.h>   // Standard Windows header file
#include <direct.h>    // DirectDraw definitions
#include <d3drmwin.h>  // Direct3D Retained Mode definitions

Global Declarations

The sample defines some constants and global variables to help organize information.

The application-defined RELEASE macro releases an object only if the object is not NULL and ensures that an object is initialized to NULL after it has been released. This practice eliminates the problem of trying to release an object that has already been released, which can cause undesired results, such as page faults.

// Macro to release an object.
#define RELEASE(x) if (x != NULL) {x->Release(); x = NULL;}

The application-defined DISPLAYMSG macro uses the Windows MessageBox function to display information to the user. Using this macro rather than direct calls to MessageBox throughout the sample code makes the code cleaner and easier to read.

// Macro to display a message box containing the given string.
#define DISPLAYMSG(x) MessageBox(NULL, x, "D3DRM Sample", MB_OK);

Global variables keep track of the key objects, such as the Direct3D Retained Mode and DirectDrawClipper objects (the DirectDrawClipper object restricts drawing to a designated area). The myglobs structure collects device, window device, viewport, scene, and camera information, as well as information about whether the application is minimized and whether objects have been initialized. Note that RMBegin2 adds a Direct3D Retained Mode window device to the objects RMBegin1 uses.

// Global Variables
LPDIRECT3DRM3 lpD3DRM = NULL;            // Direct3D Retained Mode object
LPDIRECTDRAWCLIPPER lpDDClipper = NULL; // DirectDrawClipper object

// Global Structure
struct _myglobs {

   // Direct3DRM device.
    LPDIRECT3DRMDEVICE3 dev;

    // Direct3DRM window device.
    LPDIRECT3DRMWINDEVICE windevice;

    // Direct3DRM viewport through which to view the scene.
    LPDIRECT3DRMVIEWPORT2 view;

    // Master frame in which other frames are placed.
    LPDIRECT3DRMFRAME3 scene;

    // Frame describing the users point of view.
    LPDIRECT3DRMFRAME3 camera;

    // Application is minimized
    BOOL bMinimized;

    // All Direct3D Retained Mode objects have been initialized.
    BOOL bInitialized;

} myglobs;

Function Summaries

RMBegin2.cpp contains the following functions.

BuildScene creates the scene to be rendered. It loads meshes from DirectX files, scales the meshes, adds color to the meshes, creates a hierarchy of frames, and adds lights to the scene. BuildScene also sets the position of objects and how objects should be rotated. CreateObjects, which initializes global variables and creates default devices, frames, and viewports, uses this function. Although conceptually similar to the RMBegin1 BuildScene function, the RMBegin2 BuildScene functions creates a more complex scene.

BOOL BuildScene(LPDIRECT3DRM3, LPDIRECT3DRMDEVICE3,
                LPDIRECT3DRMFRAME3, LPDIRECT3DRMFRAME3);

RenderScene draws the scene that BuildScene created. Each time WinMain uses this function, RenderScene moves the scene, giving the effect of a spinning object. This function is identical to the RenderScene function provided by the RMBegin1 sample.

static BOOL RenderScene(void);

AddMediaPath provides a path to the textures and .x files needed by the application by searching the registry.

VOID AddMediaPath(LPDIRECT3DRM3 pD3DRM)

CreateObjects initializes the global variables and creates a default device, window device, camera frame, scene frame, and viewport. CreateObjects uses BuildScene to create the scene to be rendered. InitApp, which creates the application's window, uses CreateObjects. This function is identical to the CreateObjects function provided by the RMBegin1 sample, except that it also creates a window device.

BOOL CreateObjects(HWND win);

InitApp provides standard, Windows application code to create the window class and the application's window. It uses CreateObjects to initialize global objects. This function is identical to the InitApp function provided by the RMBegin1 sample, except that it provides a different window caption.

static HWND InitApp(HINSTANCE, int);

WinMain provides the application's message loop. It uses InitApp to initialize the application and uses RenderScene to draw the scene. This function is identical to the WinMain function provided by the RMBegin1 sample.

int APIENTRY WinMain(HINSTANCE, HINSTANCE, LPSTR, int);

WindowProc handles messages for the application. It handles cases where the application is minimized, resized, activated, painted, or destroyed.

LRESULT CALLBACK WindowProc(HWND, UINT, WPARAM, LPARAM);

For more information about these functions, see the following topics in this article.

  • BuildScene
  • RenderScene
  • AddMediaPath
  • CreateObjects
  • InitApp
  • WinMain
  • WindowProc

BuildScene

The BuildScene function creates the scene to be rendered. All Direct3D Retained Mode applications must create a scene, but the code required depends on the scene. Applications typically create frames and lights, add visuals to the scene, and set the position of objects. This function also scales objects and sets up a hierarchy of frames.

This section of this article provides code fragments from the BuildScene function and presents the steps the RMBegin2 sample performs to build the sun, planet, and moon scene. This section also presents the complete source code for the RMBegin2 sample's BuildScene function. If an error occurs, the code uses goto statements to jump to the end of the function and ensure that all objects are properly released before returning from the function.

  1. Load meshes from DirectX files by using the IDirect3DRM3::CreateMeshBuilder and IDirect3DRMMeshBuilder3::Load methods. The following code fragment loads one mesh. The sample uses a similar process to load the other meshes.
        if (FAILED(lpD3DRM->CreateMeshBuilder(&sun_builder)))
        goto generic_error;

    rval = sun_builder->Load("sphere2.x", NULL,
                    D3DRMLOAD_FROMFILE, NULL, NULL);
    if (FAILED(rval)) {
        DISPLAYMSG("Failed to load sphere2.x file.");
        goto ret_with_error;
    }
  2. Scale and color the meshes. The three spheres that the sample loads are all nearly the same size, so the sample increases the size of the sun sphere and decreases the size of the planet and moon spheres. The following code fragment shows this process for one mesh.
        if (FAILED(sun_builder->Scale(D3DVAL(1.2), D3DVAL(1.2),
                                  D3DVAL(1.2))))
        goto generic_error;
    if (FAILED(sun_builder->SetColorRGB(D3DVAL(1.0), D3DVAL(1.0),
                                        D3DVAL(0.0))))
        goto generic_error;
  3. Create a hierarchy of frames within the scene by using the IDirect3DRM3::CreateFrame method. The following code fragment creates a sun frame within the master scene frame, a planet frame within the sun frame, and a moon frame within the planet frame. When the sample sets the object's rotation, this hierarchy governs which objects revolve around the other objects.
        if (FAILED(lpD3DRM->CreateFrame(scene, &sun)))
        goto generic_error;
    if (FAILED(lpD3DRM->CreateFrame(sun, &planet)))
        goto generic_error;
    if (FAILED(lpD3DRM->CreateFrame(planet, &moon)))
        goto generic_error;
  4. Use the meshbuilder object to convert to the underlying meshes by using IDirect3DRMMeshBuilder3::CreateMesh. This code fragment creates the sun mesh.
        if (FAILED(sun_builder->CreateMesh(&sun_mesh)))
        goto generic_error;
  5. Add the loaded meshes into the appropriate child frames by using the IDirect3DRMFrame3::AddVisual method. This code fragment adds the sun mesh into the sun frame.
        if (FAILED(sun->AddVisual((LPDIRECT3DRMVISUAL) sun_mesh)))
        goto generic_error;
  6. Set the camera position within the scene by using the IDirect3DRMFrame3::SetPosition method. Set the other object's position, as well. This code fragment sets the camera's and sun's positions. The sun appears to be straight in front of the camera because the x-coordinate and y-coordinate for the sun position and camera position are the same (0,0).
        if (FAILED(camera->SetPosition(scene, D3DVAL(0), D3DVAL(0),
                                   -D3DVAL(25))))
        goto generic_error;
    if (FAILED(sun->SetPosition(scene, D3DVAL(0), D3DVAL(0),
                                D3DVAL(0))))
        goto generic_error;
  7. Set the frame's rotation by using the IDirect3DRMFrame3::SetRotation method. This fragment sets the sun's rotation.
        if (FAILED(sun->SetRotation(scene, D3DVAL(0), D3DVAL(0),
                                D3DVAL(1),
                                D3DVAL(0.01))))
  8. Create a light frame that is a child of the scene by using the IDirect3DRM3::CreateFrame method. Position the light frame within the scene by using the IDirect3DRMFrame3::SetPosition method. Create a bright point light and add it to the light frame by using the IDirect3DRM3::CreateLightRGB and IDirect3DRMFrame3::AddLight methods.
        if (FAILED(lpD3DRM->CreateFrame(scene, &lights)))
        goto generic_error;
    if (FAILED(lights->SetPosition(scene, D3DVAL(0), D3DVAL(0),
                                -D3DVAL(7))))
        goto generic_error;
    if (FAILED(lpD3DRM->CreateLightRGB(D3DRMLIGHT_POINT, D3DVAL(0.9),
                                  D3DVAL(0.8), D3DVAL(0.7), &light1)))
        goto generic_error;
    if (FAILED(lights->AddLight(light1)))
        goto generic_error;
  9. Create a dim, ambient light and add it to the scene, again by using the IDirect3DRM3::CreateLightRGB and IDirect3DRMFrame3::AddLight methods.
        if (FAILED(lpD3DRM->CreateLightRGB(D3DRMLIGHT_AMBIENT, D3DVAL(0.1),
                                  D3DVAL(0.1), D3DVAL(0.1), &light2)))
        goto generic_error;
    if (FAILED(scene->AddLight(light2)))
        goto generic_error;
  10. Create a bright, parallel point light and add it to the light frame, using the same methods used to create ambient light.
        if (FAILED(lpD3DRM->CreateLightRGB(D3DRMLIGHT_PARALLELPOINT,
                                  D3DVAL(0.9), D3DVAL(0.9), D3DVAL(0.9),
                                  &light3)))
        goto generic_error;
    if (FAILED(sun->AddLight(light3)))
        goto generic_error;
  11. Clean up by releasing all of the objects created by this function.
        RELEASE(sun_builder);
    RELEASE(planet_builder);
    RELEASE(moon_builder);
    RELEASE(sun_mesh);
    RELEASE(planet_mesh);
    RELEASE(moon_mesh);
    RELEASE(sun);
    RELEASE(planet);
    RELEASE(moon);
    RELEASE(lights);
    RELEASE(light1);
    RELEASE(light2);
    RELEASE(light3);

BuildScene Function Source Code

// Create the scene to be rendered.

BOOL BuildScene(LPDIRECT3DRM3 lpD3DRM,  LPDIRECT3DRMDEVICE3 dev,
                 LPDIRECT3DRMFRAME3 scene, LPDIRECT3DRMFRAME3 camera)
{
    LPDIRECT3DRMMESHBUILDER3 sun_builder = NULL;
    LPDIRECT3DRMMESHBUILDER3 planet_builder = NULL;
    LPDIRECT3DRMMESHBUILDER3 moon_builder = NULL;
    LPDIRECT3DRMMESH sun_mesh = NULL;
    LPDIRECT3DRMMESH planet_mesh = NULL;
    LPDIRECT3DRMMESH moon_mesh = NULL;
    LPDIRECT3DRMFRAME3 sun = NULL;
    LPDIRECT3DRMFRAME3 planet = NULL;
    LPDIRECT3DRMFRAME3 moon = NULL;
    LPDIRECT3DRMLIGHT light1 = NULL;
    LPDIRECT3DRMLIGHT light2 = NULL;
    LPDIRECT3DRMLIGHT light3 = NULL;
    LPDIRECT3DRMFRAME3 lights = NULL;
    HRESULT rval;

    // Create a meshbuilder for each DirectX file to be loaded (one
    // for sun, planet, and moon) and load the meshes.
    if (FAILED(lpD3DRM->CreateMeshBuilder(&sun_builder)))
        goto generic_error;
    if (FAILED(lpD3DRM->CreateMeshBuilder(&planet_builder)))
        goto generic_error;
    if (FAILED(lpD3DRM->CreateMeshBuilder(&moon_builder)))
        goto generic_error;

    rval = sun_builder->Load("sphere2.x", NULL,
                    D3DRMLOAD_FROMFILE, NULL, NULL);
    if (FAILED(rval)) {
        DISPLAYMSG("Failed to load sphere2.x file.");
        goto ret_with_error;
    }

    rval = planet_builder->Load("sphere1.x", NULL,
                    D3DRMLOAD_FROMFILE, NULL, NULL);
    if (FAILED(rval)) {
        DISPLAYMSG("Failed to load sphere1.x file.");
    goto ret_with_error;
    }

    rval = moon_builder->Load("sphere0.x", NULL,
                    D3DRMLOAD_FROMFILE, NULL, NULL);
    if (FAILED(rval)) {
        DISPLAYMSG("Failed to load sphere0.x file.");
        goto ret_with_error;
    }

    // Adjust the scale (size) of the sun, planet, and moon meshes.
    // Scale equally in the x-, y-, and z-directions to maintain the
    // spherical shape of each mesh. Increase the size of the sun
    // and decrease the size of the planet and moon meshes to
    // achieve the desired relative sizes.
    if (FAILED(sun_builder->Scale(D3DVAL(1.2), D3DVAL(1.2),
                                  D3DVAL(1.2))))
        goto generic_error;
    if (FAILED(planet_builder->Scale(D3DVAL(0.5), D3DVAL(0.5),
                                     D3DVAL(0.5))))
        goto generic_error;
    if (FAILED(moon_builder->Scale(D3DVAL(0.2), D3DVAL(0.2),
                                   D3DVAL(0.2))))
        goto generic_error;

    // Adjust the color of the sun, planet, and moon meshes.
    // Set the sun to yellow, the planet to greenish-blue, and the
    // moon to red.
    if (FAILED(sun_builder->SetColorRGB(D3DVAL(1.0), D3DVAL(1.0),
                                        D3DVAL(0.0))))
        goto generic_error;
    if (FAILED(planet_builder->SetColorRGB(D3DVAL(0.2), D3DVAL(1.0),
                                           D3DVAL(0.8))))
        goto generic_error;
    if (FAILED(moon_builder->SetColorRGB(D3DVAL(0.7), D3DVAL(0.2),
                                         D3DVAL(0.3))))
        goto generic_error;

    // Create hierarchies of frames:
    // - Sun frame within the master scene frame
    // - Planet frame within the sun frame
    // - Moon frame within the planet frame
    if (FAILED(lpD3DRM->CreateFrame(scene, &sun)))
        goto generic_error;
    if (FAILED(lpD3DRM->CreateFrame(sun, &planet)))
        goto generic_error;
    if (FAILED(lpD3DRM->CreateFrame(planet, &moon)))
        goto generic_error;

    // Create meshes from the meshbuilders to avoid the same future
    // conversion by Direct3D Retained Mode. The meshbuilders could be
    // released now, but for clarity they are released with the other
    // objects at the end of this function.
    if (FAILED(sun_builder->CreateMesh(&sun_mesh)))
        goto generic_error;
    if (FAILED(planet_builder->CreateMesh(&planet_mesh)))
        goto generic_error;
    if (FAILED(moon_builder->CreateMesh(&moon_mesh)))
        goto generic_error;

    // Add the meshes into the frames.
    if (FAILED(sun->AddVisual((LPDIRECT3DRMVISUAL) sun_mesh)))
        goto generic_error;
    if (FAILED(planet->AddVisual((LPDIRECT3DRMVISUAL) planet_mesh)))
        goto generic_error;
    if (FAILED(moon->AddVisual((LPDIRECT3DRMVISUAL) moon_mesh)))
        goto generic_error;

    // Set up the frame positions.
    if (FAILED(camera->SetPosition(scene, D3DVAL(0), D3DVAL(0),
                                   -D3DVAL(25))))
        goto generic_error;
    if (FAILED(sun->SetPosition(scene, D3DVAL(0), D3DVAL(0),
                                D3DVAL(0))))
        goto generic_error;
    if (FAILED(planet->SetPosition(sun, D3DVAL(7), D3DVAL(0),
                                   D3DVAL(0))))
        goto generic_error;
    if (FAILED(moon->SetPosition(planet, D3DVAL(0), D3DVAL(3),
                                 D3DVAL(0))))
        goto generic_error;

    // Set up the frame rotations.
    if (FAILED(sun->SetRotation(scene, D3DVAL(0), D3DVAL(0),
                                D3DVAL(1),
                                D3DVAL(0.01))))
        goto generic_error;
    if (FAILED(planet->SetRotation(sun, D3DVAL(1), D3DVAL(0),
                                   D3DVAL(0),
                                   D3DVAL(0.02))))
        goto generic_error;
    if (FAILED(moon->SetRotation(planet, D3DVAL(0.1), D3DVAL(0.2),
                               D3DVAL(0.7),
                               D3DVAL(0.03))))
       goto generic_error;

    // Initialize the lights in the scene.
    // - Create a light frame. Set its position within the scene
    //   (straight ahead, directly in front of the sun, to illuminate
    //   the sun) and attach a point light to the light frame.
    // - Create a soft, ambient light and add it to the scene.
    // - Create a bright, parallel point light and add it to the sun
    //   frame to properly illuminate the planet and moon as they
    //   revolve around the sun.

    // Create a point light in front of sun.
    if (FAILED(lpD3DRM->CreateFrame(scene, &lights)))
        goto generic_error;
    if (FAILED(lights->SetPosition(scene, D3DVAL(0), D3DVAL(0),
                                -D3DVAL(7))))
        goto generic_error;
    if (FAILED(lpD3DRM->CreateLightRGB(D3DRMLIGHT_POINT, D3DVAL(0.9),
                                  D3DVAL(0.8), D3DVAL(0.7), &light1)))
        goto generic_error;
    if (FAILED(lights->AddLight(light1)))
        goto generic_error;

    // Create an ambient light and add it to the scene.
    if (FAILED(lpD3DRM->CreateLightRGB(D3DRMLIGHT_AMBIENT, D3DVAL(0.1),
                                  D3DVAL(0.1), D3DVAL(0.1), &light2)))
        goto generic_error;
    if (FAILED(scene->AddLight(light2)))
        goto generic_error;

    // Create a parallel point light and add it to the sun frame.
    if (FAILED(lpD3DRM->CreateLightRGB(D3DRMLIGHT_PARALLELPOINT,
                                  D3DVAL(0.9), D3DVAL(0.9), D3DVAL(0.9),
                                  &light3)))
        goto generic_error;
    if (FAILED(sun->AddLight(light3)))
        goto generic_error;

    // Clean up.
    RELEASE(sun_builder);
    RELEASE(planet_builder);
    RELEASE(moon_builder);
    RELEASE(sun_mesh);
    RELEASE(planet_mesh);
    RELEASE(moon_mesh);
    RELEASE(sun);
    RELEASE(planet);
    RELEASE(moon);
    RELEASE(lights);
    RELEASE(light1);
    RELEASE(light2);
    RELEASE(light3);
    return TRUE;

generic_error:
    DISPLAYMSG("A failure occurred while building the scene.");
ret_with_error:
    RELEASE(sun_builder);
    RELEASE(planet_builder);
    RELEASE(moon_builder);
    RELEASE(sun_mesh);
    RELEASE(planet_mesh);
    RELEASE(moon_mesh);
    RELEASE(sun);
    RELEASE(planet);
    RELEASE(moon);
    RELEASE(lights);
    RELEASE(light1);
    RELEASE(light2);
    RELEASE(light3);
    return FALSE;
}

RenderScene

RenderScene performs the actual drawing to the screen. It draws the scene that BuildScene created by performing the following steps.

  1. Move the scene by using IDirect3DRMFrame3::Move.
  2. Clear the viewport by using IDirect3DRMViewport2::Clear.
  3. Render the scene by using IDirect3DRMViewport2::Render.
  4. Update the window by using IDirect3DRMDevice3::Update.

RenderScene Function Source Code

// Clear the viewport, render the next frame, and update the window.

static BOOL RenderScene()
{
    HRESULT rval;

    // Move the scene.
    rval = myglobs.scene->Move(D3DVAL(1.0));
    if (FAILED(rval))
    {
        DISPLAYMSG("Moving scene failed.");
        return FALSE;
    }

    // Clear the viewport.
    rval = myglobs.view->Clear();
    if (FAILED(rval))
    {
        DISPLAYMSG("Clearing viewport failed.");
        return FALSE;
    }

    // Render the scene to the viewport.
    rval = myglobs.view->Render(myglobs.scene);
    if (FAILED(rval))
    {
        DISPLAYMSG("Rendering scene failed.");
        return FALSE;
    }

    // Update the window.
    rval = myglobs.dev->Update();
    if (FAILED(rval))
    {
        DISPLAYMSG("Updating device failed.");
        return FALSE;
    }
    return TRUE;
}

AddMediaPath

AddMediaPath provides a path to the textures and .x files needed by the application. The function searches the system registry for the location of the DirectX 6.x samples, prepends that location to the path of the directory containing the Retained Mode media files, and adds the whole path to the media files to the end of the current file search path.

AddMediaPath Function Source Code

// Looks in the system registry to determine the media path for the
// sample, then adds that path to the end of the current file search path.

VOID AddMediaPath(LPDIRECT3DRM3 pD3DRM)
{
    HKEY   key;
    LONG   result;
    TCHAR  strPath[512];
    DWORD  type, size = 512;

    // Open the registry
    result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\Microsoft\\DirectX",
                          0, KEY_READ, &key);
    if(ERROR_SUCCESS != result)
        return;

    // Search for the desired registry value, and close the registry
    result = RegQueryValueEx(key, "DX6SDK Samples Path", NULL, &type,
                             (BYTE*)strPath, &size);
    RegCloseKey(key);

    if(ERROR_SUCCESS != result)
        return;

    strcat(strPath, "\\D3DRM\\Media");

    pD3DRM->AddSearchPath(strPath);

    return;
}

CreateObjects

CreateObjects initializes the sample's global variables and creates objects. After initializing global variables, CreateObjects performs the steps necessary to create a device, associate it with the application's main window, and create the master scene frame, the camera frame, and the viewport as follows:

  1. Use the DirectDraw DirectDrawCreateClipper function to create a DirectDrawClipper object.
  2. Use the DirectDrawClipper object's SetHWnd method to associate the application's window with the DirectDrawClipper. The DirectDrawClipper object restricts subsequent drawing to a designated area—in this case, the application window.
  3. Use the Direct3DRMCreate function to create a Direct3D Retained Mode object, then query for the IDirect3DRM3 interface.
  4. Use the Windows GetClientRect function to obtain the height and width of the application's main window.
  5. Use the Direct3D Retained Mode object's CreateDeviceFromClipper method to create a device, passing NULL to create a default device, and passing the width and height of the application's window to the method.
  6. Create a Direct3D Retained Mode window device by querying the device for support of the IDirect3DRMWinDevice interface. The window device handles the WM_ACTIVATE and WM_PAINT messages.
  7. Create the master scene frame by using IDirect3DRM3::CreateFrame.
  8. Create the camera frame by using IDirect3DRM3::CreateFrame.
  9. Create the Direct3D Retained Mode viewport by using IDirect3DRM3::CreateViewport.
  10. Use BuildScene to create the scene.

CreateObjects Function Source Code

// Initialize globals, and create the device and objects.

BOOL CreateObjects(HWND win)
{
    HRESULT rval; // Return value
    RECT rc;      // Bounding rectangle for main window
    int width;    // Device's width
    int height;   // Device's height

    // Initialize the entire global variable structure to zero.
    memset(&myglobs, 0, sizeof(myglobs));

    // Create a DirectDrawClipper object and associate the window with it.
    rval = DirectDrawCreateClipper(0, &lpDDClipper, NULL);
    if (FAILED(rval)) {
        DISPLAYMSG("Failed to create DirectDrawClipper object.");
        return FALSE;
    }
    rval = lpDDClipper->SetHWnd(0, win);
    if (FAILED(rval)) {
        DISPLAYMSG("Failed to set the window handle for the DirectDrawClipper.");
        return FALSE;
    }

   // Create the Direct3DRM object.
    LPDIRECT3DRM pD3DRMTemp;
    rval = Direct3DRMCreate(&pD3DRMTemp);
    if (FAILED(rval))
    {
        DISPLAYMSG("Failed to create Direct3DRM.");
        return FALSE;
    }
    if( FAILED(pD3DRMTemp->QueryInterface(IID_IDirect3DRM3, (void **)&lpD3DRM)))
    {
        RELEASE(pD3DRMTemp);
        DISPLAYMSG("Failed query for Direct3DRM3.\n" );
        return FALSE;
    }
    RELEASE(pD3DRMTemp);

    // Create a default Direct3D Retained Mode device.
    GetClientRect(win, &rc);

    rval = lpD3DRM->CreateDeviceFromClipper(lpDDClipper,
                           NULL, // Default device
                           rc.right, rc.bottom, &myglobs.dev);

    if (FAILED(rval)) {
        DISPLAYMSG("Failed to create the D3DRM device.");
        return FALSE;
    }

    // Create a Direct3D Retained Mode window device to handle the
    // WM_ACTIVATE and WM_PAINT messages.
    rval = myglobs.dev->QueryInterface(IID_IDirect3DRMWinDevice,
                                       (void **) &myglobs.windevice);
    if (FAILED(rval)) {
        DISPLAYMSG("Failed to create the window device.");
        return FALSE;
    }

    // Create the master scene frame and the camera frame.
    rval = lpD3DRM->CreateFrame(NULL, &myglobs.scene);
    if (FAILED(rval)) {
        DISPLAYMSG("Failed to create the master scene frame.");
        return FALSE;
    }

    rval = lpD3DRM->CreateFrame(myglobs.scene, &myglobs.camera);
    if (FAILED(rval)) {
        DISPLAYMSG("Failed to create the camera's frame.");
        return FALSE;
    }

    // Create the Direct3D Retained Mode viewport using the device, camera frame,
    // and the device's width and height.
    width = myglobs.dev->GetWidth();
    height = myglobs.dev->GetHeight();

    rval = lpD3DRM->CreateViewport(myglobs.dev, myglobs.camera, 0, 0,
                                   width, height, &myglobs.view);
    if (FAILED(rval)) {
        myglobs.bInitialized = FALSE;
        RELEASE(myglobs.dev);
        return FALSE;
    }

    // Add the media path so textures and .x files can be found.
    AddMediaPath( lpD3DRM );

    // Create the scene to be rendered.
    if (!BuildScene(lpD3DRM, myglobs.dev, myglobs.scene,
                    myglobs.camera))
        return FALSE;

    // Globals are initialized.
    myglobs.bInitialized = TRUE;

    return TRUE;
}

InitApp

The InitApp function creates the main window class and the main window, as is typical of Windows applications. The only Direct3D Retained Mode–related call in InitApp is the call to CreateObjects.

InitApp Function Source Code

// Create the main window and initialize objects.

static HWND InitApp(HINSTANCE this_inst, int cmdshow)
{
    HWND win;     // Main window handle
    WNDCLASS wc;

    // Set up and register the window class.
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = WindowProc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = sizeof(DWORD);
    wc.hInstance = this_inst;
    wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
    wc.lpszMenuName = NULL;
    wc.lpszClassName = "D3DRM Example";
    if (!RegisterClass(&wc))
        return FALSE;

    // Create the window.
    win = CreateWindow(
            "D3DRM Example",                   // class
            "RMBegin2: Direct3DRM Sample Two", // caption
            WS_OVERLAPPEDWINDOW,               // style
            CW_USEDEFAULT,                     // init. x pos
            CW_USEDEFAULT,                     // init. y pos
            350,                               // init. x size
            300,                               // init. y size
            NULL,                              // parent window
            NULL,                              // menu handle
            this_inst,                         // program handle
            NULL                               // create parms
        );
    if (!win)
        return FALSE;

    // Initialize global variables, enumerate devices, and create the
    // Direct3D Retained Mode objects.
    if (!CreateObjects(win))
        return FALSE;

    // Display the window.
    ShowWindow(win, cmdshow);
    UpdateWindow(win);

    return win;
}

WinMain

WinMain provides the main message loop for the application. As long as the global variables are initialized and the application is not minimized, WinMain uses RenderScene to draw the scene to the screen.

WinMain Function Source Code

// Initialize the application, process messages, and render the scene.

int APIENTRY WinMain (HINSTANCE this_inst,
                      HINSTANCE prev_inst,
                      LPSTR cmdline,
                      int cmdshow)
{
    HWND    hwnd;
    MSG     msg;
    prev_inst;
    cmdline;

    // Create the window and initialize objects.
    if (!(hwnd = InitApp(this_inst, cmdshow)))
        return 1;

    while (TRUE) {
        // Monitor the message queue and process messages. PeekMessage
        // returns control to the application immediately so that the
        // application can both process messages and continue rendering.
        // If the message is WM_QUIT, break out of this function
        // because the application is terminating.
        if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {

            if (msg.message == WM_QUIT)
                break;
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }

        // If the application is not minimized, and the Direct3D Retained
        // Mode objects are initialized, render.
        if (!myglobs.bMinimized && myglobs.bInitialized) {

            // Render one frame of the scene. If rendering fails, post
            // the WM_DESTROY message, enabling the application to
            // free resources before terminating the application.
            if (!RenderScene()) {
                DISPLAYMSG("Rendering failed. Aborting execution.");
                PostMessage(NULL, WM_DESTROY, 0, 0);
                break;
            }

        // Yield to other applications if this application is
        // not currently rendering.
        } else
              WaitMessage();

    }
    return msg.wParam;
}

WindowProc

WindowProc handles messages for the main application window. WindowProc sets a flag so that the application stops rendering while minimized. This function also handles resizing of the application window, activating the window, painting, and releasing objects when the application shuts down.

When the user resizes the application window, the RMBegin2 sample increases or decreases the size of the scene so that it continues to fill the window. This function performs the following steps to handle the WM_SIZE message (window resizing).

  • If the application was minimized, set the minimized flag and break out of the function because there is no more resizing to handle.
  • Obtain the current width and height of the window, viewport, and device.
  • If the application window was resized larger than the current device, destroy the old viewport, device, and window device and create new ones. If the application was resized smaller than the current device, re-create only the viewport.

WindowProc uses the window device to handle the WM_ACTIVATE and WM_PAINT messages by using the IDirect3DRMWinDevice::HandleActivate and IDirect3DRMWinDevice::HandlePaint methods, respectively.

WindowProc Function Source Code

// Handle messages for the main window.

LRESULT CALLBACK WindowProc(HWND win,
                            UINT msg,
                            WPARAM wparam,
                            LPARAM lparam)
{
HRESULT rval;

switch (msg) {

    case WM_SIZE:
        // Handle resizing of the window. If the application was
        // minimized, set a flag so that rendering will stop while minimized
        // and break out of this function. Otherwise, make sure the
        // minimized flag is clear and check for window resizing other
        // than minimized.
        {
        if (SIZE_MINIMIZED == wparam)
        {
            myglobs.bMinimized = TRUE;
            break;
        }
        else
            myglobs.bMinimized = FALSE;

        // Handle resizing of the window. Obtain the window's current
        // width and height.
        int width = LOWORD(lparam);
        int height = HIWORD(lparam);

        // If the global variables, such as the viewport and device,
        // have been initialized, obtain the viewport's and the
        // device's width and height. Create a new device and window
        // device or viewport, as needed. A new device and window device
        // are only needed if the window is larger than the old device.
        if (myglobs.bInitialized)
        {
            int view_width = myglobs.view->GetWidth();
            int view_height = myglobs.view->GetHeight();
            int dev_width = myglobs.dev->GetWidth();
            int dev_height = myglobs.dev->GetHeight();

            // Check whether the window size increased in either
            // width or height.
            if (width > dev_width || height > dev_height)
            {
                // Application window is now larger than the current
                // device. Destroy the old viewport and device and create
                // new ones. Be sure to free the viewport before freeing
                // the device, or a general protection fault might occur.
                myglobs.bInitialized = FALSE;
                RELEASE(myglobs.view);
                RELEASE(myglobs.dev);

                // Create a new, default Direct3D Retained Mode device.
                rval = lpD3DRM->CreateDeviceFromClipper(lpDDClipper,
                                        NULL, // Default device
                                        width, height,
                                        &myglobs.dev);

                if (FAILED(rval))
                {
                    // If the new device could not be created, notify
                    // the user and shut down the application.
                    DISPLAYMSG("Failed to create the D3DRM device.");
                    PostMessage(NULL, WM_DESTROY, 0, 0);
                    return FALSE;
                }

                // Destroy the old Direct3D Retained Mode window device
                // and create a new one to match the newly created
                // device. The window device handles the WM_ACTIVATE and
                // WM_PAINT messages.
                RELEASE(myglobs.windevice);
                rval = myglobs.dev->QueryInterface(
                                       IID_IDirect3DRMWinDevice,
                                       (void **) &myglobs.windevice);
                if (FAILED(rval)) {
                    DISPLAYMSG("Failed to create the window device.");
                    return FALSE;
                }

            }

            // If the window size changed, free the old viewport and
            // create a new viewport of the proper size.
            myglobs.bInitialized = FALSE;
            RELEASE(myglobs.view);
            rval = lpD3DRM->CreateViewport(myglobs.dev,
                                           myglobs.camera,
                                           0, 0, width, height,
                                           &myglobs.view);
            if (FAILED(rval))
            {
                // If the new viewport could not be created, notify
                // the user and shut down the application.
                DISPLAYMSG("Failed to create a new viewport.");
                PostMessage(NULL, WM_DESTROY, 0, 0);
                break;
            }

            myglobs.bInitialized = TRUE;
        }
        }
        break;

    case WM_ACTIVATE:
        // Use the window device's HandleActivate method to handle
        // window activation.
        if (myglobs.bInitialized)
            if (FAILED(myglobs.windevice->HandleActivate(wparam)))
                DISPLAYMSG("Failed to handle WM_ACTIVATE.");
        break;

    case WM_PAINT:
        // Use the window device's HandlePaint method to handle
        // repainting, unless global variables have not yet been
        // initialized.
        if (!myglobs.bInitialized)
            return DefWindowProc(win, msg, wparam, lparam);

        // Use the window device to handle repainting.
        RECT rc;
        PAINTSTRUCT ps;

        if (GetUpdateRect(win, &rc, FALSE)) {
            BeginPaint(win, &ps);
            if (FAILED(myglobs.windevice->HandlePaint(ps.hdc)))
                DISPLAYMSG("Failed to handle WM_PAINT.");
        }
        EndPaint(win, &ps);
        break;

    case WM_DESTROY:
        // Clear the bInitialized flag, free objects, and post the WM_QUIT
        // message to terminate the application. Be sure to free the
        // viewport before freeing the device, or a general protection
        // fault might occur.
        myglobs.bInitialized = FALSE;
        RELEASE(myglobs.view);
        RELEASE(myglobs.windevice);
        RELEASE(myglobs.dev);
        RELEASE(lpD3DRM);
        RELEASE(lpDDClipper);
        PostQuitMessage(0);
        break;

    default:
        return DefWindowProc(win, msg, wparam, lparam);
    }
    return 0L;
}

Related Topics

Now that you are familiar with the basics of creating objects and putting something on the screen using Direct3D Retained Mode, the code in the Direct3D Retained Mode samples should be easier to understand. Nearly all of these samples use the helper code provided by RMMain to create a device and render a scene. They each provide their own BuildScene function to create unique scenes.

As a next step, you can look at some of the other Direct3D Retained Mode samples, such as Egg or Globe, which provide functionality similar to RMBegin1 and RMBegin2.

For information about another common task in Direct3D Retained Mode, see Enumerating Devices: The RMEnum Sample, which provides a walkthrough of the RMEnum sample code. RMEnum focuses on how to enumerate devices.

For brief summaries of all of the Retained Mode samples, see Samples.


Enumerating Devices: The RMEnum Sample

Device enumeration is one of the fundamental concepts in Microsoft® Direct3D® Retained Mode. You can create a default device without device enumeration, but enumerating devices provides more flexibility for your application. It enables you to identify the devices present on a given system, and to choose the device that is most appropriate for your needs and can offer more advanced capabilities.

This article walks you through code from the RMEnum sample. RMEnum enumerates the hardware and software devices on the system, makes an intelligent choice about which device to use, and creates the device. It adds the enumerated devices to the application's File menu and enables the user to switch between devices by choosing devices from the menu. Unlike a real-world Direct3D Retained Mode application, RMEnum does not display any three-dimensional (3-D) objects or render any graphics. It focuses on enumeration for the sake of simplicity and clarity.

This article assumes you are an experienced C or C++ programmer and are familiar with beginning Windows programming concepts, such as the message loop, creating a window, and using menus.

This article contains the following sections.

  • Dependencies
  • Global Declarations
  • Function Summaries
  • Related Topics

Dependencies

RMEnum links to DDraw.lib and D3DRM.lib. It uses the Msg and D3DRMErrorToString helper functions from Error.c to provide detailed information in case of errors. By default, Error.c resides in the Samples\Misc directory of the Microsoft® DirectX® Software Development Kit (SDK). RMEnum could just as easily use the standard Microsoft® Windows® MessageBox function instead of using these helper functions, but the error reporting would not be as clean or detailed. The sample also links to the menus and other resources provided by RMEnum.rc.

To properly initialize globally unique identifiers (GUIDs), Direct3D applications must contain the following definition at the top of their code.

#define INITGUID

The sample's RMEnum.cpp file includes the following header files.

#include <windows.h>   /* Standard Windows header file */
#include <direct.h>    /* DirectDraw definitions */
#include <d3drmwin.h>  /* D3DRM definitions */
#include "RMEnum.h"    /* Defines constants used in RMEnum.rc */
#include "rmerror.h"   /* Prototypes for error reporting functions in
                             rmerror.c */

Global Declarations

The sample defines some constants and global variables to help organize information.

For simplicity, RMEnum.cpp sets an arbitrary limit on the number of drivers it will enumerate. You could enumerate drivers once to count how many are available, and enumerate again to examine each driver's capabilities as this sample does. A real-world same could also maintain a linked list of driver information rather than a fixed size array as RMEnum does.

#define MAX_DRIVERS 5  /* Arbitrary limit for the maximum number of
                            Direct3D drivers expected to be found */

The application-defined RELEASE macro releases an object only if the object is not NULL and ensures that an object is initialized to NULL after it has been released. This practice eliminates the problem of trying to release an object that has already been released, which can, in turn, cause undesired results, such as page faults.

/* Macro to release an object. */
#define RELEASE(x) if (x != NULL) {x->Release(); x = NULL;}

The myglobs structure collects device and driver information, as well as information about the current application state. The Direct3D Retained Mode and DirectDrawClipper objects are also global (the DirectDrawClipper object restricts drawing to a designated area).

/*
 * GLOBAL VARIABLES
 */
LPDIRECT3DRM lpD3DRM = NULL;            /* Direct3DRM object */
LPDIRECTDRAWCLIPPER lpDDClipper = NULL; /* DirectDrawClipper object */

struct _myglobs {
    /* Direct3DRM device */
    LPDIRECT3DRMDEVICE dev;

    /* GUIDs of the available Direct3D (D3D) drivers */
    GUID DriverGUID[MAX_DRIVERS];

    /* names of the available D3D drivers */
    char DriverName[MAX_DRIVERS][50];

    /* counter indicating the number of available D3D drivers */
    int  NumDrivers;

    /* number of the D3D driver currently being used; set to
     * the preferred driver by enumDeviceFunc */
    int  CurrDriver;

    /* program is about to terminate */
    BOOL bQuit;

    /* all D3DRM objects have been initialized */
    BOOL bInitialized;

    /* bit depth of the current display mode */
    DWORD BPP;
} myglobs;

Function Summaries

RMEnum.cpp contains the following functions.

CreateObjects is the master function that initializes the global variables, uses EnumDevices to enumerate the devices, and creates objects. InitApp uses CreateObjects.

BOOL CreateObjects(HWND win);

GetCurrentBitDepth returns the current bit depth to CreateObjects.

static DWORD GetCurrentBitDepth(HWND);

EnumDevices obtains the Direct3D object to use for device enumeration, uses the Immediate Mode IDirect3D::EnumDevices function, passing the enumDeviceFunc callback function as a parameter, and places the enumerated devices on the File menu.

static BOOL EnumDevices(HWND);

The enumDeviceFunc callback function cycles through the available drivers, chooses the usable drivers, and selects a preferred driver.

static HRESULT WINAPI enumDeviceFunc(LPGUID,
                                            LPSTR,
                                            LPSTR,
                                            LPD3DDEVICEDESC,
                                            LPD3DDEVICEDESC,
                                            LPVOID);

RMEnum uses ChangeDriver in response to the user's menu choice that switches to a differenct available driver.

void ChangeDriver(HWND, WPARAM);

CleanUpAndQuit releases objects in preparation for application termination.

static void CleanUpAndQuit(void);

The remaining functions (InitApp, WinMain, AppAbout, and WindowProc) are primarily based on the standard Windows functions and contain little code specific to the RMEnum sample.

static HWND InitApp(HINSTANCE, int);
int APIENTRY WinMain (HINSTANCE, HINSTANCE, LPSTR, int);
LRESULT CALLBACK AppAbout(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK WindowProc(HWND, UINT, WPARAM, LPARAM);

For more information about these functions, see the following topics in this article.

  • CreateObjects
  • GetCurrentBitDepth
  • EnumDevices
  • enumDeviceFunc
  • ChangeDriver
  • CleanUpAndQuit
  • Standard Windows Functions

CreateObjects

CreateObjects provides and uses the core code in the RMEnum sample. After initializing global variables and obtaining the current bit depth, it uses EnumDevices to actually enumerate the devices. The enumDeviceFunc callback function later uses the bit depth to determine which drivers support the current bit depth.

After enumerating devices, CreateObjects performs the steps necessary to create a device and associate it with the application's main window as follows:

  1. Uses Direct3DRMCreate to create a Direct3D Retained Mode object.
  2. Uses the DirectDraw DirectDrawCreateClipper function to create a DirectDrawClipper object.
  3. Uses the DirectDrawClipper's SetHWnd method to associate the application's window with the clipper. The DirectDrawClipper object restricts subsequent drawing to a designated area—in this case, to the application window.
  4. Uses the Windows GetClientRect function to obtain the height and width of the application's main window.
  5. Uses the Direct3D Retained Mode object's CreateDeviceFromClipper method to create the device, passing the preferred driver selected by the enumeration, and the width and height of the application's window, to the method.

The CreateObjects function's source code follows:

/*
 * Initialize globals, enumerate devices and create objects.
 */
BOOL CreateObjects(HWND win)
{
    HRESULT rval; /* Return value */
    RECT rc;      /* Bounding rectangle for main window */

    /*
     * Initialize the global variables.
     */
    memset(&myglobs, 0, sizeof(myglobs));

    /*
     * Record the current display bit depth.
     */
     myglobs.BPP = GetCurrentBitDepth(win);

    /*
     * Enumerate the D3D drivers and select one.
     */
    if (!EnumDevices(win))
        return FALSE;

    /*
     * Create the Direct3DRM object and the window object.
     */
    rval = Direct3DRMCreate(&lpD3DRM);
    if (rval != D3DRM_OK) {
        Msg("Failed to create Direct3DRM.\n%s", D3DRMErrorToString(rval));
        return FALSE;
    }

    /*
     * Create a DirectDrawClipper object and associate the window with it.
     */
    rval = DirectDrawCreateClipper(0, &lpDDClipper, NULL);
    if (rval != DD_OK) {
        Msg("Failed to create DirectDrawClipper object");
        return FALSE;
    }
    rval = lpDDClipper->SetHWnd(0, win);
    if (rval != DD_OK) {
        Msg("Failed to set the window handle for the DirectDrawClipper");
        return FALSE;
    }
    /*
     * Create the D3DRM device with the selected D3D driver. The GUID can
     * be NULL to create a default device without enumeration.
     */
    GetClientRect(win, &rc);

    rval = lpD3DRM->CreateDeviceFromClipper(lpDDClipper,
                           &myglobs.DriverGUID[myglobs.CurrDriver],
                           rc.right, rc.bottom, &myglobs.dev);

    if (rval) {
        Msg("Failed to create the D3DRM device.\n%s",
            D3DRMErrorToString(rval));
        return FALSE;
    }

    /*
     * Globals are initialized
     */
    myglobs.bInitialized = TRUE;

    return TRUE;
}

GetCurrentBitDepth

The GetCurrentBitDepth function determines the current device's bit depth capabilities and returns that information in the form of a DirectDraw bit depth flag. Bit depth refers to the device's color settings, such as 8-bit, 16-bit, or 24-bit color.

/*
 * Retrieve a DirectDraw bit depth flag reflecting the current
 * display bit depth in bits per pixel (BPP).
 */
static DWORD GetCurrentBitDepth(HWND win)
{
    HDC hdc;
    int BPP;

    /*
     * Record the current display's BPP.
     */
    hdc = GetDC(win);
    BPP = GetDeviceCaps(hdc, BITSPIXEL);
    ReleaseDC(win, hdc);

    /*
     * Map BPP value to DirectDraw bit depth.
     */
    switch(BPP) {
        case 1:
            return DDBD_1;
        case 2:
            return DDBD_2;
        case 4:
            return DDBD_4;
        case 8:
            return DDBD_8;
        case 16:
            return DDBD_16;
        case 24:
            return DDBD_24;
        case 32:
            return DDBD_32;
        default:
            return 0;
    }
}

EnumDevices

The RMEnum EnumDevices function performs the following steps to enumerate devices. The steps include variables and code fragments from the sample.

  1. Uses the DirectDrawCreate function to create a DirectDraw object.
    LPDIRECTDRAW lpDD;
HRESULT rval;
rval = DirectDrawCreate(NULL, &lpDD, NULL);
  2. Uses the DirectDraw object's QueryInterface method to obtain a Direct3D Immediate Mode object. For more information on Direct3D Immediate Mode, see the DirectX Foundation SDK.
    LPDIRECT3D lpD3D;
rval = lpDD->QueryInterface(IID_IDirect3D, (void**) &lpD3D);
  3. Uses the Direct3D Immediate Mode object's IDirect3D::EnumDevices function to enumerate the devices on the system. IDirect3D::EnumDevices passes the enumDeviceFunc callback function as a parameter.
    rval = lpD3D->EnumDevices(enumDeviceFunc, &myglobs.CurrDriver);

    The callback function cycles through the available devices and selects the drivers that are compatible with certain criteria.

After it has enumerated the drivers, RMEnum's EnumDevices function releases the DirectDraw and Direct3D devices and adds the drivers to the application's File menu.

lpD3D->Release();
lpDD->Release();

Complete source code for RMEnum's EnumDevices function follows:

/*
 * EnumDevices
 * Enumerate the available Direct3D drivers, add them to the file menu,
 * and choose one to use.
 */
static BOOL EnumDevices(HWND win)
{
    LPDIRECTDRAW lpDD;
    LPDIRECT3D lpD3D;
    HRESULT rval;
    HMENU hmenu;
    int i;

    /*
     * Create a DirectDraw object and query for the Direct3D interface
     * to use to enumerate the drivers.
     */
    rval = DirectDrawCreate(NULL, &lpDD, NULL);
    if (rval != DD_OK) {
        Msg("Creation of DirectDraw HEL failed.\n%s",
            D3DRMErrorToString(rval));
        return FALSE;
    }
    rval = lpDD->QueryInterface(IID_IDirect3D, (void**) &lpD3D);
    if (rval != DD_OK) {
        Msg("Creation of Direct3D interface failed.\n%s",
            D3DRMErrorToString(rval));
        lpDD->Release();
        return FALSE;
    }
    /*
     * Enumerate the drivers. Pass the arbitrary value of -1 as
     * application-defined data. The enumDeviceFunc callback function
     * performs special-case initialization code in response to a -1.
     */
    myglobs.CurrDriver = -1;
    rval = lpD3D->EnumDevices(enumDeviceFunc, &myglobs.CurrDriver);
    if (rval != DD_OK) {
        Msg("Enumeration of drivers failed.\n%s",
            D3DRMErrorToString(rval));
        return FALSE;
    }
    /*
     * Make sure we found at least one valid driver.
     */
    if (myglobs.NumDrivers == 0) {
        Msg("Could not find a D3D driver that is compatible with this \
            display depth");
        return FALSE;
    }
    lpD3D->Release();
    lpDD->Release();
    /*
     * Add the driver names to the File menu.
     */
    hmenu = GetSubMenu(GetMenu(win), 0);
    for (i = 0; i < myglobs.NumDrivers; i++) {
        InsertMenu(hmenu, 2 + i, MF_BYPOSITION | MF_STRING,
                   MENU_FIRST_DRIVER + i,
                   myglobs.DriverName[i]);
    }
    return TRUE;
}

enumDeviceFunc

Direct3D Immediate Mode defines D3DENUMDEVICESCALLBACK as the prototype definition for the callback function to enumerate installed Direct3D devices. RMEnum provides enumDeviceFunc as this enumeration callback function. Direct3D Immediate Mode calls enumDeviceFunc repeatedly, once for each device on the system, and passes device information to enumDeviceFunc each time. As D3D Immediate Mode loops through the available drivers, enumDeviceFunc saves information about drivers that can render in the current display bit depth into global variables. enumDeviceFunc chooses hardware drivers over software emulation drivers because hardware drivers typically render faster and chooses color lights over monochromatic lights for better-looking 3-D lighting. These choices do not actually come into play with this sample, because RMEnum does no rendering, but they do effect real applications and can have a large impact on the appearance of 3-D graphics.

enumDeviceFunc's parameters include the device's globally unique identifier (GUID), a textual description of the device, and the device name. Other parameters include pointers to two Direct3D Immediate Mode D3DDEVICEDESC structures. The first structure (lpHWDesc) contains the hardware capabilities of the Direct3D device and the other structure (lpHELDesc) contains the Hardware Emulation Layer (HEL) software emulation capabilities of the device. The last parameter is application-defined data passed to this callback function the first time Direct3D Immediate Mode calls it.

Complete source code for RMEnum's enumDeviceFunc callback function follows:

/*
 * enumDeviceFunc
 * Callback function which records each usable D3D driver's name and
 * GUID. It selects the preferred driver on the system by choosing
 * hardware drivers over software drivers, and color lights over
 * monochrome lights. It sets myglobs.CurrDriver to indicate the
 * preferred driver.
 */
static HRESULT WINAPI enumDeviceFunc(LPGUID lpGuid,
                                     LPSTR lpDeviceDescription,
                                     LPSTR lpDeviceName,
                                     LPD3DDEVICEDESC lpHWDesc,
                                     LPD3DDEVICEDESC lpHELDesc,
                                     LPVOID lpContext)
{
    static BOOL hardware = FALSE; /* current start driver is software */
    static BOOL mono = FALSE;     /* current start driver is color */
    LPD3DDEVICEDESC lpDesc;       /* description of current driver */

    /*
     * Data defined by this application that, when it equals -1,
     * indicates that the current driver is the first to be enumerated
     */
    int *lpStartDriver = (int *)lpContext;

    /*
     * Decide which device description to consult. The driver is either
     * hardware (HW) or software. Software drivers provide support
     * through the hardware emulation layer (HEL).
     */
    lpDesc = lpHWDesc->dcmColorModel ? lpHWDesc : lpHELDesc;
    /*
     * If this driver cannot render in the current display bit depth,
     * return D3DENUMRET_OK to skip this driver. Enumeration continues
     * automatically as D3D calls enumDeviceFunc again for the next
     * driver.
     */
    if (!(lpDesc->dwDeviceRenderBitDepth & myglobs.BPP))
        return D3DENUMRET_OK;
    /*
     * Record this driver's GUID and name.
     */
    memcpy(&myglobs.DriverGUID[myglobs.NumDrivers], lpGuid, sizeof(GUID));
    lstrcpy(&myglobs.DriverName[myglobs.NumDrivers][0], lpDeviceName);
    /*
     * Choose hardware over software, and color lights over monochrome
     * lights.
     */
    if (*lpStartDriver == (int)-1) {
        /*
         * This is the first valid driver, so record whether this driver
         * is a hardware driver or not, and whether it is limited to
         * monochrome lights or not.
         */
        myglobs.CurrDriver = myglobs.NumDrivers;
        hardware = lpDesc == lpHWDesc ? TRUE : FALSE;
        mono = lpDesc->dcmColorModel & D3DCOLOR_MONO ? TRUE : FALSE;
    } else if (lpDesc == lpHWDesc && !hardware) {
        /*
         * If this driver is a hardware driver and the start driver is not,
         * then make this driver the new preferred driver and record
         * its hardware and mono capabilities. The next time D3D calls
         * enumDeviceFunc, that driver will be compared against this
         * new start driver.
         */
        myglobs.CurrDriver = myglobs.NumDrivers;
        hardware = lpDesc == lpHWDesc ? TRUE : FALSE;
        mono = lpDesc->dcmColorModel & D3DCOLOR_MONO ? TRUE : FALSE;
    } else if ((lpDesc == lpHWDesc && hardware ) || (lpDesc == lpHELDesc
                                                     && !hardware)) {
        if (lpDesc->dcmColorModel == D3DCOLOR_RGB && mono) {
            /*
             * If this driver and the start driver are the same type
             * (both hardware or both software) and this driver is
             * color while the start driver is not, then make this driver
             * the new preferred driver and record its capabilities.
             * The next time D3D calls enumDeviceFunc, that driver will
             * be compared against this new start driver.
             */
            myglobs.CurrDriver = myglobs.NumDrivers;
            hardware = lpDesc == lpHWDesc ? TRUE : FALSE;
            mono = lpDesc->dcmColorModel & D3DCOLOR_MONO ? TRUE : FALSE;
        }
    }
    /*
     * Increment the current driver number in preparation for the next
     * driver.
     */
    myglobs.NumDrivers++;

    /* Maximum number of drivers reached, stop enumeration. */
    if (myglobs.NumDrivers == MAX_DRIVERS)
        return (D3DENUMRET_CANCEL);
    /*
     * Continue enumerating drivers. D3D will call enumDeviceFunc
     * again with information for the next driver.
     */
    return (D3DENUMRET_OK);
}

ChangeDriver

ChangeDriver is not a required function in the RMEnum sample, but it does add flexibility by enabling the user to choose between drivers. ChangeDriver changes the current driver in response to a menu selection. It re-creates the device by using the Direct3D Retained Mode object's CreateDeviceFromClipper method, much as RMEnum's CreateObjects function originally created the device.

The ChangeDriver source code follows:

/*
 * Release the current device and create the new one.
 */
void ChangeDriver(HWND win, WPARAM wparam)
{
    HRESULT rval;
    RECT rc;

    /*
     * Save the previous driver selection as LastDriver.
     */
    int LastDriver = myglobs.CurrDriver;

    /*
     * Globals are no longer correct since the selection is changing.
     */
    myglobs.bInitialized = FALSE;

    /*
     * Release the current device.
     */
    RELEASE(myglobs.dev);

    /*
     * Set the current driver to the driver selected through the menu.
     */
    myglobs.CurrDriver = LOWORD(wparam)-MENU_FIRST_DRIVER;

    /*
     * Obtain the window rectangle and create the new current driver
     * for that window using the global DirectDrawClipper object.
     */
    GetClientRect(win, &rc);

    rval = lpD3DRM->CreateDeviceFromClipper(lpDDClipper,
                             &myglobs.DriverGUID[myglobs.CurrDriver],
                             rc.right, rc.bottom, &myglobs.dev);

    /*
     * If an error occurred, try to recreate the previous driver.
     */
    if (rval) {
        myglobs.CurrDriver = LastDriver;

        rval = lpD3DRM->CreateDeviceFromClipper(lpDDClipper,
                                 &myglobs.DriverGUID[myglobs.CurrDriver],
                                 rc.right, rc.bottom, &myglobs.dev);
        if (rval) {
            Msg("Failed to create the D3DRM device.\n%s",
                D3DRMErrorToString(rval));
            CleanUpAndQuit();
        }
        else {
            Msg("There was not enough video memory available to use the \
                 3D accelerated hardware device.\nRestoring old software \
                 device.");
            myglobs.bInitialized = TRUE;
        }
    }
    else {
        /*
         * Globals are properly initialized again.
         */
        myglobs.bInitialized = TRUE;
    }
}

CleanUpAndQuit

The small CleanUpAndQuit function releases global objects and sets the quit flag to TRUE to indicate that the application is ready to quit.

void CleanUpAndQuit(void)
{
    myglobs.bInitialized = FALSE;
    RELEASE(myglobs.dev);
    RELEASE(lpD3DRM);
    RELEASE(lpDDClipper);
    myglobs.bQuit = TRUE;
}

Standard Windows Functions

The remaining functions in RMEnum.cpp (InitApp, WinMain, AppAbout, and WindowProc) are primarily the standard Windows functions and contain little code that is specific to the RMEnum sample. See the RMEnum sample code for more information.

  • InitApp creates the main window and uses the sample's CreateObjects function.
  • WinMain calls the InitApp function. It also contains the main Windows message loop that handles messages until the global myglobs.bQuit variable is TRUE. WinMain uses CleanUpAndQuit in response to the standard Windows WM_QUIT message, indicating that the application is terminating.
  • AppAbout handles messages for the application's About dialog box.
  • WindowProc handles messages for the main application window. It initializes the File menu with the enumerated driver choices and handles the user's driver selection by using the application's ChangeDriver function. WindowProc uses CleanUpAndQuit to release resources in response to the standard Windows WM_DESTROY message indicating that Windows is in the process of destroying the application window because the user terminated the application.

Related Topics

Now that you are familiar with how to enumerate devices, the code in the Direct3D Retained Mode samples should be easier to understand. Nearly all of these samples use the helper code provided by RMMain to enumerate devices. As a next step, you can look at the Egg or the Globe sample to see how they perform rendering, knowing that they use device enumeration behind the scenes.

For brief summaries of all of the Retained Mode samples, see Samples.


Technical Background

The following topics describe some of the technical concepts you need to understand before you write programs that incorporate 3-D graphics. In these sections, you will find a general discussion of coordinate systems and transformations. This is not a discussion of broad architectural details, such as setting up models, lights, and viewing parameters. For more information about these topics, see Direct3D Retained Mode Architecture.

If you are already experienced in producing 3-D graphics, simply scan the following topics for information that is unique to Microsoft® Direct3D® Retained Mode:

  • 3-D Coordinate Systems
  • 3-D Transformations
  • Polygons
  • Triangle Strips and Fans
  • Vectors, Vertices, and Quaternions
  • Z-Buffers and Overlays

3-D Coordinate Systems

There are two varieties of Cartesian coordinate systems in 3-D graphics: left-handed and right-handed. In both coordinate systems, the positive x-axis points to the right and the positive y-axis points up. You can remember which direction the positive z-axis points by pointing the fingers of either your left or right hand in the positive x-direction and curling them into the positive y-direction. The direction your thumb points, either toward or away from you, is the direction the positive z-axis points for that coordinate system.

This section describes the Direct3D coordinate system and coordinate types that your application can use.

  • Direct3D Coordinate System
  • U- and V-Coordinates

Direct3D Coordinate System

Direct3D uses the left-handed coordinate system by default. This means the positive z-axis points away from the viewer, as shown in the following illustration:

Direct3D coordinate system

In a left-handed coordinate system, rotations occur clockwise around any axis that is pointed at the viewer.

If you need to work in a right-handed coordinate system—for example, if you are porting an application that relies on right-handedness—you can do so by making two simple changes to the data passed to Direct3D.

Note: Beginning with DirectX version 6.0, you can use IDirect3DRM3::SetOptions to instruct Direct3D Retained Mode to use a right-handed coordinate system. If you use IDirect3DRM3::SetOptions, changing data is not necessary.

Versions of DirectX prior to version 6.0 require the following changes to the data passed to Direct3D Retained Mode to use right-handed coordinates.

  • Flip the order of triangle vertices so that the system traverses them clockwise from the front. In other words, if the vertices are v0, v1, v2, pass them to Direct3D as v0, v2, v1.
  • Scale the projection matrix by –1 in the z-direction. To do this, flip the signs of the _13, _23, _33, and _43 members of the D3DMATRIX structure.

U- and V-Coordinates

Direct3D also uses texture coordinates. These coordinates (u and v) are used when mapping textures onto an object. The v-vector describes the direction or orientation of the texture and lies along the z-axis. The u-vector (or the up vector) typically lies along the y-axis, with its origin at [0,0,0]. For more information about u- and v-coordinates, see Wraps.

3-D Transformations

In programs that work with 3-D graphics, you can use geometrical transformations to:

  • Express the location of an object relative to another object.
  • Rotate, shear, and size objects.
  • Change viewing positions, directions, and perspective.

You can transform any point into another point by using a 4×4 matrix. In the following example, a matrix is used to reinterpret the point (x, y, z), producing the new point (x', y', z'):

Transformation of a point with a 4×4 matrix

You perform the following operations on (x, y, z) and the matrix to produce the point (x', y', z'):

Operations within the matrix transformation

The most common transformations are translation, rotation, and scaling. You can combine the matrices that produce these effects into a single matrix to calculate several transformations at once. For example, you can build a single matrix to translate and rotate a series of points.

Matrices are specified in row order. For example, the following matrix could be represented by an array:

Sample matrix that is represented by the array below

The array for this matrix would look like the following:

D3DMATRIX scale = {
    D3DVAL(s),    0,            0,            0,
    0,            D3DVAL(s),    D3DVAL(t),    0,
    0,            0,            D3DVAL(s),    D3DVAL(v),
    0,            0,            0,            D3DVAL(1)
};

This section describes the 3-D transformations available to your applications through Direct3D.

  • Translation
  • Rotation
  • Scaling

Other parts of this documentation also discuss transformations. You can find a general discussion of transformations in the section devoted to viewports in Retained Mode, Transformations. For a discussion of transformations in frames, see Transformations. Although each of these sections discusses Retained Mode API, the architecture and mathematics of the transformations apply to both Retained Mode and Immediate Mode.

Translation

The following transformation translates the point (x, y, z) to a new point (x', y', z'):

Matrix that translates a point

Rotation

The transformations described in this section are for left-handed coordinate systems, and so they may be different from transformation matrices you have seen elsewhere.

The following transformation rotates the point (x, y, z) around the x-axis, producing a new point (x', y', z'):

Matrix that rotates a point around the x-axis

The following transformation rotates the point around the y-axis:

Matrix that rotates a point around the y-axis

The following transformation rotates the point around the z-axis:

Matrix that rotates a point around the z-axis

Note that in these example matrices, the Greek letter theta stands for the angle of rotation, specified in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Scaling

The following transformation scales the point (x, y, z) by arbitrary values in the x-, y-, and z-directions to a new point (x', y', z'):

Matrix that scales a point

Polygons

Three-dimensional objects in Direct3D are made up of meshes. A mesh is a set of faces, each of which is described by a simple polygon. The fundamental polygon type is the triangle. Although Retained Mode applications can specify polygons with more than three vertices, the system translates these into triangles before the objects are rendered. Immediate Mode applications must use triangles.

This section describes how your applications can use Direct3D polygons.

  • Geometry Requirements
  • Face and Vertex Normals
  • Shade Modes
  • Interpolated Triangle Characteristics

Geometry Requirements

Triangles are the preferred polygon type because they are always convex, and they are always planar—two conditions that are required of polygons by the renderer. A polygon is convex if a line drawn between any two points of the polygon is also inside the polygon.

Diagram of concave and convex polygons

The three vertices of a triangle always describe a plane, but it is easy to accidentally create a nonplanar polygon by adding another vertex.

Diagram of nonplanar polygon

Face and Vertex Normals

Each face in a mesh has a perpendicular face normal vector whose direction is determined by the order in which the vertices are defined and by whether the coordinate system is right- or left-handed. If the normal vector of a face is oriented toward the viewer, that side of the face is its front. In Direct3D, only the front side of a face is visible, and a front face is one in which vertices are defined in clockwise order.

Diagram of a polygon face's vertices and normal vector

Direct3D applications do not need to specify face normals; the system calculates them automatically when they are needed. The system uses face normals in the flat shade mode. For Phong and Gouraud shade modes, and for controlling lighting and texturing effects, the system uses vertex normals.

Diagram of vertex normals and face normals

Shade Modes

In the flat shade mode, the system duplicates the color of one vertex across all the other faces of the primitive. In the Gouraud and Phong shade modes, vertex normals are used to give a smooth look to a polygonal object. In Gouraud shading, the color and intensity of adjacent vertices is interpolated across the space that separates them. In Phong shading, the system calculates the appropriate shade value for each pixel on a face.

Note Phong shading is not currently supported.

Most applications use Gouraud shading because it allows objects to appear smooth and is computationally efficient. However, Gouraud shading can miss details that Phong shading will not. For example, Gouraud and Phong shading would produce very different results as shown by the following illustration, in which a spotlight is completely contained within a face.

Diagram of a spotlight on a face for comparison of Gouraud and Phong shading

In this case, the Phong shade mode would calculate the value for each pixel and display the spotlight. The Gouraud shade mode, which interpolates between vertices, would miss the spotlight altogether; the face would be rendered as though the spotlight did not exist.

In the flat shade mode, the following pyramid would be displayed with a sharp edge between adjoining faces; the system would generate automatic face normals. In the Gouraud or Phong shade modes, however, shading values would be interpolated across the edge, and the final appearance would be of a curved surface.

A pyramid in the flat shade mode

If you want to use the Gouraud or Phong shade mode to display curved surfaces, and you also want to include some objects with sharp edges, your application would need to duplicate the vertex normals at any intersection of faces where a sharp edge was required, as shown in the following illustration.

Vertex normals needed to retain sharp edge in shading other than flat

In addition to allowing a single object to have both curved and flat surfaces, the Gouraud shade mode lights flat surfaces more realistically than the flat shade mode. A face in the flat shade mode is a uniform color, but Gouraud shading allows light to fall across a face correctly. This effect is particularly obvious if there is a nearby point source. Gouraud shading is the preferred shade mode for most Direct3D applications.

Interpolated Triangle Characteristics

The system interpolates the characteristics of a triangle's vertices across the triangle when it renders a face. The following triangle characteristics are interpolated:

  • Color
  • Specular
  • Fog
  • Alpha

All of the triangle's interpolated characteristics are modified by the current shade mode:

Flat | No interpolation is done. Instead, the color of the first vertex in the triangle is applied across the entire face.
Gouraud | Linear interpolation is performed between all three vertices.
Phong | Vertex parameters are re-evaluated for each pixel in the face, using the current lighting. The Phong shade mode is not currently supported.

The interpolated color and specular characteristics are treated differently, depending on the color model. In the RGB color model (D3DCOLOR_RGB), the system uses the red, green, and blue color components in the interpolation. In the monochromatic model (D3DCOLOR_MONO), the system uses only the blue component of the vertex color.

For example, if the red component of the color of vertex 1 were 0.8 and the red component of vertex 2 were 0.4, in the Gouraud shade mode and RGB color model the system would use interpolation to assign a red component of 0.6 to the pixel at the midpoint of the line between these vertices.

The alpha component of a color is treated as a separate interpolated characteristic because device drivers can implement transparency in two different ways: by using texture blending or by using stippling.

An application can use the dwShadeCaps member of the D3DPRIMCAPS structure to determine what forms of interpolation the current device driver supports.

Triangle Strips and Fans

You can use triangle strips and triangle fans to specify an entire surface without having to provide all three vertices for each of the triangles. For example, only seven vertices are required to define the following triangle strip.

Sample triangle strip and its vertices

The system uses vertices v1, v2, and v3 to draw the first triangle; v2, v4, and v3 to draw the second triangle; v3, v4, and v5 to draw the third; v4, v6, and v5 to draw the fourth; and so on. Notice that the vertices of the second and fourth triangles are out of order. This is required to make sure that all of the triangles are drawn in a clockwise orientation.

A triangle fan is similar to a triangle strip, except that all of the triangles share one vertex.

Diagram of a triangle fan

The system uses vertices v1, v2, and v3 to draw the first triangle; v3, v4, and v1 to draw the second triangle; v1, v4, and v5 to draw the third triangle; and so on.

You can use the wFlags member of the D3DTRIANGLE structure to specify the flags that build triangle strips and fans.

Vectors, Vertices, and Quaternions

Throughout Direct3D, vertices describe position and orientation. Each vertex in a primitive is described by a vector that gives its position, a normal vector that gives its orientation, texture coordinates, and a color. (In Retained Mode, the D3DRMVERTEX structure contains these values.)

Quaternions add a fourth element to the [x, y, z] values that define a vector. Quaternions are an alternative to the matrix methods that are typically used for 3-D rotations. A quaternion represents an axis in 3-D space and a rotation around that axis. For example, a quaternion could represent a (1,1,2) axis and a rotation of 1 radian. Quaternions carry valuable information, but their true power comes from the two operations that you can perform on them: composition and interpolation.

Performing composition on quaternions is similar to combining them. The composition of two quaternions is notated as follows:

Equation showing composition of two quaternions

The composition of two quaternions applied to a geometry means "rotate the geometry around axis2 by rotation2, then rotate it around axis1 by rotation1." In this case, Q represents a rotation around a single axis that is the result of applying q2, then q1 to the geometry.

Using quaternion interpolation, an application can calculate a smooth and reasonable path from one axis and orientation to another. Therefore, interpolation between q1 and q2 provides a simple way to animate from one orientation to another.

When you use composition and interpolation together, they provide you with a simple way to manipulate a geometry in a manner that appears complex. For example, imagine that you have a geometry that you want to rotate to a given orientation. You know that you want to rotate it r2 degrees around axis2, then rotate it r1 degrees around axis1, but you don't know the final quaternion. By using composition, you could combine the two rotations on the geometry to get a single quaternion that is the result. Then, you could interpolate from the original to the composed quaternion to achieve a smooth transition from one to the other.

Direct3D Retained Mode includes some functions that help you work with quaternions. For example, the D3DRMQuaternionFromRotation function adds a rotation value to a vector that defines an axis of rotation, and returns the result in a quaternion defined by a D3DRMQUATERNION structure. Additionally, the D3DRMQuaternionMultiply function composes quaternions and the D3DRMQuaternionSlerp performs spherical linear interpolation between two quaternions.

Retained Mode applications can use the following functions to simplify the task of working with vectors and quaternions:

  • D3DRMQuaternionFromRotation
  • D3DRMQuaternionMultiply
  • D3DRMQuaternionSlerp
  • D3DRMVectorAdd
  • D3DRMVectorCrossProduct
  • D3DRMVectorDotProduct
  • D3DRMVectorModulus
  • D3DRMVectorNormalize
  • D3DRMVectorRandom
  • D3DRMVectorReflect
  • D3DRMVectorRotate
  • D3DRMVectorScale
  • D3DRMVectorSubtract

Z-Buffers and Overlays

The order in the z-buffer determines the order in which overlays clip each other. Overlays are assumed to be on top of all other screen components. Overlays that do not have a specified z-order behave in unpredictable ways when overlaying the same area on the primary surface. Direct3D Retained Mode does not sort overlays if you do not have a z-buffer. Overlays without a specified z-order are assumed to have a z-order of 0, and will appear in the order they are rendered. The possible z-order of overlays ranges from 0, which is just on top of the primary surface, to 4 billion, which is as close to the viewer as possible. An overlay with a z-order of 2 would obscure an overlay with a z-order of 1. No two overlays can have the same z-order.


Architecture

This section gives an overview of the Microsoft® Direct3D® Retained Mode objects and COM architecture. The following topics are discussed:

  • Objects gives a brief description of the Direct3D Retained Mode objects.
  • Objects and Interfaces lists the interfaces supported by each object, as well as information on creating interfaces to both single objects and array objects.
  • Objects and Reference Counting gives tips on reference counting in Direct3D Retained Mode.

Direct3D Retained Mode Objects

All access to Direct3D Retained Mode is through a small set of objects. The following table lists these objects and a brief description of each:

Object | Description
Direct3DRMAnimation2 | Defines how a transformation will be modified—often in reference to a Direct3DRMFrame3 object. You can use it to animate the position, orientation, and scaling of Direct3DRMVisual, of Direct3DRMLight, and of Direct3DRMViewport2 objects. Same as the Direct3DRMAnimation object, but allows access to the keys and frame of an animation.
Direct3DRMAnimationArray | Retrieves the number of animations in the array, and an interface to the requested animation.
Direct3DRMAnimationSet2 | Allows Direct3DRMAnimation2 objects to be grouped together. Same as the Direct3DRMAnimationSet object, but allows access to the constituent animations.
Direct3DRMClippedVisual | Allows clipping visuals to arbitrary planes before rendering.
Direct3DRMDevice3 | Represents the visual display destination for the renderer. Extends the Direct3DRMDevice2 object by enabling you to set and retrieve materials. Direct3DRMDevice2 offers the same functionality as the Direct3DRMDevice object but with enhanced control of transparency.
Direct3DRMFace2 | Represents a single polygon in a mesh.
Direct3DRMFrame3 | Positions objects within a scene and defines the positions and orientations of visual objects. Extends the Direct3DRMFrame object by enabling access to the frame axes, bounding boxes, and materials. Also supports ray picking. Extends the Direct3DRMFrame2 object by adding to the transform, traversal, and fogging capabilities.
Direct3DRMInterpolator | Stores actions and applies the actions to objects with automatic calculation of in-between values.
Direct3DRMLight | Defines one of five types of lights that are used to illuminate the visual objects in a scene.
Direct3DRMMaterial2 | Defines how a surface reflects light. Same as the Direct3DRMMaterial object, but allows finer control over material properties.
Direct3DRMMesh | Consists of a set of polygonal faces. You can use this object to manipulate groups of faces and vertices.
Direct3DRMMeshBuilder3 | Allows you to work with individual vertices and faces in a mesh. Extends Direct3DRMMeshBuilder objects by providing more control over normals and allowing retrieval of a face on a mesh. Extends Direct3DRMMeshBuilder2 objects by using the Immediate Mode DrawPrimitive interface when created with the IDirect3DRM3 interface.
Direct3DRMObject | Used as a base class by all other Direct3D Retained Mode objects. It has characteristics that are common to all objects.
Direct3DRMObject2 | Used as a base class by all other Direct3D Retained Mode objects. It has characteristics that are common to all objects. Enhances Direct3DRMObject by allowing more flexible data association with an object.
Direct3DRMPickedArray | Identifies a visual object that corresponds to a given 2-D point.
Direct3DRMPicked2Array | Identifies a visual object that corresponds to a given ray intersection.
Direct3DRMProgressiveMesh | Consists of a coarse base mesh together with records describing how to incrementally refine the mesh. This allows a generalized level of detail to be set on the mesh, as well as progressive download of the mesh from a remote source.
Direct3DRMShadow2 | Defines a shadow. Same as the Direct3DRMShadow object except that shadow properties can be set and retrieved after creation.
Direct3DRMTexture3 | Consists of a rectangular array of colored pixels. Same as the Direct3DRMTexture object except that resources can be loaded from files other than the currently executing file, textures can be created from images in memory, and you can generate mipmaps. Enhances the Direct3DRMTexture2 object by allowing finer control over texture management.
Direct3DRMUserVisual | Provides functionality not otherwise available in the system. It is defined by an application.
Direct3DRMViewport2 | Defines how the 3-D scene is rendered into a 2-D window. Same as the Direct3DRMViewport object except allows you to specify what should be cleared.
Direct3DRMVisual | Consists of anything that can be rendered in a scene. Visual objects need not be visible; for example, a frame can be added as a visual object.
Direct3DRMWrap | Calculates texture coordinates for a face or mesh.

Many objects can be grouped into arrays, called array objects. Array objects make it simpler to apply operations to the entire group. The Component Object Model (COM) interfaces that allow you to work with array objects contain the GetElement and GetSize methods. These methods retrieve a pointer to an element in the array and the size of the array, respectively. For more information about array interfaces, see the interface reference section.

Objects and Interfaces

Using the IObjectName::QueryInterface method retrieves a valid interface pointer only if the object supports that interface; therefore, you could use the IDirect3DRMDevice3::QueryInterface method to retrieve the IDirect3DRMWinDevice interface, but not to retrieve the IDirect3DRMVisual interface.

Object name | Supported interfaces
Direct3DRMAnimation2 | IDirect3DRMAnimation2
Direct3DRMAnimationSet2 | IDirect3DRMAnimationSet2
Direct3DRMClippedVisual | IDirect3DRMClippedVisual, IDirect3DRMVisual
Direct3DRMDevice3 | IDirect3DRMDevice3, IDirect3DRMWinDevice
Direct3DRMFace2 | IDirect3DRMFace2
Direct3DRMFrame3 | IDirect3DRMFrame3, IDirect3DRMVisual
Direct3DRMInterpolator | IDirect3DRInterpolator
Direct3DRMLight | IDirect3DRMLight
Direct3DRMMaterial2 | IDirect3DRMMaterial2
Direct3DRMMesh | IDirect3DRMMesh, IDirect3DRMVisual
Direct3DRMMeshBuilder3 | IDirect3DRMMeshBuilder3, IDirect3DRMVisual
Direct3DRMProgressiveMesh | IDirect3DRMProgressiveMesh, IDirect3DRMVisual
Direct3DRMShadow2 | IDirect3DRMShadow2, IDirect3DRMVisual
Direct3DRMTexture3 | IDirect3DRMTexture3, IDirect3DRMVisual
Direct3DRMUserVisual | IDirect3DRMUserVisual, IDirect3DRMVisual
Direct3DRMViewport2 | IDirect3DRMViewport2
Direct3DRMWrap | IDirect3DRMWrap

The following example illustrates how to create two interfaces to a single Direct3DRMDevice3 object. The IDirect3DRM3::CreateObject method creates an uninitialized Direct3DRMDevice3 object. The IDirect3DRMDevice3::InitFromClipper method initializes the object. The call to the IDirect3DRMDevice3::QueryInterface method creates a second interface to the Direct3DRMDevice3 object—an IDirect3DRMWinDevice interface that the application will use to handle WM_PAINT and WM_ACTIVATE messages.

d3drmapi->CreateObject(CLSID_CDirect3DRMDevice, NULL,
    IID_IDirect3DRMDevice3,(LPVOID FAR*)&dev1);
dev1->InitFromClipper(lpDDClipper, IID_IDirect3DRMDevice3,
    r.right, r.bottom);
dev1->QueryInterface(IID_IDirect3DRMWinDevice, (LPVOID*) &dev2);

To determine whether two interfaces refer to the same object, use the QueryInterface method of each interface, and compare the values of the pointers they return. If the pointer values are the same, the interfaces refer to the same object.

All Direct3D Retained Mode objects support the IDirect3DRMObject, IDirect3DRMObject2 and IUnknown interfaces in addition to the interfaces in the preceding list. Array objects are not derived from IDirect3DRMObject. Array objects have no class identifiers (CLSIDs) because they are not needed. Applications cannot create array objects in a call to the IDirect3DRM3::CreateObject method; instead, they should use the creation methods listed below for each interface:

Array interface | Creation method
IDirect3DRMAnimationArray | IDirect3DRMAnimationSet2::GetAnimations
IDirect3DRMDeviceArray | IDirect3DRM3::GetDevices
IDirect3DRMFaceArray | IDirect3DRMMeshBuilder3::GetFaces
IDirect3DRMFrameArray | IDirect3DRMPickedArray::GetPick, IDirect3DRMPicked2Array::GetPick, or IDirect3DRMFrame3::GetChildren
IDirect3DRMLightArray | IDirect3DRMFrame3::GetLights
IDirect3DRMObjectArray | IDirect3DRMInterpolator::GetAttachedObjects
IDirect3DRMPickedArray | IDirect3DRMViewport2::Pick
IDirect3DRMPicked2Array | IDirect3DRMFrame3::RayPick
IDirect3DRMViewportArray | IDirect3DRM3::CreateFrame
IDirect3DRMVisualArray | IDirect3DRMFrame3::GetVisuals

Objects and Reference Counting

When an object is created, its reference count is incremented. Each time an application creates a child of an object or a method returns a pointer to an object, the system increments the reference count for that object. The object is not deleted until its reference count reaches zero. When you are finished with an object be sure to call the object's Release method to decrement its reference count. For example, you could call IDirect3DRM3::CreateMeshBuilder to create an IDirect3DRMMeshBuilder3 object and IDirect3DRMMeshBuilder3::GetFaces to retrieve an IDirect3DRMFaceArray object. Before your application terminates you should call the Release method on the IDirect3DRMMeshBuilder3 object and also call the Release method on the IDirect3DRMFaceArray object. If you do not call Release, the objects will not be properly released and your application will leak resources. For other examples of when to release objects, see the Direct3D Retained Mode sample code.

In Direct3D Retained Mode there is internal and external reference counting. If you have created or imported objects, such as textures, and applied them to objects in your scene, such as frames or meshes, you can then release your copy of the created or imported object's interface, and when the scene is finished with the object it will be automatically released by D3DRM for you. For example, if you create a meshbuilder object, its reference count is 1. If you then add it to a frame, its reference count is 2. You can then release your copy of the pointer to the meshbuilder object, and the meshbuilder object's reference count will be 1. Then, when you release the scene containing the frame, the reference count of the meshbuilder object will be decremented (to 0) for you and the object will be released. As another example, if you import a texture, the texture object's reference count is 1. If you apply the texture to a mesh, its reference count is 2. You can then release your copy of the pointer to the texture object, and its reference count is 1. When the mesh goes away, the texture object's reference count will be decremented and it will be released as well.

If you always release your objects after they have been applied in the scene, your application does not need to keep track of the reference count for them, but only for the root of the scene. Retained Mode keeps track of the other reference counts automatically. In this case, your application should be able to simply release the scene, the viewport, and the device when it cleans up before exiting. (When your application releases the viewport, the system automatically takes care of the camera's references.)

The reference count of a child or visual object increases when it is added to a frame. When you use the IDirect3DRMFrame3::AddChild method to move a child from one parent to another, the system handles the reference counting automatically.

After your application loads a visual object into a scene, the scene handles the reference counting for the visual object. The application no longer needs the visual object and can release it.

Creating and applying a wrap does not increase the reference count of any objects because wrapping is really just a convenient method of calculating texture coordinates.


Overviews

This section provides overview articles that discuss various aspects of Microsoft® Direct3D® Retained Mode. The first two topics provide general information concerning the Direct3D Retained Mode interfaces, including a hierarchy chart and an article that details the history and changes between versions of the interfaces.

  • Interface Hierarchy Chart
  • Interface Changes

The following topics focus on a specific aspect of Direct3D Retained Mode. For a description of each interface's methods, see the appropriate entry in the Reference.

  • Eliminating Redundant State Changes
  • Frames
  • Interpolators
  • Lights
  • Output Devices
  • Textures
  • Viewports
  • Wraps

Direct3D Retained Mode 6 has added support for external visuals. External Visuals provide a method to allow custom hierarchy objects in the Direct3D Retained Mode (D3DRM) hierarchy. These are COM objects which support the IDirect3DRMExternalVisual interface (and any others they wish to support). D3DRM treats these objects as first-class visual objects, allowing for custom rendering, picking, bounding box reporting, and other behaviors. This is more powerful than the User Visuals supported in earlier versions of D3DRM, which only allowed for custom rendering using a callback function. External Visuals provides an extension mechanism that allows any type of visual object, such as deformable meshes or inverse kinematic solvers, to be inserted into the D3DRM visual hierarchy.

Although you can access External Visuals from D3DRM, they support DirectX Transform interfaces and can be used from the DirectX Transform DXETool.exe. For this reason, they are documented in DirectX Transform in the DirectX Media SDK. For more information about External Visuals, please see the Reference section of the DirectX Transform documentation in the DirectX Media SDK.


Interface Hierarchy Chart

Direct3D Retained Mode Interface Hierarchy

 IUnknown
 |
 +--IDirect3DRM (replaced)
 |
 +--IDirect3DRM2 (replaced)
 |
 +--IDirect3DRM3
 |
 +--IDirect3DRMArray
 |  |
 |  +--IDirect3DRMAnimationArray
 |  |
 |  +--IDirect3DRMDeviceArray
 |  |
 |  +--IDirect3DRMFaceArray
 |  |
 |  +--IDirect3DRMFrameArray
 |  |
 |  +--IDirect3DRMLightArray
 |  |
 |  +--IDirect3DRMObjectArray
 |  |
 |  +--IDirect3DRMPicked2Array
 |  |
 |  +--IDirect3DRMPickedArray
 |  |
 |  +--IDirect3DRMViewportArray
 |  |
 |  +--IDirect3DRMVisualArray
 |
 +--IDirect3DRMObject
 |  |
 |  +--IDirect3DRMAnimation (replaced)
 |  |
 |  +--IDirect3DRMAnimation2
 |  |
 |  +--IDirect3DRMAnimationSet (replaced)
 |  |
 |  +--IDirect3DRMAnimationSet2
 |  |
 |  +--IDirect3DRMDevice (replaced)
 |  |  |
 |  |  +--IDirect3DRMDevice2 (replaced)
 |  |
 |  +--IDirect3DRMDevice3
 |  |
 |  +--IDirect3DRMFace2
 |  |
 |  +--IDirect3DRMInterpolator
 |  |
 |  +--IDirect3DRMLight
 |  |
 |  +--IDirect3DRMMaterial (replaced)
 |  |
 |  +--IDirect3DRMMaterial2
 |  |
 |  +--IDirect3DRMViewport (replaced)
 |  |
 |  +--IDirect3DRMViewport2
 |  |
 |  +--IDirect3DRMVisual
 |  |  |
 |  |  +--IDirect3DRMFrame (replaced)
 |  |  |  |
 |  |  |  +--IDirect3DRMFrame2 (replaced)
 |  |  |
 |  |  +--IDirect3DRMFrame3
 |  |  |
 |  |  +--IDirect3DRMMesh
 |  |  |
 |  |  +--IDirect3DRMMeshBuilder (replaced)
 |  |  |  |
 |  |  |  +--IDirect3DRMMeshBuilder2 (replaced)
 |  |  |
 |  |  +--IDirect3DRMMeshBuilder3
 |  |  |
 |  |  +--IDirect3DRMProgressiveMesh
 |  |  |
 |  |  +--IDirect3DRMShadow (replaced)
 |  |  |
 |  |  +--IDirect3DRMShadow2
 |  |  |
 |  |  +--IDirect3DRMTexture (replaced)
 |  |  |  |
 |  |  |  +--IDirect3DRMTexture2 (replaced)
 |  |  |
 |  |  +--IDirect3DRMTexture3
 |  |  |
 |  |  +--IDirect3DRMUserVisual
 |  |
 |  +--IDirect3DRMWinDevice
 |  |
 |  +--IDirect3DRMWrap
 |
 +--IDirect3DRMObject2


Interface Changes

This article outlines the changes in Microsoft® Direct3D® Retained Mode interfaces throughout their history. It discusses the naming convention of sequentially numbered interfaces and lists interfaces that replace older interfaces. It also lists methods added by new interfaces and by successive versions of interfaces.

This article contains the following sections.

  • Sequentially Numbered Interfaces and Methods
  • New and Replaced Interfaces
  • Added and Changed Methods

Sequentially Numbered Interfaces and Methods

Component Object Model (COM) systems, such as Direct3D Retained Mode, provide new methods and functionality through the use of new interfaces that are sequentially numbered. For example, the IDirect3DRMFrame3 interface adds methods to those exposed by IDirect3DRMFrame2. IDirect3DRMFrame2 adds methods to the those exposed by IDirect3DRMFrame.

Beginning with DirectX 6.0, new Direct3D Retained Mode interfaces do not inherit from their predecessor interfaces. For example, IDirect3DRMFrame2, which was introduced in DirectX 5.0, inherits directly from IDirect3DRMFrame, but IDirect3DRMFrame3, which was introduced in DirectX 6.0, does not inherit from IDirect3DRMFrame2 or IDirect3DRMFrame. For a diagram showing the relationship between all Direct3D Retained Mode interfaces, see the Interface Hierarchy Chart.

Beginning with DirectX 6.0, new Direct3D Retained Mode interfaces also require the latest version of input parameters, such as pointers to the latest interface objects. The older interfaces remain unchanged, so you will not have to rewrite your existing applications. For example, IDirect3DRMFrame3 provides all of the functionality present in IDirect3DRMFrame2 and IDirect3DRMFrame. IDirect3DRMFrame3::AddChild takes a pointer to an IDirect3DRMFrame3 interface as its parameter while the same method on the older interfaces takes a pointer to the base IDirect3DRMFrame interface as its parameter. For a list of the interfaces introduced in DirectX 6.0, see New and Replaced Interfaces in this article.

The Direct3D Retained Mode library and run time include the earlier, unchanged interfaces for backward compatibility, but this documentation covers only the latest interfaces and methods to decrease redundant material. This article notes the widespread changes. The documentation for the individual interfaces and methods notes more limited changes between versions. Although you could use the older interfaces to create new applications, it is recommended that you use the newer interfaces to take advantage of their increased functionality.

Prior to DirectX 6.0, new Direct3D Retained Mode methods always accepted the base interface object for input parameters. For output parameters, the new methods return the new interface or object. If the parameters for a particular method change, the name of the changed method is numbered sequentially (for example, by appending a "2" to the name), and that method is added to the new interface. For example, IDirect3DRMFrame::AddMoveCallback has two parameters. In order to expand the functionality, a new version of that method that takes an additional parameter is exposed on a new, sequentially numbered interface as IDirect3DRMFrame2::AddMoveCallback2. Beginning with DirectX 6.0, the practice of appending a number to changed method names is no longer necessary because the new interfaces do not inherit from the old interfaces. Therefore, some Direct3D Retained Mode method names that were appended with a "2" in DirectX 5.0 drop the "2" in DirectX 6.0 or later. Specifically, IDirect3DRMFrame3::AddMoveCallback replaces IDirect3DRMFrame2::AddMoveCallback2 and IDirect3DRMMeshBuilder3::GenerateNormals replaces IDirect3DRMMeshBuilder2::GenerateNormals2.

New and Replaced Interfaces

The following list shows the new interfaces introduced in version 6.0 of the Microsoft DirectX® Software Development Kit (SDK). It also lists old interfaces when those interfaces have been replaced by newer interfaces.
Old interface | New interface
None | IDirect3DRMClippedVisual
None | IDirect3DRMAnimationArray
None | IDirect3DRMObject2
IDirect3DRM | IDirect3DRM3
IDirect3DRM2 | IDirect3DRM3
IDirect3DRMAnimation | IDirect3DRMAnimation2
IDirect3DRMAnimationSet | IDirect3DRMAnimationSet2
IDirect3DRMDevice | IDirect3DRMDevice3
IDirect3DRMDevice2 | IDirect3DRMDevice3
IDirect3DRMFrame | IDirect3DRMFrame3
IDirect3DRMFrame2 | IDirect3DRMFrame3
IDirect3DRMMaterial | IDirect3DRMMaterial2
IDirect3DRMMeshBuilder | IDirect3DRMMeshBuilder3
IDirect3DRMMeshBuilder2 | IDirect3DRMMeshBuilder3
IDirect3DRMShadow | IDirect3DRMShadow2
IDirect3DRMTexture | IDirect3DRMTexture3
IDirect3DRMTexture2 | IDirect3DRMTexture3
IDirect3DRMViewport | IDirect3DRMViewport2

Added and Changed Methods

The following provides the history of Direct3D Retained Mode by listing the methods and the version in which each method and interface was added or changed. In cases where more than two interface versions exist (such as with IDirect3DRM3, IDirect3DRM2, and IDirect3DRM), all versions except the first are listed to show the incremental functionality between versions. Interfaces that remain unchanged since the inception of Direct3D Retained Mode are not listed. The version of the DirectX SDK in which an interface was introduced is indicated in parentheses beside the interface name.

  • IDirect3DRM2 (DirectX 5.0, superseded in DirectX 6.0 by IDirect3DRM3)
    • CreateProgressiveMesh
  • IDirect3DRM3 (DirectX 6.0)
    • CreateDeviceFromSurface
    • GetOptions
    • RegisterClient
    • SetOptions
    • UnregisterClient
  • IDirect3DRMAnimation2 (DirectX 6.0)
    • AddKey
    • DeleteKeyByID
    • GetFrame
    • GetKeys
    • ModifyKey
  • IDirect3DRMAnimationArray (DirectX 6.0)
    • GetElement
    • GetSize
  • IDirect3DRMAnimationSet2 (DirectX 6.0)
    • GetAnimations
  • IDirect3DRMClippedVisual (DirectX 6.0)
    • AddPlane
    • DeletePlane
    • GetPlane
    • GetPlaneIDs
    • Init
    • SetPlane
  • IDirect3DRMDevice2 (DirectX 5.0, superseded in DirectX 6.0 by IDirect3DRMDevice3)
    • GetDirect3DDevice2
    • GetRenderMode
    • InitFromD3D2
    • InitFromSurface
    • SetRenderMode
  • IDirect3DRMDevice3 (DirectX 6.0)
    • FindPreferredTextureFormat
  • IDirect3DRMFrame2 (DirectX 5.0, superseded in DirectX 6.0 by IDirect3DRMFrame3)
    • AddMoveCallback2 (Replaced by IDirect3DRMFrame3::AddMoveCallback)
    • GetAxes
    • GetBox
    • GetBoxEnable
    • GetHierarchyBox
    • GetInheritAxes
    • GetMaterial
    • RayPick
    • Save
    • SetAxes
    • SetBox
    • SetBoxEnable
    • SetInheritAxes
    • SetMaterial
    • SetQuaternion
  • IDirect3DRMFrame3 (DirectX 6.0)
    • GetMaterialOverride
    • GetSceneFogMethod
    • GetTransform (Extends IDirect3DRMFrame::GetTransform)
    • GetTraversalOptions
    • InverseTransformVectors
    • SetMaterialOverride
    • SetSceneFogMethod
    • SetTraversalOptions
    • TransformVectors
  • IDirect3DRMMaterial2 (DirectX 6.0)
    • GetAmbient
    • SetAmbient
  • IDirect3DRMMeshBuilder2 (DirectX 5.0, superseded in DirectX 6.0 by IDirect3DRMMeshBuilder3)
    • GenerateNormals2 (Replaced by IDirect3DRMMeshBuilder3::GenerateNormals)
    • GetFace
  • IDirect3DRMMeshBuilder3 (DirectX 6.0)
    • AddFacesIndexed
    • AddTriangles
    • CreateSubMesh
    • DeleteFace
    • DeleteNormals
    • DeleteSubMesh
    • DeleteVertices
    • Empty
    • Enable
    • GetEnable
    • GetNormal
    • GetGeometry (Replaces IDirect3DRMMeshBuilder::GetVertices)
    • GetNormalCount
    • GetNormals
    • GetParentMesh
    • GetSubMeshes
    • GetVertex
    • GetVertices (See GetGeometry for IDirect3DRMMeshBuilder::GetVertices functionality)
    • Optimize
    • SetNormals
    • SetVertices
  • IDirect3DRMObject2 (DirectX 6.0)

    Note that this interface does not replace IDirect3DRMObject.

    • AddDestroyCallback
    • Clone
    • DeleteDestroyCallback
    • GetAge
    • GetClientData
    • GetDirect3DRM
    • GetName
    • SetClientData
    • SetName
  • IDirect3DRMShadow2 (DirectX 6.0)
    • GetLight
    • GetOptions
    • GetPlane
    • GetVisual
    • SetLight
    • SetOptions
    • SetPlane
    • SetVisual
  • IDirect3DRMTexture2 (DirectX 5.0, superseded in DirectX 6.0 by IDirect3DRMTexture3)
    • GenerateMIPMap
    • InitFromImage
    • InitFromResource2
  • IDirect3DRMTexture3 (DirectX 6.0)
    • Changed (Extends IDirect3DRMTexture::Changed)
    • GetCacheOptions
    • GetSurface
    • SetCacheOptions
    • SetDownsampleCallback
    • SetValidationCallback
  • IDirect3DRMViewport2 (DirectX 6.0)
    • Clear (Extends IDirect3DRMViewport::Clear)


Eliminating Redundant State Changes

In earlier versions of Microsoft® Direct3D® Retained Mode, Retained Mode could not assume render and light states would remain the same from one call to the next. This led to many redundant state changes in a typical application because Retained Mode set the state to a value equal to its current value. The IDirect3DRMDevice3 interface introduces several methods that can be used to eliminate these redundant changes for a modest performance boost: GetStateChangeOptions, LightStateChange, RenderStateChange, and SetStateChangeOptions. To use these methods, follow these steps:

  1. Turn on the redundant state change check by using the following two methods on the IDirect3DRMDevice3 interface. This indicates that you will not change any render or light state without notice.
    Dev3->SetStateChangeOptions(D3DRMSTATECHANGE_RENDER, 0,
                            D3DRMSTATECHANGE_NONVOLATILE);
Dev3->SetStateChangeOptions(D3DRMSTATECHANGE_LIGHT, 0, D3DRMSTATECHANGE_NONVOLATILE);
  2. When you change a render or light state (either through an execute buffer or a draw primitive), you must inform Direct3D Retained Mode of the change so that the state cache is updated. You can do this in two ways. You can have Retained Mode change the state for you (and prevent redundant changes) or you can inform Retained Mode that you have changed the state to a new value. Both use the LightStateChange and RenderStateChange methods.

For example, the following code shows you how to change the texture handle and update the state cache.

Dev3->RenderStateChange(D3DRENDERSTATE_TEXTUREHANDLE, hTex, 0UL);

If you have changed the state and just want Retained Mode to update its state cache, use the UPDATEONLY flag, as shown in the following:

Dev3->RenderStateChange(D3DRENDERSTATE_TEXTUREHANDLE, hTex,
                        D3DRMSTATECHANGE_UPDATEONLY);

If you are going to be changing a state value many times and do not want Retained Mode to keep track of current values, you can turn off redundant state checking for the specified state with the following code. However, this is not recommended because you will lose performance benefits.

Dev3->SetStateChangeOptions(D3DRMSTATECHANGE_RENDER, D3DRENDERSTATE_TEXTUREHANDLE,
                            D3DRMSTATECHANGE_VOLATILE);


Frames

The term frame is derived from an object's physical frame of reference. The frame's role in Retained Mode is similar to a window's role in a windowing system. Objects can be placed in a scene by stating their spatial relationship to a relevant reference frame; they are not simply placed in world space. A frame is used to position objects in a scene, and visuals take their positions and orientation from frames.

A scene in Retained Mode is defined by a frame that has no parent frame; that is, a frame at the top of the hierarchy of frames. This frame is also sometimes called a root frame or master frame. The scene defines the frame of reference for all of the other objects. You can create a scene by calling the IDirect3DRM3::CreateFrame method and specifying NULL for the first parameter.

The IDirect3DRMFrame3 interface is an extension of the IDirect3DRMFrame2 interface. IDirect3DRMFrame2 has methods that enable using materials, bounding boxes, and axes with frames. IDirect3DRMFrame2 also supports ray picking.

By using the IDirect3DRMFrame3::SetAxes method and using the right-handed projection types in the D3DRMPROJECTIONTYPE structure with the IDirect3DRMViewport2::SetProjection method, you can enable right-handed projection.

For related information, see IDirect3DRMFrame3.

This section describes frames and how your application can use them.

  • Hierarchies
  • Transformations
  • Motion
  • Callback Functions

Hierarchies

The frames in a scene are arranged in a tree structure. Frames can have a parent frame and child frames. Remember, a frame that has no parent frame defines a scene and is called a root frame.

Child frames have positions and orientations relative to their parent frames. If the parent frame moves, the child frames also move.

An application can set the position and orientation of a frame relative to any other frame in the scene, including the root frame if it needs to set an absolute position. You can also remove frames from one parent frame and add them to another at any time by using the IDirect3DRMFrame3::AddChild method. To remove a child frame entirely, use the IDirect3DRMFrame3::DeleteChild method. To retrieve a frame's child and parent frames, use the IDirect3DRMFrame3::GetChildren and IDirect3DRMFrame3::GetParent methods.

You can add frames as visuals to other frames, allowing you to use a given hierarchy many times throughout a scene. The new hierarchies are referred to as instances. Be careful to avoid instancing a parent frame into its children because that will degrade performance. Retained Mode does no run-time checking for cyclic hierarchies. You cannot create a cyclic hierarchy by using the methods of the IDirect3DRMFrame3 interface; instead, this is possible only when you add a frame as a visual.

Transformations

You can think of the position and orientation of a frame relative to its parent frame as a linear transformation. This transformation takes vectors defined relative to the child frame and changes them to equivalent vectors defined relative to the parent.

Transformations can be represented by 4×4 matrices, and coordinates can be represented by four-element row vectors, [x, y, z,1].

If vchild is a coordinate in the child frame, then vparent, the equivalent coordinate in the parent frame, is defined as:

Definition of the parent frame

Tchild is the child frame's transformation matrix.

The transformations of all the parent frames above a child frame up to the root frame are concatenated with the transformation of that child to produce a world transformation. This world transformation is then applied to the visuals on the child frame before rendering. Coordinates relative to the child frame are sometimes called model coordinates. After the world transformation is applied, coordinates are called world coordinates.

The transformation of a frame can be modified directly by using the IDirect3DRMFrame3::AddTransform, IDirect3DRMFrame3::AddScale, IDirect3DRMFrame3::AddRotation, and IDirect3DRMFrame3::AddTranslation methods. Each of these methods specifies a member of the D3DRMCOMBINETYPE enumerated type, which specifies how the matrix supplied by the application should be combined with the current frame's matrix.

The IDirect3DRMFrame3::GetRotation and IDirect3DRMFrame3::GetTransform methods allow you to retrieve a frame's rotation axis and transformation matrix. To change the rotation of a frame, use the IDirect3DRMFrame3::SetRotation method.

Use the IDirect3DRMFrame3::Transform and IDirect3DRMFrame3::InverseTransform methods to change between world coordinates and model coordinates.

You can find a more general discussion of transformations in the Transformations section devoted to viewports. For an overview of the mathematics of transformations, see 3-D Transformations.

Motion

Every frame has an intrinsic rotation and velocity. Frames that are neither rotating nor translating simply have zero values for these attributes. These attributes are used before each scene is rendered to move objects in the scene, and they can also be used to create simple animations.

Callback Functions

Frames support a callback function that you can use to support more complex animations. The application registers a function that the frame calls before the motion attributes are applied. When there are multiple frames in a hierarchy, each with associated callback functions, the parent frames are called before the child frames. For a given hierarchy, rendering does not take place until all of the required callback functions have been invoked.

To add this callback function, use the IDirect3DRMFrame3::AddMoveCallback method; to remove it, use the IDirect3DRMFrame3::DeleteMoveCallback method.

You can use these callback functions to provide new positions and orientations from a preprogrammed animation sequence or to implement dynamic motion in which the activities of visuals depend upon the positions of other objects in the scene.


Interpolators

Interpolators provide a way of storing actions and applying them to objects with automatic calculation of in-between values. For example, you can set a scene's background color to red at time zero and green at time ten, and the interpolator will automatically tint successive scenes to blend from red to green. With an interpolator, you can blend colors, move objects smoothly between positions, morph meshes, and perform many other transformations.

In the Direct3D Retained Mode implementation, interpolators are a generalization of the IDirect3DRMAnimation2 interface that increases the kinds of object parameters you can animate. While the IDirect3DRMAnimation2 interface allows animation of an object's position, size and orientation, the IDirect3DRMInterpolator interface further enables animation of colors, meshes, textures, and materials.

This article contains the following sections.

  • Interpolator Keys
  • Interpolator Types
  • Interpolator Example
  • Methods Supported by the Interpolator
  • Interpolator Index Span
  • Interpolation Options

Interpolator Keys

The actions stored by the interpolator are called keys. A key is a stored procedure call and has an index associated with it. The interpolator automatically calculates between the key values.

Keys are stored in the interpolator by calling one of the supported interface methods that can be interpolated. The method and the parameter values passed to it make up the key. Methods Supported by the Interpolator supplies a list of supported methods.

Every key stored inside an interpolator has an index value. When the key is recorded, it is stamped with the current interpolator index value. The key's index value never changes once this value is set.

Interpolator Types

Objects can be attached to interpolators of an associated type; for example, a Mesh can be attached to a MeshInterpolator. The interpolator types are:

  • FrameInterpolator
  • LightInterpolator
  • MaterialInterpolator
  • MeshInterpolator
  • TextureInterpolator
  • ViewportInterpolator

Other interpolators can also be attached to an interpolator. When you change the index of an interpolator, it sets the indices of any attached interpolators to the same value.

Note that for MeshInterpolators, you add a SetVertices key to a MeshInterpolator object by calling SetVertices on the MeshInterpolator object's IDirect3DRMMesh interface. The group index used with SetVertices must correspond to a valid group index in the Mesh object or objects that the interpolator is applied to.

Interpolator Example

As an example, if you want to interpolate a frame's position, you will need a FrameInterpolator object with two interfaces, IDirect3DRMInterpolator and IDirect3DRMFrame3.

pd3drm->CreateObject(CLSID_CDirect3DRMFrameInterpolator, 0,

     IID_IDirect3DRMInterpolator, &pInterp);
pInterp->QueryInterface(IID_IDirect3DRMFrame3, &pFrameInterp);

To add a position key to the interpolator, set the interpolator's internal index by calling IDirect3DRMInterpolator::SetIndex, and record the position by calling SetPosition on the IDirect3DRMFrame3 interface. This method is applied to the interpolator rather than to a real frame. The function call and its parameters are stored in the interpolator as a new key with the current index.

pInterp->SetIndex(keytime);
pFrameInterp->SetPosition(NULL, keypos.x, keypos.y, keypos.z);

You can add more keys by repeating the sequence of setting the index with IDirect3DRMInterpolator::SetIndex followed by one or more object methods. To play actions back through a real frame, attach the frame to the interpolator.

pInterp->AttachObject(pRealFrame);

Now call IDirect3DRMInterpolator::Interpolate to set the position of the pRealFrame parameter using the interpolated position.

pInterp->Interpolate(time, NULL,

      D3DRMINTERPOLATIONSPLINE | D3DRMINTERPOLATION_OPEN);

The interpolator will call the attached frame's SetPosition method, passing it a position it has calculated by interpolating (in this case, using a B-spline) between the nearest SetPosition keys.

Alternatively, you can use the immediate form of Interpolate and pass the object as the second parameter. This overrides any attached objects.

pInterp->Interpolate(time, pRealFrame,
    D3DRMINTERPOLATIONSPLINE | D3DRMINTERPOLATION_OPEN);

You can use the same interpolator to store other keys such as orientation, scale, velocity, and color keys. Each property exists on a parallel timeline, and calling Interpolate assigns the interpolated value for each property to the attached frames.

It is possible to interpolate more than one method. For example, you can store SetGroupColor and SetVertices keys in the same interpolator. It is not possible to interpolate between keys of different methods, so they are stored in parallel execution threads called Key Chains. Also, if you specify two keys from different groups, such as SetGroupColor(0, black) and SetGroupColor(2, white), it does not make sense for the interpolator to generate an in-between action of SetGroupColor(1, gray) because the keys apply to different groups. In this case, the keys are also stored in separate chains.

Methods Supported by the Interpolator

Viewport

SetFront(value)
SetBack(value)
SetField(value)
SetPlane(left, right, bottom, top)

Frame

SetPosition(reference*, x, y, z)
SetRotation(reference*, x, y, z, theta)
SetVelocity(reference*, x, y, z, withRotation*)
SetOrientation(reference*, dx, dy, dz, ux, uy, uz)
SetColor(color)
SetColorRGB(red, green, blue)
SetSceneBackground(color)
SetSceneBackgroundRGB(red, green, blue)
SetSceneFogColor(color)
SetSceneFogParams(start, end, density)
SetQuaternion(reference*, quat)

Mesh

Translate(x, y, z)
SetVertices(group*, index*, count*, vertices)
SetGroupColor(group*, color)
SetGroupColorRGB(group*, red, green, blue)

Light

SetColor(color)
SetColorRGB(red, green, blue)
SetRange(value)
SetUmbra(value)
SetPenumbra(value)
SetConstantAttenuation(value)
SetLinearAttenuation(value)
SetQuadraticAttenuation(value)

Texture

SetDecalSize(width, height)
SetDecalOrigin(x, y)
SetDecalTransparentColor(color)

Material

SetPower(value)
SetSpecular(red, green, blue)
SetEmissive(red, green, blue)

*—Indicates keys with different values for this parameter are inserted in separate chains

An attempt to set a key of any unsupported method will result in a non-fatal D3DRMERR_BADOBJECT error.

Interpolator Index Span

The interpolator covers a span of index values. This index span is dictated by the following rules:

  • The start of the span is the minimum of all key index values and the current index.
  • The end of the span is the maximum of all key index values and the current index.

Interpolation Options

The d3drmInterpFlags parameter of IDirect3DRMInterpolator::Interpolate allows you to perform interpolation by specifying one or more of the following options:

  • D3DRMINTERPOLATION_CLOSED
  • D3DRMINTERPOLATION_LINEAR
  • D3DRMINTERPOLATION_NEAREST
  • D3DRMINTERPOLATION_OPEN
  • D3DRMINTERPOLATION_SLERPNORMALS
  • D3DRMINTERPOLATION_SPLINE
  • D3DRMINTERPOLATION_VERTEXCOLOR

If the interpolator is executed CLOSED, the interpolation is cyclic. The keys effectively repeat infinitely with a period equal to the index span. For compatibility with animations, any key with an index equal to the end of the span is ignored.

If the interpolation is OPEN, the first and last keys of each key chain fix the interpolated values outside of the index span.

The NEAREST, LINEAR, and SPLINE options specify how in-betweening is performed on each key chain. In-betweening is the calculation of intermediate values that smoothly connect key data points. If NEAREST is specified the nearest key value is used. LINEAR performs linear interpolation between the 2 nearest keys. SPLINE uses a B-spline blending function on the 4 nearest keys.

The following two options affect only the interpolation of IDirect3DRMMesh::SetVertices:

  • VERTEXCOLOR specifies that vertex colors should be interpolated.
  • SLERPNORMALS specifies that vertex normals should be spherically interpolated (not currently implemented).


Lights

Lighting effects are employed to increase the visual fidelity of a scene. The system colors each object based on the object's orientation to the light sources in the scene. The contribution of each light source is combined to determine the color of the object during rendering. All lights have color and intensity that can be varied independently.

An application can attach lights to a frame to represent a light source in a scene. When a light is attached to a frame, it illuminates visual objects in the scene. The frame provides both position and orientation for the light. In other words, the light originates from the origin of the frame it is attached to. An application can move and redirect a light source simply by moving and reorienting the frame the light source is attached to.

Each viewport owns one or more lights. No light can be owned by more than one viewport.

Retained Mode currently provides five types of light sources: ambient, directional, parallel point, point, and spotlight.

For a reference to the methods of the IDirect3DRMLight interface, see IDirect3DRMLight.

This section describes lighting effects available in Direct3D and how your application can use them.

  • Ambient
  • Directional
  • Parallel Point
  • Point
  • Spotlight

Ambient

An ambient light source illuminates everything in the scene, regardless of the orientation, position, and surface characteristics of the objects in the scene. Because ambient light illuminates a scene with equal strength everywhere, the position and orientation of the frame it is attached to are inconsequential. Multiple ambient light sources are combined within a scene.

Directional

A directional light source has orientation but no position. The light is attached to a frame but appears to illuminate all objects with equal intensity, as if it were at an infinite distance from the objects. The directional source is commonly used to simulate distant light sources, such as the sun. It is the best choice of light to use for maximum rendering speed.

Parallel Point

A parallel point light source illuminates objects with parallel light, but the orientation of the light is taken from the position of the parallel point light source. That is, like a directional light source, a parallel point light source has orientation, but it also has position. For example, two meshes on either side of a parallel point light source are lit on the side that faces the position of the source. The parallel point light source offers similar rendering-speed performance to the directional light source.

Point

A point light source radiates light equally in all directions from its origin. It requires the calculation of a new lighting vector for every facet or normal it illuminates, and for this reason it is computationally more expensive than a parallel point light source. It does, however, produce a more faithful lighting effect and should be chosen where visual fidelity is the deciding concern.

Spotlight

A spotlight emits a cone of light. Only objects within the cone are illuminated. The cone produces light of two degrees of intensity, with a central brightly lit section (the umbra) that acts as a point source, and a surrounding dimly lit section (the penumbra) that merges with the surrounding deep shadow. The angles of these two sections can be individually specified by using the IDirect3DRMLight::GetPenumbra, IDirect3DRMLight::GetUmbra, IDirect3DRMLight::SetPenumbra, and IDirect3DRMLight::SetUmbra methods.

Illustration of penumbra angle, umbra angle, and umbra cone


Output Devices

All forms of rendered output must be associated with an output device. The device object represents the visual display destination for the renderer.

The renderer's behavior depends on the type of output device that is specified. You can define multiple viewports on a device, allowing different aspects of the scene to be viewed simultaneously. You can also specify any number of devices, allowing multiple destination devices for the same scene.

Retained Mode supports devices that render directly to the screen, to windows, or into application memory.

Applications use the IDirect3DRMDevice3, IDirect3DRMDevice2, and IDirect3DRMDevice interfaces to interact with the output device. For related information, see IDirect3DRMDevice3.

This section describes the options available to display Direct3D images to output devices.

  • Quality
  • Color Models
  • Window Management

Quality

The output device allows the scene and its component parts to be rendered with various degrees of realism. The device rendering quality is the maximum quality at which rendering can take place on the rendering surface of that device. Mesh, progressive mesh, and mesh builder objects can also have a specified rendering quality.

A device's or object's quality has three components: shade mode (flat or Gouraud; Phong is not yet implemented and will default to Gouraud shading), lighting type (on or off), and fill mode (point, wireframe or solid).

You can set the quality of a device with IDirect3DRMDevice3::SetQuality and IDirect3DRMDevice3::SetQuality methods. By default, the device quality is D3DRMRENDER_FLAT (flat shading, lights on, and solid fill).

You can set the quality of a Direct3DRMProgressiveMesh, Direct3DRMMeshBuilder3, or Direct3DRMMeshBuilder3 object with their respective SetQuality methods: IDirect3DRMProgressiveMesh::SetQuality, IDirect3DRMMeshBuilder3::SetQuality, and IDirect3DRMMeshBuilder3::SetQuality. By default, the quality of these objects is D3DRMRENDER_GOURAUD (Gouraud shading, lights on, and solid fill).

Tip: Gourad shading gets better performance on progressive mesh objects that change level of detail, often or quickly.

Direct3D Retained Mode renders an object at the lowest quality setting based on the device and object's current setting for each individual component. For example, if the object's current quality setting is D3DRMRENDER_GOURAUD, and the device is D3DRMRENDER_FLAT then the object will be rendered with flat shading, solid fill, and lights on.

If the object's current quality setting is D3DRMSHADE_GOURAUD|D3DRMLIGHT_OFF|D3DRMFILL_WIREFRAME and the device's quality setting is D3DRMSHADE_FLAT|D3DRMLIGHT_ON|D3DRMFILL_POINT, then the object will be rendered with flat shading, lights off, and point fill mode.

These rules apply to Direct3DRMMeshBuilder3 object s, Direct3DRMMeshBuilder3 objects, and Direct3DRMProgressiveMesh objects. However, Direct3DRMMesh objects do not follow these rules. Mesh objects ignore the device's quality settings and use the group quality setting (which defaults to D3DRMRENDER_GOURAUD).

Color Models

Retained Mode supports two color models: an RGB model and a monochromatic (or ramp) model. To retrieve the color model, an application can use the IDirect3DRMDevice3::GetColorModel method.

The RGB model treats color as a combination of red, green, and blue light, and it supports multiple light sources that can be colored. There is no limit to the number of colors in the scene. You can use this model with 8-, 16-, 24-, and 32-bit displays. If the display depth is less than 24 bits, the limited color resolution can produce banding artifacts. You can avoid these artifacts by using optional dithering.

The monochromatic model also supports multiple light sources, but their color content is ignored. Each source is set to a gray intensity. RGB colors at a vertex are interpreted as brightness levels. Brightness levels between vertices with different brightness are interpolated (in Gouraud shading) across the intervening face. The number of differently colored objects in the scene is limited; after all the system's free palette entries are used up, the system's internal palette manager finds colors that already exist in the palette and that most closely match the intended colors. Like the RGB model, you can use this model with 8-, 16-, 24-, and 32-bit displays. (The monochromatic model supports only 8-bit textures, however.) The advantage of the monochromatic model over the RGB model is better performance.

It is not possible to change the color model of a Direct3D device. Your application should use the IDirect3D::EnumDevices or IDirect3D::FindDevice method to identify a driver that supports the required color model, then specify this driver in one of the device-creation methods.

Palettes are supported for textures, off-screen surfaces, and overlay surfaces, none of which is required to have the same palette as the primary surface. If a device supports a 4-bit indexed palette (16 colors) and you have 8-bit indexed art (256 colors), Retained Mode will render the art as 4-bit by taking the first 16 entries from your palette and remapping to those. Therefore, you should put your 16 preferred colors at the front of the palette if possible.

Window Management

For correct operation, applications must inform Direct3D when the WM_MOVE, WM_PAINT, and WM_ACTIVATE messages are received from the operating system by using the IDirect3DRMWinDevice::HandlePaint and IDirect3DRMWinDevice::HandleActivate methods.

For related information, see IDirect3DRMWinDevice.


Textures

A texture is a rectangular array of colored pixels. (The rectangle does not necessarily have to be square, although the system deals most efficiently with square textures.) You can use textures for texture-mapping faces, in which case their dimensions must be powers of two.

Your application can use the IDirect3DRM3::CreateTexture method to create a texture from a D3DRMIMAGE structure, or the IDirect3DRM3::CreateTextureFromSurface method to create a texture from a DirectDraw surface. The IDirect3DRM3::LoadTexture method allows your application to load a texture from a file; the texture should be in Microsoft® Windows® bitmap (.bmp) or Portable Pixmap (.ppm) format. To avoid unnecessary delays when creating textures, hold onto textures you want to use again, instead of creating them each time they're needed. For optimal performance, use a texture surface format that is supported by the device you are using. This will avoid a costly format conversion when the texture is created and any time it changes. If your textures consist of 16 colors or less, consider using the 4-bit palettized surface format to reduce video memory usage on hardware devices.

The texture coordinates of each face define the region in the texture that is mapped onto that particular face. Your application can use a wrap to calculate texture coordinates. For more information, see Wraps.

The IDirect3DRMTexture3 interface is an extension of the IDirect3DRMTexture2 interface, which is an extension of the IDirect3DRMTexture interface.

Textures are loaded from BMP and DIB (device-independent bitmap) files right-side up in IDirect3DRMTexture3::InitFromFile, IDirect3DRMTexture3::InitFromResource2, and in the IDirect3DRMTexture2 versions of these methods, unlike IDirect3DRMTexture::InitFromFile and IDirect3DRMTexture::InitFromResource2 where they are loaded inverted.

For a reference to the methods of these interfaces, see IDirect3DRMTexture3.

Note that you should not use DDSCAPS2_TEXTUREMANAGE flag in Retained Mode. Instead, create textures in system memory, and Retained Mode will manage them.

This section describes the types of textures supported by Direct3D and how your application can use them.

  • Decals
  • Texture Colors
  • Mipmaps
  • Texture Filtering
  • Texture Transparency
  • Texture Format Selection Rules

Decals

Textures can also be rendered directly, as visuals. Textures used this way are sometimes known as decals, a term adopted by Retained Mode. A decal is rendered into a viewport-aligned rectangle. The rectangle can optionally be scaled by the depth component of the decal's position. The size of the decal is taken from a rectangle defined relative to the containing frame by using the IDirect3DRMTexture3::SetDecalSize method. (An application can retrieve the size of the decal by using the IDirect3DRMTexture3::GetDecalSize method.) The decal is then transformed and perspective projection is applied.

Decals have origins that your application can set and retrieve by using the IDirect3DRMTexture3::SetDecalOrigin and IDirect3DRMTexture3::GetDecalOrigin methods. The origin is an offset from the top-left corner of the decal. The default origin is [0, 0]. The decal's origin is aligned with its frame's position when rendering.

Texture Colors

You can set and retrieve the number of colors that are used to render a texture by using the IDirect3DRMTexture3::SetColors and IDirect3DRMTexture3::GetColors methods.

If your application uses the RGB color model, you can use 8-bit, 24-bit, and 32-bit textures. If you use the monochromatic (or ramp) color model, however, you can use only 8-bit textures.

Several shades of each color are used when lighting a scene. An application can set and retrieve the number of shades used for each color by calling the IDirect3DRMTexture3::SetShades and IDirect3DRMTexture3::GetShades methods.

A Direct3DRMTexture object uses a D3DRMIMAGE structure to define the bitmap that the texture will be rendered from. If the application provides the D3DRMIMAGE structure, the texture can easily be animated or altered during rendering.

Mipmaps

A mipmap is a sequence of textures, each of which is a progressively lower resolution, prefiltered representation of the same image. Mipmapping is a computationally low-cost way of improving the quality of rendered textures. Each prefiltered image, or level, in the mipmap is a power of two smaller than the previous level. You can specify mipmaps when filtering textures by calling the IDirect3DRMDevice3::SetTextureQuality method.

For more information about mipmaps, see Mipmaps.

Texture Filtering

After a texture has been mapped to a surface, the texture elements (texels) of the texture rarely correspond to individual pixels in the final image. A pixel in the final image can correspond to a large collection of texels or to a small piece of a single texel. You can use texture filtering to specify how to interpolate texel values to pixels.

You can use the IDirect3DRMDevice3::SetTextureQuality method and the D3DRMTEXTUREQUALITY enumerated type to specify the texture filtering mode for your application.

Texture Transparency

You can use the IDirect3DRMTexture3::SetDecalTransparency method to produce transparent textures. Another method for achieving transparency is to use DirectDraw's support for color keys. Color keys are colors or ranges of colors that can be part of either the source or destination of a blit or overlay operation. You can specify that these colors should always be overwritten or never be overwritten.

For more information about DirectDraw's support for color keys, see Color Keying.

Texture Format Selection Rules

When you use a device-independent source image to create a device-dependent texture surface for rendering, the rules are (in order of precedence):

1. Preserve RGB/palettized nature

2. Preserve alpha channel

3. Preserve bit depth or palette size

4. Preserve RBGA masks

5. Prefer 8-bit palettized or 16-bit RGB

For more information about texture pixel formats, see Texture Map Formats.

For related information, see IDirect3DRMTexture3.


Viewports

The viewport defines how the 3-D scene is rendered into a 2-D window. The viewport defines a rectangular area on a device that objects will be rendered into.

For a reference to the methods of this interface, see IDirect3DRMViewport2.

This section describes the viewport, its components, and techniques for their use.

  • Camera
  • Viewing Frustum
  • Transformations
  • Picking

Camera

The viewport uses a Direct3DRMFrame object as a camera. The camera frame defines which scene is rendered and the viewing position and direction. The viewport renders only what is visible along the positive z-axis of the camera frame, with the up direction being in the direction of the positive y-axis.

An application can call the IDirect3DRMViewport2::SetCamera method to set a camera for a given viewport. This method sets a viewport's position, direction, and orientation to that of the given camera frame. To retrieve the current camera settings, call the IDirect3DRMViewport2::GetCamera method.

Viewing Frustum

The viewing frustum is a 3-D volume in a scene positioned relative to the viewport's camera. For perspective viewing, the camera is positioned at the tip of an imaginary pyramid. This pyramid is intersected by two clipping planes, the front clipping plane and the back clipping plane. The volume in the pyramid between the front and back clipping planes is the viewing frustum. Only objects in the viewing frustum are visible.

Diagram showing the front and back clipping plane and the viewing frustum

The z-axis of the camera runs from the tip of the pyramid to the center of the back clipping plane. Your application can set and retrieve the positions of the front and back clipping planes by using the IDirect3DRMViewport2::SetFront, IDirect3DRMViewport2::SetBack, IDirect3DRMViewport2::GetFront, and IDirect3DRMViewport2::GetBack methods.

The dimensions of the viewport on the front clipping plane determine the apparent focal length of the camera's lens. (You can also think of this as a way to set the magnification of objects in the frustum.) To set and retrieve proportional dimensions for the viewport on the front clipping plane, use the IDirect3DRMViewport2::SetField and IDirect3DRMViewport2::GetField methods. To set and retrieve arbitrary dimensions for the viewport on the front clipping plane, use the IDirect3DRMViewport2::SetPlane and IDirect3DRMViewport2::GetPlane methods.

You can use the following equation to determine the relationship between the height (or width) of the front clipping plane and the viewing angle:

Equation showing relationship between the front clipping plane and the viewing angle

In this formula, the viewing angle is A, the front clipping plane is a distance D from the camera, and the height or width of the front clipping plane is 2h. If the device is not square, and thus the clipping planes are not square, the viewing angle is calculated using half the height or half the width of the front clipping plane, whichever is larger. The scale factors are set to the major axis of the device so you don't get distorted objects. If this is not what you want, you need to set uniform scaling.

Illustration of the dimensions used in the previous equation

The viewing frustum is a pyramid only for perspective viewing. For orthographic viewing, the viewing frustum is cuboid. These viewing types (or projection types) are defined by the D3DRMPROJECTIONTYPE enumerated type and used by the IDirect3DRMViewport2::GetProjection and IDirect3DRMViewport2::SetProjection methods.

Units of Measurement

DirectSound is the only module of DirectX where there is a default unit of measurement, the meter. This can be changed by the use of a distance factor. However, in both Direct3D Immediate Mode and Retained Mode there is no particular default unit. The developer must decide which units are most appropriate for the application, and build this into the program. For most applications measurements in meters, or feet, are appropriate, but for some they will not be. For example, if suns and moons are in the picture, distances could be measured in miles, or when modeling insects, or even atomic particles, the measurements might be very much less than a foot or a meter. DirectX simply works on the basis of "units" and has no concept of any real distance.

The absence of built in measurements can become a problem when importing DirectX files from a variety of sources. Not only is the measurement not included in the file, the "units" can be arbitrary, so need not be any standard measurement. This could make proper scaling of, say, two aircraft from different sources, difficult. If one model is in meters, and the other in feet, all that is needed is to scale one of the models when it is loaded. The IDirect3DRMMeshBuilder3::Scale function can be used in cases where the units of measurement of a model are known. Trial and error, or inspired guesswork, may be needed if a developer has little information as to the units used by the modeller.

If a developer wishes to use DirectSound, then setting the default measurement for the whole application to meters makes sense. For more information see the Units of Measure and Distance Factors section in the DirectSound documentation.

Transformations

To render objects with 3-D coordinates in a 2-D window, the object must be transformed into the camera's frame. A projection matrix is then used to give a four-element homogeneous coordinate [x y z w], which is used to derive a three-element coordinate [x/w y/w z/w], where [x/w y/w] is the coordinate to be used in the window and z/w is the depth, ranging from 0 at the front clipping plane to 1 at the back clipping plane. The projection matrix is a combination of a perspective transformation followed by a scaling and translation to scale the objects into the window.

The following values are the elements of the projection matrix. In these formulas, h is the half-height of the viewing frustum, F is the distance from the camera, and D is the position in z-coordinates of the front clipping plane:

After projection, the next step is clipping and the conversion of x and y to screen-pixel coordinates within a viewport. Use the D3DVIEWPORT data members for this. The viewport is a rectangular window on the rendering surface.

typedef struct _D3DVIEWPORT {
    DWORD    dwSize;
    DWORD    dwX;
    DWORD    dwY;
    DWORD    dwWidth;
    DWORD    dwHeight;
    D3DVALUE dvScaleX;
    D3DVALUE dvScaleY;
    D3DVALUE dvMaxX;
    D3DVALUE dvMaxY;
    D3DVALUE dvMinZ;
    D3DVALUE dvMaxZ;
} D3DVIEWPORT, *LPD3DVIEWPORT;

The dwX and dwY fields specify the offset in screen pixels to the top left of the viewport on the surface.

The dwWidth and dwHeight fields are the width and height of the viewport in screen pixels.

The dvScaleX and dvScaleY fields are the scaling factors that are applied to the x and y values to yield screen coordinates. You would usually want to map the entire normalized perspective view volume onto the viewport using the following formulas:

  dvScaleX = dwWidth / 2
  dvScaleY = dwHeight / 2

X coordinates, for example, in the range of -1 to 1, will be scaled into the range of -dwWidth / 2 to dwWidth / 2. An offset of dwWidth / 2 is then added. This scaling occurs after clipping.

If the window is not square and you would like to preserve a correct aspect ratio, use the larger of the two window dimensions for both scaling values. You will also need to clip some of the view volume.

The dvMaxX, dvMaxY, dvinZ, and dvMaxZ fields specify the clipping planes: x = dvMaxX, x = —dvMaxX, y = dvMaxy, y = —dvMaxY, z = dvMinZ, z = dvMaxZ. To display all of the view volume, for example, you would set dvMaxX = dvMaxY = dvMaxZ = 1 and dvMinZ = 0. As noted above, if you want to preserve the correct aspect ratio on a nonsquare window, you will need to clip some of the view volume. To do so, use the following equations. These equations also work with square viewports, so use them all the time.

dvMaxX = dwWidth / (2 * dvScaleX)
dvMaxY = dwHeight / (2 * dvScaleY)

An application uses the viewport transformation to ensure that the distance by which the object is moved in world coordinates is scaled by the object's distance from the camera to account for perspective. Note that the result from IDirect3DRMViewport2::Transform is a four-element homogeneous vector. This avoids the problems associated with coordinates being scaled by an infinite amount near the camera's position.

For information about transformations for frames, see Transformations. For an overview of the mathematics of transformations, see 3-D Transformations.

Picking

Picking is the process of searching for visuals in the scene given a 2-D coordinate in the viewport's window. An application can use the IDirect3DRMViewport2::Pick method to retrieve either the closest object in the scene or a depth-sorted list of objects.


Wraps

You can use a wrap to calculate texture coordinates for a face or mesh. To create a wrap, the application must specify a type, a reference frame, an origin, a direction vector, and an up vector. The application must also specify a pair of scaling factors and an origin for the texture coordinates.

Your application calls the IDirect3DRM3::CreateWrap function to create an IDirect3DRMWrap interface. This interface has two unique methods: IDirect3DRMWrap::Apply, which applies a wrap to the vertices of the object, and IDirect3DRMWrap::ApplyRelative, which transforms the vertices of a wrap as it is applied.

In the examples, the direction vector (the v vector) lies along the z-axis, and the up vector (the u vector) lies along the y-axis, with the origin at [0 0 0].

For a reference to the methods of the IDirect3DRMWrap interface, see IDirect3DRMWrap.

This section describes the wrapping flags and the four wrapping types.

  • Wrapping Flags
  • Flat
  • Cylindrical
  • Spherical
  • Chrome

Wrapping Flags

The D3DRMMAPPING type includes the D3DRMMAP_WRAPU and D3DRMMAP_WRAPV flags. These flags determine how the rasterizer interprets texture coordinates. The rasterizer always interpolates the shortest distance between texture coordinates—that is, a line. The path taken by this line, and the valid values for the u- and v-coordinates, varies with the use of the wrapping flags. If either or both flags is set, the line can wrap around the texture edge in the u or v direction, as if the texture had a cylindrical or toroidal topology.

  • In flat wrapping mode, in which neither of the wrapping flags is set, the plane specified by the u- and v-coordinates is an infinite tiling of the texture. In this case, values greater than 1.0 are valid for u and v. The shortest line between (0.1, 0.1) and (0.9, 0.9) passes through (0.5, 0.5).
  • If either D3DRMMAP_WRAPU or D3DRMMAP_WRAPV is set, the texture is a cylinder with an infinite length and a circumference of 1.0. Texture coordinates greater than 1.0 are valid only in the dimension that is not wrapped. The shortest distance between texture coordinates varies with the wrapping flag; if D3DRMMAP_WRAPU is set, the shortest line between (0.1, 0.1) and (0.9, 0.9) passes through (0, 0.5).
  • If both D3DRMMAP_WRAPU and D3DRMMAP_WRAPV are set, the texture is a torus. Because the system is closed, texture coordinates greater that 1.0 are invalid. The shortest line between (0.1, 0.1) and (0.9, 0.9) passes through (0, 0).

Although texture coordinates that are outside the valid range may be truncated to valid values, this behavior is not defined.

Typically, applications set a wrap flag for cylindrical wraps when the intersection of the texture edges does not match the edges of the face; applications do not set a wrap flag when more than half of a texture is applied to a single face.

Flat

The flat wrap conforms to the faces of an object as if the texture were a piece of rubber that was stretched over the object.

The [u v] coordinates are derived from a vector [x y z] by using the following equations:

Equations for deriving u-v coordinates from a vector in a flat wrap

In these formulas, s is the window-scaling factor and o is the window origin. The application should choose a pair of scaling factors and offsets that map the ranges of x and y to the range from 0 to 1 for u and v.

Cylindrical

The cylindrical wrap treats the texture as if it were a piece of paper that is wrapped around a cylinder so that the left edge is joined to the right edge. The object is then placed in the middle of the cylinder and the texture is deformed inward onto the surface of the object.

For a cylindrical texture map, the effects of the various vectors are shown in the following illustration.

Diagram showing the effects of vectors on a cylindrical wrap

The direction vector specifies the axis of the cylinder, and the up vector specifies the point on the outside of the cylinder where u equals 0. To calculate the texture [u v] coordinates for a vector [x y z], the system uses the following equations:

Equations for deriving u-v coordinates from a vector in a cylindrical wrap

Typically, u would be left unscaled and v would be scaled and translated so that the range of z maps to the range from 0 to 1 for v.

Spherical

For a spherical wrap, the u-coordinate is derived from the angle that the vector [x y 0] makes with the x-axis (as in the cylindrical map) and the v-coordinate from the angle that the vector [x y z] makes with the z-axis. Note that this mapping causes distortion of the texture at the z-axis.

Diagram showing the effects of vectors on a spherical wrap

This translates to the following equations:

Equations for deriving u-v coordinates from a vector in a spherical wrap

The scaling factors and texture origin will often not be needed here as the unscaled range of u and v is already 0 through 1.

Chrome

A chrome wrap allocates texture coordinates so that the texture appears to be reflected onto the objects. The chrome wrap takes the reference frame position and uses the vertex normals in the mesh to calculate reflected vectors. The texture u- and v-coordinates are then calculated from the intersection of these reflected vectors with an imaginary sphere that surrounds the mesh. This gives the effect of the mesh reflecting whatever is wrapped on the sphere.


Tutorial

To create a Microsoft® Windows®-based, Direct3D® Retained Mode application, you set up the features of two different environments: the devices, viewports, and color capabilities of the Windows environment, and the models, textures, lights, and positions of the virtual environment. This section is a tutorial that contains all the code for a simple Retained Mode application. The following illustration is a single frame from the running animation:

Single frame from running animation

The tutorial is divided into the following sections:

  • Making the Helworld Sample
  • Definitions and Global Variables
  • Windows Setup and Initialization
  • Enumerating Device Drivers
  • Setting up the 3-D Environment
  • The Rendering Loop
  • Creating the Scene
  • Cleaning Up

Making the Helworld Sample

This tutorial includes all the code for a working Direct3D Retained Mode application. You can copy the code from this tutorial into a single .c file and then compile and run it if the following conditions are met:

  • You have the Direct3D header files (D3d.h, D3drm.h, and so on) in your include path.
  • You link with the Winmm.lib, D3drm.lib, and Ddraw.lib static libraries.
  • Your compiler can find the Sphere3.x file in the media directory of the Microsoft® DirectX® Software Development Kit.
  • You supply a bitmap called Tutor.bmp.

    Note that this bitmap must have pixel dimensions that are a power of 2; for example, a 16×16 pixel bitmap, a 128×1024 pixel bitmap, a 512×256 pixel bitmap, and so on.

Most of the code responsible for 3-D effects in this sample has been broken out into discrete functions so that you can modify parts of the system incrementally in your own experiments. You should look at the samples in the DirectX SDK for implementations of more complicated features of Direct3D.

The following topics describe some of the concerns that apply to the overall development of a simple Direct3D Retained Mode application.

  • Limitations of the Sample
  • DirectDraw Windowed Mode

Limitations of the Sample

This tutorial contains the Helworld.c example code, which creates a sphere, applies a texture to it, and rotates it in a window. This is the only C source file required to build this application. The only other files you need are Sphere3.x, a mesh file that ships in the Media directory of the DirectX SDK; and Tutor.bmp, a bitmap you supply. (Note that you must have the Direct3D header files in your include path and link to the Winmm.lib, D3drm.lib, and Ddraw.lib static libraries.)

This tutorial is a simplified version of the Globe sample that is part of the DirectX SDK. The Globe sample, like all the Direct3D Retained Mode samples in the SDK, requires the inclusion of a file named Rmmain.cpp and a number of header files. In Helworld.c, the relevant parts of Rmmain.cpp have been converted to C from C++ and integrated into the source code.

The code shown in this tutorial should not be mistaken for production code. The only possible user interactions with the program are starting it, stopping it, and minimizing the window while it is running. Most of the error checking has been removed for clarity. The purpose of this example is analogous to the purpose of the beginning program that prints "Hello, world!" on the screen: to produce output with as little confusion as possible.

DirectDraw Windowed Mode

Nearly all Direct3D applications will use DirectDraw® to display their graphics on the screen. These applications will either use DirectDraw's exclusive (full-screen) mode or nonexclusive (windowed) mode. The code in this documentation uses windowed mode. Although the full-screen mode offers some benefits in performance and convenience, it is much easier to debug code written in windowed mode. Most developers will write their code in windowed mode and port it to full-screen mode late in the development cycle, when most of the bugs have been worked out.

Definitions and Global Variables

Below are the first lines of the Helworld.c example. You won't need any other C source files to build this application, but be sure to give your file the .c extension rather than .cpp. The C compiler assumes a file with the .cpp extension contains C++ code and handles the lpVtbl pointer and the additional this parameter for you. See Accessing COM Objects by Using C in the DirectX SDK documentation for more details. Because this tutorial is written in C it explicitly includes the lpVtbl pointer and adds the initial this parameter. The compiler generates many compile errors on the same file if it has the .cpp extension.

Notice that INITGUID must be defined prior to all other includes and defines. This is a crucial point that is sometimes missed by developers who are new to DirectX.

/////////////////////////////////////////////////////////////////////
//
//  Copyright (C) 1996 Microsoft Corporation. All Rights Reserved.
//
//  File: Helworld.c
//
//  Simplified Direct3D Retained Mode example, based on
//  the "Globe" SDK sample.
//
/////////////////////////////////////////////////////////////////////

#define INITGUID           // Must precede other defines and includes

#include <windows.h>
#include <malloc.h>        // Required by memset call
#include <d3drmwin.h>

#define MAX_DRIVERS 5           // Maximum D3D drivers expected

// Global variables

LPDIRECT3DRM lpD3DRM;           // Direct3DRM object
LPDIRECTDRAWCLIPPER lpDDClipper;// DirectDrawClipper object

struct _myglobs {
    LPDIRECT3DRMDEVICE dev;     // Direct3DRM device
    LPDIRECT3DRMVIEWPORT view;  // Direct3DRM viewport through which
                                // the scene is viewed
    LPDIRECT3DRMFRAME scene;    // Master frame in which others are
                                // placed
    LPDIRECT3DRMFRAME camera;   // Frame describing the user's POV

    GUID DriverGUID[MAX_DRIVERS];     // GUIDs of available D3D drivers
    char DriverName[MAX_DRIVERS][50]; // Names of available D3D drivers
    int  NumDrivers;                  // Number of available D3D drivers
    int  CurrDriver;                  // Number of D3D driver currently
                                      // being used

    BOOL bQuit;                 // Program is about to terminate
    BOOL bInitialized;          // All D3DRM objects are initialized
    BOOL bMinimized;            // Window is minimized

    int BPP;                    // Bit depth of the current display mode

} myglobs;

// Function prototypes.

static BOOL InitApp(HINSTANCE, int);
long FAR PASCAL WindowProc(HWND, UINT, WPARAM, LPARAM);
static BOOL EnumDrivers(HWND win);
static HRESULT WINAPI enumDeviceFunc(LPGUID lpGuid,
    LPSTR lpDeviceDescription, LPSTR lpDeviceName,
    LPD3DDEVICEDESC lpHWDesc, LPD3DDEVICEDESC lpHELDesc,
    LPVOID lpContext);
static DWORD BPPToDDBD(int bpp);
static BOOL CreateDevAndView(LPDIRECTDRAWCLIPPER lpDDClipper,
    int driver, int width, int height);
static BOOL SetRenderState(void);
static BOOL RenderLoop(void);
static BOOL MyScene(LPDIRECT3DRMDEVICE dev, LPDIRECT3DRMVIEWPORT view,
    LPDIRECT3DRMFRAME scene, LPDIRECT3DRMFRAME camera);
void MakeMyFrames(LPDIRECT3DRMFRAME lpScene, LPDIRECT3DRMFRAME lpCamera,
    LPDIRECT3DRMFRAME * lplpLightFrame1,
    LPDIRECT3DRMFRAME * lplpWorld_frame);
void MakeMyLights(LPDIRECT3DRMFRAME lpScene, LPDIRECT3DRMFRAME lpCamera,
    LPDIRECT3DRMFRAME lpLightFrame1,
    LPDIRECT3DRMLIGHT * lplpLight1, LPDIRECT3DRMLIGHT * lplpLight2);
void SetMyPositions(LPDIRECT3DRMFRAME lpScene,
    LPDIRECT3DRMFRAME lpCamera, LPDIRECT3DRMFRAME lpLightFrame1,
    LPDIRECT3DRMFRAME lpWorld_frame);
void MakeMyMesh(LPDIRECT3DRMMESHBUILDER  * lplpSphere3_builder);
void MakeMyWrap(LPDIRECT3DRMMESHBUILDER  sphere3_builder,
                LPDIRECT3DRMWRAP * lpWrap);
void AddMyTexture(LPDIRECT3DRMMESHBUILDER  lpSphere3_builder,
                  LPDIRECT3DRMTEXTURE * lplpTex);
static void CleanUp(void);

Windows Setup and Initialization

This section describes the standard setup and initialization functions in a Windows program, as implemented in the Helworld.c sample code.

  • The WinMain Function
  • The InitApp Function
  • The Main Window Procedure

The WinMain Function

The WinMain function in Helworld.c has only a few lines of code that are unique to an application that uses DirectDraw and Direct3D Retained Mode. The InitApp and CleanUp functions are standard parts of a Windows program, although in the case of Helworld, they perform some unique tasks. The most important call in WinMain, from the perspective of Direct3D, is the call to the RenderLoop function. RenderLoop is responsible for drawing each new frame of the animation. For more information about the RenderLoop function, see The Rendering Loop.

/////////////////////////////////////////////////////////////////////
//
// WinMain
// Initializes the application and enters a message loop.
// The message loop renders the scene until a quit message is received.
//
/////////////////////////////////////////////////////////////////////

int PASCAL
WinMain (HINSTANCE this_inst, HINSTANCE prev_inst, LPSTR cmdline,
    int cmdshow)
{
    MSG     msg;
    HACCEL  accel = NULL;
    int     failcount = 0;  // Number of times RenderLoop has failed

    prev_inst;
    cmdline;

    // Create the window and initialize all objects needed to begin
    // rendering.

    if (!InitApp(this_inst, cmdshow))
        return 1;

    while (!myglobs.bQuit) {

        // Monitor the message queue until there are no pressing
        // messages.

        while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
            if (!TranslateAccelerator(msg.hwnd, accel, &msg)) {
                TranslateMessage(&msg);
                DispatchMessage(&msg);
            }
        }

        // If the app is not minimized, not about to quit, and D3DRM has
        // been initialized, begin rendering.

        if (!myglobs.bMinimized && !myglobs.bQuit &&
             myglobs.bInitialized) {

            // Attempt to render a frame. If rendering fails more than
            // twice, abort execution.

            if (!RenderLoop())
                ++failcount;
            if (failcount > 2) {
                CleanUp();
                break;
            }
        }
    }
    return msg.wParam;
}

The InitApp Function

The initialization function (InitApp) in Helworld.c creates the window class and main application window, just as in most Windows-based applications. After this, however, InitApp does some work that is unique to applications using DirectDraw and Direct3D.

Next, InitApp retrieves the current display's bits per pixel. This information is used to help set the rendering quality for the application. For more information, see Setting the Render State.

InitApp then uses the locally defined EnumDrivers function to determine which Direct3D drivers are available and to choose one. For more information about enumerating drivers, see Enumerating Device Drivers.

Next, the code uses the Direct3DRMCreate function to create an IDirect3DRM interface. It uses this interface in the calls to IDirect3DRM::CreateFrame and IDirect3DRMFrame::SetPosition that create the scene and camera frames, and position the camera in the scene.

A DirectDrawClipper object makes it simple to manage the clipping planes that control which parts are visible of a 3-D scene. Helworld.c uses the DirectDrawCreateClipper function to create an IDirectDrawClipper interface, and then uses the IDirectDrawClipper::SetHWnd method to set the window handle that obtains the clipping information.

Now the InitApp function uses the locally defined CreateDevAndView function to create the Direct3D device and viewport. For more information about this function, see Creating the Device and Viewport.

When the entire supporting structure of a Direct3D application has been put into place, the details of the 3-D scene can be constructed. The MyScene function does this. For more information about MyScene, see Creating the Device and Viewport.

Finally, just as in a standard initialization function, InitApp displays and updates the window.

/////////////////////////////////////////////////////////////////////
//
// InitApp
// Creates window and initializes all objects necessary to begin
// rendering.
//
/////////////////////////////////////////////////////////////////////

static BOOL
InitApp(HINSTANCE this_inst, int cmdshow)
{
    HWND win;
    HDC hdc;
    WNDCLASS wc;
    RECT rc;

    // Set up and register the window class.

    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = WindowProc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = sizeof(DWORD);
    wc.hInstance = this_inst;
    wc.hIcon = LoadIcon(this_inst, "AppIcon");
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
    wc.lpszMenuName = NULL;
    wc.lpszClassName = "D3DRM Example";
    if (!RegisterClass(&wc))
        return FALSE;

    // Initialize the global variables.

    memset(&myglobs, 0, sizeof(myglobs));

    // Create the window.

    win =
        CreateWindow
        (   "D3DRM Example",            // Class
            "Hello World (Direct3DRM)", // Title bar
            WS_VISIBLE | WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU |
                 WS_MINIMIZEBOX | WS_MAXIMIZEBOX,
            CW_USEDEFAULT,              // Init. x pos
            CW_USEDEFAULT,              // Init. y pos
            300,                        // Init. x size
            300,                        // Init. y size
            NULL,                       // Parent window
            NULL,                       // Menu handle
            this_inst,                  // Program handle
            NULL                        // Create parms
        );
    if (!win)
        return FALSE;

    // Record the current display bits-per-pixel.

    hdc = GetDC(win);
    myglobs.BPP = GetDeviceCaps(hdc, BITSPIXEL);
    ReleaseDC(win, hdc);

    // Enumerate the D3D drivers and select one.

    if (!EnumDrivers(win))
        return FALSE;

    // Create the D3DRM object and the D3DRM window object.

    lpD3DRM = NULL;
    Direct3DRMCreate(&lpD3DRM);

    // Create the master scene frame and camera frame.

    lpD3DRM->lpVtbl->CreateFrame(lpD3DRM, NULL, &myglobs.scene);
    lpD3DRM->lpVtbl->CreateFrame(lpD3DRM, myglobs.scene,
        &myglobs.camera);
    myglobs.camera->lpVtbl->SetPosition(myglobs.camera, myglobs.scene,
        D3DVAL(0.0), D3DVAL(0.0), D3DVAL(0.0));

    // Create a DirectDrawClipper object and associate the
    // window with it.

    DirectDrawCreateClipper(0, &lpDDClipper, NULL);
    lpDDClipper->lpVtbl->SetHWnd(lpDDClipper, 0, win);

    // Create the D3DRM device by using the selected D3D driver.

    GetClientRect(win, &rc);
    if (!CreateDevAndView(lpDDClipper, myglobs.CurrDriver, rc.right,
            rc.bottom)) {
        return FALSE;
    }

    // Create the scene to be rendered.

    if (!MyScene(myglobs.dev, myglobs.view, myglobs.scene,
            myglobs.camera))
        return FALSE;

    myglobs.bInitialized = TRUE;  // Initialization completed

    // Display the window.

    ShowWindow(win, cmdshow);
    UpdateWindow(win);

    return TRUE;
}

The Main Window Procedure

The Helworld.c sample has a very simple main window procedure—after all, the application allows practically no user interaction.

When the window procedure receives a WM_DESTROY message, it uses the CleanUp function, just as you would expect.

When it receives a WM_ACTIVATE message, it retrieves an IDirect3DRMWinDevice interface and uses the IDirect3DRMWinDevice::HandleActivate method to ensure that the colors are correct in the active rendering window. Similarly, the function reacts to a WM_PAINT message by using the IDirect3DRMWinDevice::HandlePaint method.

/////////////////////////////////////////////////////////////////////
//
// WindowProc
// Main window message handler.
//
/////////////////////////////////////////////////////////////////////

LONG FAR PASCAL WindowProc(HWND win, UINT msg,
    WPARAM wparam, LPARAM lparam)
{
    RECT r;
    PAINTSTRUCT ps;
    LPDIRECT3DRMWINDEVICE lpD3DRMWinDev;

    switch (msg)    {

    case WM_DESTROY:
        CleanUp();
        break;

    case WM_ACTIVATE:
        {

        // Create a Windows-specific Direct3D Retained Mode window device to handle this
        // message.

        if (!myglobs.dev)
            break;
        myglobs.dev->lpVtbl->QueryInterface(myglobs.dev,
            &IID_IDirect3DRMWinDevice, (void **) &lpD3DRMWinDev);
        lpD3DRMWinDev->lpVtbl->HandleActivate(lpD3DRMWinDev,
            (WORD) wparam);
        lpD3DRMWinDev->lpVtbl->Release(lpD3DRMWinDev);
        }
        break;

    case WM_PAINT:
        if (!myglobs.bInitialized || !myglobs.dev)
            return DefWindowProc(win, msg, wparam, lparam);

        // Create a Windows-specific Direct3D Retained Mode window device to handle this
        // message.

        if (GetUpdateRect(win, &r, FALSE)) {
            BeginPaint(win, &ps);
            myglobs.dev->lpVtbl->QueryInterface(myglobs.dev,
                &IID_IDirect3DRMWinDevice, (void **) &lpD3DRMWinDev);
            lpD3DRMWinDev->lpVtbl->HandlePaint(lpD3DRMWinDev,
                ps.hdc);
            lpD3DRMWinDev->lpVtbl->Release(lpD3DRMWinDev);
            EndPaint(win, &ps);
        }
        break;
    default:
        return DefWindowProc(win, msg, wparam, lparam);
    }
    return 0L;
}

Enumerating Device Drivers

Applications that use Direct3D always enumerate the available drivers and choose the one that best matches their needs. The following sections each describe one of the functions that perform this task:

  • The EnumDrivers Function
  • The enumDeviceFunc Callback Function
  • The BPPToDDBD Helper Function

The EnumDrivers Function

The EnumDrivers function is used by the InitApp function just before InitApp creates the application's scene and camera.

The IDirect3D Component Object Model (COM) interface is really an interface to a DirectDraw object, so the first thing this enumeration function does is use the DirectDrawCreate function to create a DirectDrawObject. Then EnumDrivers uses the QueryInterface method to create an IDirect3D interface. Notice that the C implementation of QueryInterface requires that you pass the address of the interface identifier as the second parameter, not simply the constant itself (like in the C++ implementation).

The enumeration is handled by the IDirect3D::EnumDevices method, which depends on the locally defined enumDeviceFunc callback function. For more information about this callback function, see The enumDeviceFunc Callback Function.

Notice that IDirect3D::EnumDevices is a Direct3D method, not a Direct3DRM method; there is no enumeration method in the Retained Mode API. This is a good example of the natural use of both Retained Mode and Immediate Mode methods in a single application.

/////////////////////////////////////////////////////////////////////
//
// EnumDrivers
// Enumerate the available D3D drivers and choose one.
//
/////////////////////////////////////////////////////////////////////

static BOOL
EnumDrivers(HWND win)
{
    LPDIRECTDRAW lpDD;
    LPDIRECT3D lpD3D;
    HRESULT rval;

    // Create a DirectDraw object and query for the Direct3D interface
    // to use to enumerate the drivers.

    DirectDrawCreate(NULL, &lpDD, NULL);
    rval = lpDD->lpVtbl->QueryInterface(lpDD, &IID_IDirect3D,
        (void**) &lpD3D);
    if (rval != DD_OK) {
        lpDD->lpVtbl->Release(lpDD);
        return FALSE;
    }

    // Enumerate the drivers, setting CurrDriver to -1 to initialize the
    // driver selection code in enumDeviceFunc.

    myglobs.CurrDriver = -1;
    lpD3D->lpVtbl->EnumDevices(lpD3D, enumDeviceFunc,
        &myglobs.CurrDriver);

    // Ensure at least one valid driver was found.

    if (myglobs.NumDrivers == 0) {
        return FALSE;
    }
    lpD3D->lpVtbl->Release(lpD3D);
    lpDD->lpVtbl->Release(lpDD);

    return TRUE;
}

The enumDeviceFunc Callback Function

The enumDeviceFunc callback function is of the D3DENUMDEVICESCALLBACK type, as defined in the D3dcaps.h header file. The system uses this function with identifiers and names for each Direct3D driver in the system, as well as the hardware and emulated capabilities of the driver.

The callback function uses the dcmColorModel member of the D3DDEVICEDESC structure to determine whether to examine the hardware or emulated driver description. If the member has been filled by the hardware description, the function consults the hardware description.

Next, the callback function determines whether the driver being enumerated can render in the current bit depth. If not, the function returns D3DENUMRET_OK to skip the rest of the process for this driver and continue the enumeration with the next driver. The callback function uses the locally defined BPPToDDBD function to compare the reported bit depth against the bits-per-pixel retrieved by the call to the GetDeviceCaps function in the InitApp function. (BPPToDDBD stands for bits-per-pixel to DirectDraw bit-depth.) For the code for this function, see The BPPToDDBD Helper Function.

If the driver being enumerated passes a few simple tests, other parts of D3DDEVICEDESC are examined. The callback function will choose hardware over software emulation, and monochromatic lighting capabilities over RGB lighting capabilities.

/////////////////////////////////////////////////////////////////////
//
// enumDeviceFunc
// Callback function that records each usable D3D driver's name
// and GUID. Chooses a driver and sets *lpContext to this driver.
//
/////////////////////////////////////////////////////////////////////

static HRESULT
WINAPI enumDeviceFunc(LPGUID lpGuid, LPSTR lpDeviceDescription,
    LPSTR lpDeviceName, LPD3DDEVICEDESC lpHWDesc,
    LPD3DDEVICEDESC lpHELDesc, LPVOID lpContext)
{
    static BOOL hardware = FALSE; // Current start driver is hardware
    static BOOL mono = FALSE;     // Current start driver is mono light
    LPD3DDEVICEDESC lpDesc;
    int *lpStartDriver = (int *)lpContext;

    // Decide which device description should be consulted.

    lpDesc = lpHWDesc->dcmColorModel ? lpHWDesc : lpHELDesc;

    // If this driver cannot render in the current display bit-depth,
    // skip it and continue with the enumeration.

    if (!(lpDesc->dwDeviceRenderBitDepth & BPPToDDBD(myglobs.BPP)))
        return D3DENUMRET_OK;

    // Record this driver's name and GUID.

    memcpy(&myglobs.DriverGUID[myglobs.NumDrivers], lpGuid,
        sizeof(GUID));
    lstrcpy(&myglobs.DriverName[myglobs.NumDrivers][0], lpDeviceName);

    // Choose hardware over software, RGB lights over mono lights.

    if (*lpStartDriver == -1) {

        // This is the first valid driver.

        *lpStartDriver = myglobs.NumDrivers;
        hardware = lpDesc == lpHWDesc ? TRUE : FALSE;
        mono = lpDesc->dcmColorModel & D3DCOLOR_MONO ? TRUE : FALSE;
    } else if (lpDesc == lpHWDesc && !hardware) {

        // This driver is hardware and the start driver is not.

        *lpStartDriver = myglobs.NumDrivers;
        hardware = lpDesc == lpHWDesc ? TRUE : FALSE;
        mono = lpDesc->dcmColorModel & D3DCOLOR_MONO ? TRUE : FALSE;
    } else if ((lpDesc == lpHWDesc && hardware ) ||
               (lpDesc == lpHELDesc && !hardware)) {
        if (lpDesc->dcmColorModel == D3DCOLOR_MONO && !mono) {

            // This driver and the start driver are the same type, and
            // this driver is mono whereas the start driver is not.

            *lpStartDriver = myglobs.NumDrivers;
            hardware = lpDesc == lpHWDesc ? TRUE : FALSE;
            mono = lpDesc->dcmColorModel & D3DCOLOR_MONO ? TRUE : FALSE;
        }
    }
    myglobs.NumDrivers++;
    if (myglobs.NumDrivers == MAX_DRIVERS)
        return (D3DENUMRET_CANCEL);
    return (D3DENUMRET_OK);
}

BPPToDDBD Helper Function

The enumDeviceFunc callback function uses the BPPToDDBD helper function to convert the stored bits-per-pixel the current device supports to a form that can be compared against the bit depth for the driver being enumerated. For more information about enumDeviceFunc, see The enumDeviceFunc Callback Function.

/////////////////////////////////////////////////////////////////////
//
// BPPToDDBD
// Converts bits-per-pixel to a DirectDraw bit-depth flag.
//
/////////////////////////////////////////////////////////////////////

static DWORD
BPPToDDBD(int bpp)
{
    switch(bpp) {
        case 1:
            return DDBD_1;
        case 2:
            return DDBD_2;
        case 4:
            return DDBD_4;
        case 8:
            return DDBD_8;
        case 16:
            return DDBD_16;
        case 24:
            return DDBD_24;
        case 32:
            return DDBD_32;
        default:
            return 0;
    }
}

Setting up the 3-D Environment

This section describes the code in Helworld.c that establishes the 3-D environment. The following sections describe the two functions that perform this task:

  • Creating the Device and Viewport
  • Setting the Render State

These functions do not populate the 3-D environment with objects, frames, and lights. That is done by the MyScene function and the functions it uses. For information about filling up the 3-D environment, see Creating the Scene.

Creating the Device and Viewport

The Direct3D device and viewport are created as part of the application's initialization. After creating a DirectDrawClipper object, the InitApp function uses CreateDevAndView, passing as parameters the DirectDrawClipper object, the driver that was chosen, and the dimensions of the client rectangle.

The CreateDevAndView function uses the IDirect3DRM::CreateDeviceFromClipper method to create a Direct3DRM device, using the driver that was selected during the enumeration process. It uses this IDirect3DRMDevice interface to retrieve the device's width and height, by using IDirect3DRMDevice::GetWidth and IDirect3DRMDevice::GetHeight methods. After it has retrieved this information, it uses the IDirect3DRM::CreateViewport method to retrieve the IDirect3DRMViewport interface.

When CreateDevAndView has used the IDirect3DRMViewport::SetBack method to set the back clipping plane of the viewport, it uses the locally defined SetRenderState function. SetRenderState is described in the next section, Setting the Render State.

/////////////////////////////////////////////////////////////////////
//
// CreateDevAndView
// Create the D3DRM device and viewport with the given D3D driver and
// with the specified size.
//
/////////////////////////////////////////////////////////////////////

static BOOL
CreateDevAndView(LPDIRECTDRAWCLIPPER lpDDClipper, int driver,
    int width, int height)
{
    HRESULT rval;

    // Create the D3DRM device from this window by using the specified
    // D3D driver.

    lpD3DRM->lpVtbl->CreateDeviceFromClipper(lpD3DRM, lpDDClipper,
        &myglobs.DriverGUID[driver], width, height, &myglobs.dev);

    // Create the D3DRM viewport by using the camera frame. Set the
    // background depth to a large number. The width and height
    // might have been slightly adjusted, so get them from the device.

    width = myglobs.dev->lpVtbl->GetWidth(myglobs.dev);
    height = myglobs.dev->lpVtbl->GetHeight(myglobs.dev);
    rval = lpD3DRM->lpVtbl->CreateViewport(lpD3DRM, myglobs.dev,
        myglobs.camera, 0, 0, width, height, &myglobs.view);
    if (rval != D3DRM_OK) {
        myglobs.dev->lpVtbl->Release(myglobs.dev);
        return FALSE;
    }
    rval = myglobs.view->lpVtbl->SetBack(myglobs.view, D3DVAL(5000.0));
    if (rval != D3DRM_OK) {
        myglobs.dev->lpVtbl->Release(myglobs.dev);
        myglobs.view->lpVtbl->Release(myglobs.view);
        return FALSE;
    }

    // Set the render quality, fill mode, lighting state,
    // and color shade info.

    if (!SetRenderState())
        return FALSE;
    return TRUE;
}

Setting the Render State

Direct3D is a state machine; applications set up the state of the lighting, rendering, and transformation modules and then pass data through them. This architecture is integral to Immediate Mode, but it is partially hidden by the Retained Mode API. The SetRenderState function is a simple way to set the rendering state for a Retained Mode application.

First, SetRenderState uses the IDirect3DRMDevice::SetQuality method, specifying that the lights are on, that the fill mode is solid, and that Gouraud shading should be used. At this point, applications that need to change the dithering mode or texture quality can use the IDirect3DRMDevice::SetDither or IDirect3DRMDevice::SetTextureQuality methods.

/////////////////////////////////////////////////////////////////////
//
// SetRenderState
// Set the render quality and shade information.
//
/////////////////////////////////////////////////////////////////////

BOOL
SetRenderState(void)
{
    HRESULT rval;

    // Set the render quality (light toggle, fill mode, shade mode).

    rval = myglobs.dev->lpVtbl->SetQuality(myglobs.dev,
        D3DRMLIGHT_ON | D3DRMFILL_SOLID | D3DRMSHADE_GOURAUD);
    if (rval != D3DRM_OK) {
        return FALSE;
    }

    // If you want to change the dithering mode, use SetDither here.

    // If you want a texture quality other than D3DRMTEXTURE_NEAREST
    // (the default value), use SetTextureQuality here.

   return TRUE;
}

Rendering Loop

The WinMain function uses the RenderLoop function to draw each new frame of the animation. The RenderLoop function performs a few simple tasks:

  • Uses the IDirect3DRMFrame::Move method to apply the rotations and velocities for all frames in the hierarchy.
  • Uses the IDirect3DRMViewport::Clear method to clear the current viewport, setting it to the current background color.
  • Uses the IDirect3DRMViewport::Render method to render the current scene into the current viewport.
  • Uses the IDirect3DRMDevice::Update method to copy the rendered image to the display.
/////////////////////////////////////////////////////////////////////
//
// RenderLoop
// Clear the viewport, render the next frame, and update the window.
//
/////////////////////////////////////////////////////////////////////

static BOOL
RenderLoop()
{
    HRESULT rval;

    // Tick the scene.

    rval = myglobs.scene->lpVtbl->Move(myglobs.scene, D3DVAL(1.0));
    if (rval != D3DRM_OK) {
        return FALSE;
    }

    // Clear the viewport.

    rval = myglobs.view->lpVtbl->Clear(myglobs.view);
    if (rval != D3DRM_OK) {
        return FALSE;
    }

    // Render the scene to the viewport.

    rval = myglobs.view->lpVtbl->Render(myglobs.view, myglobs.scene);
    if (rval != D3DRM_OK) {
        return FALSE;
    }

    // Update the window.

    rval = myglobs.dev->lpVtbl->Update(myglobs.dev);
    if (rval != D3DRM_OK) {
        return FALSE;
    }
    return TRUE;
}

Creating the Scene

After setting up the 3-D environment—choosing a device driver, creating the 3-D device and viewport, setting the rendering state, and so on—Helworld.c uses a series of functions to populate this 3-D environment with objects, frames, and lights:

  • The MyScene Function
  • The MakeMyFrames Function
  • The MakeMyLights Function
  • The SetMyPositions Function
  • The MakeMyMesh Function
  • The MakeMyWrap Function
  • The AddMyTexture Function

The MyScene Function

The MyScene function in Helworld.c corresponds to the BuildScene function that is implemented in all the Direct3D samples in the DirectX SDK. This is where all the work occurs that displays unique objects with unique textures and lighting effects.

The MyScene function uses a series of locally defined functions that set up the separate features of the scene that is being created. These functions are:

  • MakeMyFrames
  • MakeMyLights
  • SetMyPositions
  • MakeMyMesh
  • MakeMyWrap
  • AddMyTexture

When these functions have set up the visual object, MyScene uses the IDirect3DRMFrame::AddVisual method to add the object to the environment's world frame. After adding the visual object, MyScene no longer needs the interfaces it has created, so it uses the Release method repeatedly to release them all.

/////////////////////////////////////////////////////////////////////
//
// MyScene
// Uses the functions that create the frames, lights, mesh, and
// texture. Releases all interfaces on completion.
//
/////////////////////////////////////////////////////////////////////

BOOL
MyScene(LPDIRECT3DRMDEVICE dev, LPDIRECT3DRMVIEWPORT view,
    LPDIRECT3DRMFRAME lpScene, LPDIRECT3DRMFRAME lpCamera)
{
    LPDIRECT3DRMFRAME lpLightframe1 = NULL;
    LPDIRECT3DRMFRAME lpWorld_frame = NULL;
    LPDIRECT3DRMLIGHT lpLight1      = NULL;
    LPDIRECT3DRMLIGHT lpLight2      = NULL;
    LPDIRECT3DRMTEXTURE lpTex       = NULL;
    LPDIRECT3DRMWRAP lpWrap         = NULL;
    LPDIRECT3DRMMESHBUILDER  lpSphere3_builder = NULL;

    MakeMyFrames(lpScene, lpCamera, &lpLightframe1, &lpWorld_frame);
    MakeMyLights(lpScene, lpCamera, lpLightframe1, &lpLight1,
        &lpLight2);
    SetMyPositions(lpScene, lpCamera, lpLightframe1, lpWorld_frame);
    MakeMyMesh(&lpSphere3_builder);
    MakeMyWrap(lpSphere3_builder, &lpWrap);
    AddMyTexture(lpSphere3_builder, &lpTex);

    // If you need to create a material (for example, to create
    // a shiny surface), use CreateMaterial and SetMaterial here.

    // Now that the visual object has been created, add it
    // to the world frame.

    lpWorld_frame->lpVtbl->AddVisual(lpWorld_frame,
        (LPDIRECT3DRMVISUAL) lpSphere3_builder);

    lpLightframe1->lpVtbl->Release(lpLightframe1);
    lpWorld_frame->lpVtbl->Release(lpWorld_frame);
    lpSphere3_builder->lpVtbl->Release(lpSphere3_builder);
    lpLight1->lpVtbl->Release(lpLight1);
    lpLight2->lpVtbl->Release(lpLight2);
    lpTex->lpVtbl->Release(lpTex);
    lpWrap->lpVtbl->Release(lpWrap);

    return TRUE;
}

The MakeMyFrames Function

The MyScene function uses the MakeMyFrames function to create the frames for the directional light and the world frame used in Helworld.c. MakeMyFrames does this work by using the IDirect3DRM::CreateFrame method.

/////////////////////////////////////////////////////////////////////
//
// MakeMyFrames
// Create frames used in the scene.
//
/////////////////////////////////////////////////////////////////////

void MakeMyFrames(LPDIRECT3DRMFRAME lpScene, LPDIRECT3DRMFRAME lpCamera,
    LPDIRECT3DRMFRAME * lplpLightFrame1,
    LPDIRECT3DRMFRAME * lplpWorld_frame)
{
    lpD3DRM->lpVtbl->CreateFrame(lpD3DRM, lpScene, lplpLightFrame1);
    lpD3DRM->lpVtbl->CreateFrame(lpD3DRM, lpScene, lplpWorld_frame);
}

The MakeMyLights Function

The MyScene function uses the MakeMyLights function to create the directional and ambient lights used in Helworld.c. MakeMyLights uses the IDirect3DRM::CreateLightRGB and IDirect3DRMFrame::AddLight methods to create a bright directional light and add it to a light frame, and to create a dim ambient light and add it to the entire scene. (Ambient lights are always associated with an entire scene.)

/////////////////////////////////////////////////////////////////////
//
// MakeMyLights
// Create lights used in the scene.
//
/////////////////////////////////////////////////////////////////////

void MakeMyLights(LPDIRECT3DRMFRAME lpScene, LPDIRECT3DRMFRAME lpCamera,
    LPDIRECT3DRMFRAME lpLightFrame1,
    LPDIRECT3DRMLIGHT * lplpLight1, LPDIRECT3DRMLIGHT * lplpLight2)
{
    lpD3DRM->lpVtbl->CreateLightRGB(lpD3DRM, D3DRMLIGHT_DIRECTIONAL,
        D3DVAL(0.9), D3DVAL(0.9), D3DVAL(0.9), lplpLight1);

    lpLightFrame1->lpVtbl->AddLight(lpLightFrame1, *lplpLight1);

    lpD3DRM->lpVtbl->CreateLightRGB(lpD3DRM, D3DRMLIGHT_AMBIENT,
        D3DVAL(0.1), D3DVAL(0.1), D3DVAL(0.1), lplpLight2);

    lpScene->lpVtbl->AddLight(lpScene, *lplpLight2);
}

The SetMyPositions Function

The MyScene function uses the SetMyPositions function to set the positions and orientations of the frames used in Helworld.c. SetMyPositions does this work by using the IDirect3DRMFrame::SetPosition and IDirect3DRMFrame::SetOrientation methods. The IDirect3DRMFrame::SetRotation method imparts a spin to the frame to which the sphere will be added.

/////////////////////////////////////////////////////////////////////
//
// SetMyPositions
// Set the positions and orientations of the light, camera, and
// world frames. Establish a rotation for the globe.
//
/////////////////////////////////////////////////////////////////////

void SetMyPositions(LPDIRECT3DRMFRAME lpScene,
    LPDIRECT3DRMFRAME lpCamera, LPDIRECT3DRMFRAME lpLightFrame1,
    LPDIRECT3DRMFRAME lpWorld_frame)
{

    lpLightFrame1->lpVtbl->SetPosition(lpLightFrame1, lpScene,
        D3DVAL(2), D3DVAL(0.0), D3DVAL(22));

    lpCamera->lpVtbl->SetPosition(lpCamera, lpScene,
        D3DVAL(0.0), D3DVAL(0.0), D3DVAL(0.0));
    lpCamera->lpVtbl->SetOrientation(lpCamera, lpScene,
        D3DVAL(0.0), D3DVAL(0.0), D3DVAL(1),
        D3DVAL(0.0), D3DVAL(1), D3DVAL(0.0));

    lpWorld_frame->lpVtbl->SetPosition(lpWorld_frame, lpScene,
        D3DVAL(0.0), D3DVAL(0.0), D3DVAL(15));
    lpWorld_frame->lpVtbl->SetOrientation(lpWorld_frame, lpScene,
        D3DVAL(0.0), D3DVAL(0.0), D3DVAL(1),
        D3DVAL(0.0), D3DVAL(1), D3DVAL(0.0));

    lpWorld_frame->lpVtbl->SetRotation(lpWorld_frame, lpScene,
        D3DVAL(0.0), D3DVAL(0.1), D3DVAL(0.0), D3DVAL(0.05));
}

The MakeMyMesh Function

The MyScene function uses the MakeMyMesh function to load and set the spherical mesh used in Helworld.c. MakeMyMesh uses the IDirect3DRM::CreateMeshBuilder method to create an IDirect3DRMMeshBuilder interface. Then it uses the IDirect3DRMMeshBuilder::Load, IDirect3DRMMeshBuilder::Scale, and IDirect3DRMMeshBuilder::SetColorRGB methods to prepare the mesh represented by the Sphere3.x file. (The Sphere3.x file is included in the DirectX SDK, as part of the media provided for use with the sample code.)

/////////////////////////////////////////////////////////////////////
//
// MakeMyMesh
// Create MeshBuilder object, load, scale, and color the mesh.
//
/////////////////////////////////////////////////////////////////////

void MakeMyMesh(LPDIRECT3DRMMESHBUILDER  * lplpSphere3_builder)
{
    lpD3DRM->lpVtbl->CreateMeshBuilder(lpD3DRM, lplpSphere3_builder);

    (*lplpSphere3_builder)->lpVtbl->Load(*lplpSphere3_builder,
        "sphere3.x", NULL, D3DRMLOAD_FROMFILE, NULL, NULL);

    (*lplpSphere3_builder)->lpVtbl->Scale(*lplpSphere3_builder,
        D3DVAL(2), D3DVAL(2), D3DVAL(2));

    // Set sphere to white to avoid unexpected texture-blending results.

    (*lplpSphere3_builder)->lpVtbl->SetColorRGB(*lplpSphere3_builder,
        D3DVAL(1), D3DVAL(1), D3DVAL(1));
}

The MakeMyWrap Function

The MyScene function uses the MakeMyWrap function to create and apply texture coordinates to the sphere loaded by the MakeMyMesh function. MakeMyWrap uses the IDirect3DRMMeshBuilder::GetBox method to retrieve the bounding box that contains the sphere and uses the dimensions of that bounding box in a call to the IDirect3DRM::CreateWrap method, which creates a cylindrical texture wrap and retrieves the IDirect3DRMWrap interface. A call to the IDirect3DRMWrap::Apply method applies the texture coordinates to the sphere.

/////////////////////////////////////////////////////////////////////
//
// MakeMyWrap
// Creates and applies wrap for texture.
//
/////////////////////////////////////////////////////////////////////

void MakeMyWrap(LPDIRECT3DRMMESHBUILDER  sphere3_builder,
                LPDIRECT3DRMWRAP * lpWrap)
{
    D3DVALUE miny, maxy, height;
    D3DRMBOX box;

    sphere3_builder->lpVtbl->GetBox(sphere3_builder, &box);

    maxy = box.max.y;
    miny = box.min.y;
    height = maxy - miny;

    lpD3DRM->lpVtbl->CreateWrap
        (lpD3DRM, D3DRMWRAP_CYLINDER, NULL,
        D3DVAL(0.0), D3DVAL(0.0), D3DVAL(0.0),
        D3DVAL(0.0), D3DVAL(1.0), D3DVAL(0.0),
        D3DVAL(0.0), D3DVAL(0.0), D3DVAL(1.0),
        D3DVAL(0.0), D3DDivide(miny, height),
        D3DVAL(1.0), D3DDivide(D3DVAL(1.0), height),
        lpWrap);

    (*lpWrap)->lpVtbl->Apply(*lpWrap, (LPDIRECT3DRMOBJECT)
        sphere3_builder);

}

The AddMyTexture Function

The MyScene function uses the AddMyTexture function to load a texture and associate it with the sphere. AddMyTexture uses the IDirect3DRM::LoadTexture method to load a bitmap called Tutor.bmp, and then it uses the IDirect3DRMMeshBuilder::SetTexture method to associate the bitmap with the sphere.

Bitmap used as a texture on the sphere

/////////////////////////////////////////////////////////////////////
//
// AddMyTexture
// Creates and applies wrap for texture.
//
/////////////////////////////////////////////////////////////////////

void AddMyTexture(LPDIRECT3DRMMESHBUILDER  lpSphere3_builder,
    LPDIRECT3DRMTEXTURE * lplpTex)
{
    lpD3DRM->lpVtbl->LoadTexture(lpD3DRM, "tutor.bmp", lplpTex);

    // If you need a color depth other than the default (16),
    // use IDirect3DRMTexture::SetShades here.

    lpSphere3_builder->lpVtbl->SetTexture(lpSphere3_builder, *lplpTex);

}

Cleaning Up

Helworld.c uses the CleanUp function when it receives a WM_DESTROY message or after several consecutive unsuccessful attempts to use the RenderLoop function.

/////////////////////////////////////////////////////////////////////
//
// CleanUp
// Release all D3DRM objects and set the bQuit flag.
//
/////////////////////////////////////////////////////////////////////

void
CleanUp(void)
{
    myglobs.bInitialized = FALSE;
    myglobs.scene->lpVtbl->Release(myglobs.scene);
    myglobs.camera->lpVtbl->Release(myglobs.camera);
    myglobs.view->lpVtbl->Release(myglobs.view);
    myglobs.dev->lpVtbl->Release(myglobs.dev);
    lpD3DRM->lpVtbl->Release(lpD3DRM);
    lpDDClipper->lpVtbl->Release(lpDDClipper);

    myglobs.bQuit = TRUE;
}


C++/COM Reference

The Microsoft® Direct3D® Retained Mode C++/COM Reference provides detailed information about the interfaces, methods (interface member functions), nonmember functions, and callback functions, with syntax, parameter descriptions, and flag descriptions. It also describes the members of Direct3D Retained Mode structures, enumerated types, other defined types, and the possible error values that can be returned. This section contains the following topics.

Functions and Interfaces

  • Callback Functions
  • Interfaces
  • Nonmember Functions

Data Types

  • Constants
  • Enumerated Types
  • Structures

Other Topics

  • Return Values
  • Further Reading


C++ Callback Functions

The Microsoft® Direct3D® Retained Mode callback functions for C++ are:

  • D3DRMDEVICE3UPDATECALLBACK (replaces D3DRMUPDATECALLBACK)
  • D3DRMDOWNSAMPLECALLBACK
  • D3DRMFRAME3MOVECALLBACK (replaces D3DRMFRAMEMOVECALLBACK)
  • D3DRMLOADCALLBACK
  • D3DRMLOADTEXTURECALLBACK
  • D3DRMLOADTEXTURE3CALLBACK
  • D3DRMOBJECTCALLBACK
  • D3DRMUSERVISUALCALLBACK
  • D3DRMVALIDATIONCALLBACK
  • D3DRMWRAPCALLBACK

D3DRMDEVICE3UPDATECALLBACK

Alerts the application when the device changes. This callback function is application-defined.

Syntax

void (*D3DRMDEVICE3UPDATECALLBACK)(
  LPDIRECT3DRMDEVICE3 lpobj,
  LPVOID lpArg,
  int iRectCount,
  LPD3DRECT d3dRectUpdate);

Parameters

lpobj
Address of a pointer to the Direct3DRMDevice3 object to which this callback function applies.
lpArg
Address of a pointer to application-defined data passed to this callback function.
iRectCount
Number of rectangles specified in the d3dRectUpdate parameter.
d3dRectUpdate
Array of one or more D3DRECT structures that describe the area to be updated. The coordinates are specified in device units.

Return Value

No return value.

Remarks

When determining the order in which to use callback functions, the system searches the objects highest in the hierarchy first, and then uses their callback functions in the order in which they were created.

D3DRMDEVICE3UPDATECALLBACK was introduced with DirectX version 6.0 and replaces the older D3DRMUPDATECALLBACK. The only difference between the two callbacks is that the new callback takes a Direct3DRMDevice3 object, rather than a Direct3DRMDevice object for the lpobj parameter.

See Also

IDirect3DRMDevice3::AddUpdateCallback, IDirect3DRMDevice3::DeleteUpdateCallback, IDirect3DRMDevice3::Update

D3DRMDOWNSAMPLECALLBACK

Called when the video memory is getting overloaded and the texture surfaces need to be reduced in size. Direct3D Retained Mode provides default methods for reducing texture sizes, such as DirectDraw blitting and bilinear filtering, but users can define their own method to scale down texture size with this callback. This callback function is application-defined.

Syntax

HRESULT (*D3DRMDOWNSAMPLECALLBACK)(
  LPDIRECT3DRMTEXTURE3 lpDirect3DRMTexture,
  LPVOID lpArg,
  LPDIRECTDRAWSURFACE pDDSSrc,
  LPDIRECTDRAWSURFACE pDDSDst);

Parameters

lpDirect3DRMTexture
Address of a pointer to the Direct3DRMTexture3 object to which this callback function applies.
lpArg
Address of a pointer to application-defined data passed to this callback function.
pDDSSrc
Pointer to the system memory prototype surface.
pDDSDst
Pointer to the scaled down surface.

Return Value

No return value.

Remarks

D3DRMDOWNSAMPLECALLBACK was introduced with DirectX version 6.0.

See Also

IDirect3DRMTexture3::SetDownsampleCallback

D3DRMFRAME3MOVECALLBACK

Enables an application to apply customized algorithms when a frame is moved or updated. You can use this callback function to compensate for changing frame rates. This callback function is application-defined.

Syntax

void (*D3DRMFRAME3MOVECALLBACK)(
  LPDIRECT3DRMFRAME3 lpD3DRMFrame,
  LPVOID lpArg,
  D3DVALUE delta);

Parameters

lpD3DRMFrame
Address of a pointer to the Direct3DRMFrame3 object that is being moved.
lpArg
Address of a pointer to application-defined data passed to this callback function.
delta
Amount of change to apply to the movement. There are two components to the change in position of a frame: linear and rotational. The change in each component is equal to velocity_of_component × delta. Although either or both of these velocities can be set relative to any frame, the system automatically converts them to velocities relative to the parent frame for the purpose of applying time deltas.

Return Value

No return value.

Remarks

Your application can synthesize the acceleration of a frame relative to its parent frame. To do so, on each tick your application should set the velocity of the child frame relative to itself to (a units per tick) × 1 tick, where a is the required acceleration. This is equal to a × delta units per tick. Internally, a × delta units per tick relative to the child frame is converted to (v + (a × delta)) units per tick relative to the parent frame, where v is the current velocity of the child relative to the parent.

You can add and remove this callback function from your application by using the IDirect3DRMFrame3::AddMoveCallback and IDirect3DRMFrame3::DeleteMoveCallback methods.

When determining the order in which to use callback functions, the system searches the objects highest in the hierarchy first, and then uses their callback functions in the order in which they were created.

D3DRMFRAME3MOVECALLBACK was introduced with DirectX version 6.0 and replaces the older D3DRMFRAMEMOVECALLBACK. The only difference between the two callbacks is that the new callback takes a Direct3DRMFrame3 object rather than a Direct3DRMFrame object for the lpD3DRMFrame parameter.

D3DRMLOADCALLBACK

Loads objects named in a call to the IDirect3DRM3::Load method. This callback function is application-defined.

Syntax

void (*D3DRMLOADCALLBACK)(
  LPDIRECT3DRMOBJECT lpObject,
  REFIID ObjectGuid,
  LPVOID lpArg);

Parameters

lpObject
Address of a pointer to the Direct3DRMObject being loaded.
ObjectGuid
Globally unique identifier (GUID) of the object being loaded.
lpArg
Address of a pointer to application-defined data passed to this callback function.

Return Value

No return value.

Remarks

When determining the order in which to use callback functions, the system searches the objects highest in the hierarchy first, and then uses their callback functions in the order in which they were created.

See Also

IDirect3DRM3::Load

D3DRMLOADTEXTURECALLBACK

Loads texture maps from a file or resource named in a call to one of the Load methods. This callback function is application-defined.

Syntax

HRESULT (*D3DRMLOADTEXTURECALLBACK)(
  char *tex_name,
  void *lpArg,
  LPDIRECT3DRMTEXTURE *lpD3DRMTex);

Parameters

tex_name
Address of a pointer to a string containing the name of the texture.
lpArg
Address of a pointer to application-specific data.
lpD3DRMTex
Address of a pointer to the Direct3DRMTexture object.

Return Value

Should return D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

In order to maintain an accurate reference count, you should call AddRef on texture objects created in a texture callback.

Applications can use this callback function to implement support for textures that are not in the Microsoft® Windows® bitmap (.bmp) or Portable Pixelmap bitmap (.ppm) P6 format. The P6 format is a binary file format for color images.

When determining the order in which to use callback functions, the system searches the objects highest in the hierarchy first, and then uses their callback functions in the order in which they were created.

See Also

IDirect3DRM3::Load, IDirect3DRMAnimationSet2::Load, IDirect3DRMFrame3::Load, IDirect3DRMMeshBuilder3::Load

D3DRMLOADTEXTURE3CALLBACK

Loads texture maps from a file or resource named in a call to one of the Load methods. This callback function is application-defined.

Syntax

HRESULT (*D3DRMLOADTEXTURE3CALLBACK)(
  char *tex_name,
  void *lpArg,
  LPDIRECT3DRMTEXTURE3 *lpD3DRMTex3);

Parameters

tex_name
Address of a pointer to a string containing the name of the texture.
lpArg
Address of a pointer to application-specific data.
lpD3DRMTex3
Address of a pointer to the Direct3DRMTexture3 object.

Return Value

Should return D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

In order to maintain an accurate reference count, you should call AddRef on texture objects created in a texture callback.

Applications can use this callback function to implement support for textures that are not in the Microsoft® Windows® bitmap (.bmp) or Portable Pixelmap bitmap (.ppm) P6 format. The P6 format is a binary file format for color images.

When determining the order in which to use callback functions, the system searches the objects highest in the hierarchy first, and then uses their callback functions in the order in which they were created.

See Also

IDirect3DRM3::Load, IDirect3DRMAnimationSet2::Load, IDirect3DRMFrame3::Load, IDirect3DRMMeshBuilder3::Load

D3DRMOBJECTCALLBACK

Enumerates objects in response to a call to the IDirect3DRM3::EnumerateObjects method. This callback function is application-defined.

Syntax

void (*D3DRMOBJECTCALLBACK)(
  LPDIRECT3DRMOBJECT lpD3DRMobj,
  LPVOID lpArg);

Parameters

lpD3DRMobj
Pointer to the IDirect3DRMObject interface for the object being enumerated. The application must use the Release method for each enumerated object.
lpArg
Address of a pointer to application-defined data passed to this callback function.

Return Value

No return value.

Remarks

When determining the order in which to use callback functions, the system searches the objects highest in the hierarchy first, and then uses their callback functions in the order in which they were created.

See Also

IDirect3DRM3::EnumerateObjects

D3DRMUSERVISUALCALLBACK

Alerts an application that supplies user-visual objects that it should execute the execute buffer. This function is application-defined.

Syntax

int (*D3DRMUSERVISUALCALLBACK)(
  LPDIRECT3DRMUSERVISUAL lpD3DRMUV,
  LPVOID lpArg,
  D3DRMUSERVISUALREASON lpD3DRMUVreason,
  LPDIRECT3DRMDEVICE lpD3DRMDev,
  LPDIRECT3DRMVIEWPORT lpD3DRMview);

Parameters

lpD3DRMUV
Address of a pointer to the Direct3DRMUserVisual object.
lpArg
Address of a pointer to application-defined data passed to this callback function.
lpD3DRMUVreason
One of the members of the D3DRMUSERVISUALREASON enumerated type:
D3DRMUSERVISUAL_CANSEE
The application should return TRUE if the user-visual object is visible in the viewport. In this case, the application uses the device specified in the lpD3DRMview parameter.
D3DRMUSERVISUAL_RENDER
The application should render the user-visual element. In this case, the application uses the device specified in the lpD3DRMDev parameter.
lpD3DRMDev
Address of a pointer to a Direct3DRMDevice object used to render the Direct3DRMUserVisual object.
lpD3DRMview
Address of a pointer to a Direct3DRMViewport object used to determine whether the Direct3DRMUserVisual object is visible.

Return Value

Returns TRUE if the lpD3DRMUVreason parameter is D3DRMUSERVISUAL_CANSEE, and the user-visual object is visible in the viewport. Returns FALSE otherwise. If the lpD3DRMUVreason parameter is D3DRMUSERVISUAL_RENDER, the return value is application-defined. It is always safe to return TRUE.

Remarks

If the application changes the render state, it should restore the render state before returning from this function.

When determining the order in which to use callback functions, the system searches the objects highest in the hierarchy first, and then uses their callback functions in the order in which they were created.

See Also

IDirect3DRMUserVisual::Init and IDirect3DRM3::CreateUserVisual

D3DRMVALIDATIONCALLBACK

Called when a texture region that has previously been marked as invalid, meaning it has changed but not been updated, now needs to be updated. This callback function is application-defined.

Syntax

HRESULT (*D3DRMVALIDATIONCALLBACK)(
  LPDIRECT3DRMTEXTURE3 lpDirect3DRMTexture,
  LPVOID lpArg,
  DWORD dwFlags,
  DWORD dwcRects,
  LPRECT pRects);

Parameters

lpDirect3DRMTexture
Address of a pointer to the Direct3DRMTexture3 object to which this callback function applies.
lpArg
Address of a pointer to application-defined data passed to this callback function.
dwFlags
Not used. Set to 0.
dwcRects
Number of rectangles specified in the pRects parameter.
pRects
Array of one or more RECT structures that describe the area to be updated. The coordinates are specified in device units.

Return Value

No return value.

Remarks

When you want to inform Direct3D Retained Mode that a texture region has been changed but want to defer changing it, you can say the region is invalid and store the region in the array pointed to by pRects. Then, if the texture is needed, call this callback function to inform your application to update the texture region.

D3DRMVALIDATIONCALLBACK was introduced with DirectX version 6.0.

See Also

IDirect3DRMTexture3::SetValidationCallback

D3DRMWRAPCALLBACK

This callback function is not supported.

Syntax

void (*D3DRMWRAPCALLBACK)(
  LPD3DVECTOR lpD3DVector,
  int *lpU,
  int *lpV,
  LPD3DVECTOR lpD3DRMVA,
  LPD3DVECTOR lpD3DRMVB,
  LPVOID lpArg);


C++ Interfaces

This section contains information on the following Microsoft® Direct3D® Retained Mode interfaces for C++.

  • IDirect3DRM3
  • IDirect3DRMAnimation2
  • IDirect3DRMAnimationArray
  • IDirect3DRMAnimationSet2
  • IDirect3DRMArray
  • IDirect3DRMClippedVisual
  • IDirect3DRMDevice3
  • IDirect3DRMDeviceArray
  • IDirect3DRMFace2
  • IDirect3DRMFaceArray
  • IDirect3DRMFrame3
  • IDirect3DRMFrameArray
  • IDirect3DRMInterpolator
  • IDirect3DRMLight
  • IDirect3DRMLightArray
  • IDirect3DRMMaterial2
  • IDirect3DRMMesh
  • IDirect3DRMMeshBuilder3
  • IDirect3DRMObject
  • IDirect3DRMObject2
  • IDirect3DRMObjectArray
  • IDirect3DRMPicked2Array
  • IDirect3DRMPickedArray
  • IDirect3DRMProgressiveMesh
  • IDirect3DRMShadow2
  • IDirect3DRMTexture3
  • IDirect3DRMUserVisual
  • IDirect3DRMViewport2
  • IDirect3DRMViewportArray
  • IDirect3DRMVisual
  • IDirect3DRMVisualArray
  • IDirect3DRMWinDevice
  • IDirect3DRMWrap


IDirect3DRM3

Applications use the IDirect3DRM3 interface to create Direct3DRM3 objects and work with system-level variables. For a history of the Direct3D Retained Mode interfaces, see Interface Changes.

The methods of the IDirect3DRM3, IDirect3DRM2, and IDirect3DRM interfaces create the following objects:

  • Animations and animation sets
  • ClippedVisuals
  • Devices
  • Faces
  • Frames
  • Generic uninitialized objects
  • Lights
  • Materials
  • Meshes and mesh builders
  • Shadows
  • Textures
  • UserVisuals
  • Viewports
  • Wraps

Microsoft DirectX version 6.0 introduced the IDirect3DRM3 interface. IDirect3DRM3 supports all of the methods provided by the IDirect3DRM2 and IDirect3DRM interfaces and replaces these two older interfaces. It adds a flag parameter to IDirect3DRM2's CreateDeviceFromSurface, and adds RegisterClient, UnregisterClient, and CreateClippedVisual methods to the methods IDirect3DRM2 provides. IDirect3DRM3 also adds the GetOptions and SetOptions methods to set and retrieve whether left-handed or right-handed geometry should be used.

IDirect3DRM3, like IDirect3DRM2, supports all the methods in IDirect3DRM. It adds the CreateProgressiveMesh method to the methods IDirect3DRM provides. The CreateDeviceFromSurface, CreateDeviceFromD3D, and CreateDeviceFromClipper methods all create a DIRECT3DRMDEVICE2 object with IDirect3DRM2 and a DIRECT3DRMDEVICE3 object with IDirect3DRM3. The CreateViewport method creates a viewport on a DirectDRMDevice2 object. The LoadTexture and LoadTextureFromResource methods load a Direct3DRMTexture2 object with IDirect3DRM2 and a Direct3DRMTexture3 object with IDirect3DRM3.

To access the IDirect3DRM3 or IDirect3DRM2 Component Object Model (COM) interfaces, create an IDirect3DRM object with Direct3DRMCreate, then query for IDirect3DRM3 or IDirect3DRM2, respectively, from IDirect3DRM. You can also access the main Direct3D Retained Mode object directly using CoCreateInstance.

When you create a MeshBuilder object using the IDirect3DRM3 interface, the MeshBuilder uses the Immediate Mode DrawPrimitive interface for its implementation.

When you create Lights using the IDirect3DRM3 interface, they take advantage of the latest Immediate Mode functionality and use the D3DLIGHT2 structure.

Applications use the IDirect3DRMDevice3, IDirect3DRMDevice2, and IDirect3DRMDevice interfaces to interact with the output device. For more information about the capabilities of the output device when you create it using the IDirect3DRM3, IDirect3DRM2, or IDirect3DRM interfaces, see IDirect3DRMDevice3. For a conceptual overview of output devices, see Output Devices.

The methods of the IDirect3DRM3 interface can be organized into the following groups:
Animation | CreateAnimation
 | CreateAnimationSet
Application-specific Data | RegisterClient
 | UnregisterClient
Clipped Visuals | CreateClippedVisual
Devices | CreateDevice
 | CreateDeviceFromClipper
 | CreateDeviceFromD3D
 | CreateDeviceFromSurface
 | GetDevices
Enumeration | EnumerateObjects
Faces | CreateFace
Frames | CreateFrame
Lights | CreateLight
 | CreateLightRGB
Materials | CreateMaterial
Meshes | CreateMesh
 | CreateMeshBuilder
Miscellaneous | CreateObject
 | CreateUserVisual
 | GetNamedObject
 | GetOptions
 | Load
 | SetOptions
 | Tick
Progressive Meshes | CreateProgressiveMesh
Search paths | AddSearchPath
 | GetSearchPath
 | SetSearchPath
Shadows | CreateShadow
Textures | CreateTexture
 | CreateTextureFromSurface
 | LoadTexture
 | LoadTextureFromResource
 | SetDefaultTextureColors
 | SetDefaultTextureShades
Viewports | CreateViewport
Wraps | CreateWrap

The IDirect3DRM3 interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:
AddRef
QueryInterface
Release

IDirect3DRM3::AddSearchPath

IDirect3DRM3

Adds a list of directories to the end of the current file search path.

Syntax

HRESULT AddSearchPath(
  LPCSTR lpPath
  );

Parameters

lpPath
Address of a null-terminated string specifying the path to add to the current search path.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

For Microsoft® Windows®, the path should be a list of directories separated by semicolons (;).

See Also

IDirect3DRM3::SetSearchPath

IDirect3DRM3::CreateAnimation

IDirect3DRM3

Creates an empty Direct3DRMAnimation object.

Syntax

HRESULT CreateAnimation(
  LPDIRECT3DRMANIMATION2  *lplpD3DRMAnimation
  );

Parameters

lplpD3DRMAnimation
Address that will be filled with a pointer to an IDirect3DRMAnimation2 interface if the call succeeds.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

IDirect3DRM3::CreateAnimationSet

IDirect3DRM3

Creates an empty Direct3DRMAnimationSet object.

Syntax

HRESULT CreateAnimationSet (
  LPDIRECT3DRMANIMATIONSET2  *lplpD3DRMAnimationSet
  );

Parameters

lplpD3DRMAnimationSet
Address that will be filled with a pointer to an IDirect3DRMAnimationSet2 interface if the call succeeds.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

IDirect3DRM3::CreateClippedVisual

IDirect3DRM3

Creates a clipped visual object.

Syntax

HRESULT CreateClippedVisual(
  LPDIRECT3DRMVISUAL lpVisual,
  LPDIRECT3DRMCLIPPEDVISUAL  *lpClippedVisual);

Parameters

lpVisual
Pointer to a visual object, such as a meshbuilder object.
lpClippedVisual
Pointer to receive the created IDirect3DRMClippedVisual clipped visual object.

Return Value

Returns one of the following values:
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRM3::CreateDevice

IDirect3DRM3

Not implemented on the Windows platform.

Syntax

HRESULT CreateDevice(
  DWORD dwWidth,
  DWORD dwHeight,
  LPDIRECT3DRMDEVICE3 *lplpD3DRMDevice
  );

IDirect3DRM3::CreateDeviceFromClipper

IDirect3DRM3

Creates a Direct3D Retained Mode Windows device by using a specified DirectDrawClipper object.

Syntax

HRESULT CreateDeviceFromClipper(
  LPDIRECTDRAWCLIPPER lpDDClipper,
  LPGUID lpGUID,
  int width,
  int height,
  LPDIRECT3DRMDEVICE3  *lplpD3DRMDevice
  );

Parameters

lpDDClipper
Address of a DirectDrawClipper object.
lpGUID
Address of a globally unique identifier (GUID). This parameter can be NULL.
width and height
Width and height of the device to be created.
lplpD3DRMDevice
Address that will be filled with a pointer to an IDirect3DRMDevice3 interface if the call succeeds.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

If the lpGUID parameter is NULL, the system searches for a device with a default set of device capabilities. This is the recommended way to create a Retained Mode device because it always works, even if the user installs new hardware.

The system describes the default settings by using the following flags from the D3DPRIMCAPS structure in internal device-enumeration calls:
D3DPSHADECAPS_ALPHAFLATSTIPPLED
D3DPTBLENDCAPS_COPY | D3DPTBLENDCAPS_MODULATE
D3DPMISCCAPS_CULLCCW
D3DPRASTERCAPS_FOGVERTEX
D3DPCMPCAPS_LESSEQUAL
D3DPTFILTERCAPS_NEAREST
D3DPTEXTURECAPS_PERSPECTIVE | D3DPTEXTURECAPS_TRANSPARENCY
D3DPTADDRESSCAPS_WRAP

If a hardware device is not found, the monochromatic (ramp) software driver is loaded. An application should enumerate devices instead of specifying NULL in the lpGUID parameter if it has special needs that are not met by this list of default settings.

For more information about devices, see Output Devices and IDirect3DRMDevice3.

IDirect3DRM3::CreateDeviceFromD3D

IDirect3DRM3

Creates a Direct3D Retained Mode Windows device by using specified Direct3D objects.

Syntax

HRESULT CreateDeviceFromD3D(
  LPDIRECT3D2 lpD3D,
  LPDIRECT3DDEVICE2 lpD3DDev,
  LPDIRECT3DRMDEVICE3  *lplpD3DRMDevice
  );

Parameters

lpD3D
Pointer to an instance of a Direct3D Immediate Mode Direct3D2 object.
lpD3DDev
Pointer to a Direct3D Immediate Mode Direct3DDevice2 object.
lplpD3DRMDevice
Address that will be filled with a pointer to an IDirect3DRMDevice3 interface if the call succeeds.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

For more information about devices, see Output Devices and IDirect3DRMDevice3.

IDirect3DRM3::CreateDeviceFromSurface

IDirect3DRM3

Creates a Direct3D Retained Mode Windows device for rendering from the specified DirectDraw surfaces.

Syntax

HRESULT CreateDeviceFromSurface(
  LPGUID lpGUID,
  LPDIRECTDRAW lpDD,
  LPDIRECTDRAWSURFACE lpDDSBack,
  DWORD dwFlags,
  LPDIRECT3DRMDEVICE3 *lplpD3DRMDevice);

Parameters

lpGUID
Address of the globally unique identifier (GUID) used as the required device driver. If this parameter is NULL, the default device driver is used.
lpDD
Address of the DirectDraw object that is the source of the DirectDraw surface.
lpDDSBack
Address of the DirectDrawSurface object that represents the back buffer.
dwFlags
The only currently defined flag is:
D3DRMDEVICE_NOZBUFFER
Indicates that if the lpDDSBack parameter has no z-buffer attached, no z-buffer is to be created. By default, a z-buffer will be created.
lplpD3DRMDevice
Address that will be filled with a pointer to an IDirect3DRMDevice3 interface if the call succeeds.

Return Value

Returns one of the following values:
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY
DD_OK

Remarks

This method was introduced with DirectX version 6.0. This method adds the dwFlags parameter to the older IDirect3DRM2::CreateDeviceFromSurface method which it replaces.

For more information about devices, see Output Devices and IDirect3DRMDevice3.

IDirect3DRM3::CreateFace

IDirect3DRM3

Creates an instance of the IDirect3DRMFace2 interface.

Syntax

HRESULT CreateFace(
  LPDIRECT3DRMFACE2  *lplpd3drmFace2
  );

Parameters

lplpd3drmFace2
Address that will be filled with a pointer to an IDirect3DRMFace2 interface if the call succeeds.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

IDirect3DRM3::CreateFrame

IDirect3DRM3

Creates a new child frame of the given parent frame.

Syntax

HRESULT CreateFrame(
  LPDIRECT3DRMFRAME3 lpD3DRMFrame,
  LPDIRECT3DRMFRAME3 *lplpD3DRMFrame
  );

Parameters

lpD3DRMFrame
Address of a IDirect3DRMFrame3 object that is to be the parent of the new frame.
lplpD3DRMFrame
Address that will be filled with a pointer to an IDirect3DRMFrame3 interface if the call succeeds.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

The child frame inherits the motion attributes of its parent. For example, if the parent is moving with a given velocity, the child frame will also move with that velocity. Furthermore, if the parent is set rotating, the child frame will rotate about the origin of the parent. Frames that have no parent are called scenes. To create a scene, specify NULL as the parent. An application can create a frame with no parent and then associate it with a parent frame later by using the IDirect3DRMFrame3::AddChild method.

If an application calls IDirect3DRM3::SetOptions to set right-handed geometry, the default axes for root frames (frames with NULL as the parent) becomes v = (0, 0, -1) and u = (0, 1, 0). Therefore IDirect3DRMFrame3::GetOrientation and IDirect3DRMFrame3::SetOrientation work correctly in right-handed mode.

See Also

IDirect3DRMFrame3::AddChild

IDirect3DRM3::CreateLight

IDirect3DRM3

Creates a new light source with the given type and color.

Syntax

HRESULT CreateLight(
  D3DRMLIGHTTYPE d3drmltLightType,
  D3DCOLOR cColor,
  LPDIRECT3DRMLIGHT *lplpD3DRMLight
  );

Parameters

d3drmltLightType
One of the lighting types given in the D3DRMLIGHTTYPE enumerated type.
cColor
Color of the light.
lplpD3DRMLight
Address that will be filled with a pointer to an IDirect3DRMLight interface if the call succeeds.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

IDirect3DRM3::CreateLightRGB

IDirect3DRM3

Creates a new light source with the given type and color.

Syntax

HRESULT CreateLightRGB(
  D3DRMLIGHTTYPE ltLightType,
  D3DVALUE vRed,
  D3DVALUE vGreen,
  D3DVALUE vBlue,
  LPDIRECT3DRMLIGHT *lplpD3DRMLight
  );

Parameters

ltLightType
One of the lighting types given in the D3DRMLIGHTTYPE enumerated type.
vRed, vGreen, and vBlue
Color of the light. Each component of the color should be in the range 0.0 to 1.0.
lplpD3DRMLight
Address that will be filled with a pointer to an IDirect3DRMLight interface if the call succeeds.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

The following code fragment calls CreateLightRGB to create a bright directional light. It assumes the Direct3D Retained Mode object has already been created using the Direct3DRMCreate function.

LPDIRECT3DRM3 lpD3DRM;
LPDIRECT3DRMLIGHT light;

if (FAILED(lpD3DRM->CreateLightRGB(D3DRMLIGHT_DIRECTIONAL,
                                   D3DVAL(0.9), D3DVAL(0.9), D3DVAL(0.9),
                                   &light))
{
    // error
}

IDirect3DRM3::CreateMaterial

IDirect3DRM3

Creates a material with the given specular property.

Syntax

HRESULT CreateMaterial(
  D3DVALUE vPower,
  LPDIRECT3DRMMATERIAL2  *lplpD3DRMMaterial
  );

Parameters

vPower
Sharpness of the reflected highlights, with a value of 5 giving a metallic look and higher values giving a more plastic look to the rendered surface.
lplpD3DRMMaterial
Address that will be filled with a pointer to an IDirect3DRMMaterial2 interface if the call succeeds.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

IDirect3DRM3::CreateMesh

IDirect3DRM3

Creates a new mesh object with no faces. The mesh is not visible until it is added to a frame.

Syntax

HRESULT CreateMesh(
  LPDIRECT3DRMMESH *lplpD3DRMMesh
  );

Parameters

lplpD3DRMMesh
Address that will be filled with a pointer to an IDirect3DRMMesh interface if the call succeeds.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

IDirect3DRM3::CreateMeshBuilder

IDirect3DRM3

Creates a new mesh builder object.

Syntax

HRESULT CreateMeshBuilder(
  LPDIRECT3DRMMESHBUILDER3  *lplpD3DRMMeshBuilder3
  );

Parameters

lplpD3DRMMeshBuilder3
Address that will be filled with a pointer to an IDirect3DRMMeshBuilder3 interface if the call succeeds.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

By default, perspective correction is on.

IDirect3DRM3::CreateObject

IDirect3DRM3

Creates a new object without initializing the object.

Syntax

HRESULT CreateObject(
  REFCLSID rclsid,
  LPUNKNOWN pUnkOuter,
  REFIID riid,
  LPVOID FAR *ppv
  );

Parameters

rclsid
Class identifier for the new object.
pUnkOuter
Pointer to the outer IUnknown that allows COM aggregation features.
riid
Interface identifier of the object to be created.
ppv
Address of a pointer to the object when the method returns.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

An application that uses this method must initialize the object that has been created. (The other creation methods of the IDirect3DRM3 interface initialize the object automatically.) In some cases, for example, for Direct3DRMViewport2 objects, you can use the Init method for that object. An application should use the Init method only once to initialize any given object.

Applications can use this method to implement aggregation in Direct3DRM objects.

IDirect3DRM3::CreateProgressiveMesh

IDirect3DRM3

Creates a new progressive mesh object with no faces. The mesh is not visible until it is added to a frame.

Syntax

HRESULT CreateProgressiveMesh(
  LPDIRECT3DRMPROGRESSIVEMESH *lplpD3DRMProgressiveMesh
  );

Parameters

lplpD3DRMProgressiveMesh
Address that will be filled with a pointer to an IDirect3DRMProgressiveMesh interface if the call succeeds.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

IDirect3DRM3::CreateShadow

IDirect3DRM3

Creates a shadow by using the specified visual and light, projecting the shadow onto the specified plane. The shadow is a visual that should be added to the frame that contains the visual.

Syntax

HRESULT CreateShadow(
  LPUNKNOWN pUnk,
  LPDIRECT3DRMLIGHT lpLight,
  D3DVALUE px,
  D3DVALUE py,
  D3DVALUE pz,
  D3DVALUE nx,
  D3DVALUE ny,
  D3DVALUE nz,
  LPDIRECT3DRMSHADOW2  *lplpShadow
  );

Parameters

pUnk
Pointer to the object casting the shadow.
lpLight
Address of the IDirect3DRMLight interface that is the light source.
px, py, and pz
Plane that the shadow is to be projected on.
nx, ny, and nz
Normal to the plane that the shadow is to be projected on.
lplpShadow
Address of a pointer to be initialized with a valid pointer to the shadow visual, if the call succeeds.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

IDirect3DRM3::CreateTexture

IDirect3DRM3

Creates a texture from an image in memory.

Syntax

HRESULT CreateTexture(
  LPD3DRMIMAGE lpImage,
  LPDIRECT3DRMTEXTURE3 *lplpD3DRMTexture3
  );

Parameters

lpImage
Address of a D3DRMIMAGE structure describing the source for the texture.
lplpD3DRMTexture3
Address that will be filled with a pointer to an IDirect3DRMTexture3 interface if the call succeeds.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

The memory associated with the image is used each time the texture is rendered, rather than the memory being copied into Direct3D Retained Mode buffers. This enables the image to be used both as a rendering target and as a texture.

IDirect3DRM3::CreateTextureFromSurface

IDirect3DRM3

Creates a texture from a specified DirectDraw surface.

Syntax

HRESULT CreateTextureFromSurface(
  LPDIRECTDRAWSURFACE lpDDS,
  LPDIRECT3DRMTEXTURE3  *lplpD3DRMTexture3
  );

Parameters

lpDDS
Address of the DirectDrawSurface object containing the texture.
lplpD3DRMTexture3
Address that will be filled with a pointer to an IDirect3DRMTexture3 interface if the call succeeds.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

When you create a texture from a DirectDraw surface, it is best to create the surface in system memory. This enables optimal performance for software devices and allows Direct3D Retained Mode to manage the use of video memory more effectively for hardware devices.

IDirect3DRM3::CreateUserVisual

IDirect3DRM3

Creates an application-defined visual object, which can then be added to a scene and rendered by using an application-defined handler.

Syntax

HRESULT CreateUserVisual(
  D3DRMUSERVISUALCALLBACK fn,
  LPVOID lpArg,
  LPDIRECT3DRMUSERVISUAL  *lplpD3DRMUV
  );

Parameters

fn
Application-defined D3DRMUSERVISUALCALLBACK callback function.

lpArg
Address of application-defined data passed to the callback function.
lplpD3DRMUV
Address that will be filled with a pointer to an IDirect3DRMUserVisual interface if the call succeeds.

Return Value

Should return D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMUserVisual::Init

IDirect3DRM3::CreateViewport

IDirect3DRM3

Creates a viewport on a device with device coordinates (dwXPos, dwYPos) to (dwXPos + dwWidth, dwYPos + dwHeight).

Syntax

HRESULT CreateViewport(
  LPDIRECT3DRMDEVICE3 lpDev,
  LPDIRECT3DRMFRAME3 lpCamera,
  DWORD dwXPos,
  DWORD dwYPos,
  DWORD dwWidth,
  DWORD dwHeight,
  LPDIRECT3DRMVIEWPORT2 *lplpD3DRMViewport
  );

Parameters

lpDev
Address of a IDirect3DRMDevice3 device on which the viewport is to be created.
lpCamera
Address of a frame that describes the position and direction of the view.
dwXPos, dwYPos, dwWidth, and dwHeight
Position and size of the viewport, in device coordinates. The viewport size cannot be larger than the physical device or the method will fail.
lplpD3DRMViewport
Address that will be filled with a pointer to an IDirect3DRMViewport2 interface if the call succeeds.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. If the viewport size is larger than the physical device, returns D3DRMERR_BADVALUE. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

The viewport displays objects in the scene that contains the camera, with the view direction and up vector taken from the camera. The viewport size cannot be larger than the physical device.

For more information about devices, see Output Devices and IDirect3DRMDevice3.

IDirect3DRM3::CreateWrap

IDirect3DRM3

Creates a wrapping function that can be used to assign texture coordinates to faces and meshes. The vector [ox oy oz] gives the origin of the wrap, [dx dy dz] gives its z-axis, and [ux uy uz] gives its y-axis. The 2-D vectors [ou ov] and [su sv] give an origin and scale factor in the texture applied to the result of the wrapping function.

Syntax

HRESULT CreateWrap(
  D3DRMWRAPTYPE type,
  LPDIRECT3DRMFRAME3 lpRef,
  D3DVALUE ox,
  D3DVALUE oy,
  D3DVALUE oz,
  D3DVALUE dx,
  D3DVALUE dy,
  D3DVALUE dz,
  D3DVALUE ux,
  D3DVALUE uy,
  D3DVALUE uz,
  D3DVALUE ou,
  D3DVALUE ov,
  D3DVALUE su,
  D3DVALUE sv,
  LPDIRECT3DRMWRAP *lplpD3DRMWrap
  );

Parameters

type
One of the members of the D3DRMWRAPTYPE enumerated type.
lpRef
Reference frame for the wrap.
ox, oy, and oz
Origin of the wrap.
dx, dy, and dz
The z-axis of the wrap.
ux, uy, and uz
The y-axis of the wrap.
ou and ov
Origin in the texture.
su and sv
Scale factor in the texture.
lplpD3DRMWrap
Address that will be filled with a pointer to an IDirect3DRMWrap interface if the call succeeds.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMWrap

IDirect3DRM3::EnumerateObjects

IDirect3DRM3

Uses the callback function specified by the func parameter on each of the active Direct3DRM objects.

Syntax

HRESULT EnumerateObjects(
  D3DRMOBJECTCALLBACK func,
  LPVOID lpArg
  );

Parameters

func
Application-defined D3DRMOBJECTCALLBACK callback function to be used with each Direct3DRMObject object and the application-defined argument.
lpArg
Address of application-defined data passed to the callback function.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

IDirect3DRM3::GetDevices

IDirect3DRM3

Returns all the Direct3DRM devices that have been created in the system.

Syntax

HRESULT GetDevices(
  LPDIRECT3DRMDEVICEARRAY *lplpDevArray
  );

Parameters

lplpDevArray
Address of a pointer that will be filled with the resulting array of Direct3DRM devices. For information about the Direct3DRMDeviceArray object, see the IDirect3DRMDeviceArray interface.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

IDirect3DRM3::GetNamedObject

IDirect3DRM3

Finds a Direct3DRMObject given the Direct3DRMObject name.

Syntax

HRESULT GetNamedObject(
  const char  *lpName,
  LPDIRECT3DRMOBJECT *lplpD3DRMObject
  );

Parameters

lpName
Name of the object to be searched for.
lplpD3DRMObject
Address of a pointer to be initialized with a valid Direct3DRMObject pointer if the call succeeds.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

If the system does not find an object with the name specified in the lpName parameter, this method returns D3DRM_OK but the lplpD3DRMObject parameter is NULL.

IDirect3DRM3::GetOptions

IDirect3DRM3

Retrieves whether Direct3D Retained Mode uses left-handed or right-handed geometry.

Syntax

HRESULT GetOptions(
  LPDWORD lpdwOptions);

Parameters

lpdwOptions
Pointer to a flag value that indicates the current Direct3D Retained Mode options. Currently defined flags are:
D3DRMOPTIONS_LEFTHANDED
Use left-handed geometry. This value is the default.
D3DRMOPTIONS_RIGHTHANDED
Use right-handed geometry.

Return Value

Returns one of the following values:
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

D3DRMOPTIONS_LEFTHANDED and D3DRMOPTIONS_RIGHTHANDED affect the following objects as well as picking and ray picking.

  • IDirect3DRMClippedVisual
  • IDirect3DRMMesh
  • IDirect3DRMMeshBuilder3
  • IDirect3DRMProgressiveMesh
  • IDirect3DRMShadow2
  • IDirect3DRMTexture3
  • IDirect3DRMViewport2

This method was introduced in DirectX version 6.0.

See Also

Direct3D Coordinate System

IDirect3DRM3::SetOptions

IDirect3DRM3::GetSearchPath

IDirect3DRM3

Returns the current search path. For Windows, the path is a list of directories separated by semicolons (;).

Syntax

HRESULT GetSearchPath(
  DWORD  *lpdwSize,
  LPSTR lpszPath
  );

Parameters

lpdwSize
Pointer to a DWORD. Should contain the length of lpszPath when GetSearchPath is used. On return, contains the length of the string in lpszPath containing the current search path. This parameter cannot be NULL.
lpszPath
A pointer to a null-terminated string specifying the search path. If lpszPath equals NULL when GetSearchPath is used, the method returns the length of the current string in the location pointed to by the lpdwSize parameter.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRM3::SetSearchPath

IDirect3DRM3::Load

IDirect3DRM3

Loads an object.

Syntax

HRESULT Load(
  LPVOID lpvObjSource,
  LPVOID lpvObjID,
  LPIID  *lplpGUIDs,
  DWORD dwcGUIDs,
  D3DRMLOADOPTIONS d3drmLOFlags,
  D3DRMLOADCALLBACK d3drmLoadProc,
  LPVOID lpArgLP,
  D3DRMLOADTEXTURE3CALLBACK d3drmLoadTextureProc,
  LPVOID lpArgLTP,
  LPDIRECT3DRMFRAME3 lpParentFrame
  );

Parameters

lpvObjSource
Source for the object to be loaded. This source can be a file, resource, memory block, or stream, depending on the source flags specified in the d3drmLOFlags parameter.
lpvObjID
Object name or position to be loaded. The use of this parameter depends on the identifier flags specified in the d3drmLOFlags parameter. If the D3DRMLOAD_BYPOSITION flag is specified, this parameter is a pointer to a DWORD value that gives the object's order in the file. This parameter can be NULL.
lplpGUIDs
Address of an array of interface identifiers to be loaded. For example, if this parameter is a two-element array containing IID_IDirect3DRMMeshBuilder3 and IID_IDirect3DRMAnimationSet2, this method loads all the animation sets and mesh-builder objects. Possible GUIDs must be one or more of the following: IID_IDirect3DRMProgressiveMesh, IID_IDirect3DRMMeshBuilder3, IID_IDirect3DRMAnimationSet2, IID_IDirect3DRMAnimation2, and IID_IDirect3DRMFrame3.
dwcGUIDs
Number of elements specified in the lplpGUIDs parameter.
d3drmLOFlags
Value of the D3DRMLOADOPTIONS type describing the load options.
d3drmLoadProc
A D3DRMLOAD3CALLBACK callback function used when the system reads the specified object.
lpArgLP
Address of application-defined data passed to the D3DRMLOADCALLBACK callback function.
d3drmLoadTextureProc
A D3DRMLOADTEXTURE3CALLBACK callback function used to load any textures used by an object that require special formatting. This parameter can be NULL.
lpArgLTP
Address of application-defined data passed to the D3DRMLOADTEXTURE3CALLBACK callback function.
lpParentFrame
Address of a parent Direct3DRMFrame object. This argument only affects the loading of animation sets. When an animation that is loaded from an .x file references an unparented frame in the .x file, the unparented frame's parent is set to the parent frame at lpParentFrame. However, if you use Load to load any frames in the .x file, the parent frame at lpParentFrame will not be used as the parent frame for frames in the .x file with no parent. That is, lpParentFrame is used only when you load animation sets. This value of lpParentFrame can be NULL.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

By default, perspective correction is on.

This method allows great flexibility in loading objects from Microsoft® DirectX® files. Here is an example of how to use it:

Sample Code

#include <windows.h>
#include <stdio.h>
#include <initguid.h>
#include <d3drm.h>

LPDIRECT3DRM d3dApi;

int totalMesh = 0, totalAnim = 0, totalFrames = 0;

HRESULT loadTexture(LPSTR name, LPVOID lpArg, LPDIRECT3DRMTEXTURE *tex)
{
    return d3dApi->lpVtbl->LoadTexture(d3dApi, name, tex);
}

void loadCallback(LPDIRECT3DRMOBJECT lpObject, REFIID objGuid, LPVOID lpArg)
{
    if (IsEqualIID(objGuid, &IID_IDirect3DRMFrame3)) {
        totalFrames ++;
        return;
    }

    if (IsEqualIID(objGuid, &IID_IDirect3DRMAnimationSet2)) {
        totalAnim ++;
        return;
    }

    if (IsEqualIID(objGuid, &IID_IDirect3DRMMeshBuilder)) {
        totalMesh ++;
        return;
    }

    return;
}

BOOL loadObjects(LPSTR filename)
{
    LPGUID guids[] = { (LPGUID)&IID_IDirect3DRMMeshBuilder,
        (LPGUID)&IID_IDirect3DRMAnimationSet2,
        (LPGUID)&IID_IDirect3DRMFrame3 };

    /* Tell the loader which objects you're interested in */

    if (FAILED(d3dApi->lpVtbl->Load(d3dApi, filename, NULL,
            guids, 3, D3DRMLOAD_FROMFILE,
            loadCallback, NULL, loadTexture, NULL, NULL)))
        return FALSE;

    printf("Total Frames loaded = %d\n", totalFrames);
    printf("Total Animation Sets loaded = %d\n", totalAnim);
    printf("Total Meshbuilders loaded = %d\n", totalMesh);

    return TRUE;
}

int main(int argc, char **argv)
{

    if (FAILED(Direct3DRMCreate(&d3dApi)))
        return FALSE;

    if (argc != 2) {
        fprintf(stderr, "usage: %s filename\n", argv[0]);
        return FALSE;
    }

    if (!loadObjects(argv[1])) return FALSE;

  return(0);
}

IDirect3DRM3::LoadTexture

IDirect3DRM3

Loads a Direct3DRMTexture2 texture from the specified file. This texture can have 8, 24, or 32 bits-per-pixel, and it should be in either the Windows bitmap (.bmp) or Portable Pixmap (.ppm) P6 format.

Syntax

HRESULT LoadTexture(
  const char  *lpFileName,
  LPDIRECT3DRMTEXTURE3 *lplpD3DRMTexture
  );

Parameters

lpFileName
Address of the name of the required .bmp or .ppm file.
lplpD3DRMTexture
Address of a pointer to be initialized with a valid IDirect3DRMTexture3 pointer if the call succeeds.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

LoadTexture checks whether the texture is in BMP or PPM format, which are the formats it can load. If you want to load other formats, you can add code to the callback to load the image into a D3DRMIMAGE structure and then use IDirect3DRM3::CreateTexture.

If you write your own texture callback, the LoadTexture call in the texture callback does not take a reference to the texture. For example:

HRESULT loadTextures(char *name, void *arg, LPDIRECT3DRMTEXTURE2 *tex)
{
    return lpD3DRM2->LoadTexture(name, tex);
}

In this sample, no reference is taken for tex. If you want to keep a reference to each texture loaded by your texture callback, you should AddRef the texture. For example:

LPDIRECT3DRMTEXTURE2 *texarray;

HRESULT loadTextures(char *name, void *arg, LPDIRECT3DRMTEXTURE2 *tex)
{
    if (FAILED(lpD3DRM2->LoadTexture(name, tex)) {
        return NULL;
    }

    texArray[current++] = tex;
    tex->AddRef();

    return tex;
}

IDirect3DRM3::LoadTextureFromResource

IDirect3DRM3

Loads a Direct3DRMTexture2 texture from a specified resource.

Syntax

HRESULT LoadTextureFromResource(
  HMODULE hModule,
  LPCTSTR strName,
  LPCTSTR strType,
  LPDIRECT3DRMTEXTURE3  *lplpD3DRMTexture
  );

Parameters

hModule
Handle of the module whose executable file contains the resource.
strName
A null-terminated string specifying the name of the resource to be used as the texture.
strType
A null-terminated string specifying the type name of the resource. This parameter can be one of the following resource types or a user-defined type:
Value | Meaning
RT_BITMAP | Bitmap resource
RT_RCDATA | Application-defined resource (raw data)
lplpD3DRMTexture
Address of a pointer to be initialized with a valid IDirect3DRMTexture3 object if the call succeeds.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

IDirect3DRM3::RegisterClient

IDirect3DRM3

Registers a client (application) with which data can be associated.

Syntax

HRESULT RegisterClient(
  REFGUID rguid,
  LPDWORD lpdwID);

Parameters

rguid
Reference to a GUID that represents the application.
lpdwID
Address that receives a unique ID that the application can use with IDirect3DRMObject2::SetClientData and IDirect3DRMObject2::GetClientData to associate data with the Retained Mode object.

Return Value

Returns one of the following values:
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_OUTOFMEMORY
DD_OK

Remarks

The application passes a GUID and receives a DWORD identifier that can then be used with IDirect3DRMObject2::SetClientData and IDirect3DRMObject2::GetClientData to associate data with the Retained Mode object. When an application uses UnregisterClient, any data stored by the application by means of IDirect3DRMObject2::SetClientData is released in a manner dependent on its type. The same ID is returned for multiple invocations of this method with the same GUID. This method was introduced in DirectX version 6.0.

IDirect3DRM3::SetDefaultTextureColors

IDirect3DRM3

Sets the default colors to be used for a Direct3DRMTexture2 object.

Syntax

HRESULT SetDefaultTextureColors(
  DWORD dwColors
  );

Parameters

dwColors
Number of colors.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

This method affects the texture colors only when it is used before the IDirect3DRM3::CreateTexture method; it has no effect on textures that have already been created.

IDirect3DRM3::SetDefaultTextureShades

IDirect3DRM3

Sets the default shades to be used for an Direct3DRMTexture2 object.

Syntax

HRESULT SetDefaultTextureShades(
  DWORD dwShades
  );

Parameters

dwShades
Number of shades.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

This method affects the texture shades only when it is used before the IDirect3DRM3::CreateTexture method; it has no effect on textures that have already been created.

IDirect3DRM3::SetOptions

IDirect3DRM3

Sets whether Direct3D Retained Mode uses left-handed or right-handed geometry.

Syntax

HRESULT SetOptions(
  LPDWORD dwOptions);

Parameters

dwOptions
Flag value that indicates the current Direct3D Retained Mode options. Currently defined flags are:
D3DRMOPTIONS_LEFTHANDED
Use left-handed geometry. This value is the default.
D3DRMOPTIONS_RIGHTHANDED
Use right-handed geometry.

Return Value

Returns one of the following values:
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

D3DRMOPTIONS_LEFTHANDED and D3DRMOPTIONS_RIGHTHANDED affect the following objects as well as picking and ray picking.

  • IDirect3DRMClippedVisual
  • IDirect3DRMMesh
  • IDirect3DRMMeshBuilder3
  • IDirect3DRMProgressiveMesh
  • IDirect3DRMShadow2
  • IDirect3DRMTexture3
  • IDirect3DRMViewport2

This method was introduced in DirectX version 6.0.

See Also

Direct3D Coordinate System

IDirect3DRM3::GetOptions

IDirect3DRM3::SetSearchPath

IDirect3DRM3

Sets the current file search path from a list of directories. For Windows, the path should be a list of directories separated by semicolons (;).

Syntax

HRESULT SetSearchPath(
  LPCSTR lpPath
  );

Parameters

lpPath
Address of a null-terminated string specifying the path to set as the current search path.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

The default search path is taken from the value of the D3DPATH environment variable. If this is not set, the search path will be empty. When opening a file, the system first looks for the file in the current working directory and then checks every directory in the search path.

D3DPATH is an environment variable that sets the default search path.

See Also

IDirect3DRM3::GetSearchPath

IDirect3DRM3::Tick

IDirect3DRM3

Performs the Direct3DRM system heartbeat. When this method is used, the positions of all moving frames are updated according to their current motion attributes, the scene is rendered to the current device, and relevant callback functions are used at their appropriate times. Control is returned when the rendering cycle is complete.

Syntax

HRESULT Tick(
  D3DVALUE d3dvalTick
  );

Parameters

d3dvalTick
Velocity and rotation step for the IDirect3DRMFrame3::SetRotation and IDirect3DRMFrame3::SetVelocity methods.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

You can implement this method by using other Retained Mode methods to allow more flexibility in rendering a scene.

IDirect3DRM3::UnregisterClient

IDirect3DRM3

Disassociates all data and object associations set by IDirect3DRMObject2::SetClientData and frees the data in a manner dependent on its type.

Syntax

HRESULT UnregisterClient(
  REFGUID rguid);

Parameters

rguid
Reference to a GUID that represents the application.

Return Value

Returns one of the following values:
D3DRMERR_CLIENTNOTREGISTERED
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.


IDirect3DRMAnimation2

Applications use the methods of the IDirect3DRMAnimation2 interface to animate the position, orientation, and scaling of visuals, lights, and viewports.

An animation in Retained Mode is defined by a set of keys. A key is a time value associated with a scaling operation, an orientation, or a position. A Direct3DRMAnimation object defines how a transformation is modified according to the time value. The animation can be set to operate on a Direct3DRMFrame object, so it could be used to animate the position, orientation, and scaling of Direct3DRMVisual, Direct3DRMLight, and Direct3DRMViewport objects.

The IDirect3DRMAnimation2::AddPositionKey, AddRotateKey, and AddScaleKey methods each specify a time value whose units are arbitrary. If an application adds a position key with a time value of 99, for example, a new position key with a time value of 49 would occur exactly halfway between the (zero-based) beginning of the animation and the first position key.

The animation is driven by calling the IDirect3DRMAnimation2::SetTime method. This sets the visual object's transformation to the interpolated position, orientation, and scale of the nearby keys in the animation. As with the methods that add animation keys, the time value for IDirect3DRMAnimation2::SetTime is an arbitrary value, based on the positions of keys the application has already added.

Microsoft DirectX version 6.0 introduced the IDirect3DRMAnimation2 interface. IDirect3DRMAnimation2 extends the older IDirect3DRMAnimation interface that it replaces by adding the AddKey, DeleteKeyByID, GetKeys, and ModifyKey methods that allow access to the keys of an animation. It also adds the GetFrame method that returns the frame of the corresponding animation. For a history of the Direct3D Retained Mode interfaces, see Interface Changes.

The methods of the IDirect3DRMAnimation2 interface can be organized into the following groups:

Keys | AddKey
 | AddPositionKey
 | AddRotateKey
 | AddScaleKey
 | DeleteKey
 | DeleteKeyByID
 | GetKeys
 | ModifyKey
Miscellaneous | GetFrame
 | SetFrame
 | SetTime
Options | GetOptions
 | SetOptions

The IDirect3DRMAnimation2 interface, like all Component Object Model (COM) interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:
AddRef
QueryInterface
Release

In addition, the IDirect3DRMAnimation2 interface inherits the following methods from the IDirect3DRMObject interface:
AddDestroyCallback
Clone
DeleteDestroyCallback
GetAppData
GetClassName
GetName
SetAppData
SetName

The Direct3DRMAnimation object is obtained by calling the IDirect3DRM3::CreateAnimation method.

IDirect3DRMAnimation2::AddKey

IDirect3DRMAnimation2

Adds a new key.

Syntax

HRESULT AddKey
(LPD3DRMANIMATIONKEY lpKey);

Parameters

lpKey
D3DRMANIMATIONKEY structure that defines a new key. The dwID member of the structure is ignored and is filled in with the ID of the new key upon return.

Return Value

Returns one of the following values:
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMAnimation2::AddPositionKey

IDirect3DRMAnimation2

Adds a position key to the animation.

Syntax

HRESULT AddPositionKey(
  D3DVALUE rvTime,
  D3DVALUE rvX,
  D3DVALUE rvY,
  D3DVALUE rvZ
  );

Parameters

rvTime
Time in the animation to store the position key. The time units are arbitrary and zero-based; a key whose rvTime value is 49 occurs exactly in the middle of an animation whose last key has an rvTime value of 99.
rvX, rvY, and rvZ
Position.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

The transformation applied by this method is a translation. For information about the matrix mathematics involved in transformations, see 3-D Transformations.

See Also

IDirect3DRMAnimation2::DeleteKey

IDirect3DRMAnimation2::AddRotateKey

IDirect3DRMAnimation2

Adds a rotate key to the animation.

Syntax

HRESULT AddRotateKey(
  D3DVALUE rvTime,
  D3DRMQUATERNION *rqQuat
  );

Parameters

rvTime
Time in the animation to store the rotate key. The time units are arbitrary and zero-based; a key whose rvTime value is 49 occurs exactly in the middle of an animation whose last key has an rvTime value of 99.
rqQuat
Quaternion representing the rotation.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

This method applies a rotation transformation. For information about the matrix mathematics involved in transformations, see 3-D Transformations.

See Also

IDirect3DRMAnimation2::DeleteKey

IDirect3DRMAnimation2::AddScaleKey

IDirect3DRMAnimation2

Adds a scale key to the animation.

Syntax

HRESULT AddScaleKey(
  D3DVALUE rvTime,
  D3DVALUE rvX,
  D3DVALUE rvY,
  D3DVALUE rvZ
  );

Parameters

rvTime
Time in the animation to store the scale key. The time units are arbitrary and zero-based; a key whose rvTime value is 49 occurs exactly in the middle of an animation whose last key has an rvTime value of 99.
rvX, rvY, and rvZ
Scale factor.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

This method applies a scaling transformation. For information about the matrix mathematics involved in transformations, see 3-D Transformations.

See Also

IDirect3DRMAnimation2::DeleteKey

IDirect3DRMAnimation2::DeleteKey

IDirect3DRMAnimation2

Removes all the keys with the given time from an animation. For example, if an animation has a scale key with time t and a rotation key with time t then both keys will be deleted.

Syntax

HRESULT DeleteKey(
  D3DVALUE rvTime
  );

Parameters

rvTime
Time identifying the key that will be removed from the animation.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMAnimation2::DeleteKeyByID

IDirect3DRMAnimation2

Deletes the key corresponding to a particular ID.

Syntax

HRESULT DeleteKeyByID
(DWORD dwID);

Parameters

dwID
ID of the key to delete.

Return Value

Returns one of the following values:
D3DRMERR_NOSUCHKEY
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMAnimation2::GetFrame

IDirect3DRMAnimation2

Retrieves the frame corresponding to the animation.

Syntax

HRESULT GetFrame
(LPDIRECT3DRMFRAME3 *lplpFrame);

Parameters

lplpFrame
Pointer to receive an interface of the current Direct3DRMFrame object that the animation references. This can be NULL.

Return Value

Returns one of the following values:
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMAnimation2::GetKeys

IDirect3DRMAnimation2

Retrieves the keys corresponding to a particular time.

Syntax

HRESULT GetKeys
(D3DVALUE dvTimeMin,
D3DVALUE dvTimeMax,
LPDWORD lpdwNumKeys,
LPD3DRMANIMATIONKEY lpKey);

Parameters

dvTimeMin
Minimum time value of keys to be returned.
dvTimeMax
Maximum time value of keys to be returned.
lpdwNumKeys
Pointer to a variable the contains the number of keys to be returned in lpKey. If lpKey is NULL, lpdwNumKeys is filled in with the number of keys at the specified time.
lpKey
Pointer to a D3DRMANIMATIONKEY structure that will be filled in with the key value. If lpKey is NULL, lpdwNumKeys will be filled in with the number of keys at the specified time. If lpKey is non-NULL, it will be filled in with the keys corresponding to the specified time up to a maximum number of keys indicated by lpdwNumKeys.

Return Value

Returns one of the following values:
D3DRMERR_NOSUCHKEY
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMAnimation2::GetOptions

IDirect3DRMAnimation2

Retrieves animation options.

Syntax

D3DRMANIMATIONOPTIONS GetOptions( );

Return Value

Returns the value of the D3DRMANIMATIONOPTIONS type describing the animation options.

See Also

IDirect3DRMAnimation2::SetOptions

IDirect3DRMAnimation2::ModifyKey

IDirect3DRMAnimation2

Modifies the value of a key.

Syntax

HRESULT Modify
(LPD3DRMANIMATIONKEY lpKey);

Parameters

lpKey
D3DRMANIMATIONKEY structure that defines an existing key's value. The dwID member of the structure must be an existing key.

Return Value

Returns one of the following values:
D3DRMERR_INCOMPATIBLEKEY
D3DRMERR_NOSUCHKEY
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

You cannot modify a key's type. To change a key's type you must delete the original key and then add a new key. You can modify a key's time and position, rotation, and scale values.

IDirect3DRMAnimation2::SetFrame

IDirect3DRMAnimation2

Sets the frame for the animation.

Syntax

HRESULT SetFrame(
  LPDIRECT3DRMFRAME3 lpD3DRMFrame
  );

Parameters

lpD3DRMFrame
Address of a variable representing the frame to set for the animation.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMAnimation2::SetOptions

IDirect3DRMAnimation2

Sets the animation options.

Syntax

HRESULT SetOptions(
  D3DRMANIMATIONOPTIONS d3drmanimFlags
  );

Parameters

d3drmanimFlags
Value of the D3DRMANIMATIONOPTIONS type describing the animation options.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMAnimation2::GetOptions

IDirect3DRMAnimation2::SetTime

IDirect3DRMAnimation2

Sets the current time for this animation.

Syntax

HRESULT SetTime(
  D3DVALUE rvTime
  );

Parameters

rvTime
New current time for the animation. The time units are arbitrary and zero-based; a key whose rvTime value is 49 occurs exactly in the middle of an animation whose last key has an rvTime value of 99.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.


IDirect3DRMAnimationArray

The IDirect3DRMAnimationArray interface enables you to retrieve the number of animations in the array and request the interface for an animation.

This interface supports the GetElement and GetSize methods.

The IDirect3DRMAnimationArray interface, like all Component Object Model (COM) interfaces, inherits the IUnknown interface methods. This interface supports the following three methods.
AddRef
QueryInterface
Release

IDirect3DRMAnimationArray::GetElement

IDirect3DRMAnimationArray

Retrieves an interface for the requested animation.

Syntax

DWORD GetElement(
  DWORD dwIndex,
  LPDIRECT3DRMANIMATION2 &lplpDirect3DRMAnimation);

Parameters

dwIndex
Index in the array of the animation to be retrieved.
lplpDirect3DRMAnimation
Pointer to the Direct3DRMAnimation object.

Return Value

Returns one of the following values:
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMAnimationArray::GetSize

IDirect3DRMAnimationArray

Retrieves the number of animations in the array.

Syntax

DWORD GetSize();

Return Value

Number of animations.

Remarks

This method was introduced with DirectX version 6.0.


IDirect3DRMAnimationSet2

Applications use the methods of the IDirect3DRMAnimationSet2 interface to group Direct3DRMAnimation objects together, which can simplify the playback of complex animation sequences.

A Direct3DRMAnimationSet object allows Direct3DRMAnimation objects to be grouped together. This allows all the animations in an animation set to share the same time parameter, simplifying the playback of complex articulated animation sequences. An application can add an animation to an animation set by using the IDirect3DRMAnimationSet2::AddAnimation method, and it can remove one by using the IDirect3DRMAnimationSet2::DeleteAnimation method. Animation sets are driven by calling the IDirect3DRMAnimationSet2::SetTime method.

Microsoft DirectX version 6.0 introduced the IDirect3DRMAnimationSet2 interface. IDirect3DRMAnimationSet2 extends the older IDirect3DRMAnimationSet interface that it replaces by adding the GetAnimations method that allows you to retrieve the constituent animations. For a history of the Direct3D Retained Mode interfaces, see Interface Changes.

The methods of the IDirect3DRMAnimationSet2 interface can be organized into the following groups:

Adding, removing, retrieving, and loading | AddAnimation
 | DeleteAnimation
 | GetAnimations
 | Load
Time | SetTime

The IDirect3DRMAnimationSet2 interface, like all Component Object Model (COM) interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:
AddRef
QueryInterface
Release

In addition, the IDirect3DRMAnimationSet2 interface inherits the following methods from the IDirect3DRMObject interface:
AddDestroyCallback
Clone
DeleteDestroyCallback
GetAppData
GetClassName
GetName
SetAppData
SetName

The Direct3DRMAnimationSet object is obtained by calling the IDirect3DRM3::CreateAnimationSet method.

IDirect3DRMAnimationSet2::AddAnimation

IDirect3DRMAnimationSet2

Adds an animation to the animation set.

Syntax

HRESULT AddAnimation(
  LPDIRECT3DRMANIMATION2 lpD3DRMAnimation
  );

Parameters

lpD3DRMAnimation
Address of the Direct3DRMAnimation object to be added to the animation set.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

IDirect3DRMAnimationSet2::DeleteAnimation

IDirect3DRMAnimationSet2

Removes a previously added animation from the animation set.

Syntax

HRESULT DeleteAnimation(
  LPDIRECT3DRMANIMATION2 lpD3DRMAnimation
  );

Parameters

lpD3DRMAnimation
Address of the Direct3DRMAnimation object to be removed from the animation set.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

IDirect3DRMAnimationSet2::GetAnimations

IDirect3DRMAnimationSet2

Retrieves an array containing the animations in the animation set.

Syntax

HRESULT GetAnimations
(LPDIRECT3DRMANIMATIONARRAY *lplpArray);

Parameters

lplpArray
Array that receives a pointer to the corresponding Direct3DRMAnimationArray object.

Return Value

Returns one of the following values.

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMAnimationSet2::Load

IDirect3DRMAnimationSet2

Loads an animation set.

Syntax

HRESULT Load(
  LPVOID lpvObjSource,
  LPVOID lpvObjID,
  D3DRMLOADOPTIONS d3drmLOFlags,
  D3DRMLOADTEXTURE3CALLBACK d3drmLoadTextureProc,
  LPVOID lpArgLTP,
  LPDIRECT3DRMFRAME3 lpParentFrame
  );

Parameters

lpvObjSource
Source for the object to be loaded. This source can be a file, resource, memory block, or stream, depending on the source flags specified in the d3drmLOFlags parameter.
lpvObjID
Object name or position to be loaded. The use of this parameter depends on the identifier flags specified in the d3drmLOFlags parameter. If the D3DRMLOAD_BYPOSITION flag is specified, this parameter is a pointer to a DWORD value that gives the object's order in the file. This parameter can be NULL.
d3drmLOFlags
Value of the D3DRMLOADOPTIONS type describing the load options.
d3drmLoadTextureProc
D3DRMLOADTEXTURE3CALLBACK callback function used to load any textures used by the object that require special formatting. This parameter can be NULL.
lpArgLTP
Address of application-defined data passed to the D3DRMLOADTEXTURE3CALLBACK callback function.
lpParentFrame
Address of a parent Direct3DRMFrame object. This argument only affects the loading of animation sets. When an animation that is loaded from an .x file references an unparented frame in the .x file, the frame's parent is set to this parent frame argument. However, if you use Load to load any frames in the .x file, the parent frame argument will not be used as the parent frame for frames in the .x file with no parent. That is, the parent frame argument is used only when you load animation sets. The value of this argument can be NULL.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

By default, this method loads the first animation set in the file specified by the lpvObjSource parameter. By default, perspective correction is on.

IDirect3DRMAnimationSet2::SetTime

IDirect3DRMAnimationSet2

Sets the time for this animation set.

Syntax

HRESULT SetTime(
  D3DVALUE rvTime
  );

Parameters

rvTime
New time.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.


IDirect3DRMArray

The IDirect3DRMArray interface organizes groups of objects. Applications typically use the particular array interface they need (for example, IDirect3DRMFaceArray), rather than using this interface directly.

The IDirect3DRMArray interface supports the GetSize method.

The IDirect3DRMArray interface, like all Component Object Model (COM) interfaces, inherits the IUnknown interface methods. This interface supports the following three methods:
AddRef
QueryInterface
Release

IDirect3DRMArray::GetSize

IDirect3DRMArray

Retrieves the size, in number of objects, of the Direct3DRMArray object.

Syntax

DWORD GetSize( );

Return Value

Returns the size.


IDirect3DRMClippedVisual

Microsoft® DirectX® version 6.0 introduced the IDirect3DRMClippedVisual interface. This interface allows applications to clip visual objects against arbitrary planes, specified in world space, before rendering. You create a clipped visual from another visual in much the same way you create a shadow from another visual. For example, you can create a clipped visual from a sphere and pass a clipping plane straight through the middle of the sphere to have only half of the sphere render. Create clipped visual objects by calling the IDirect3DRM3::CreateClippedVisual method. Then add the clipped visual to the scene by using the IDirect3DRMFrame3::AddVisual method.

IDirect3DRMClippedVisual inherits from IDirect3DRMVisual, as the other visual interfaces do. When the reference frame moves, the clipping plane does not move (see the AddPlane method for more information).

For a history of the Microsoft Direct3D® Retained Mode interfaces, see Interface Changes.

The methods of the IDirect3DRMClippedVisual interface can be organized into the following groups.
Initialization | Init
Planes | AddPlane
 | DeletePlane
 | GetPlane
 | GetPlaneIDs
 | SetPlane

The IDirect3DRMClippedVisual interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods.
AddRef
QueryInterface
Release

In addition, the IDirect3DRMClippedVisual interface inherits the following methods from the IDirect3DRMObject interface.
AddDestroyCallback
Clone
DeleteDestroyCallback
GetAppData
GetClassName
GetName
SetAppData
SetName

You can create an Direct3DRMClippedVisual object by using the IDirect3DRM3 interface.

IDirect3DRMClippedVisual::AddPlane

IDirect3DRMClippedVisual

Adds a clipping plane.

Syntax

HRESULT AddPlane(
  LPDIRECT3DRMFRAME3 lpRef,
  LPD3DVECTOR lpdvPoint,
  LPD3DVECTOR lpdvNormal,
  DWORD dwFlags,
  LPDWORD lpdwReturnID);

Parameters

lpRef
Reference frame for the point and normal paramters.
lpdvPoint
Point on the plane relative to the reference frame.
lpdvNormal
Vector normal to the plane relative to the reference frame.
dwFlags
Unused flags. Must be zero.
lpdwReturnID
Pointer that receives a unique ID number for the plane on successful return.

Return Value

Returns DD_OK or DDERR_INVALIDPARAMS.

Remarks

Clipping planes are stored internally as world coordinates. When the reference frame moves, the clipping plane does not move. Use the SetPlane method to update the position and orientation of the clipping plane, as needed.

This method was introduced with DirectX version 6.0.

IDirect3DRMClippedVisual::DeletePlane

IDirect3DRMClippedVisual

Deletes a clipping plane.

Syntax

HRESULT DeletePlane(
  DWORD dwID,
  DWORD dwFlags);

Parameters

dwID
ID number of the plane to delete.
dwFlags
Unused flags.

Return Value

Returns DD_OK if successful.

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMClippedVisual::GetPlane

IDirect3DRMClippedVisual

Retrieves information about a clipping plane.

Syntax

HRESULT GetPlane(
  DWORD dwID,
  LPDIRECT3DRMFRAME3 lpRef,
  LPD3DVECTOR lpdvPoint,
  LPD3DVECTOR lpdvNormal,
  DWORD dwFlags);

Parameters

lpRef
Reference frame for this operation.
dwID
ID of the plane.
lpdvPoint
Pointer that receives a point on the plane relative to the reference frame on successful return.
lpdvNormal
Pointer that receives a vector normal to the plane, relative to the reference frame on successful return.
dwFlags
Unused flags. Must be zero.

Return Value

Returns DD_OK or DDERR_INVALIDPARAMS.

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMClippedVisual::GetPlaneIDs

IDirect3DRMClippedVisual

Retrieves an array of IDs.

Syntax

HRESULT GetPlanes(
  LPDWORD lpdwCount,
  LPDWORD lpdwID,
  DWORD dwFlags);

Parameters

lpdwCount
Pointer that receives the number of planes on successful return.
lpdwID
Addresss of a buffer large enough to contain an array of all the plane ID numbers. On successful return, contains the IDs of the planes. If NULL, only the number of planes is returned.
dwFlags
Unused flags. Must be zero.

Return Value

Returns DD_OK or DDERR_INVALIDPARAMS.

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMClippedVisual::Init

IDirect3DRMClippedVisual

Initializes the clipped visual.

Syntax

HRESULT Init(
  LPDIRECT3DRMVISUAL lpD3DRMVisual);

Parameters

lpD3DRMVisual
Visual that is to be clipped and rendered.

Return Value

Returns DD_OK if successful.

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMClippedVisual::SetPlane

IDirect3DRMClippedVisual

Changes the parameters of a clipping plane that has already been added.

Syntax

HRESULT SetPlane(
  DWORD dwID,
  LPDIRECT3DRMFRAME3 lpRef,
  LPD3DVECTOR lpdvPoint,
  LPD3DVECTOR lpdvNormal,
  DWORD dwFlags);

Parameters

dwID
ID number of the plane to be changed.
lpRef
The reference frame for the point and normal paramters. If this parameter is NULL, lpdvPoint and lpdvNormal are in world space.
lpdvPoint
Point on the plane relative to the reference frame.
lpdvNormal
Vector normal to the plane, relative to the reference frame.
dwFlags
Flag value. Must be zero.
lpdwReturnID
Pointer that receives a unique ID number for the plane on successful return.

Return Value

Returns DD_OK or DDERR_INVALIDPARAMS.

Remarks

This method was introduced with DirectX version 6.0.


IDirect3DRMDevice3

Applications use the IDirect3DRMDevice3, IDirect3DRMDevice2, and IDirect3DRMDevice interfaces to interact with the output device. For a conceptual overview, see Output Devices.

IDirect3DRMDevice3 contains all the methods in the older IDirect3DRMDevice2 and IDirect3DRMDevice interfaces, but adds the FindPreferredTextureFormat method to select a texture format based on certain criteria and also adds four methods that eliminate redundant state changes (setting a state to a value equal to its current value): GetStateChangeOptions, LightStateChange, RenderStateChange, and SetStateChangeOptions.

IDirect3DRMDevice2 contains all the methods in IDirect3DRMDevice, plus: two additional methods that enable you to control transparency, GetRenderMode and SetRenderMode; one additional initialization method, InitFromSurface; and two changed methods, GetDirect3DDevice2 and InitFromD3D2, which get and initialize an IDirect3DRMDevice2 object rather than an IDirect3DRMDevice object.

When you create the IDirect3DRMDevice3 or IDirect3DRMDevice2 interface from the IDirect3DRM3 or IDirect3DRM2 interface, respectively, or initialize either interface using its respective InitFromClipper, InitFromD3D2, or InitFromSurface IDirect3DRMDevice3 methods, the interface works with an IDirect3DDevice3 or IDirect3DDevice2 Immediate Mode device, respectively. The IDirect3DDevice3 and IDirect3DDevice2 devices support the DrawPrimitive interface, as well as execute buffers, and are required for progressive meshes, for alpha blending and sorting of transparent objects. When you create the old IDirect3DRMDevice interface from the IDirect3DRM interface, the IDirect3DRMDevice Retained Mode interface works with an IDirect3DDevice Immediate Mode device.

The InitFromClipper and InitFromSurface methods use the IDirect3DRM3::CreateDevice method to create a Direct3DRMDevice3 object.

The InitFromD3D2 method uses an IDirect3D2 Immediate Mode object and an IDirect3DDevice2 Immediate Mode device to initialize an IDirect3DDevice2 Direct3D Retained Mode device.

You can still query between the IDirect3DRMDevice3, IDirect3DRMDevice2, and IDirect3DRMDevice interfaces. The main difference is in how the underlying Immediate Mode device is created.

The methods of the IDirect3DRMDevice3 interface can be organized into the following groups:
Buffer counts | GetBufferCount
 | SetBufferCount
Color models | GetColorModel
Dithering | GetDither
 | SetDither
Eliminating Redundant State Changes | GetStateChangeOptions
 | LightStateChange
 | RenderStateChange
 | SetStateChangeOptions
Initialization | Init
 | InitFromClipper
 | InitFromD3D2
 | InitFromSurface
Miscellaneous | GetDirect3DDevice2
 | GetHeight
 | GetTrianglesDrawn
 | GetViewports
 | GetWidth
 | GetWireframeOptions
 | Update
Notifications | AddUpdateCallback
 | DeleteUpdateCallback
Rendering quality | GetQuality
 | SetQuality
Shading | GetShades
 | SetShades
Textures | FindPreferredTextureFormat
 | GetTextureQuality
 | SetTextureQuality
Transparency | GetRenderMode
 | SetRenderMode

The IDirect3DRMDevice3 interface, like all Component Object Model (COM) interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:
AddRef
QueryInterface
Release

In addition, the IDirect3DRMDevice3 interface inherits the following methods from the IDirect3DRMObject interface:
AddDestroyCallback
Clone
DeleteDestroyCallback
GetAppData
GetClassName
GetName
SetAppData
SetName

The Direct3DRMDevice3 object is obtained by calling the IDirect3DRM3::CreateDevice method.

IDirect3DRMDevice3::AddUpdateCallback

IDirect3DRMDevice3

Adds a callback function that alerts the application when a change occurs to the device. The system uses this callback function when the application uses the IDirect3DRMDevice3::Update method.

Syntax

HRESULT AddUpdateCallback(
  D3DRMDEVICE3UPDATECALLBACK d3drmUpdateProc,
  LPVOID arg
  );

Parameters

d3drmUpdateProc
Pointer to an application-defined callback function, D3DRMDEVICE3UPDATECALLBACK.
arg
Pointer to private data to be passed to the update callback function.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return values, see Direct3D Retained Mode Return Values.

Remarks

IDirect3DRMDevice2::AddUpdateCallback and IDirect3DRMDevice::AddUpdateCallback take a D3DRMUPDATECALLBACK type callback for the d3drmUpdateProc parameter. With DirectX version 6.0, IDirect3DRMDevice3 introduced the newer D3DRMDEVICE3UPDATECALLBACK callback.

See Also

IDirect3DRMDevice3::DeleteUpdateCallback, IDirect3DRMDevice3::Update, D3DRMDEVICE3UPDATECALLBACK

IDirect3DRMDevice3::DeleteUpdateCallback

IDirect3DRMDevice3

Removes an update callback function that was added by using the IDirect3DRMDevice3::AddUpdateCallback method.

Syntax

HRESULT DeleteUpdateCallback(
  D3DRMDEVICE3UPDATECALLBACK d3drmUpdateProc,
  LPVOID arg
  );

Parameters

d3drmUpdateProc
Pointer to an application-defined callback function, D3DRMDEVICE3UPDATECALLBACK.
arg
Pointer to private data that was passed to the update callback function.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return values, see Direct3D Retained Mode Return Values.

Remarks

IDirect3DRMDevice2::DeleteUpdateCallback and IDirect3DRMDevice::DeleteUpdateCallback take a D3DRMUPDATECALLBACK type callback for the d3drmUpdateProc parameter. With DirectX version 6.0, IDirect3DRMDevice3 introduced the newer D3DRMDEVICE3UPDATECALLBACK callback.

See Also

IDirect3DRMDevice3::AddUpdateCallback, IDirect3DRMDevice3::Update, D3DRMDEVICE3UPDATECALLBACK

IDirect3DRMDevice3::FindPreferredTextureFormat

IDirect3DRMDevice3

Finds a texture format that meets the user criteria and that the underlying Immediate Mode device supports. For optimal performance of the texture cache, use this function to choose the pixel format of texture surfaces.

Syntax

HRESULT FindPreferredTextureFormat(
  DWORD dwBitDepths,
  DWORD dwFlags,
  LPDDPIXELFORMAT  lpDDPF);

Parameters

dwBitDepths
Requested texture format bit depth. Specify zero to indicate that any bit depth is acceptable. Specify other values, using a logical combination of one or more of the following DirectDraw bit-depth flags.
DDBD_4
DDBD_8
DDBD_16
DDBD_24
DDBD_32
dwFlags
Flags that specify additional requirements. Specify zero to use the default preferences. Other valid values must be a logical combination of one or more of the following values.
D3DRMFPTF_ALPHA
The returned texture format must have an alpha channel.
D3DRMFPTF_NOALPHA
The returned texture format must not have an alpha channel. Omit both the D3DRMFPTF_ALPHA and D3DRMFPTF_NOALPHA flags to indicate that the absence of an alpha channel is preferred, but not required.
D3DRMFPTF_PALETTIZED
The returned texture format must be palettized.
D3DRMFPTF_NOTPALETTIZED
The returned texture format must not be palettized. Omit both the D3DRMFPTF_PALETTIZED and D3DRMFPTF_NOTPALETTIZED flags to indicate that the absence of a palette is preferred, but not required.
lpDDPF
Pointer to receive the texture format.

Return Value

Returns one of the following values.
D3DRMERR_TEXTUREFORMATNOTFOUND
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

FindPreferredTextureFormat returns D3DRMERR_TEXTUREFORMATNOTFOUND if the does not find an acceptable format.

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMDevice3::GetBufferCount

IDirect3DRMDevice3

Retrieves the value set in a call to the IDirect3DRMDevice3::SetBufferCount method.

Syntax

DWORD GetBufferCount( );

Return Value

Returns the number of buffers—one for single-buffering, two for double-buffering, and so on.

IDirect3DRMDevice3::GetColorModel

IDirect3DRMDevice3

Retrieves the color model of a device.

Syntax

D3DCOLORMODEL GetColorModel( );

Return Value

Returns a value from the D3DCOLORMODEL enumerated type that describes the Direct3D color model (RGB or monochrome).

See Also

Color Models

IDirect3DRMDevice3::GetDirect3DDevice2

IDirect3DRMDevice3

Retrieves a pointer to an IDirect3DDevice2 Immediate Mode device.

Syntax

HRESULT GetDirect3DDevice2(
  LPDIRECT3DDEVICE2 *lplpD3DDevice
  );

Parameters

lplpD3DDevice
Address of a pointer that is initialized with a pointer to an IDirect3DDevice2 Immediate Mode device object.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

The IDirect3DDevice2 device will support the DrawPrimitive interface and execute buffers and is required for progressive meshes and for alpha blending and sorting of transparent objects.

IDirect3DRMDevice3::GetDither

IDirect3DRMDevice3

Retrieves the dither flag for the device.

Syntax

BOOL GetDither( );

Return Value

Returns TRUE if the dither flag is set, or FALSE otherwise.

See Also

IDirect3DRMDevice3::SetDither

IDirect3DRMDevice3::GetHeight

IDirect3DRMDevice3

Retrieves the height, in pixels, of a device. This method is a convenience function.

Syntax

DWORD GetHeight( );

Return Value

Returns the height.

IDirect3DRMDevice3::GetQuality

IDirect3DRMDevice3

Retrieves the rendering quality for the device.

Syntax

D3DRMRENDERQUALITY GetQuality( );

Return Value

Returns one or more of the members of the enumerated types represented by the D3DRMRENDERQUALITY enumerated type.

See Also

IDirect3DRMDevice3::SetQuality

IDirect3DRMDevice3::GetRenderMode

IDirect3DRMDevice3

Retrieves the current transparency flags.

Syntax

DWORD GetRenderMode( );

Return Value

Returns the value of the current transparency flags.

Remarks

Transparency flags have the following values.
Flag | Value
No flag set (default) | 0
D3DRMRENDERMODE_BLENDEDTRANSPARENCY | 1
D3DRMRENDERMODE_DISABLESORTEDALPHAZWRITE | 32
D3DRMRENDERMODE_LIGHTINMODELSPACE | 8
D3DRMRENDERMODE_SORTEDTRANSPARENCY | 2
D3DRMRENDERMODE_VIEWDEPENDENTSPECULAR | 16

See Also

IDirect3DRMDevice3::SetRenderMode

IDirect3DRMDevice3::GetShades

IDirect3DRMDevice3

Retrieves the number of shades in a ramp of colors used for shading in the monochromatic (or ramp) model.

Syntax

DWORD GetShades( );

Return Value

Returns the number of shades.

See Also

IDirect3DRMDevice3::SetShades

IDirect3DRMDevice3::GetStateChangeOptions

IDirect3DRMDevice3

Retrieves the state change options flags associated with a render or light state. See Eliminating Redundant State Changes for more details.

Syntax

HRESULT GetStateChangeOptions(
  DWORD dwStateClass,
  DWORD dwStateNum,
  LPDWORD pdwFlags
  );

Parameters

dwStateClass
Class of states to which this state belongs. The value can be D3DRMSTATECHANGE_LIGHT or D3DRMSTATECHANGE_RENDER.
dwStateNum
Appropriate D3DRENDERSTATE or D3DLIGHTSTATE number. A zero value indicates that all states of the given class should be affected.
pdwFlags
Pointer to the options flags. Contains one of the following values:
D3DRMSTATECHANGE_NONVOLATILE
D3DRMSTATECHANGE_VOLATILE

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

This method was introduced with DirectX version 6.0.

The following example code gets the options on the texture handle render state.

lpDirect3DRMDev3->GetStateChangeOptions(D3DRMSTATECHANGE_RENDER,
                          D3DRENDERSTATE_TEXTUREHANDLE, &dwFlags);

See Also

IDirect3DRMDevice3::SetStateChangeOptions

IDirect3DRMDevice3::GetTextureQuality

IDirect3DRMDevice3

Retrieves the current texture quality parameter for the device. Texture quality is relevant only for an RGB device.

Syntax

D3DRMTEXTUREQUALITY GetTextureQuality( );

Return Value

Returns one of the members of the D3DRMTEXTUREQUALITY enumerated type.

See Also

IDirect3DRMDevice3::SetTextureQuality

IDirect3DRMDevice3::GetTrianglesDrawn

IDirect3DRMDevice3

Retrieves the number of triangles drawn to a device since its creation. This method is a convenience function.

Syntax

DWORD GetTrianglesDrawn( );

Return Value

Returns the number of triangles.

Remarks

The number of triangles includes those that were passed to the renderer but were not drawn because they were backfacing (facing away from the camera). The number does not include triangles that were rejected for lying outside of the viewing frustum.

IDirect3DRMDevice3::GetViewports

IDirect3DRMDevice3

Constructs a Direct3DRMViewportArray object that represents the viewports currently constructed from the device.

Syntax

HRESULT GetViewports(
  LPDIRECT3DRMVIEWPORTARRAY *lplpViewports
  );

Parameters

lplpViewports
Address of a pointer that is initialized with a valid Direct3DRMViewportArray object if the call succeeds.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

IDirect3DRMDevice3::GetWidth

IDirect3DRMDevice3

Retrieves the width, in pixels, of a device. This method is a convenience function.

Syntax

DWORD GetWidth( );

Return Value

Returns the width of the device, in pixels.

IDirect3DRMDevice3::GetWireframeOptions

IDirect3DRMDevice3

Retrieves the wire-frame options of a given device.

Syntax

DWORD GetWireframeOptions( );

Return Value

Returns a bitwise or one of the following values.

D3DRMWIREFRAME_CULL
The backfacing faces are not drawn.
D3DRMWIREFRAME_HIDDENLINE
Wire-frame-rendered lines are obscured by nearer objects.

IDirect3DRMDevice3::Init

IDirect3DRMDevice3

Not implemented on the Microsoft® Windows® platform.

Syntax

HRESULT Init(
  ULONG width,
  ULONG height
  );

IDirect3DRMDevice3::InitFromClipper

IDirect3DRMDevice3

Initializes an IDirect3DDevice2 device from a specified DirectDrawClipper object using IDirect3DRM3::CreateDevice.

Syntax

HRESULT InitFromClipper(
  LPDIRECTDRAWCLIPPER lpDDClipper,
  LPGUID lpGUID,
  int width,
  int height
  );

Parameters

lpDDClipper
Pointer to the DirectDrawClipper object to use as an initializer.
lpGUID
Direct3D device driver to use.
width and height
Width and height of the device in pixels.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

IDirect3DRMDevice3::InitFromD3D2

IDirect3DRMDevice3

Initializes an IDirect3DRMDevice2 Retained Mode device from an IDirect3D2 Immediate Mode object and an IDirect3DDevice2 Immediate Mode device.

Syntax

HRESULT InitFromD3D2(
  LPDIRECT3D2 lpD3D,
  LPDIRECT3DDEVICE2 lpD3DIMDev
  );

Parameters

lpD3D
Pointer to the IDirect3D2 Immediate Mode object to use to initialize the Retained Mode device.
lpD3DIMDev
Pointer to the IDirect3DDevice2 Immediate Mode device to use to initialize the Retained Mode device.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

The IDirect3DRMDevice2 device initialized from IDirect3DDevice2 will support the DrawPrimitive interface and execute buffers and is required for progressive meshes and for alpha blending and sorting of transparent objects.

IDirect3DRMDevice3::InitFromSurface

IDirect3DRMDevice3

Initializes a IDirect3DDevice2 device from a specified DirectDraw surface, using the IDirect3DRM3::CreateDevice method.

Syntax

HRESULT InitFromSurface(
  LPGUID lpGUID,
  LPDIRECTDRAW lpDD,
  LPDIRECTDRAWSURFACE lpDDSBack
  );

Parameters

lpGUID
Pointer to the globally unique identifier (GUID) that identifies the Direct3D device driver to use.
lpDD
Pointer to the interface of a DirectDraw object that created the DirectDrawSurface.
lpDDSBack
Pointer to the interface of a DirectDrawSurface back buffer onto which the device will render.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

The IDirect3DRMDevice2 device initialized will support the DrawPrimitive methods and execute buffers, and is required for progressive meshes and for alpha blending and sorting of transparent objects.

IDirect3DRMDevice3::LightStateChange

IDirect3DRMDevice3

Changes a light state or informs Direct3D Retained Mode of a change to a render state. If the D3DRMSTATECHANGE_NONVOLATILE flag is associated with the render state, Retained Mode eliminates redundant changes to the state made by using IDirect3DRMDevice3 (it won't set the state to a value equal to its current value). See Eliminating Redundant State Changes for more details.

Syntax

HRESULT LightStateChange(
  DWORD dwStateNum,
  DWORD dwVal,
  DWORD dwFlags
  );

Parameters

dwStateNum
Appropriate D3DLIGHTSTATE number.
dwVal
New value of the state.
dwFlags
Flag that indicates whether Retained Mode should update the cache only. If this flag is set to D3DRMSTATECHANGE_UPDATEONLY, only the value held in the internal cache is updated. You can use D3DRMSTATECHANGE_UPDATEONLY to indicate a state change.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

This method was introduced with DirectX version 6.0.

The following code sets the material handle light state, eliminating redundant changes if the D3DRMSTATECHANGE_NONVOLATILE flag has been associated with the state.

lpDirect3DRMDev3->LightStateChange(D3DLIGHTSTATE_MATERIAL, hMat, 0);

The following indicates a change to the fog mode.

lpDirect3DRMDev3->LightStateChange(D3DLIGHTSTATE_FOGMODE, D3DFOG_NONE,
                                   D3DRMSTATECHANGE_UPDATEONLY);

See Also

IDirect3DRMDevice3::SetStateChangeOptions

IDirect3DRMDevice3::RenderStateChange

IDirect3DRMDevice3

Changes a render state or indicates a change to a render state. If the D3DRMSTATECHANGE_NONVOLATILE flag is associated with the render state, Retained Mode eliminates redundant changes to the state made by using IDirect3DRMDevice3 (it won't set the state to a value equal to its current value). See Eliminating Redundant State Changes for more details.

Syntax

HRESULT RenderStateChange(
  DWORD dwStateNum,
  DWORD dwVal,
  DWORD dwFlags
  );

Parameters

dwStateNum
Appropriate D3DRENDERSTATE number.
dwVal
New value of the state.
dwFlags
Flag that indicates whether to update the cache only. If this flag is set to D3DRMSTATECHANGE_UPDATEONLY, only the value held in the internal cache is updated. You can use D3DRMSTATECHANGE_UPDATEONLY to indicate a change made to the state.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

This method was introduced with DirectX version 6.0.

The following code sets the fill mode render state, eliminating redundant changes if the D3DRMSTATECHANGE_NONVOLATILE flag has been associated with the state.

lpDirect3DRMDev3->RenderStateChange(D3DRENDERSTATE_FILLMODE,
                          D3DFILL_SOLID, 0);

The following code indicates a change to the texture handle render state.

lpDirect3DRMDev3->RenderStateChange(D3DRENDERSTATE_TEXTUREHANDLE, hTex,
                                    D3DRMSTATECHANGE_UPDATEONLY);

See Also

IDirect3DRMDevice3::SetStateChangeOptions

IDirect3DRMDevice3::SetBufferCount

IDirect3DRMDevice3

Sets the number of buffers currently being used by the application.

Syntax

HRESULT SetBufferCount(
  DWORD dwCount
  );

Parameters

dwCount
Number of buffers—one for single-buffering, two for double-buffering, and so on. The default value is one, which is correct only for a single-buffered window operation.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

An application that employs double-buffering or triple-buffering must use this method to inform the system of how many buffers it is using so that the system can calculate how much of the window to clear and update on each frame.

See Also

IDirect3DRMDevice3::GetBufferCount

IDirect3DRMDevice3::SetDither

IDirect3DRMDevice3

Sets the dither flag for the device.

Syntax

HRESULT SetDither(
  BOOL bDither
  );

Parameters

bDither
New dithering mode for the device. The default is TRUE.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMDevice3::GetDither

IDirect3DRMDevice3::SetQuality

IDirect3DRMDevice3

Sets the rendering quality of a device.

Syntax

HRESULT SetQuality (
  D3DRMRENDERQUALITY rqQuality
  );

Parameters

rqQuality
One or more of the members of the enumerated types represented by the D3DRMRENDERQUALITY enumerated type. The default setting is D3DRMRENDER_FLAT.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

The rendering quality is the maximum quality at which rendering can take place on the rendering surface of that device.

An object's quality has three components: shade mode (flat or Gouraud; Phong is not yet implemented and will default to Gouraud shading), lighting type (on or off), and fill mode (point, wire frame, or solid).

You set the quality of a device with SetQuality. By default it is D3DRMRENDER_FLAT (flat shading, lights on, and solid fill).

You can set the quality of a Direct3DRMProgressiveMesh or Direct3DRMMeshBuilder3 object with their respective SetQuality methods. By default, the quality of these objects is D3DRMRENDER_GOURAUD (Gouraud shading, lights on, and solid fill).

Tip: Gouraud shading gets better performance on progressive mesh objects that change level of detail, often or quickly.

Direct3D Retained Mode renders an object at the lowest quality setting based on the device and the object's current setting for each individual component. For example, if the object's current quality setting is D3DRMRENDER_GOURAUD, and the device is D3DRMRENDER_FLAT, the object will be rendered with flat shading, solid fill, and lights on.

If the object's current quality setting is D3DRMSHADE_GOURAUD|D3DRMLIGHT_OFF|D3DRMFILL_WIREFRAME, and the device's quality setting is D3DRMSHADE_FLAT|D3DRMLIGHT_ON|D3DRMFILL_POINT, the object will be rendered with flat shading, lights off, and point fill mode.

These rules apply to Direct3DRMMeshBuilder3 objects and Direct3DRMProgressiveMesh objects. However, Direct3DRMMesh objects do not follow these rules. Mesh objects ignore the device's quality settings and use the group quality setting (which defaults to D3DRMRENDER_GOURAUD).

See Also

IDirect3DRMDevice3::GetQuality

IDirect3DRMDevice3::SetRenderMode

IDirect3DRMDevice3

Sets the transparency mode. The mode type determines how transparent objects will be rendered. The default mode renders transparent objects with stippled transparency.

Syntax

HRESULT SetRenderMode(
  DWORD dwFlags
  );

Parameters

dwFlags
One or more of the transparent mode flags. The default (dwFlags = 0) sets the transparency mode to stippled transparency. Stippled (or "screen door") transparency is achieved by replacing some of the pixels in one image with pixels from the other image (as if you are seeing one image through a screen door painted with the second image).

In addition, flags can have one or more of the following values:

D3DRMRENDERMODE_BLENDEDTRANSPARENCY (dwFlags = 1) sets the transparency mode to alpha blending. Blended transparency is achieved by combining two images by adding the color values at each pixel.
D3DRMRENDERMODE_DISABLESORTEDALPHAZWRITE (dwFlags = 32) specifies that no depth information will be written to the z-buffer when drawing sorted, transparent objects.
D3DRMRENDERMODE_LIGHTINMODELSPACE (dwFlags = 8). Reserved. Do not use.
D3DRMRENDERMODE_SORTEDTRANSPARENCY (dwFlags = 2) sets the transparency mode so that transparent polygons in the scene are buffered, sorted, and rendered in a second pass. This flag has no effect if the D3DRMRENDERMODE_BLENDEDTRANSPARENCY flag is not also set. Transparent polygons in external visuals or user visuals are not sorted. Only native Direct3D Retained Mode visuals (such as D3DRMMesh objects and D3DRMMeshBuilder objects) are sorted.
D3DRMRENDERMODE_VIEWDEPENDENTSPECULAR (dwFlags = 16) enables more realistic specular lights that depend both on the light direction and the viewer's location. Previous versions of DirectX Foundation only supported flat specular light that did not take into account the viewer's location. If this flag is set, Direct3D Retained Mode uses the D3DLIGHT2 structure to define the light type when calling Direct3D Immediate Mode's IDirect3DLight::SetLight. If this flag is not set, Direct3D Retained Mode uses the D3DLIGHT structure, and you will get the lighting behavior of previous versions of DirectX.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

If the D3DRMRENDERMODE_BLENDEDTRANSPARENCY and D3DRMRENDERMODE_SORTEDTRANSPARENCY flags are set together, it ensures that when two transparent objects are rendered one on top of the other, the image will blend in the correct order to ensure the right visual result.

The D3DRMRENDERMODE_SORTEDTRANSPARENCY turns on the per triangle back-to-front sorting of alpha polygons. Only native Direct3D Retained Mode visuals (such as D3DRMMesh objects and D3DRMMeshBuilder objects) are sorted. You cannot add triangles from external visuals to the sorted list.

The D3DRMRENDERMODE_BLENDEDTRANSPARENCY flag turns on true alpha blending as opposed to stippled alpha. In true alpha blending, the pixels of overlapping triangles are blended together. In stippled alpha, some pixels from the triangle in front are not drawn revealing the triangle below (this is also called screen-door transparency). When doing stippled alpha, it is not necessary to sort triangles since the result is the same no matter what order you render the triangles in.

The only valid parameters to SetSortMode are 0 (stippled alpha with no sorting), BLENDEDTRANSPARENCY (true alpha with no sorting), and both BLENDEDTRANSPARENCY and SORTEDTRANSPARENCY (per triangle sorted true alpha).

See Also

IDirect3DRMDevice3::GetRenderMode

IDirect3DRMDevice3::SetShades

IDirect3DRMDevice3

Sets the number of shades in a ramp of colors used for shading in the monochromatic (or ramp) model.

Syntax

HRESULT SetShades(
  DWORD ulShades
  );

Parameters

ulShades
New number of shades. This parameter must be a power of two. The default is 32.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMDevice3::GetShades

IDirect3DRMDevice3::SetStateChangeOptions

IDirect3DRMDevice3

Changes the options flags associated with one or more render or light states. The default value for all render and light states is D3DRMSTATECHANGE_VOLATILE. If the D3DRMSTATECHANGE_NONVOLATILE flag is associated with a render or light state, Direct3D Retained Mode caches the value and eliminates redundant changes (it won't set the state to a value equal to its current value). You must, however, indicate when you change the state with either the LightStateChange or RenderStateChange method. See Eliminating Redundant State Changes for more details.

Syntax

HRESULT SetStateChangeOptions(
  DWORD dwStateClass,
  DWORD dwStateNum,
  DWORD dwFlags
  );

Parameters

dwStateClass
Class of states to which this state belongs. The value can be D3DRMSTATECHANGE_LIGHT or D3DRMSTATECHANGE_RENDER.
dwStateNum
Appropriate D3DRENDERSTATE or D3DLIGHTSTATE number. A zero value indicates that all states of the given class should be affected.
dwFlags
Options flags. One of the following values:
D3DRMSTATECHANGE_NONVOLATILE
D3DRMSTATECHANGE_VOLATILE

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

This method was introduced with DirectX version 6.0.

The following code sets the D3DRMSTATECHANGE_NONVOLATILE flag on all render states.

lpDirect3DRMDev3->SetStateChangeOptions(D3DRMSTATECHANGE_RENDER, 0,
                                        D3DRMSTATECHANGE_NONVOLATILE);

The following code sets the D3DRMSTATECHANGE_VOLATILE flag on the texture handle render state.

lpDirect3DRMDev3->SetStateChangeOptions(D3DRMSTATECHANGE_RENDER,
                                        D3DRENDERSTATE_TEXTUREHANDLE,
                                        D3DRMSTATECHANGE_VOLATILE);

See Also

IDirect3DRMDevice3::GetStateChangeOptions

IDirect3DRMDevice3::SetTextureQuality

IDirect3DRMDevice3

Sets the texture quality for the device.

Syntax

HRESULT SetTextureQuality(
  D3DRMTEXTUREQUALITY tqTextureQuality
  );

Parameters

tqTextureQuality
One of the members of the D3DRMTEXTUREQUALITY enumerated type. The default is D3DRMTEXTURE_NEAREST.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMDevice3::GetTextureQuality

IDirect3DRMDevice3::Update

IDirect3DRMDevice3

Copies the image that has been rendered to the display. It also provides a heartbeat function to the device driver, letting it know when to update the image.

Syntax

HRESULT Update( );

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

Each call to this method causes the system to call an application-defined callback function, D3DRMDEVICE3UPDATECALLBACK. To add a callback function, use the IDirect3DRMDevice3::AddUpdateCallback method.

IDirect3DRMDevice2::Update and IDirect3DRMDevice::Update cause the system to call a D3DRMUPDATECALLBACK type callback. With DirectX version 6.0, IDirect3DRMDevice3 introduced the newer D3DRMDEVICE3UPDATECALLBACK callback.

See Also

IDirect3DRMDevice3::AddUpdateCallback, D3DRMDEVICE3UPDATECALLBACK


IDirect3DRMDeviceArray

Applications use the methods of the IDirect3DRMDeviceArray interface to organize device objects. This section is a reference to the methods of this interface. For a conceptual overview, see Output Devices.

The IDirect3DRMDeviceArray interface supports the following methods:
GetElement
GetSize

The IDirect3DRMDeviceArray interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:
AddRef
QueryInterface
Release

The Direct3DRMDeviceArray object is obtained by calling the IDirect3DRM3::GetDevices method.

IDirect3DRMDeviceArray::GetElement

IDirect3DRMDeviceArray

Retrieves a specified element in a Direct3DRMDeviceArray object.

Syntax

HRESULT GetElement(
  DWORD index,
  LPDIRECT3DRMDEVICE *lplpD3DRMDevice
  );

Parameters

index
Element in the array.
lplpD3DRMDevice
Address that will be filled with a pointer to an IDirect3DRMDevice interface.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

You can use QueryInterface to obtain a pointer to the version of IDirect3DRMDevice that you want, for example, IDirect3DRMDevice3. You cannot simply cast the lplpD3DRMDevice parameter to a different version. You must use QueryInterface.

IDirect3DRMDeviceArray::GetSize

IDirect3DRMDeviceArray

Retrieves the number of elements contained in a Direct3DRMDeviceArray object.

Syntax

DWORD GetSize( );

Return Value

Returns the number of elements.


IDirect3DRMFace2

Applications use the methods of the IDirect3DRMFace2 interface to interact with a face. A face represents a single polygon in a mesh. An application can set the color, texture, and material of the face by using the IDirect3DRMFace2::SetColor, IDirect3DRMFace2::SetColorRGB, IDirect3DRMFace2::SetTexture, and IDirect3DRMFace2::SetMaterial methods.

Faces are constructed from vertices by using the IDirect3DRMFace2::AddVertex and IDirect3DRMFace2::AddVertexAndNormalIndexed methods. An application can read the vertices of a face by using the IDirect3DRMFace2::GetVertices and IDirect3DRMFace2::GetVertex methods.

In IDirect3DRMFace2, the SetTexture method can now specify a texture whose width and height are not a power of two.

The methods of the IDirect3DRMFace2 interface can be organized into the following groups:

Color | GetColor
 | SetColor
 | SetColorRGB
Materials | GetMaterial
 | SetMaterial
Textures | GetTexture
 | GetTextureCoordinateIndex
 | GetTextureCoordinates
 | SetTexture
 | SetTextureCoordinates
 | SetTextureTopology
Vertices and normals | AddVertex
 | AddVertexAndNormalIndexed
 | GetNormal
 | GetVertex
 | GetVertexCount
 | GetVertexIndex
 | GetVertices

The IDirect3DRMFace2 interface, like all Component Object Model (COM) interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:
AddRef
QueryInterface
Release

In addition, the IDirect3DRMFace2 interface inherits the following methods from the IDirect3DRMObject interface:
AddDestroyCallback
Clone
DeleteDestroyCallback
GetAppData
GetClassName
GetName
SetAppData
SetName

The Direct3DRMFace2 object is obtained by using the IDirect3DRM3::CreateFace method.

IDirect3DRMFace2::AddVertex

IDirect3DRMFace2

Adds a vertex to a Direct3DRMFace2 object.

Syntax

HRESULT AddVertex(
  D3DVALUE x,
  D3DVALUE y,
  D3DVALUE z
  );

Parameters

x, y, and z
The x, y, and z components of the new vertex position.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMFace2::AddVertexAndNormalIndexed

IDirect3DRMFace2

Adds a vertex and a normal to a Direct3DRMFace2 object, using an index for the vertex and an index for the normal in the containing mesh builder. The face, vertex, and normal must already be part of a Direct3DRMMeshBuilder3 object .

Syntax

HRESULT AddVertexAndNormalIndexed(
  DWORD vertex,
  DWORD normal
  );

Parameters

vertex and normal
Indexes of the vertex and normal to add.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMFace2::GetColor

IDirect3DRMFace2

Retrieves the color of a Direct3DRMFace2 object.

Syntax

D3DCOLOR GetColor( );

Return Value

Returns the color.

See Also

IDirect3DRMFace2::SetColor

IDirect3DRMFace2::GetMaterial

IDirect3DRMFace2

Retrieves the material of a Direct3DRMFace2 object.

Syntax

HRESULT GetMaterial(
  LPDIRECT3DRMMATERIAL *lplpMaterial
  );

Parameters

lplpMaterial
Address of the pointer to the Direct3DRMMaterial object applied to the face.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMFace2::SetMaterial

IDirect3DRMFace2::GetNormal

IDirect3DRMFace2

Retrieves the normal vector of a Direct3DRMFace2 object.

Syntax

HRESULT GetNormal(
  D3DVECTOR *lpNormal
  );

Parameters

lpNormal
Address of a D3DVECTOR structure that will be filled with the normal vector of the face.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMFace2::GetTexture

IDirect3DRMFace2

Retrieves the Direct3DRMTexture object applied to a Direct3DRMFace2 object.

Syntax

HRESULT GetTexture(
  LPDIRECT3DRMTEXTURE *lplpTexture
  );

Parameters

lplpTexture
Address of a variable that will be filled with a pointer to the texture applied to the face.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMFace2::SetTexture

IDirect3DRMFace2::GetTextureCoordinateIndex

IDirect3DRMFace2

Retrieves the index of the vertex for texture coordinates in the face's mesh. You pass in the face-relative vertex index in the which parameter, and this method returns the corresponding mesh-relative vertex index.

Syntax

int GetTextureCoordinateIndex(
  DWORD which
  );

Parameters

which
Index within the face of the vertex whose coorresponding mesh vertex index is being retrieved.

Return Value

Returns the face's mesh-relative vertex index.

IDirect3DRMFace2::GetTextureCoordinates

IDirect3DRMFace2

Retrieves the texture coordinates of a vertex in a Direct3DRMFace2 object.

Syntax

HRESULT GetTextureCoordinates(
  DWORD index,
  D3DVALUE *lpU,
  D3DVALUE *lpV
  );

Parameters

index
Index of the vertex.
lpU and lpV
Addresses of variables that are filled with the texture coordinates of the vertex.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMFace2::GetVertex

IDirect3DRMFace2

Retrieves the position and normal of a vertex in a Direct3DRMFace2 object.

Syntax

HRESULT GetVertex(
  DWORD index,
  D3DVECTOR *lpPosition,
  D3DVECTOR *lpNormal
  );

Parameters

index
Index of the vertex.
lpPosition and lpNormal
Addresses of D3DVECTOR structures that will be filled with the position and normal of the vertex, respectively.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMFace2::GetVertexCount

IDirect3DRMFace2

Retrieves the number of vertices in a Direct3DRMFace2 object.

Syntax

int GetVertexCount( );

Return Value

Returns the number of vertices.

IDirect3DRMFace2::GetVertexIndex

IDirect3DRMFace2

Retrieves the index of the vertex in the face's mesh. You pass in the face-relative vertex index in the which parameter, and this method returns the corresponding mesh-relative vertex index.

Syntax

int GetVertexIndex (
  DWORD which
  );

Parameters

which
Index within the face of the vertex whose coorresponding mesh vertex index is being retrieved.

Return Value

Returns the mesh-relative vertex index.

IDirect3DRMFace2::GetVertices

IDirect3DRMFace2

Retrieves the position and normal vector of each vertex in a Direct3DRMFace2 object.

Syntax

HRESULT GetVertices(
  DWORD *lpdwVertexCount,
  D3DVECTOR *lpPosition,
  D3DVECTOR *lpNormal
  );

Parameters

lpdwVertexCount
Address of a variable that contains the number of vertices. If both lpPosition and lpNormal are NULL, lpdwVertexCount is filled with the number of vertices that will be retrieved. This parameter cannot be NULL.
lpPosition and lpNormal
Arrays of D3DVECTOR structures that will be filled with the positions and normal vectors of the vertices, respectively. If both of these parameters are NULL, the method will fill the lpdwVertexCount parameter with the number of vertices that will be retrieved.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMFace2::SetColor

IDirect3DRMFace2

Sets a Direct3DRMFace2 object to a given color.

Syntax

HRESULT SetColor(
  D3DCOLOR color
  );

Parameters

color
Color to set. Be sure to set the alpha component as well as the red, green, and blue color components or your objects might not be visible. The RGBA_MAKE DirectX macro allows you to specify these values.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMFace2::GetColor

IDirect3DRMFace2::SetColorRGB

IDirect3DRMFace2

Sets a Direct3DRMFace2 object to a given color.

Syntax

HRESULT SetColorRGB(
  D3DVALUE red,
  D3DVALUE green,
  D3DVALUE blue
  );

Parameters

red, green, and blue
The red, green, and blue components of the color.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMFace2::SetMaterial

IDirect3DRMFace2

Sets the material of a Direct3DRMFace2 object.

Syntax

HRESULT SetMaterial(
  LPDIRECT3DRMMATERIAL lpD3DRMMaterial
  );

Parameters

lpD3DRMMaterial
Address of the material.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMFace2::GetMaterial

IDirect3DRMFace2::SetTexture

IDirect3DRMFace2

Sets the texture of a Direct3DRMFace2 object.

Syntax

HRESULT SetTexture(
  LPDIRECT3DRMTEXTURE lpD3DRMTexture
  );

Parameters

lpD3DRMTexture
Address of the texture.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

Starting with DirectX Foundation 6, the width and height of the texture are not required to be a power of two.

See Also

IDirect3DRMFace2::GetTexture

IDirect3DRMFace2::SetTextureCoordinates

IDirect3DRMFace2

Sets the texture coordinates of a specified vertex in a Direct3DRMFace2 object.

Syntax

HRESULT SetTextureCoordinates(
  DWORD vertex,
  D3DVALUE u,
  D3DVALUE v
  );

Parameters

vertex
Index of the vertex to be set. For example, if the face were a triangle, the possible vertex indices would be 0, 1, and 2.
u and v
Texture coordinates to assign to the specified vertex.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMFace2::SetTextureTopology

IDirect3DRMFace2

Sets the texture topology of a Direct3DRMFace2 object.

Syntax

HRESULT SetTextureTopology(
  BOOL cylU,
  BOOL cylV
  );

Parameters

cylU and cylV
Specify whether the texture has a cylindrical topology in the u and v dimensions.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

Several interfaces provide SetTextureTopology methods. See IDirect3DRMeshBuilder3::SetTextureTopology for more information about the relationship between the SetTextureTopology methods, and for more information about the purpose of the cylU and cylV parameters.


IDirect3DRMFaceArray

Applications use the methods of the IDirect3DRMFaceArray interface to organize faces in a mesh. For more information about faces, see IDirect3DRMFace2.

The IDirect3DRMFaceArray interface supports the following methods:
GetElement
GetSize

The IDirect3DRMFaceArray interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:
AddRef
QueryInterface
Release

The Direct3DRMFaceArray object is obtained by calling the IDirect3DRMMeshBuilder3::GetFaces method.

IDirect3DRMFaceArray::GetElement

IDirect3DRMFaceArray

Retrieves a specified element in a Direct3DRMFaceArray object.

Syntax

HRESULT GetElement(
  DWORD index,
  LPDIRECT3DRMFACE *lplpD3DRMFace
  );

Parameters

index
Element in the array.
lplpD3DRMFace
Address that will be filled with a pointer to an IDirect3DRMFace interface.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMFaceArray::GetSize

IDirect3DRMFaceArray

Retrieves the number of elements contained in a Direct3DRMFaceArray object.

Syntax

DWORD GetSize( );

Return Value

Returns the number of elements.


IDirect3DRMFrame3

Applications use the methods of the IDirect3DRMFrame3 interface to interact with frames—an object's frame of reference. For a conceptual overview, see Frames.

The IDirect3DRMFrame3 interface is an extension of the IDirect3DRMFrame2 interface. IDirect3DRMFrame3 provides methods that enable additional transformation capabilities, setting and retrieving traversal options, and setting and retrieving the scene fogging method.

IDirect3DRMFrame2 builds upon the functionality of IDirect3DRMFrame by providing additional methods that enable using materials, bounding boxes, and axes with frames. IDirect3DRMFrame2 also adds a RayPick method to calculate the intersections of visuals in the frame with a ray of specified position and direction. In addition, IDirect3DRMFrame2 has one changed method AddMoveCallback2.

See Interface Changes for a list of all the methods added by each interface.

The methods of the IDirect3DRMFrame3 interface can be organized into the following groups:

Axes | GetAxes
 | GetInheritAxes
 | SetAxes
 | SetInheritAxes
Background | GetSceneBackground
 | GetSceneBackgroundDepth
 | SetSceneBackground
 | SetSceneBackgroundDepth
 | SetSceneBackgroundImage (obsolete)
 | SetSceneBackgroundRGB
Bounding Box | GetBox
 | GetBoxEnable
 | GetHierarchyBox
 | SetBox
 | SetBoxEnable
Color | GetColor
 | SetColor
 | SetColorRGB
Fog | GetSceneFogColor
 | GetSceneFogEnable
 | GetSceneFogMethod
 | GetSceneFogMode
 | GetSceneFogParams
 | SetSceneFogColor
 | SetSceneFogEnable
 | SetSceneFogMethod
 | SetSceneFogMode
 | SetSceneFogParams
Hierarchies | AddChild
 | DeleteChild
 | GetChildren
 | GetParent
 | GetScene
Lighting | AddLight
 | DeleteLight
 | GetLights
Loading | Load
Material | GetMaterial
 | GetMaterialOverride
 | SetMaterial
 | SetMaterialOverride
Material modes | GetMaterialMode
 | SetMaterialMode
Positioning and movement | AddMoveCallback
 | AddRotation
 | AddScale
 | AddTranslation
 | DeleteMoveCallback
 | GetOrientation
 | GetPosition
 | GetRotation
 | GetVelocity
 | LookAt
 | Move
 | SetOrientation
 | SetPosition
 | SetQuaternion
 | SetRotation
 | SetVelocity
Ray Picking | RayPick
Sorting | GetSortMode
 | GetZbufferMode
 | SetSortMode
 | SetZbufferMode
Textures | GetTexture
 | SetTexture
Transformations | AddTransform
 | GetTransform
 | InverseTransform
 | InverseTransformVectors
 | Transform
 | TransformVectors
Traversal | GetTraversalOptions
 | SetTraversalOptions
Visual objects | AddVisual
 | DeleteVisual
 | GetVisuals

The IDirect3DRMFrame3 interface, like all Component Object Model (COM) interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:
AddRef
QueryInterface
Release

In addition, the IDirect3DRMFrame3 interface inherits the following methods from the IDirect3DRMObject interface:
AddDestroyCallback
Clone
DeleteDestroyCallback
GetAppData
GetClassName
GetName
SetAppData
SetName

Obtain the Direct3DRMFrame3 object by using the IDirect3DRM3::CreateFrame method.


IDirect3DRMFrameArray

Applications use the methods of the IDirect3DRMFrameArray interface to organize frame objects. This section is a reference to the methods of this interface. For a conceptual overview, see Frames.

The IDirect3DRMFrameArray interface supports the following methods:
GetElement
GetSize

The IDirect3DRMFrameArray interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:
AddRef
QueryInterface
Release

The Direct3DRMFrameArray object is obtained by calling the IDirect3DRMPickedArray::GetPick, IDirect3DRMPicked2Array::GetPick, or IDirect3DRMFrame3::GetChildren method.

IDirect3DRMFrameArray::GetElement

IDirect3DRMFrameArray

Retrieves a specified element in a Direct3DRMFrameArray object.

Syntax

HRESULT GetElement(
  DWORD index,
  LPDIRECT3DRMFRAME  *lplpD3DRMFrame
  );

Parameters

index
Element in the array.
lplpD3DRMFrame
Address that will be filled with a pointer to an IDirect3DRMFrame interface.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

You can use QueryInterface to obtain a pointer to the version of IDirect3DRMFrame that you want, for example, IDirect3DRMFrame3. You cannot simply cast the lplpD3DRMFrame parameter to a different version. You must use QueryInterface.

IDirect3DRMFrameArray::GetSize

IDirect3DRMFrameArray

Retrieves the number of elements contained in a Direct3DRMFrameArray object.

Syntax

DWORD GetSize( );

Return Value

Returns the number of elements.


IDirect3DRMInterpolator

Interpolators provide a way of storing actions and applying them to objects with automatic calculation of in-between values. With an interpolator you can blend colors, move objects smoothly between positions, morph meshes, and perform many other transformations.

The IDirect3DRMInterpolator interface is a superset of the IDirect3DRMAnimation2 interface that increases the kinds of object parameters you can animate. While IDirect3DRMAnimation2 allows animation of an object's position, size, and orientation, IDirect3DRMInterpolator further enables animation of color, meshes, texture, and material.

For a conceptual overview, see IDirect3DRMInterpolator Overview.

In addition to the standard IUnknown and IDirect3DRMObject methods, IDirect3DRMInterpolator contains the following methods:

Attaching Objects | AttachObject
 | DetachObject
 | GetAttachedObjects
Interpolating | GetIndex
 | Interpolate
 | SetIndex

The IDirect3DRMInterpolator interface, like all Component Object Model (COM) interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:
AddRef
QueryInterface
Release

In addition, IDirect3DRMInterpolator interface inherits the following methods from the IDirect3DRMObject interface:
AddDestroyCallback
Clone
DeleteDestroyCallback
GetAppData
GetClassName
GetName
SetAppData
SetName

IDirect3DRMInterpolator::AttachObject

IDirect3DRMInterpolator

Connects an object to the interpolator.

Syntax

HRESULT AttachObject(
  LPDIRECT3DRMOBJECT lpD3DRMObject
  )

Parameters

lpD3DRMObject
Address of the IDirect3DRMObject object to be attached to the interpolator.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

The attached object can be another interpolator or an object of type x where the interpolator is of type xInterpolator. For example, a Viewport can be attached to a ViewportInterpolator. The interpolator types are:

  • FrameInterpolator
  • LightInterpolator
  • MaterialInterpolator
  • MeshInterpolator
  • TextureInterpolator
  • ViewportInterpolator

IDirect3DRMInterpolator::DetachObject

IDirect3DRMInterpolator

Detaches an object from the interpolator.

Syntax

HRESULT DetachObject(
  LPDIRECT3DRMOBJECT lpD3DRMObject
  )

Parameters

lpD3DRMObject
Address of the IDirect3DRMObject object to be detached from the interpolator.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMInterpolator::GetAttachedObjects

IDirect3DRMInterpolator

Retrieves an array of objects currently attached to the interpolator.

Syntax

HRESULT GetAttachedObjects(
  LPDIRECT3DRMOBJECTARRAY lpD3DRMObjectArray
  )

Parameters

lpD3DRMObjectArray
Address of an IDirect3DRMObjectArray object containing the IDirect3DRMObject objects currently attached to the interpolator.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMInterpolator::GetIndex

IDirect3DRMInterpolator

Retrieves the interpolator's current internal index (time).

Syntax

D3DVALUE GetIndex( )

Return Value

Returns a D3DVALUE that contains the interpolator's current internal index.

Remarks

Every key stored in an interpolator has an index value. When a key is recorded (by using a method), the key is stamped with the current interpolator index value. The key's index value does not change after being stamped.

IDirect3DRMInterpolator::Interpolate

IDirect3DRMInterpolator

Generates a series of actions by interpolating between keys stored in the interpolator. The actions are then applied to the specified object. If no object is specified, the actions are applied to the currently attached objects.

Syntax

HRESULT Interpolate(
  D3DVALUE d3dVal,
  LPDIRECT3DRMOBJECT lpD3DRMObject,
  D3DRMINTERPOLATIONOPTIONS d3drmInterpFlags
  )

Parameters

d3dVal
A D3DVALUE that contains the interpolator's current internal index.
lpD3DRMObject
Address of the IDirect3DRMObject object which will be assigned interpolated values for all properties stored in the interpolator. Can be NULL, in which case the property values of all attached objects will be set to interpolated values.
d3drmInterpFlags
One of several flags that control the kind of interpolation done. Possible values are:
D3DRMINTERPOLATION_CLOSED
D3DRMINTERPOLATION_LINEAR
D3DRMINTERPOLATION_NEAREST
D3DRMINTERPOLATION_OPEN
D3DRMINTERPOLATION_SLERPNORMALS
D3DRMINTERPOLATION_SPLINE
D3DRMINTERPOLATION_VERTEXCOLOR
See Interpolation Options for a description of these options.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMInterpolator::SetIndex

IDirect3DRMInterpolator

Sets the interpolator's internal index (time) to the specified value. If other interpolators are attached to the interpolator, this method recursively synchronizes their indices to the same value.

Syntax

HRESULT SetIndex(
  D3DVALUE d3dVal
  )

Parameters

d3dVal
The time to set for the interpolator's internal index.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

Every key stored in an interpolator has an index value. When a key is recorded (by using a method), the key is stamped with the current interpolator index value. The key's index value does not change after being stamped.


IDirect3DRMLight

Applications use the methods of the IDirect3DRMLight interface to interact with light objects. This section is a reference to the methods of this interface. For a conceptual overview, see Lights.

The methods of the IDirect3DRMLight interface can be organized into the following groups:
Attenuation | GetConstantAttenuation
 | GetLinearAttenuation
 | GetQuadraticAttenuation
 | SetConstantAttenuation
 | SetLinearAttenuation
 | SetQuadraticAttenuation
Color | GetColor
 | SetColor
 | SetColorRGB
Enable frames | GetEnableFrame
 | SetEnableFrame
Light types | GetType
 | SetType
Range | GetRange
 | SetRange
Spotlight options | GetPenumbra
 | GetUmbra
 | SetPenumbra
 | SetUmbra

The IDirect3DRMLight interface, like all Component Object Model (COM) interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:
AddRef
QueryInterface
Release

In addition, the IDirect3DRMLight interface inherits the following methods from the IDirect3DRMObject interface:
AddDestroyCallback
Clone
DeleteDestroyCallback
GetAppData
GetClassName
GetName
SetAppData
SetName

The Direct3DRMLight object is obtained by using the IDirect3DRM3::CreateLight or IDirect3DRM3::CreateLightRGB method.

IDirect3DRMLight::GetColor

IDirect3DRMLight

Retrieves the color of the current Direct3DRMLight object.

Syntax

D3DCOLOR GetColor( );

Return Value

Returns the color.

See Also

IDirect3DRMLight::SetColor

IDirect3DRMLight::GetConstantAttenuation

IDirect3DRMLight

Retrieves the constant attenuation factor for the Direct3DRMLight object.

Syntax

D3DVALUE GetConstantAttenuation( );

Return Value

Returns the constant attenuation value.

Remarks

Lights that have a location (those that are not infinitely far away) can have attenuation factors to calculate the attenuation of the light based on the distance from the light.

The light attenuation formula used depends on whether or not the D3DRMRENDERMODE_VIEWDEPENDENTSPECULAR flag is set. This flag is set in IDirect3DRMDevice3::SetRenderMode.

If the D3DRMRENDERMODE_VIEWDEPENDENTSPECULAR flag is set, the following formulae are used for light attenuation.

The formula for the normalized distance is:

normalized_distance = (distance_from_light - light_range)/light_range

The default light_range value is 256 modeling-space units.

The formula for the total attenuation factor is:

constant_attenuation_factor + normalized_distance * linear_attenuation_factor + (normalized_distance**2) * quadratic_attenuation_factor

If the D3DRMRENDERMODE_VIEWDEPENDENTSPECULAR flag is not set, the following formula is used for light attentuation.

1 / [constant_attenuation_factor + distance * linear_attenuation_factor + (distance**2) * quadratic_attenuation_factor]

The total attenuation factor cannot be greater than 1.

When attenuation factors are not provided, the default values are 1.0 for the constant attenuation factor, 0.0 for the linear attenuation factor, and 0.0 for the quadratic attenuation factor.

See Also

IDirect3DRMLight::SetConstantAttenuation

IDirect3DRMLight::GetEnableFrame

IDirect3DRMLight

Retrieves the enable frame for a light.

Syntax

HRESULT GetEnableFrame(
  LPDIRECT3DRMFRAME  *lplpEnableFrame
  );

Parameters

lplpEnableFrame
Address of a pointer that will contain the enable frame for the current Direct3DRMFrame object.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMLight::SetEnableFrame

IDirect3DRMLight::GetLinearAttenuation

IDirect3DRMLight

Retrieves the linear attenuation factor for a light.

Syntax

D3DVALUE GetLinearAttenuation( );

Return Value

Returns the linear attenuation value.

Remarks

Lights that have a location (those that are not infinitely far away) can have attenuation factors to calculate the attenuation of the light based on the distance from the light.

The light attenuation formula used depends on whether or not the D3DRMRENDERMODE_VIEWDEPENDENTSPECULAR flag is set. This flag is set in IDirect3DRMDevice3::SetRenderMode.

If the D3DRMRENDERMODE_VIEWDEPENDENTSPECULAR flag is set, the following formulae are used for light attenuation.

The formula for the normalized distance is:

normalized_distance = (distance_from_light - light_range)/light_range

The default light_range value is 256 modeling-space units.

The formula for the total attenuation factor is:

constant_attenuation_factor + normalized_distance * linear_attenuation_factor + (normalized_distance**2) * quadratic_attenuation_factor

If the D3DRMRENDERMODE_VIEWDEPENDENTSPECULAR flag is not set, the following formula is used for light attentuation.

1 / [constant_attenuation_factor + distance * linear_attenuation_factor + (distance**2) * quadratic_attenuation_factor]

The total attenuation factor cannot be greater than 1.

When attenuation factors are not provided, the default values are 1.0 for the constant attenuation factor, 0.0 for the linear attenuation factor, and 0.0 for the quadratic attenuation factor.

See Also

IDirect3DRMLight::SetLinearAttenuation

IDirect3DRMLight::GetPenumbra

IDirect3DRMLight

Retrieves the penumbra angle of a spotlight.

Syntax

D3DVALUE GetPenumbra( );

Return Value

Returns the penumbra value in radians.

Remarks

For more information see the Spotlight section of the Lights overview.

See Also

IDirect3DRMLight::SetPenumbra

IDirect3DRMLight::GetQuadraticAttenuation

IDirect3DRMLight

Retrieves the quadratic attenuation factor for a light.

Syntax

D3DVALUE GetQuadraticAttenuation( );

Return Value

Returns the quadratic attenuation value.

Remarks

Lights that have a location (those that are not infinitely far away) can have attenuation factors to calculate the attenuation of the light based on the distance from the light.

The light attenuation formula used depends on whether or not the D3DRMRENDERMODE_VIEWDEPENDENTSPECULAR flag is set. This flag is set in IDirect3DRMDevice3::SetRenderMode.

If the D3DRMRENDERMODE_VIEWDEPENDENTSPECULAR flag is set, the following formulae are used for light attenuation.

The formula for the normalized distance is:

normalized_distance = (distance_from_light - light_range)/light_range

The default light_range value is 256 modeling-space units.

The formula for the total attenuation factor is:

constant_attenuation_factor + normalized_distance * linear_attenuation_factor + (normalized_distance**2) * quadratic_attenuation_factor

If the D3DRMRENDERMODE_VIEWDEPENDENTSPECULAR flag is not set, the following formula is used for light attentuation.

1 / [constant_attenuation_factor + distance * linear_attenuation_factor + (distance**2) * quadratic_attenuation_factor]

The total attenuation factor cannot be greater than 1.

When attenuation factors are not provided, the default values are 1.0 for the constant attenuation factor, 0.0 for the linear attenuation factor, and 0.0 for the quadratic attenuation factor.

See Also

IDirect3DRMLight::SetQuadraticAttenuation

IDirect3DRMLight::GetRange

IDirect3DRMLight

Retrieves the range of the current Direct3DRMLight object.

Syntax

D3DVALUE GetRange( );

Return Value

Returns a value describing the range.

See Also

IDirect3DRMLight::SetRange

IDirect3DRMLight::GetType

IDirect3DRMLight

Retrieves the type of a given light.

Syntax

D3DRMLIGHTTYPE GetType( );

Return Value

Returns one of the members of the D3DRMLIGHTTYPE enumerated type.

See Also

IDirect3DRMLight::SetType

IDirect3DRMLight::GetUmbra

IDirect3DRMLight

Retrieves the umbra angle of the Direct3DRMLight object. The default is 0.4 radians.

Syntax

D3DVALUE GetUmbra( );

Return Value

Returns the umbra angle in radians.

Remarks

For more information see the Spotlight section of the Lights overview.

See Also

IDirect3DRMLight::SetUmbra

IDirect3DRMLight::SetColor

IDirect3DRMLight

Sets the color of the given light.

Syntax

HRESULT SetColor(
  D3DCOLOR rcColor
  );

Parameters

rcColor
New color for the light. Be sure to set the alpha component as well as the red, green, and blue color components or your objects might not be visible. The RGBA_MAKE DirectX macro allows you to specify these values.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

This method is also used to add a color key to a Direct3DRMLightInterpolator object.

See Also

IDirect3DRMLight::GetColor

IDirect3DRMLight::SetColorRGB

IDirect3DRMLight

Sets the color of the given light.

Syntax

HRESULT SetColorRGB(
  D3DVALUE rvRed,
  D3DVALUE rvGreen,
  D3DVALUE rvBlue
  );

Parameters

rvRed, rvGreen, and rvBlue
New color for the light.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

This method is also used to add an RGB color key to a Direct3DRMLightInterpolator object.

IDirect3DRMLight::SetConstantAttenuation

IDirect3DRMLight

Sets the constant attenuation factor for a light.

Syntax

HRESULT SetConstantAttenuation(
  D3DVALUE rvAtt
  );

Parameters

rvAtt
New constant attenuation factor.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

Lights that have a location (those that are not infinitely far away) can have attenuation factors to calculate the attenuation of the light based on the distance from the light.

The light attenuation formula used depends on whether or not the D3DRMRENDERMODE_VIEWDEPENDENTSPECULAR flag is set. This flag is set in IDirect3DRMDevice3::SetRenderMode.

If the D3DRMRENDERMODE_VIEWDEPENDENTSPECULAR flag is set, the following formulae are used for light attenuation.

The formula for the normalized distance is:

normalized_distance = (distance_from_light - light_range)/light_range

The default light_range value is 256 modeling-space units.

The formula for the total attenuation factor is:

constant_attenuation_factor + normalized_distance * linear_attenuation_factor + (normalized_distance**2) * quadratic_attenuation_factor

If the D3DRMRENDERMODE_VIEWDEPENDENTSPECULAR flag is not set, the following formula is used for light attentuation.

1 / [constant_attenuation_factor + distance * linear_attenuation_factor + (distance**2) * quadratic_attenuation_factor]

The total attenuation factor cannot be greater than 1.

When attenuation factors are not provided, the default values are 1.0 for the constant attenuation factor, 0.0 for the linear attenuation factor, and 0.0 for the quadratic attenuation factor.

This method is also used to add a constant attenuation key to a Direct3DRMLightInterpolator object.

See Also

IDirect3DRMLight::GetConstantAttenuation

IDirect3DRMLight::SetEnableFrame

IDirect3DRMLight

Sets the enable frame for a light.

Syntax

HRESULT SetEnableFrame(
  LPDIRECT3DRMFRAME lpEnableFrame
  );

Parameters

lpEnableFrame
Address of the light's enable frame. Child frames of this frame are also enabled for this light source.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMLight::GetEnableFrame

IDirect3DRMLight::SetLinearAttenuation

IDirect3DRMLight

Sets the linear attenuation factor for a light.

Syntax

HRESULT SetLinearAttenuation(
  D3DVALUE rvAtt
  );

Parameters

rvAtt
New linear attenuation factor.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

Lights that have a location (those that are not infinitely far away) can have attenuation factors to calculate the attenuation of the light based on the distance from the light.

The light attenuation formula used depends on whether or not the D3DRMRENDERMODE_VIEWDEPENDENTSPECULAR flag is set. This flag is set in IDirect3DRMDevice3::SetRenderMode.

If the D3DRMRENDERMODE_VIEWDEPENDENTSPECULAR flag is set, the following formulae are used for light attenuation.

The formula for the normalized distance is:

normalized_distance = (distance_from_light - light_range)/light_range

The default light_range value is 256 modeling-space units.

The formula for the total attenuation factor is:

constant_attenuation_factor + normalized_distance * linear_attenuation_factor + (normalized_distance**2) * quadratic_attenuation_factor

If the D3DRMRENDERMODE_VIEWDEPENDENTSPECULAR flag is not set, the following formula is used for light attentuation.

1 / [constant_attenuation_factor + distance * linear_attenuation_factor + (distance**2) * quadratic_attenuation_factor]

The total attenuation factor cannot be greater than 1.

When attenuation factors are not provided, the default values are 1.0 for the constant attenuation factor, 0.0 for the linear attenuation factor, and 0.0 for the quadratic attenuation factor.

This method is also used to add a linear attenuation key to a Direct3DRMLightInterpolator object.

See Also

IDirect3DRMLight::GetLinearAttenuation

IDirect3DRMLight::SetPenumbra

IDirect3DRMLight

Sets the angle of the penumbra cone.

Syntax

HRESULT SetPenumbra(
  D3DVALUE rvAngle
  );

Parameters

rvAngle
New penumbra angle in radians. This angle must be greater than or equal to the angle of the umbra. If you set the penumbra angle to less than the umbra angle, the umbra angle will be set equal to the penumbra angle. The default value is 0.5 radians.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

This method is also used to add a penumbra angle key to a Direct3DRMLightInterpolator object.

For more information see the Spotlight section of the Lights overview.

See Also

IDirect3DRMLight::GetPenumbra

IDirect3DRMLight::SetQuadraticAttenuation

IDirect3DRMLight

Sets the quadratic attenuation factor for a light.

Syntax

HRESULT SetQuadraticAttenuation(
  D3DVALUE rvAtt
  );

Parameters

rvAtt
New quadratic attenuation factor.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

Lights that have a location (those that are not infinitely far away) can have attenuation factors to calculate the attenuation of the light based on the distance from the light.

The light attenuation formula used depends on whether or not the D3DRMRENDERMODE_VIEWDEPENDENTSPECULAR flag is set. This flag is set in IDirect3DRMDevice3::SetRenderMode.

If the D3DRMRENDERMODE_VIEWDEPENDENTSPECULAR flag is set, the following formulae are used for light attenuation.

The formula for the normalized distance is:

normalized_distance = (distance_from_light - light_range)/light_range

The default light_range value is 256 modeling-space units.

The formula for the total attenuation factor is:

constant_attenuation_factor + normalized_distance * linear_attenuation_factor + (normalized_distance**2) * quadratic_attenuation_factor

If the D3DRMRENDERMODE_VIEWDEPENDENTSPECULAR flag is not set, the following formula is used for light attentuation.

1 / [constant_attenuation_factor + distance * linear_attenuation_factor + (distance**2) * quadratic_attenuation_factor]

The total attenuation factor cannot be greater than 1.

When attenuation factors are not provided, the default values are 1.0 for the constant attenuation factor, 0.0 for the linear attenuation factor, and 0.0 for the quadratic attenuation factor.

This method is also used to add a quadratic attenuation key to a Direct3DRMLightInterpolator object.

See Also

IDirect3DRMLight::GetQuadraticAttenuation

IDirect3DRMLight::SetRange

IDirect3DRMLight

Sets the range of a spotlight. The light affects objects that are within the range only.

Syntax

HRESULT SetRange(
  D3DVALUE rvRange
  );

Parameters

rvRange
New range. The default value is 256 modeling-space units.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

The range property is for spotlights only. This method is also used to add a range key to a Direct3DRMLightInterpolator object.

See Also

IDirect3DRMLight::GetRange

IDirect3DRMLight::SetType

IDirect3DRMLight

Changes the light's type.

Syntax

HRESULT SetType(
  D3DRMLIGHTTYPE d3drmtType
  );

Parameters

d3drmtType
New light type specified by one of the members of the D3DRMLIGHTTYPE enumerated type.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMLight::GetType

IDirect3DRMLight::SetUmbra

IDirect3DRMLight

Sets the angle of the umbra cone.

Syntax

HRESULT SetUmbra(
  D3DVALUE rvAngle
  );

Parameters

rvAngle
New umbra angle in radians. This angle must be less than or equal to the angle of the penumbra. If you set the umbra angle to greater than the penumbra angle, the penumbra angle will be set equal to the umbra angle. The default value is 0.4 radians.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

This method is also used to add an umbra angle key to a Direct3DRMLightInterpolator object.

For more information see the Spotlight section of the Lights overview.

See Also

IDirect3DRMLight::GetUmbra


IDirect3DRMLightArray

Applications use the methods of the IDirect3DRMLightArray interface to organize light objects. This section is a reference to the methods of this interface. For a conceptual overview, see Lights.

The IDirect3DRMLightArray interface supports the following methods:
GetElement
GetSize

The IDirect3DRMLightArray interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:
AddRef
QueryInterface
Release

The Direct3DRMLightArray object is obtained by calling the IDirect3DRMFrame3::GetLights method.

IDirect3DRMLightArray::GetElement

IDirect3DRMLightArray

Retrieves a specified element in a Direct3DRMLightArray object.

Syntax

HRESULT GetElement(
  DWORD index,
  LPDIRECT3DRMLIGHT  *lplpD3DRMLight
  );

Parameters

index
Element in the array.
lplpD3DRMLight
Address that will be filled with a pointer to an IDirect3DRMLight interface.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMLightArray::GetSize

IDirect3DRMLightArray

Retrieves the number of elements contained in a Direct3DRMLightArray object.

Syntax

DWORD GetSize( );

Return Value

Returns the number of elements.


IDirect3DRMMaterial2

Applications use the methods of the IDirect3DRMMaterial2 interface to interact with material objects.

A material defines how a surface reflects light. A material has two components: an emissive property (whether it emits light) and a specular property, whose brightness is determined by a power setting. The value of the power determines the sharpness of the reflected highlights, with a value of 5 giving a metallic appearance and higher values giving a more plastic appearance.

An application can control the emission of a material by using the GetEmissive and SetEmissive methods, the specular component by using the GetSpecular and SetSpecular methods, and the power by using the GetPower and SetPower methods.

Microsoft DirectX version 6.0 introduced the IDirect3DRMMaterial2 interface. IDirect3DRMMaterial2 extends the older IDirect3DRMMaterial interface that it replaces by adding the GetAmbient and SetAmbient methods to allow finer control over material properties. With IDirect3DRMMaterial the ambient color could not be modified and was always equal to the face color. An IDirect3DRMMaterial2 object uses the object's face color as the ambient color until SetAmbient is called. For a history of the Direct3D Retained Mode interfaces, see Interface Changes.

The methods of the IDirect3DRMMaterial2 interface can be organized into the following groups:
Ambient | GetAmbient
 | SetAmbient
Emission | GetEmissive
 | SetEmissive
Power for | GetPower
specular exponent | SetPower
Specular | GetSpecular
 | SetSpecular

The IDirect3DRMMaterial2 interface, like all Component Object Model (COM) interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:
AddRef
QueryInterface
Release

In addition, the IDirect3DRMMaterial2 interface inherits the following methods from the IDirect3DRMObject interface:
AddDestroyCallback
Clone
DeleteDestroyCallback
GetAppData
GetClassName
GetName
SetAppData
SetName

The Direct3DRMMaterial object is obtained by using the IDirect3DRM3::CreateMaterial method.

IDirect3DRMMaterial2::GetAmbient

IDirect3DRMMaterial2

Retrieves the current ambient value for the material.

Syntax

HRESULT GetAmbient(
    LPD3DVALUE lpdvRed,
    LPD3DVALUE lpdvGreen,
    LPD3DVALUE lpdvBlue);

Parameters

lpdvRed
Will be filled in with the red component of the ambient color.
lpdvGreen
Will be filled in with the green component of the ambient color.
lpdvBlue
Will be filled in with the blue component of the ambient color.

Return Value

Returns one of the following values:
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMMaterial2::GetEmissive

IDirect3DRMMaterial2

Retrieves the setting for the emissive property of a material. The setting of this property is the color and intensity of the light the object emits.

Syntax

HRESULT GetEmissive(
  D3DVALUE *lpr,
  D3DVALUE *lpg,
  D3DVALUE *lpb
  );

Parameters

lpr, lpg, and lpb
Addresses that will contain the red, green, and blue components of the emissive color when the method returns.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMMaterial2::SetEmissive

IDirect3DRMMaterial2::GetPower

IDirect3DRMMaterial2

Retrieves the power used for the specular exponent in the given material.

Syntax

D3DVALUE GetPower( );

Return Value

Returns the value specifying the power of the specular exponent.

See Also

IDirect3DRMMaterial2::SetPower

IDirect3DRMMaterial2::GetSpecular

IDirect3DRMMaterial2

Retrieves the color of the specular highlights of a material.

Syntax

HRESULT GetSpecular(
  D3DVALUE *lpr,
  D3DVALUE *lpg,
  D3DVALUE *lpb
  );

Parameters

lpr, lpg, and lpb
Addresses that will contain the red, green, and blue components of the color of the specular highlights when the method returns.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMMaterial2::SetSpecular

IDirect3DRMMaterial2::SetAmbient

IDirect3DRMMaterial2

Sets the ambient value for the material. The default is the diffuse color. The diffuse color is the diffuse (or matte) reflective color of the surface.

Syntax

HRESULT SetAmbient(
    D3DVALUE dvRed,
    D3DVALUE dvGreen,
    D3DVALUE dvBlue);

Parameters

dvRed
The red component of the ambient color.
dvGreen
The green component of the ambient color.
dvBlue
The blue component of the ambient color.

Return Value

Returns one of the following values:
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMMaterial2::SetEmissive

IDirect3DRMMaterial2

Sets the emissive property of a material.

Syntax

HRESULT SetEmissive(
  D3DVALUE r,
  D3DVALUE g,
  D3DVALUE b
  );

Parameters

r, g, and b
Red, green, and blue components of the emissive color.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

This method is also used to add an emissive property key to a Direct3DRMMaterialInterpolator object.

See Also

IDirect3DRMMaterial2::GetEmissive

IDirect3DRMMaterial2::SetPower

IDirect3DRMMaterial2

Sets the power used for the specular exponent in a material.

Syntax

HRESULT SetPower(
  D3DVALUE rvPower
  );

Parameters

rvPower
New specular exponent.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

This method is also used to add a spectral power key to a Direct3DRMMaterialInterpolator object.

See Also

IDirect3DRMMaterial2::GetPower

IDirect3DRMMaterial2::SetSpecular

IDirect3DRMMaterial2

Sets the color of the specular highlights for a material.

Syntax

HRESULT SetSpecular(
  D3DVALUE r,
  D3DVALUE g,
  D3DVALUE b
  );

Parameters

r, g, and b
Red, green, and blue components of the color of the specular highlights.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

This method is also used to add a spectral color key to a Direct3DRMMaterialInterpolator object.

See Also

IDirect3DRMMaterial2::GetSpecular


IDirect3DRMMesh

Applications use the methods of the IDirect3DRMMesh interface to interact with groups of meshes. A mesh is a visual object that is made up of a set of polygonal faces. A mesh defines a set of vertices and a set of faces (the faces are defined in terms of the vertices and normals of the mesh). Changing a vertex or normal that is used by several faces changes the appearance of all faces sharing it.

The vertices of a mesh define the positions of faces in the mesh, and they can also be used to define 2-D coordinates within a texture map.

You can manipulate meshes in Retained Mode by using IDirect3DRMMesh and IDirect3DRMMeshBuilder3.

If an application needs to assign the same characteristics (such as material or texture) to several vertices or faces, it can use the IDirect3DRMMesh interface to combine them in a group. If the application needs to share vertices between two different groups (for example, if neighboring faces in a mesh are different colors), the vertices must be duplicated in both groups. The IDirect3DRMMesh::AddGroup method assigns a group identifier to a collection of faces. This identifier is used to refer to the group in subsequent calls.

The IDirect3DRMMeshBuilder3 and IDirect3DRMMesh interfaces allow an application to create faces with more than three sides. They also automatically split a mesh into multiple buffers if, for example, the hardware the application is rendering to has a limit of 64K and a mesh is larger than that size. These features set the Direct3DRMMesh and Direct3DRMMeshBuilder3 API apart from the Direct3D API.

You can define individual color, texture, and material properties for each face in the mesh, or for all faces in the mesh at once, by using the IDirect3DRMMesh::SetGroupColor, SetGroupColorRGB, SetGroupTexture, and SetGroupMaterial methods.

For a mesh to be rendered, you must first add it to a frame by using the IDirect3DRMFrame3::AddVisual method. You can add a single mesh to multiple frames to create multiple instances of that mesh.

Your application can use flat, Gouraud, and Phong shade modes, as specified by a call to the IDirect3DRMMesh::SetGroupQuality method. (Phong shading is not yet available, however.) This method uses values from the D3DRMRENDERQUALITY enumerated type. For more information about shade modes, see Polygons.

The methods of the IDirect3DRMMesh interface can be organized into the following groups:
Color | GetGroupColor
 | SetGroupColor
 | SetGroupColorRGB
Creation and | AddGroup
information | GetBox
 | GetGroup
 | GetGroupCount
Materials | GetGroupMaterial
 | SetGroupMaterial
Miscellaneous | Scale
 | Translate
Rendering quality | GetGroupQuality
 | SetGroupQuality
Texture mapping | GetGroupMapping
 | SetGroupMapping
Textures | GetGroupTexture
 | SetGroupTexture
Vertex positions | GetVertices
 | SetVertices

The IDirect3DRMMesh interface, like all Component Object Model (COM) interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:
AddRef
QueryInterface
Release

In addition, the IDirect3DRMMesh interface inherits the following methods from the IDirect3DRMObject interface:
AddDestroyCallback
Clone
DeleteDestroyCallback
GetAppData
GetClassName
GetName
SetAppData
SetName

The Direct3DRMMesh object is obtained by using the IDirect3DRM3::CreateMesh method.

IDirect3DRMMesh::AddGroup

IDirect3DRMMesh

Groups a collection of faces and retrieves an identifier for the group. The first group added to a mesh always has index 0. The index of each successive group increases by 1.

Syntax

HRESULT AddGroup(
  unsigned vCount,
  unsigned fCount,
  unsigned vPerFace,
  unsigned *fData,
  D3DRMGROUPINDEX *returnId
  );

Parameters

vCount and fCount
Number of vertices and faces in the group.
vPerFace
Number of vertices per face in the group, if all faces have the same vertex count. If the group contains faces with varying vertex counts, this parameter should be zero.
fData
Address of face data. If the vPerFace parameter specifies a value, this data is simply a list of indices into the group's vertex array. If vPerFace is zero, the vertex indices should be preceded by an integer specifying the number of vertices in that face. For example, if vPerFace is zero and the group is made up of triangular and quadrilateral faces, the data might be in the following form: 3 index index index 4 index index index index 3 index index index ...
returnId
Address of the variable that identifies the group when the method returns.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

A newly added group has the following default properties:

  • White
  • No texture
  • No specular reflection
  • Position, normal, and color of each vertex in the vertex array equal to zero

To set the positions of the vertices, use the IDirect3DRMMesh::SetVertices method.

IDirect3DRMMesh::GetBox

IDirect3DRMMesh

Retrieves the bounding box containing a Direct3DRMMesh object. The bounding box gives the minimum and maximum model coordinates in each dimension.

Syntax

HRESULT GetBox(
  D3DRMBOX  *lpD3DRMBox
  );

Parameters

lpD3DRMBox
Address of a D3DRMBOX structure filled with the bounding box coordinates.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMMesh::GetGroup

IDirect3DRMMesh

Retrieves the data associated with a specified group.

Syntax

HRESULT GetGroup(
  D3DRMGROUPINDEX id,
  unsigned *vCount,
  unsigned *fCount,
  unsigned *vPerFace,
  DWORD *fDataSize,
  unsigned *fData
  );

Parameters

id
Identifier of the group. This identifier must be produced by using the IDirect3DRMMesh::AddGroup method.
vCount and fCount
Addresses of variables that will contain the number of vertices and the number of faces for the group when the method returns. These parameters can be NULL.
vPerFace
Address of a variable that will contain the number of vertices per face for the group when the method returns. This parameter can be NULL.
fDataSize
Address of a variable that specifies the number of unsigned elements in the buffer that the fData parameter points to. This parameter cannot be NULL.
fData
Address of a buffer that will contain the face data for the group when the method returns. The format of this data is the same as was specified in the call to the IDirect3DRMMesh::AddGroup method. If this parameter is NULL, the method returns the required size of the buffer in the fDataSize parameter.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMMesh::GetGroupColor

IDirect3DRMMesh

Retrieves the color for a group.

Syntax

D3DCOLOR GetGroupColor(
  D3DRMGROUPINDEX id
  );

Parameters

id
Identifier of the group. This identifier must be produced by using the IDirect3DRMMesh::AddGroup method.

Return Value

Returns a D3DCOLOR variable specifying the color if successful, or zero otherwise.

See Also

IDirect3DRMMesh::SetGroupColor, IDirect3DRMMesh::SetGroupColorRGB

IDirect3DRMMesh::GetGroupCount

IDirect3DRMMesh

Retrieves the number of groups for a given Direct3DRMMesh object.

Syntax

unsigned GetGroupCount( );

Return Value

Returns the number of groups if successful, or zero otherwise.

IDirect3DRMMesh::GetGroupMapping

IDirect3DRMMesh

Retrieves a description of how textures are mapped to a group in a Direct3DRMMesh object.

Syntax

D3DRMMAPPING GetGroupMapping(
  D3DRMGROUPINDEX id
  );

Parameters

id
Identifier of the group. This identifier must be produced by using the IDirect3DRMMesh::AddGroup method.

Return Value

Returns one of the D3DRMMAPPING values that describe how textures are mapped to a group, if successful. Returns zero otherwise.

See Also

IDirect3DRMMesh::SetGroupMapping

IDirect3DRMMesh::GetGroupMaterial

IDirect3DRMMesh

Retrieves a pointer to the material associated with a group in a Direct3DRMMesh object.

Syntax

HRESULT GetGroupMaterial(
  D3DRMGROUPINDEX id,
  LPDIRECT3DRMMATERIAL *returnPtr
  );

Parameters

id
Identifier of the group. This identifier must be produced by using the IDirect3DRMMesh::AddGroup method.
returnPtr
Address of a pointer to a variable that will contain the IDirect3DRMMaterial interface for the group when the method returns.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMMesh::SetGroupMaterial

IDirect3DRMMesh::GetGroupQuality

IDirect3DRMMesh

Retrieves the rendering quality for a specified group in a Direct3DRMMesh object.

Syntax

D3DRMRENDERQUALITY GetGroupQuality(
  D3DRMGROUPINDEX id
  );

Parameters

id
Identifier of the group. This identifier must be produced by using the IDirect3DRMMesh::AddGroup method.

Return Value

Returns values from the enumerated types represented by D3DRMRENDERQUALITY if successful, or zero otherwise. These values include the shading, lighting, and fill modes for the object.

See Also

IDirect3DRMMesh::SetGroupQuality

IDirect3DRMMesh::GetGroupTexture

IDirect3DRMMesh

Retrieves an address of the texture associated with a group in a Direct3DRMMesh object.

Syntax

HRESULT GetGroupTexture(
  D3DRMGROUPINDEX id,
  LPDIRECT3DRMTEXTURE *returnPtr
  );

Parameters

id
Identifier of the group. This identifier must be produced by using the IDirect3DRMMesh::AddGroup method.
returnPtr
Address of a pointer to a variable that will contain the IDirect3DRMTexture interface for the group when the method returns.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMMesh::SetGroupTexture

IDirect3DRMMesh::GetVertices

IDirect3DRMMesh

Retrieves vertex information for a specified group in a Direct3DRMMesh object.

Syntax

HRESULT GetVertices(
  D3DRMGROUPINDEX id,
  DWORD index,
  DWORD count,
  D3DRMVERTEX *returnPtr
  );

Parameters

id
Identifier of the group. This identifier must have been produced by using the IDirect3DRMMesh::AddGroup method.
index
Index into the array of D3DRMVERTEX structures at which to begin returning vertex positions.
count
Number of D3DRMVERTEX structures (vertices) to retrieve following the index given in the index parameter. This parameter cannot be NULL. To retrieve the number of vertices in a group, use the IDirect3DRMMesh::GetGroup method.
returnPtr
Array of D3DRMVERTEX structures that will contain the vertex information (vertex positions, colors, texture coordinates, and so on) when the method returns.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMMesh::GetGroup, IDirect3DRMMesh::SetVertices

IDirect3DRMMesh::Scale

IDirect3DRMMesh

Scales a Direct3DRMMesh object by the given scaling factors, parallel to the x-, y-, and z-axes in model coordinates.

Syntax

HRESULT Scale(
  D3DVALUE sx,
  D3DVALUE sy,
  D3DVALUE sz
  );

Parameters

sx, sy, and sz
Scaling factors that are applied along the x-, y-, and z-axes.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMMesh::SetGroupColor

IDirect3DRMMesh

Sets the color of a group in a Direct3DRMMesh object.

Syntax

HRESULT SetGroupColor(
  D3DRMGROUPINDEX id,
  D3DCOLOR value
  );

Parameters

id
Identifier of the group. This identifier must be produced by using the IDirect3DRMMesh::AddGroup method.
value
Color of the group.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

This method is also used to add a group color key to a Direct3DRMMeshInterpolator object.

See Also

IDirect3DRMMesh::GetGroupColor, IDirect3DRMMesh::SetGroupColorRGB

IDirect3DRMMesh::SetGroupColorRGB

IDirect3DRMMesh

Sets the color of a group in a Direct3DRMMesh object, using individual RGB values.

Syntax

HRESULT SetGroupColorRGB(
  D3DRMGROUPINDEX id,
  D3DVALUE red,
  D3DVALUE green,
  D3DVALUE blue
  );

Parameters

id
Identifier of the group. This identifier must be produced by using the IDirect3DRMMesh::AddGroup method.
red, green, and blue
Red, green, and blue components of the group color.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

This method is also used to add a group RGB key to a Direct3DRMMeshInterpolator object.

See Also

IDirect3DRMMesh::GetGroupColor, IDirect3DRMMesh::SetGroupColor

IDirect3DRMMesh::SetGroupMapping

IDirect3DRMMesh

Sets the mapping for a group in a Direct3DRMMesh object. The mapping controls how textures are mapped to a surface.

Syntax

HRESULT SetGroupMapping(
  D3DRMGROUPINDEX id,
  D3DRMMAPPING value
  );

Parameters

id
Identifier of the group. This identifier must be produced by using the IDirect3DRMMesh::AddGroup method.
value
Value of the D3DRMMAPPING type that describes the mapping for the group.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMMesh::GetGroupMapping

IDirect3DRMMesh::SetGroupMaterial

IDirect3DRMMesh

Sets the material associated with a group in a Direct3DRMMesh object.

Syntax

HRESULT SetGroupMaterial(
  D3DRMGROUPINDEX id,
  LPDIRECT3DRMMATERIAL value
  );

Parameters

id
Identifier of the group. This identifier must be produced by using the IDirect3DRMMesh::AddGroup method.
value
Address of the IDirect3DRMMaterial interface for the Direct3DRMMesh object.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMMesh::GetGroupMaterial

IDirect3DRMMesh::SetGroupQuality

IDirect3DRMMesh

Sets the rendering quality for a specified group in a Direct3DRMMesh object.

Syntax

HRESULT SetGroupQuality(
  D3DRMGROUPINDEX id,
  D3DRMRENDERQUALITY value
  );

Parameters

id
Identifier of the group. This identifier must be produced by using the IDirect3DRMMesh::AddGroup method.
value
Values from the enumerated types represented by the D3DRMRENDERQUALITY type. These values include the shading, lighting, and fill modes for the object.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMMesh::GetGroupQuality

IDirect3DRMMesh::SetGroupTexture

IDirect3DRMMesh

Sets the texture associated with a group in a Direct3DRMMesh object.

Syntax

HRESULT SetGroupTexture(
  D3DRMGROUPINDEX id,
  LPDIRECT3DRMTEXTURE value
  );

Parameters

id
Identifier of the group. This identifier must be produced by using the IDirect3DRMMesh::AddGroup method.
value
Address of the IDirect3DRMTexture interface for the Direct3DRMMesh object.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMMesh::GetGroupTexture

IDirect3DRMMesh::SetVertices

IDirect3DRMMesh

Sets the vertex positions for a specified group in a Direct3DRMMesh object.

Syntax

HRESULT SetVertices(
  D3DRMGROUPINDEX id,
  unsigned index,
  unsigned count,
  D3DRMVERTEX *values
  );

Parameters

id
Identifier of the group. This identifier must be produced by using the IDirect3DRMMesh::AddGroup method.
index
Index of the first vertex in the mesh group to be modified.
count
Number of consecutive vertices to set. The values array must contain at least the number of count elements.
values
Array of D3DRMVERTEX structures specifying the vertex positions to be set.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

Vertices are local to the group. If an application needs to share vertices between two different groups (for example, if neighboring faces in a mesh are different colors), the vertices must be duplicated in both groups.

This method is also used to add a vertex position key to a Direct3DRMMeshInterpolator object.

See Also

IDirect3DRMMesh::GetVertices

IDirect3DRMMesh::Translate

IDirect3DRMMesh

Adds the specified offsets to the vertex positions of a Direct3DRMMesh object.

Syntax

HRESULT Translate(
  D3DVALUE tx,
  D3DVALUE ty,
  D3DVALUE tz
  );

Parameters

tx, ty, and tz
Offsets that are added to the x-, y-, and z-coordinates, respectively, of each vertex position.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.


IDirect3DRMMeshBuilder3

Applications use the methods of the IDirect3DRMMeshBuilder3 interface to interact with mesh objects. For more information about meshes, see IDirect3DRMMesh. Microsoft® DirectX® version 6.0 introduced the IDirect3DRMMeshBuilder3 interface. For a history of the Direct3D Retained Mode interfaces, see Interface Changes.

You can add vertices and faces individually to a mesh by using the IDirect3DRMMeshBuilder3::AddVertex, AddFace, and AddFaces methods. You can retrieve an individual face with the GetFace method.

You can set normals (which should be unit vectors), or normals can be calculated by averaging the face normals of the surrounding faces by using the GenerateNormals method.

IDirect3DRMMeshBuilder3 extends the older IDirect3DRMMeshBuilder2 and IDirect3DRMMeshBuilder interfaces that it replaces. It adds the DeleteFace, DeleteNormals, and DeleteVertices methods to delete those objects, and the GetNormal and GetVertex methods to retrieve those objects. IDirect3DRMMeshBuilder3 also adds the Empty and Optimize methods.

Other new IDirect3DRMMeshBuilder3 methods retrieve one or more normals, the number of normals, faces, one or more vertices, and the state (enabled or disabled) of the meshbuilder. This interface enables you to set vertices and normals, and to create and retrieve new submeshes and parent meshes of the meshbuilder. IDirect3DRMMeshBuilder3 also enables the application to add new triangles (as opposed to general polygons) to the IDirect3DRMMeshBuilder3 object and, in the process, implicitly create new faces by using the AddTriangles method.

IDirect3DRMMeshBuilder3 and the older IDirect3DRMMeshBuilder2 include the functionality of IDirect3DRMMeshBuilder and additionally extend the GenerateNormals method to give greater control over the mesh normals generated. IDirect3DRMMeshBuilder3 and IDirect3DRMMeshBuilder2 also enable you to retrieve a single mesh face with GetFace.

In DirectX 6.0 or later, you can create a Direct3DRMMeshBuilder3 object by using the IDirect3DRM3 interface, in which case the Direct3DRMMeshBuilder3 object uses the Immediate Mode DrawPrimitive interface for its the implementation.

The methods of the IDirect3DRMMeshBuilder3 interface can be organized into the following groups.
Color | GetColorSource
 | SetColor
 | SetColorRGB
 | SetColorSource
Creation | GetBox
Faces | AddFace
 | AddFaces
 | AddFacesIndexed
 | CreateFace
 | DeleteFace
 | GetFaceCount
 | GetFace
 | GetFaces
Loading | Load
Meshes | AddMesh
 | CreateMesh
Miscellaneous | AddFrame
 | AddMeshBuilder
 | AddTriangles
 | Empty
 | Enable
 | GetEnable
 | Optimize
 | ReserveSpace
 | Save
 | Scale
 | SetMaterial
 | Translate
Normals | AddNormal
 | DeleteNormals
 | GenerateNormals
 | GetNormal
 | GetNormals
 | GetNormalCount
 | SetNormal
 | SetNormals
Perspective | GetPerspective
 | SetPerspective
Rendering quality | GetQuality
 | SetQuality
SubMeshes |
 | CreateSubMesh
 | DeleteSubMesh
 | GetParentMesh
 | GetSubMeshes
Textures | GetTextureCoordinates
 | SetTexture
 | SetTextureCoordinates
 | SetTextureTopology
Vertices | AddVertex
 | DeleteVertices
 | GetGeometry
 | GetVertex
 | GetVertexColor
 | GetVertexCount
 | GetVertices
 | SetVertex
 | SetVertices
 | SetVertexColor
 | SetVertexColorRGB

The IDirect3DRMMeshBuilder3 interface, like all Component Object Model (COM) interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods.
AddRef
QueryInterface
Release

In addition, the IDirect3DRMMeshBuilder3 interface inherits the following methods from the IDirect3DRMObject interface:
AddDestroyCallback
Clone
DeleteDestroyCallback
GetAppData
GetClassName
GetName
SetAppData
SetName

The Direct3DRMMeshBuilder3 object is obtained by using the IDirect3DRM3::CreateMeshBuilder method.


IDirect3DRMObject

Applications use the methods of the IDirect3DRMObject interface to work with the object superclass of Microsoft® Direct3D® Retained Mode objects.

Direct3DRMObject is the common superclass of all objects in the system. A Direct3DRMObject object has characteristics common to all objects.

Each Direct3DRMObject object is instantiated as a COM object. In addition to the methods of the IUnknown interface, each object has a standard set of methods that are generic to all.

To create an object, the application must first have instantiated a Direct3D Retained Mode object by calling the Direct3DRMCreate function. The application then calls the method of the object's interface that creates an object, and it specifies parameters specific to the object. For example, to create a Direct3DRMAnimation object, the application would call the IDirect3DRM3::CreateAnimation method. The creation method then creates a new object, initializes some of the object's attributes from data passed in the parameters (leaving all others with their default values), and returns the object. Applications can then specify the interface for this object to modify and use the object.

Any object can store 32 bits of application-specific data. This data is not interpreted or altered by Retained Mode. The application can read this data by using the IDirect3DRMObject::GetAppData method, and it can write to it by using the IDirect3DRMObject::SetAppData method. Finding this data is simpler if the application keeps a structure for each Direct3DRMFrame object. For example, if calling the IDirect3DRMFrame3::GetParent method retrieves a Direct3DRMFrame object, the application can easily retrieve the data by using a pointer to its private structure, possibly avoiding a time-consuming search.

You might also want to assign a name to an object to help you organize an application or as part of your application's user interface. You can use the IDirect3DRMObject::SetName and IDirect3DRMObject::GetName methods to set and retrieve object names.

Another example of possible uses for application-specific data is when an application needs to group the faces within a mesh into subsets (for example, for front and back faces). You could use the application data in the face to note in which of these groups a face should be included.

An application can specify a function to call when an object is destroyed, such as when the application needs to deallocate memory associated with the object. To do this, use the IDirect3DRMObject::AddDestroyCallback method. To remove a function previously registered with this method, use the IDirect3DRMObject::DeleteDestroyCallback method.

The callback function is called only when the object is destroyed—that is, when the object's reference count has reached 0 and the system is about to deallocate the memory for the object. If an application kept additional data about an object (so that its dynamics could be implemented, for example), the application could use this callback function as a way to notify itself that it can dispose of the data.

For information about grouping objects, see IDirect3DRMObjectArray.

The methods of the IDirect3DRMObject interface can be organized into the following groups:
Application-specific | GetAppData
data | SetAppData
Cloning | Clone
Naming | GetClassName
 | GetName
 | SetName
Notifications | AddDestroyCallback
 | DeleteDestroyCallback

The IDirect3DRMObject interface, like all Component Object Model (COM) interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:
AddRef
QueryInterface
Release

The Direct3DRMObject object is obtained through the appropriate call to the QueryInterface method from any Retained Mode object. All Retained Mode objects inherit the IDirect3DRMObject interface methods.

IDirect3DRMObject::AddDestroyCallback

IDirect3DRMObject

Registers a function that will be called when an object is destroyed.

Syntax

HRESULT AddDestroyCallback(
  D3DRMOBJECTCALLBACK lpCallback,
  LPVOID lpArg
  );

Parameters

lpCallback
User-defined callback function that will be used when the object is destroyed.
lpArg
Address of application-defined data passed to the callback function. Because this function is used after the object has been destroyed, you should not use this function with the object as an argument.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMObject::Clone

IDirect3DRMObject

Creates a copy of an object.

Syntax

HRESULT Clone(
  LPUNKNOWN pUnkOuter,
  REFIID riid,
  LPVOID *ppvObj
  );

Parameters

pUnkOuter
Pointer to the outer IUnknown interface that allows COM aggregation features.
riid
Identifier of the object being copied.
ppvObj
Address that will contain the copy of the object when the method returns.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMObject::DeleteDestroyCallback

IDirect3DRMObject

Removes a function previously registered with the IDirect3DRMObject::AddDestroyCallback method.

Syntax

HRESULT DeleteDestroyCallback(
  D3DRMOBJECTCALLBACK d3drmObjProc,
  LPVOID lpArg
  );

Parameters

d3drmObjProc
User-defined D3DRMOBJECTCALLBACK callback function that will be used when the object is destroyed.
lpArg
Address of application-defined data passed to the callback function.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMObject::GetAppData

IDirect3DRMObject

Retrieves the 32 bits of application-specific data in the object. The default value of the data is 0.

Syntax

DWORD GetAppData( );

Return Value

Returns the data value defined by the application.

See Also

IDirect3DRMObject::SetAppData

IDirect3DRMObject::GetClassName

IDirect3DRMObject

Retrieves the name of the object's class.

Syntax

HRESULT GetClassName(
  LPDWORD lpdwSize,
  LPSTR lpName
  );

Parameters

lpdwSize
Address of a variable containing the size, in bytes, of the buffer pointed to by the lpName parameter.
lpName
Address of a variable that will contain a null-terminated string identifying the class name when the method returns. If this parameter is NULL, the lpdwSize parameter will contain the required size for the string when the method returns.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMObject::GetName

IDirect3DRMObject

Retrieves the object's name.

Syntax

HRESULT GetName(
  LPDWORD lpdwSize,
  LPSTR lpName
  );

Parameters

lpdwSize
Address of a variable containing the size, in bytes, of the buffer pointed to by the lpName parameter.
lpName
Address of a variable that will contain a null-terminated string identifying the object's name when the method returns. If this parameter is NULL, the lpdwSize parameter will contain the required size for the string when the method returns.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMObject::SetName

IDirect3DRMObject::SetAppData

IDirect3DRMObject

Sets the 32 bits of application-specific data in the object.

Syntax

HRESULT SetAppData(
  DWORD ulData
  );

Parameters

ulData
User-defined data to be stored with the object.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMObject::GetAppData

IDirect3DRMObject::SetName

IDirect3DRMObject

Sets the object's name.

Syntax

HRESULT SetName(
  const char  *lpName
  );

Parameters

lpName
User-defined data to name the object.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMObject::GetName


IDirect3DRMObject2

Applications use the methods of the IDirect3DRMObject2 interface to work with the object2 superclass of Microsoft® Direct3D® Retained Mode objects. Microsoft DirectX version 6.0 introduced the IDirect3DRMObject2 interface which all Retained Mode objects implement. Use QueryInterface on any Direct3D Retained Mode object to obtain a pointer to this interface.

IDirect3DRMObject2 implements the following methods which are equivalent to the IDirect3DRMObject methods of the same name:
AddDestroyCallback
Clone
DeleteDestroyCallback
GetName
SetName

Besides the methods IDirect3DRMObject2 shares with IDirect3DRMObject, it implements the following methods.
GetDirect3DRM
GetClientData
GetAge
SetClientData

IDirect3DRMObject2::GetClientData and IDirect3DRMObject2::SetClientData provide data association with an object, which is more flexible than the older IDirect3DRMObject::GetAppData and IDirect3DRMObject::SetAppData methods.

For a conceptual overview of the older object interface, see IDirect3DRMObject. For a history of the Direct3D Retained Mode interfaces, see Interface Changes.

The methods of the IDirect3DRMObject2 interface can be organized into the following groups:
Application-specific data | GetClientData
 | SetClientData
Cloning | Clone
Naming | GetName
 | SetName
Miscellaneous | GetAge
 | GetDirect3DRM
Notifications | AddDestroyCallback
 | DeleteDestroyCallback

The IDirect3DRMObject2 interface, like all Component Object Model (COM) interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:
AddRef
QueryInterface
Release

The Direct3DRMObject2 object is obtained through the appropriate call to the QueryInterface method from any Retained Mode object. All Retained Mode objects inherit the IDirect3DRMObject2 interface methods.

IDirect3DRMObject2::AddDestroyCallback

IDirect3DRMObject2

Registers a function that will be called when an object is destroyed.

Syntax

HRESULT AddDestroyCallback(
  D3DRMOBJECTCALLBACK lpCallback,
  LPVOID lpArg
  );

Parameters

lpCallback
User-defined callback function that will be used when the object is destroyed.
lpArg
Address of application-defined data passed to the callback function. Because this function is used after the object has been destroyed, you should not use this function with the object as an argument.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

This method is equivalent to the IDirect3DRMObject method of the same name.

IDirect3DRMObject2::Clone

IDirect3DRMObject2

Creates a copy of an object.

Syntax

HRESULT Clone(
  LPUNKNOWN pUnkOuter,
  REFIID riid,
  LPVOID *ppvObj
  );

Parameters

pUnkOuter
Pointer to the outer IUnknown interface that allows COM aggregation features.
riid
Identifier of the object being copied.
ppvObj
Address that will contain the copy of the object when the method returns.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMObject2::DeleteDestroyCallback

IDirect3DRMObject2

Removes a function previously registered with the IDirect3DRMObject2::AddDestroyCallback method.

Syntax

HRESULT DeleteDestroyCallback(
  D3DRMOBJECTCALLBACK d3drmObjProc,
  LPVOID lpArg
  );

Parameters

d3drmObjProc
User-defined D3DRMOBJECTCALLBACK callback function that will be used when the object is destroyed.
lpArg
Address of application-defined data passed to the callback function.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

This method is equivalent to the IDirect3DRMObject method of the same name.

IDirect3DRMObject2::GetAge

IDirect3DRMObject2

Reports the current age of the object.

Syntax

HRESULT GetAge(
  DWORD dwFlags,
  LPDWORD lpdwAge);

Parameters

dwFlags
Flag value. Must be zero if the object is not a meshbuilder. If the object is a meshbuilder, can be one of the following values.
Default (0)
The meshbuilder ages normally (aging is caused by any change to the meshbuilder).
D3DRMMESHBUILDERAGE_GEOMETRY
The meshbuilder ages whenever the mesh geometry is changed (for example, addition of vertices, faces, or another meshbuilder).
D3DRMMESHBUILDERAGE_MATERIALS
The meshbuilder ages whenever a material-related property of the mesh changes, or when faces or another mesh are added.
D3DRMMESHBUILDERAGE_TEXTURES
The meshbuilder ages whenever a texture-related property of the mesh changes, or when faces or another mesh are added.
lpdwAge
Pointer that receives the age.

Return Value

Returns one of the following values.

DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

The age increases when the object is modified.

This method was introduced in DirectX version 6.0. Aging is only supported in DirectX 6.0 and later by the following objects.

Direct3DRMDevice3
Direct3DRMTexture3
Direct3DRMMeshBuilder3
Direct3DRMUserVisual
Direct3DRMShadow2
Direct3DRMWrap

IDirect3DRMObject2::GetClientData

IDirect3DRMObject2

Retrieves the data previously associated with an object through a call to SetClientData.

Syntax

HRESULT GetClientData(
  DWORD dwID,
  LPVOID *lplpvData);

Parameters

dwID
An application ID obtained from a call to RegisterClient.
lplpvData
Address of a variable that receives the associated data. A NULL value indicates that no data has been set.

Return Value

Returns one of the following values.

D3DRMERR_CLIENTNOTREGISTERED
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DDERR_NOTFOUND
DDERR_NOTINITIALIZED
DD_OK

Remarks

If the data is of type IUnknown, this method increments the reference count before returning the data to the caller. This method was introduced in DirectX version 6.0.

IDirect3DRMObject2::GetDirect3DRM

IDirect3DRMObject2

Retrieves a pointer to an interface of the ultimate Direct3DRM object involved in the creation of this object.

Syntax

HRESULT GetDirect3DRM(
  LPLPDIRECT3DRM lplpD3DRM);

Parameters

lplpD3DRM
Address that receives a pointer to an interface of the ultimate Direct3D Retained Mode object involved in the creation of the object specified by lpDirect3DRMObject.

Return Value

Returns one of the following values:
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMObject2::GetName

IDirect3DRMObject2

Retrieves the object's name.

Syntax

HRESULT GetName(
  LPDWORD lpdwSize,
  LPSTR lpName
  );

Parameters

lpdwSize
Address of a variable containing the size, in bytes, of the buffer pointed to by the lpName parameter.
lpName
Address of a variable that will contain a null-terminated string identifying the object's name when the method returns. If this parameter is NULL, the lpdwSize parameter will contain the required size for the string when the method returns.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMObject2::SetName

Remarks

This method is equivalent to the IDirect3DRMObject method of the same name.

IDirect3DRMObject2::SetClientData

IDirect3DRMObject2

Associates an item of data with a Retained Mode object.

Syntax

HRESULT SetClientData(
  DWORD dwID,
  LPVOID lpvData,
  DWORD dwFlags);

Parameters

dwID
Application ID obtained from a call to IDirect3DRM3::RegisterClient.
lpvData
Application-specific data to be associated with the object.
dwFlags
Flags that determine how the data is interpreted by Retained Mode.
Flag | D3DRMCLIENTDATA_NONE | D3DRMCLIENTDATA_LOCALFREE | D3DRMCLIENTDATA_IUNKNOWN
Interpretation of data | No interpretation | Data has been allocated by client; Direct3DRM should free it upon disassociation | Data is assumed to point to an IUnknown interface
Behavior on SetClientData | No behavior | No behavior | Direct3D Retained Mode increments the reference count on the interface
Behavior on GetClientData | No behavior | No behavior | Direct3D Retained Mode increments the reference count on the interface before passing it to the caller
Behavior when data is disassociated from the object | No behavior | Win32 LocalFree function is used on data | Direct3D Retained Mode decrements the reference count on the interface

Return Value

Returns one of the following values:
D3DRMERR_CLIENTNOTREGISTERED
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

The data can be removed by means of a call to this method with NULL as the lpvData parameter, or destruction of the object, or by using IDirect3DRM3::UnregisterClient. If you have previously associated data with the object using the ID specified by dwID, then the previous data is released. The method of destruction depends on the flags passed to this method in the dwFlags parameter. The data can be retrieved by means of a call to GetClientData. This method was introduced in DirectX version 6.0.

IDirect3DRMObject2::SetName

IDirect3DRMObject2

Sets the object's name.

Syntax

HRESULT SetName(
  const char  *lpName
  );

Parameters

lpName
User-defined data to name the object.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

This method is equivalent to the IDirect3DRMObject method of the same name.

See Also

IDirect3DRMObject2::GetName


IDirect3DRMObjectArray

Applications use the methods of the IDirect3DRMObjectArray interface to organize Direct3DRMObject objects. For more information about Direct3DRMObject, see IDirect3DRMObject.

The IDirect3DRMObjectArray interface supports the following methods:
GetElement
GetSize

The IDirect3DRMObjectArray interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:
AddRef
QueryInterface
Release

The Direct3DRMObjectArray object is obtained by calling the IDirect3DRMInterpolator::GetAttachedObjects method.

IDirect3DRMObjectArray::GetElement

IDirect3DRMObjectArray

Retrieves a specified element in a Direct3DRMObjectArray object.

Syntax

HRESULT GetElement(
  DWORD index,
  LPDIRECT3DRMOBJECT  *lplpD3DRMObject
  );

Parameters

index
Element in the array.
lplpD3DRMObject
Address that will be filled with a pointer to an IDirect3DRMObject interface.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMObjectArray::GetSize

IDirect3DRMObjectArray

Retrieves the number of elements contained in a Direct3DRMObjectArray object.

Syntax

DWORD GetSize( );

Return Value

Returns the number of elements.


IDirect3DRMPicked2Array

Applications use the methods of the IDirect3DRMPicked2Array interface to organize pick objects and to return more information about the pick objects. See IDirect3DRMPickedArray for more information about picking.

You can use the IDirect3DRMFrame3::RayPick method to retrieve an IDirect3DRMPicked2Array interface, and then call the IDirect3DRMPicked2Array::GetPick method to retrieve an IDirect3DRMFrameArray interface, a visual object, and information about the object intersected by the ray, including the face and group identifiers, pick position, and horizontal and vertical texture coordinates for the vertex, vertex normal, and color of the object. The array of frames is the path through the hierarchy leading to the visual object.

The D3DRMPICKDESC2 structure returned by IDirect3DRMPicked2Array::GetPick contains the face and group identifiers, pick position, horizontal and vertical texture coordinates for the vertex, vertex normal, and color of the intersected objects. A pointer to this interface pointer is returned in the IDirect3DRMFrame3::RayPick method during ray picks.

The IDirect3DRMPicked2Array interface supports the following methods:
GetPick
GetSize

The IDirect3DRMPicked2Array interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:
AddRef
QueryInterface
Release

The Direct3DRMPicked2Array object is obtained by calling the IDirect3DRMFrame3::RayPick method.

IDirect3DRMPicked2Array::GetPick

IDirect3DRMPicked2Array

Retrieves the Direct3DRMVisual and Direct3DRMFrame objects intersected by the specified pick.

Syntax

HRESULT GetPick(
  DWORD index,
  LPDIRECT3DRMVISUAL  *lplpVisual,
  LPDIRECT3DRMFRAMEARRAY  *lplpFrameArray,
  LPD3DRMPICKDESC2 lpD3DRMPickDesc2
  );

Parameters

index
Index into the pick array identifying the pick for which information will be retrieved.
lplpVisual
Address that will contain a pointer to the Direct3DRMVisual object associated with the specified pick.
lplpFrameArray
Address that will contain a pointer to the Direct3DRMFrameArray object associated with the specified pick.
lpD3DRMPickDesc
Address of a D3DRMPICKDESC2 structure specifying the face and group identifiers, pick position, horizontal and vertical texture coordinates for the vertex, vertex normal, and color of the intersected objects.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Return Values.

Remarks

This method is similar to IDirect3DRMPickedArray::GetPick except that it retrieves the u- and v-values in a D3DRMPICKDESC2 structure rather than a D3DRMPICKDESC structure.

See Also

IDirect3DRMFrame3::RayPick

IDirect3DRMPicked2Array::GetSize

IDirect3DRMPicked2Array

Retrieves the number of elements contained in a Direct3DRMPicked2Array object.

Syntax

DWORD GetSize( );

Return Value

Returns the number of elements.


IDirect3DRMPickedArray

Applications use the methods of the IDirect3DRMPickedArray interface to organize pick objects. Picking is the process of searching for visuals in a scene, given a 2-D coordinate in a viewport or a vector in a frame. For information about ray picking, see the IDirect3DRMPicked2Array interface.

You can use the IDirect3DRMViewport2::Pick method to retrieve an IDirect3DRMPickedArray interface, and then call the IDirect3DRMPickedArray::GetPick method to retrieve an IDirect3DRMFrameArray interface and a visual object. The array of frames is the path through the hierarchy leading to the visual object; that is, a hierarchical list of the visual object's parent frames, with the topmost parent in the hierarchy first in the array.

The IDirect3DRMPickedArray interface supports the following methods:
GetPick
GetSize

The IDirect3DRMPickedArray interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:
AddRef
QueryInterface
Release

The Direct3DRMPickedArray object is obtained by calling the IDirect3DRMViewport2::Pick method.

IDirect3DRMPickedArray::GetPick

IDirect3DRMPickedArray

Retrieves the Direct3DRMVisual and Direct3DRMFrame objects intersected by the specified pick.

Syntax

HRESULT GetPick(
  DWORD index,
  LPDIRECT3DRMVISUAL  *lplpVisual,
  LPDIRECT3DRMFRAMEARRAY  *lplpFrameArray,
  LPD3DRMPICKDESC lpD3DRMPickDesc
  );

Parameters

index
Index into the pick array identifying the pick for which information will be retrieved.
lplpVisual
Address that will contain a pointer to the Direct3DRMVisual object associated with the specified pick.
lplpFrameArray
Address that will contain a pointer to the Direct3DRMFrameArray object associated with the specified pick.
lpD3DRMPickDesc
Address of a D3DRMPICKDESC structure specifying the pick position and face and group identifiers of the objects being retrieved.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMViewport2::Pick

IDirect3DRMPickedArray::GetSize

IDirect3DRMPickedArray

Retrieves the number of elements contained in a Direct3DRMPickedArray object.

Syntax

DWORD GetSize( );

Return Value

Returns the number of elements.


IDirect3DRMProgressiveMesh

A mesh is a visual object that is made up of a set of polygonal faces. A mesh defines a set of vertices and a set of faces. See IDirect3DRMMesh for more information about meshes.

A progressive mesh is a mesh that is stored as a base mesh (a coarse version) and a set of vertex split records that are used to increasingly refine the mesh. In other words, it allows for progressive refinement. This allows you to set the level of detail rendered for a mesh and also allows progressive download from remote sources.

The progressive mesh is a visual in Microsoft® Direct3D® Retained Mode and can be used in the standard ways that visuals are used. That is, a progressive mesh can be added to frame hierarchies, instantiated a multiple number of times, and picked.

Using the methods of the IDirect3DRMProgressiveMesh interface, you can set the number of vertices or faces to render and thereby control the render detail. You can also specify a minimum level of detail required for rendering. Normally, a progressive mesh is rendered once the base mesh is available, but with the IDirect3DRMProgressiveMesh::SetMinRenderDetail method you can specify that a greater level of detail is necessary before rendering. You can also build a Direct3DRMMesh object from a particular state of the progressive mesh using the IDirect3DRMProgressiveMesh::CreateMesh method.

You can load a progressive mesh from a file, resource, memory, or URL. Loading can be done synchronously or asynchronously. You can check the status of a download with the IDirect3DRMProgressiveMesh::GetLoadStatus method, and terminate a download with the IDirect3DRMProgressiveMesh::Abort method. If loading is asynchronous, it is up to the application to use events through the IDirect3DRMProgressiveMesh::RegisterEvents and IDirect3DRMProgressiveMesh::GetLoadStatus methods to find out how the load is progressing.

The Direct3DRMProgressiveMesh object is created by using the IDirect3DRM3::CreateProgressiveMesh method. After creation, the object can be added to a hierarchy, but will not render until at least the base mesh is available.

In addition to the standard IUnknown and IDirect3DRMObject methods, this API contains the following members:

Creating and Copying Meshes | Clone
 | CreateMesh
 | Duplicate
 | GetBox
Loading | Abort
 | GetLoadStatus
 | Load
Setting Quality | SetQuality
 | GetQuality
Managing Details | GetDetail
 | GetFaceDetail
 | GetFaceDetailRange
 | GetVertexDetail
 | GetVertexDetailRange
 | SetDetail
 | SetFaceDetail
 | SetMinRenderDetail
 | SetVertexDetail
Registering Events | RegisterEvents

The IDirect3DRMProgressiveMesh interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:
AddRef
QueryInterface
Release

In addition, the IDirect3DRMProgressiveMesh interface inherits the following methods from the IDirect3DRMObject interface:
AddDestroyCallback
Clone
DeleteDestroyCallback
GetAppData
GetClassName
GetName
SetAppData
SetName

IDirect3DRMProgressiveMesh::Abort

IDirect3DRMProgressiveMesh

Terminates the currently active download.

Syntax

HRESULT Abort(
  DWORD dwFlags
  )

Parameters

dwFlags
Must be set to zero.

Return Value

Returns D3DRM_OK if successful, or one of the following errors:
D3DRMERR_INVALIDOBJECT
D3DRMERR_INVALIDPARAMS

Remarks

If the base mesh has been downloaded before this method is used, the effect is as if the progressive mesh has loaded, the vertex splits are in a valid state, and the progressive mesh is renderable. The other progressive mesh methods will work. If the base mesh has not been downloaded before the IDirect3DRMProgressiveMesh::Abort call and you have added the progressive mesh to a scene, the IDirect3DRMViewport2::Render will succeed but the progressive mesh will not be rendered. Also, if the base mesh has not been downloaded, when you try to use the progressive mesh (to create a mesh or clone, for example) the call will return D3DRMERR_NOTENOUGHDATA.

If there are any outstanding events, they are signaled.

IDirect3DRMProgressiveMesh::Clone

IDirect3DRMProgressiveMesh

Creates a copy of the currently loaded Direct3DRMProgressiveMesh object.

Syntax

HRESULT Clone(
  LPDIRECT3DRMPROGRESSIVEMESH *lplpD3DRMPMesh
  )

Parameters

lplpD3DRMPMesh
Address of a Direct3DRMProgressiveMesh pointer that will be filled in with a pointer to the newly generated Direct3DRMProgressiveMesh object.

Return Value

Returns D3DRM_OK if successful, or one of the following errors:
D3DRMERR_CONNECTIONLOST
D3DRMERR_INVALIDOBJECT
D3DRMERR_INVALIDPARAMS
D3DRMERR_NOTENOUGHDATA

Remarks

The progressive mesh being cloned must have at least its base mesh loaded. If you use this method on a progressive mesh that is currently being asynchronously loaded, the cloned mesh only has as much detail as the loading progressive mesh had at the time it was cloned. Any vertex splits loaded after the duplication are not available to the cloned mesh.

This method does not try to share any of the progressive mesh's internal data, whereas the IDirect3DRMProgressiveMesh::Duplicate does.

See Also

IDirect3DRMProgressiveMesh::Duplicate

IDirect3DRMProgressiveMesh::CreateMesh

IDirect3DRMProgressiveMesh

Builds a mesh from the current level of detail.

Syntax

HRESULT CreateMesh(
  LPDIRECT3DRMMESH *lplpD3DRMMesh
  )

Parameters

lplpD3DRMMesh
Address of a Direct3DRMMesh pointer that will be filled in with a pointer to the newly generated Direct3DRMMesh object.

Return Value

Returns D3DRM_OK if successful, or one of the following errors:
D3DRMERR_CONNECTIONLOST
D3DRMERR_INVALIDOBJECT
D3DRMERR_INVALIDPARAMS
D3DRMERR_NOTENOUGHDATA

Remarks

If the application has requested a level of detail that is not yet available, or the base mesh is not yet available, this method returns the error D3DRMERR_NOTENOUGHDATA.

IDirect3DRMProgressiveMesh::Duplicate

IDirect3DRMProgressiveMesh

Creates a copy of the Direct3DRMProgressiveMesh object. The copy shares all geometry and face data with the original, but has a detail level that can be set independently of the original. This enables the same mesh data to be used in different parts of the hierarchy but with different levels of detail. In essence, you almost have two instances of a progressive mesh within the frame hierarchy.

Syntax

HRESULT Duplicate(
  LPDIRECT3DRMPROGRESSIVEMESH *lplpD3DRMPMesh
  )

Parameters

lplpD3DRMPMesh
Address of a Direct3DRMProgressiveMesh pointer that will be filled with a pointer to the newly generated Direct3DRMProgressiveMesh object.

Return Value

Returns DD_OK if successful, or one of the following errors:
D3DRMERR_CONNECTIONLOST
D3DRMERR_INVALIDOBJECT
D3DRMERR_INVALIDPARAMS
D3DRMERR_NOTENOUGHDATA

Remarks

The progressive mesh being duplicated must have at least its base mesh loaded. If you use this method on a progressive mesh that is currently being asynchronously loaded, the duplicated mesh only has as much detail as the loading progressive mesh had at the time it was duplicated. Any vertex splits loaded after the duplication are not available to the duplicated mesh.

A progressive mesh has a set of data representing the base mesh, and a set of data representing the vertex splits. The base mesh data and data describing the current state of the progressive mesh and the current level of detail isn't shared between meshes that are duplicated, but the vertex splits are. This method creates a new instance of the progressive mesh that shares all geometry and face data with the original, but has a detail level that can be set independently of the original.

IDirect3DRMProgressiveMesh::GetBox

IDirect3DRMProgressiveMesh

Retrieves the bounding box containing a Direct3DRMProgressiveMesh object. The bounding box gives the minimum and maximum coordinates relative to a child frame, in each dimension.

Syntax

HRESULT GetBox(
  D3DRMBOX  *lpD3DRMBox
  );

Parameters

lpD3DRMBox
Address of a D3DRMBOX structure that will be filled with the bounding box coordinates.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

IDirect3DRMProgressiveMesh::GetDetail

IDirect3DRMProgressiveMesh

Returns the current detail level of the progressive mesh normalized between 0.0 and 1.0.

Syntax

HRESULT GetDetail(
  LPD3DVALUE lpdvVal
  )

Parameters

lpdvVal
Address of a D3DVALUE that will be filled with the current detail level of the progressive mesh.

Return Value

Returns D3DRM_OK if successful, or one of the following errors:
D3DRMERR_CONNECTIONLOST
D3DRMERR_INVALIDOBJECT
D3DRMERR_INVALIDPARAMS
D3DRMERR_PENDING

Remarks

If the base mesh has not yet downloaded then this method will return D3DRMERR_PENDING. If a requested level of detail has been set, the return value will increase on each subsequent call until the requested level has been met. If no level has been requested, the detail will increase until all vertex splits have been downloaded.

The normalized value 0.0 represents the minimum number of vertices (the number of vertices in the base mesh), and the normalized value 1.0 represents the maximum number of vertices.

IDirect3DRMProgressiveMesh::GetFaceDetail

IDirect3DRMProgressiveMesh

Retrieves the number of faces in the progressive mesh.

Syntax

HRESULT GetFaceDetail(
  LPDWORD lpdwCount
  )

Parameters

lpdwCount
Address of a DWORD that will be filled in with the number of faces in the progressive mesh.

Return Value

Returns D3DRM_OK if successful, or one of the following errors:
D3DRMERR_CONNECTIONLOST
D3DRMERR_PENDING
D3DRMERR_INVALIDOBJECT
D3DRMERR_INVALIDPARAMS

Remarks

If the number of faces is not available, this method returns D3DRMERR_PENDING.

IDirect3DRMProgressiveMesh::GetFaceDetailRange

IDirect3DRMProgressiveMesh

Retrieves the minimum and maximum face count available in the progressive mesh.

Syntax

HRESULT GetFaceDetailRange(
  LPDWORD lpdwMinFaces,
  LPDWORD lpdwMaxFaces
  )

Parameters

lpdwMinFaces
Address of a DWORD that will be filled in with the minimum number of faces.
lpdwMaxFaces
Address of a DWORD that will be filled in with the maximum number of faces.

Return Value

Returns D3DRM_OK if successful, or one of the following errors:
D3DRMERR_CONNECTIONLOST
D3DRMERR_INVALIDOBJECT
D3DRMERR_INVALIDPARAMS
D3DRMERR_PENDING

Remarks

If the face count is not available, this method returns D3DRMERR_PENDING.

IDirect3DRMProgressiveMesh::GetLoadStatus

IDirect3DRMProgressiveMesh

Allows the application to inquire about the current status of the load.

Syntax

HRESULT GetLoadStatus(
  LPD3DRMPMESHLOADSTATUS lpStatus
  )

Parameters

lpStatus
Address of a D3DRMPMESHLOADSTATUS structure that contains the loading status of the progressive mesh.

Return Value

Returns D3DRM_OK if successful, or one of the following errors:
D3DRMERR_CONNECTIONLOST
D3DRMERR_INVALIDOBJECT
D3DRMERR_INVALIDPARAMS

Remarks

If the mesh is renderable (the base mesh has been downloaded and the data is not corrupt) then the dwFlags member contains D3DRMPMESHSTATUS_RENDERABLE. If the download was interrupted, the dwFlags member will contain D3DRMPMESHSTATUS_INTERRUPTED.

IDirect3DRMProgressiveMesh::GetQuality

IDirect3DRMProgressiveMesh

Retrieves a member of the D3DRMRENDERQUALITY enumerated type that specifies the rendering quality of the progressive mesh.

Syntax

HRESULT GetQuality(
  LPD3DRMRENDERQUALITY lpQuality
  );

Parameters

lpQuality
Pointer to the D3DRMRENDERQUALITY member if successful that specifies rendering quality.

Return Value

Returns D3DRM_OK if successful, or one of the following errors:

D3DRMERR_BADOBJECT
The progressive mesh is invalid.
D3DRMERR_BADVALUE
The pointer to the D3DRMRENDERQUALITY member is invalid.

See Also

IDirect3DRMProgressiveMesh::SetQuality

IDirect3DRMProgressiveMesh::GetVertexDetail

IDirect3DRMProgressiveMesh

Retrieves the number of vertices in the progressive mesh.

Syntax

HRESULT GetVertexDetail(
  LPDWORD lpdwCount
  )

Parameters

lpdwCount
Address of a DWORD that will be filled in with the number of vertices in the progressive mesh.

Return Value

Returns D3DRM_OK if successful, or one of the following errors:
D3DRMERR_CONNECTIONLOST
D3DRMERR_INVALIDOBJECT
D3DRMERR_INVALIDPARAMS
D3DRMERR_PENDING

Remarks

If the number of vertices is not available, this method returns D3DRMERR_PENDING.

IDirect3DRMProgressiveMesh::GetVertexDetailRange

IDirect3DRMProgressiveMesh

Retrieves the minimum and maximum vertex count available in the progressive mesh.

Syntax

HRESULT GetVertexDetailRange(
  LPDWORD lpdwMinVertices,
  LPDWORD lpdwMaxVertices
  )

Parameters

lpdwMinVertices
Address of a DWORD that will be filled in with the minimum number of vertices.
lpdwMaxVertices
Address of a DWORD that will be filled in with the maximum number of vertices.

Return Value

Returns D3DRM_OK if successful, or one of the following errors:
D3DRMERR_CONNECTIONLOST
D3DRMERR_INVALIDOBJECT
D3DRMERR_INVALIDPARAMS
D3DRMERR_PENDING

Remarks

If the vertex count information is not available, this method returns D3DRMERR_PENDING.

IDirect3DRMProgressiveMesh::Load

IDirect3DRMProgressiveMesh

Loads the progressive mesh object from memory, a file, a resource, or a URL. Loading can be done synchronously or asynchronously.

Syntax

HRESULT Load(
  LPVOID lpSource,
  LPVOID lpObjID,
  D3DRMLOADOPTIONS dloLoadflags,
  D3DRMLOADTEXTURECALLBACK lpCallback,
  LPVOID lpArg
  )

Parameters

lpSource
Address of the source for the object to be loaded. This source can be a file, resource, memory block, or stream, depending on the source flags specified in the dloLoadflags parameter.
lpObjID
Address of the ID of the DirectX file record that is a progressive mesh. This can either be a string or a UUID (determined by dloLoadflags). If lpObjID is NULL, dloLoadflags must be D3DRMLOAD_FIRST.
dloLoadflags
Value of the D3DRMLOADOPTIONS type describing how the load is to be performed. One flag from each of the following two groups must be included.
  • To determine which object in the DirectX file is loaded, use:
    D3DRMLOAD_BYNAME
    The lpObjID parameter is interpreted as a string.
    D3DRMLOAD_BYGUID
    The lpObjID parameter is interpreted as a UUID.
    D3DRMLOAD_FIRST
    The first progressive mesh found is loaded.
  • To determine the source of the DirectX file, use:
    D3DRMLOAD_FROMFILE
    The lpSource parameter is interpreted as a string representing a local file name.
    D3DRMLOAD_FROMRESOURCE
    The lpSource parameter is interpreted as a pointer to a D3DRMLOADRESOURCE structure.
    D3DRMLOAD_FROMMEMORY
    The lpSource parameter is interpreted as a pointer to a D3DRMLOADMEMORY structure.
    D3DRMLOAD_FROMURL
    The lpSource parameter is interpreted as a URL.

In addition, you can specify whether the download is synchronous or asynchronous. By default, loading is synchronous and the Load call will not return until all data has been loaded or an error occurs. To specify asynchronous loading, include the following flag:

D3DRMLOAD_ASYNCHRONOUS — The Load call will return immediately. It is up to the application to use events with IDirect3DRMProgressiveMesh::RegisterEvents and IDirect3DRMProgressiveMesh::GetLoadStatus to find out how the load is progressing.

lpCallback
Address of a D3DRMLOADTEXTURECALLBACK callback function that will be used to load any texture encountered. The callback will be used with the texture name as encountered by the loader and the user-defined lpArg parameter. A new thread is not spawned for the callback. If you want the application to download a texture progressively, it must spawn a thread and return with a LPDIRECT3DRMTEXTURE as normal.
lpArg
Address of user-defined data passed to the D3DRMLOADTEXTURECALLBACK callback function.

Return Value

Returns D3DRM_OK if successful, or one of the following errors:
D3DRMERR_BADPMDATA
D3DRMERR_BADFILE
D3DRMERR_CONNECTIONLOST
D3DRMERR_INVALIDOBJECT
D3DRMERR_INVALIDPARAMS

Remarks

The progressive mesh is not useful unless it has been initialized. If asynchronous download is specified, the API returns immediately, and a separate thread is spawned to perform the download.

This method, IDirect3DRMProgressiveMesh::Clone, and IDirect3DRMProgressiveMesh::Duplicate all initialize a progressive mesh. You can only initialize an object once. Therefore, you cannot clone or duplicate a progressive mesh and then try to load into the cloned or duplicated mesh, nor can you load into a previously loaded mesh.

IDirect3DRMProgressiveMesh::RegisterEvents

IDirect3DRMProgressiveMesh

Allows the application to register events with the progressive mesh object that will be signaled when the appropriate conditions are met.

Syntax

HRESULT RegisterEvents(
  HANDLE hEvent,
  DWORD dwFlags,
  DWORD dwReserved
  )

Parameters

hEvent
Event to be signaled when the required condition is met.
dwFlags
Can be one of the following flags:
D3DRMPMESHEVENT_BASEMESH
The event is signaled when the base mesh has been downloaded.
D3DRMPMESHEVENT_COMPLETE
The event is signaled when all data has been downloaded.
dwReserved
Must be zero.

Return Value

Returns D3DRM_OK if successful, or one of the following errors:

D3DRMERR_INVALIDOBJECT
D3DRMERR_INVALIDPARAMS

Remarks

This method can be used to monitor the progress of loads. Events will also be signaled if an error occurs, so your application should always use the IDirect3DRMProgressiveMesh::GetLoadStatus method after being signaled.

IDirect3DRMProgressiveMesh::SetDetail

IDirect3DRMProgressiveMesh

Sets a requested level of detail normalized between 0.0 and 1.0.

Syntax

HRESULT SetDetail(
  D3DVALUE dvVal
  )

Parameters

dvVal
The requested level of detail.

Return Value

Returns D3DRM_OK if successful, or one of the following errors:
D3DRMERR_BADPMDATA
D3DRMERR_CONNECTIONLOST
D3DRMERR_INVALIDOBJECT
D3DRMERR_INVALIDPARAMS
D3DRMERR_PENDING

Remarks

If not enough detail has been downloaded yet (but will be available), the request is acknowledged and D3DRMERR_PENDING is returned. This error is informational and indicates that the requested level will be set as soon as enough detail is available.

The normalized value 0.0 represents the minimum number of vertices (the number of vertices in the base mesh), and the normalized value 1.0 represents the maximum number of vertices.

IDirect3DRMProgressiveMesh::SetFaceDetail

IDirect3DRMProgressiveMesh

Sets the requested level of face detail.

Syntax

HRESULT SetFaceDetail(
  DWORD dwCount
  )

Parameters

dwCount
The number of faces requested.

Return Value

Returns D3DRM_OK if successful, or one of the following errors:
D3DRMERR_BADPMDATA
D3DRMERR_CONNECTIONLOST
D3DRMERR_INVALIDOBJECT
D3DRMERR_INVALIDPARAMS
D3DRMERR_PENDING
D3DRMERR_REQUESTTOOLARGE

Remarks

Sometimes it is not possible to set the progressive mesh to the number of faces requested, though it will always be within 1 of the requested value. This is because a vertex split can add 1 or 2 faces. For example, if you use SetFaceDetail(20), the progressive mesh may only be able to set the face detail to 19 or 21. You can always get the actual number of faces in the progressive mesh by using the IDirect3DRMProgressiveMesh::GetFaceDetail method.

If not enough detail has been downloaded yet (but will be available), the request is be acknowledged and D3DRMERR_PENDING is returned. This error is informational and indicates that the requested level will be set as soon as enough detail is available. If the detail requested is greater that the detail available in the progressive mesh, D3DRMERR_REQUESTTOOLARGE is returned.

See Also

IDirect3DRMProgressiveMesh::GetFaceDetail

IDirect3DRMProgressiveMesh::SetMinRenderDetail

IDirect3DRMProgressiveMesh

Sets the minimum level of detail that will be rendered during a load from 0.0 (minimum detail) to 1.0 (maximum detail). Normally, the progressive mesh will be rendered once the base mesh is available (and the mesh is in the scene graph).

Syntax

HRESULT SetMinRenderDetail(
  D3DVALUE dvCount
  )

Parameters

dvCount
Requested minimum detail.

Return Value

Returns D3DRM_OK if successful, or one of the following errors:
D3DRMERR_CONNECTIONLOST
D3DRMERR_INVALIDOBJECT
D3DRMERR_INVALIDPARAMS
D3DRMERR_PENDING
D3DRMERR_REQUESTTOOLARGE
D3DRMERR_REQUESTTOOSMALL

Remarks

This API sets the minimum number of faces/vertices that will be rendered during the load (larger than the base mesh).

Any subsequent IDirect3DRMProgressiveMesh::SetDetail, IDirect3DRMProgressiveMesh::SetFaceDetail, or IDirect3DRMProgressiveMesh::SetVertexDetail calls will override this.

IDirect3DRMProgressiveMesh::SetQuality

IDirect3DRMProgressiveMesh

Sets the rendering quality of a Direct3DRMProgressiveMesh object.

Syntax

HRESULT SetQuality(
  D3DRMRENDERQUALITY quality
  );

Parameters

quality
Member of the D3DRMRENDERQUALITY enumerated type that specifies the new rendering quality to use.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

An object's quality has three components: shade mode (flat or Gouraud, Phong is not yet implemented and will default to Gouraud shading), lighting type (on or off), and fill mode (point, wire-frame or solid).

You can set the quality of a device with IDirect3DRMDevice3::SetQuality. By default it is D3DRMRENDER_FLAT (flat shading, lights on, and solid fill).

You can set the quality of a Direct3DRMProgressiveMesh object with the SetQuality method. By default, a Direct3DRMProgressiveMesh object's quality is D3DRMRENDER_GOURAUD (Gouraud shading, lights on, and solid fill).

Tip: Gouraud shading performs better on progressive mesh objects that change their level of detail often or quickly.

Direct3D Retained Mode renders an object at the lowest quality setting based on the device and object's current setting for each individual component. For example, if the object's current quality setting is D3DRMRENDER_GOURAUD, and the device is D3DRMRENDER_FLAT, the object will be rendered with flat shading, solid fill and lights on.

If the object's current quality setting is D3DRMSHADE_GOURAUD|D3DRMLIGHT_OFF|D3DRMFILL_WIREFRAME and the device's quality setting is D3DRMSHADE_FLAT|D3DRMLIGHT_ON|D3DRMFILL_POINT, the object will be rendered with flat shading, lights off, and point fill mode.

These rules apply to Direct3DRMMeshBuilder3 objects and Direct3DRMProgressiveMesh objects. However, Direct3DRMMesh objects do not follow these rules. Mesh objects ignore the device's quality settings and use the group quality setting (which defaults to D3DRMRENDER_GOURAUD).

See Also

IDirect3DRMProgressiveMesh::GetQuality

IDirect3DRMProgressiveMesh::SetVertexDetail

IDirect3DRMProgressiveMesh

Sets the requested level of vertex detail.

Syntax

HRESULT SetVertexDetail(
  DWORD dwCount
  )

Parameters

dwCount
The number of vertices requested.

Return Value

Returns D3DRM_OK if successful, or one of the following errors:
D3DRMERR_BADPMDATA
D3DRMERR_CONNECTIONLOST
D3DRMERR_INVALIDOBJECT
D3DRMERR_INVALIDPARAMS
D3DRMERR_PENDING
D3DRMERR_REQUESTTOOLARGE

Remarks

If not enough detail has been downloaded yet (but will be available), the request will be acknowledged and D3DRMERR_PENDING is returned. This error is informational and indicates that the requested level will be set as soon as enough detail is available. If the detail requested is greater than the detail available in the progressive mesh, D3DRMERR_REQUESTTOOLARGE is returned.

See Also

IDirect3DRMProgressiveMesh::GetVertexDetail


IDirect3DRMShadow2

Applications use the IDirect3DRMShadow2 and IDirect3DRMShadow interfaces to initialize Direct3DRMShadow2 and Direct3DRMShadow objects, respectively. Note that this initialization is not necessary if the application uses the IDirect3DRM3::CreateShadow method; it is required only if the application uses the IDirect3DRM3::CreateObject method to create the shadow. An application that calls IDirect3DRM3::CreateObject then calls the IDirect3DRMShadow2::Init method to initialize the shadow.

IDirect3DRMShadow2 extends the functionality of IDirect3DRMShadow by enabling the visual, light, plane, and option shadow parameters to be changed after creation. IDirect3DRMShadow2::SetOptions enables you to set an option that eliminates visual artifacts when blended transparency is enabled. IDirect3DRMShadow2 provides the SetVisual, GetVisual, SetLight, GetLight, SetPlane, GetPlane, SetOptions, and GetOptions methods, in addition to the Init method provided by IDirect3DRMShadow.

The methods of the IDirect3DRMShadow2 interface can be organized into the following groups.

Initialization | Init
Parameter Setting and Retrieval | GetLight
 | GetOptions
 | GetPlane
 | GetVisual
 | SetLight
 | SetOptions
 | SetPlane
 | SetVisual

The IDirect3DRMShadow2 and IDirect3DRMShadow interfaces, like all Component Object Model (COM) interfaces, inherit the IUnknown interface methods. The IUnknown interface supports the following three methods.
AddRef
QueryInterface
Release

In addition, the IDirect3DRMShadow2 and IDirect3DRMShadow interfaces inherit the following methods from the IDirect3DRMObject interface.
AddDestroyCallback
Clone
DeleteDestroyCallback
GetAppData
GetClassName
GetName
SetAppData
SetName

The Direct3DRMShadow2 object is obtained by using the IDirect3DRM3::CreateShadow method.

IDirect3DRMShadow2::GetLight

IDirect3DRMShadow2

Retrieves the light source used when shadowing. If no light is associated with the shadow, an error is returned.

Syntax

HRESULT GetLight(
  LPDIRECT3DRMLIGHT  *lplpDirect3DRMLight);

Parameters

lplpDirect3DRMLight
Pointer to receive the light source.

Return Value

Returns one of the following values.
DD_OK
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMShadow2::GetOptions

IDirect3DRMShadow2

Retrieves shadow option flags.

Syntax

HRESULT GetOptions(
  LPDWORD pdwOptions);

Parameters

pdwOptions
Pointer to retrieve the current shadow options. Valid flag is:
D3DRMSHADOW_TRUEALPHA
Creates a shadow that will not have visual artifacts when rendered with true alpha enabled.

Return Value

Returns one of the following values.
DD_OK
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMShadow2::GetPlane

IDirect3DRMShadow2

Retrieves the shadow plane. The point is relative to the shadow's frame. The normal is in world space.

Syntax

HRESULT SetPlane(
  LPD3DVALUE pdvPX,
  LPD3DVALUE pdvPY,
  LPD3DVALUE pdvPZ,
  LPD3DVALUE pdvNX,
  LPD3DVALUE pdvNY,
  LPD3DVALUE pdvNZ);

Parameters

pdvPX, pdvPY, pdvPZ
Pointers to receive the x-, y-, and z-values of a point on the shadow plane relative to the shadow's frame. The values are specified as pointers to D3DVALUE data types.
pdvNX, pdvNY, pdvNZ
Pointers to receive the x-, y-, and z-values of the normal to the shadow plane as a world space vector. The values are specified as pointers to D3DVALUE data types.

Return Value

Returns one of the following values.
DD_OK
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMShadow2::GetVisual

IDirect3DRMShadow2

Retrieves the visual to be shadowed.

Syntax

HRESULT GetVisual(
  LPDIRECT3DRMVISUAL  *lplpDirect3DRMVisual);

Parameters

lplpDirect3DRMVisual
Pointer to receive the visual to be shadowed.

Return Value

Returns one of the following values.
DD_OK
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMShadow2::Init

IDirect3DRMShadow2

Initializes a Direct3DRMShadow2 object.

Syntax

HRESULT Init(
  LPUNKNOWN pUnk,
  LPDIRECT3DRMLIGHT lpD3DRMLight,
  D3DVALUE px,
  D3DVALUE py,
  D3DVALUE pz,
  D3DVALUE nx,
  D3DVALUE ny,
  D3DVALUE nz);

Parameters

pUnk
Pointer to the object casting the shadow.
lpD3DRMLight
Pointer to the Direct3DRMLight object that provides the light that defines the shadow.
px, py, and pz
Coordinates of a point on the plane on which the shadow is cast.
nx, ny, and nz
Coordinates of the normal vector of the plane on which the shadow is cast.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

After you have called this method to initialize the shadow, add the shadow to the same frame in which the shadowed visual resides, using IDirect3DRMFrame3::AddVisual.

IDirect3DRMShadow2::SetLight

IDirect3DRMShadow2

Sets the light to be used when shadowing.

Syntax

HRESULT SetLight(
  LPDIRECT3DRMLIGHT lpDirect3DRMLight,
  DWORD dwFlags);

Parameters

lpDirect3DRMLight
Light to be used when shadowing.
dwFlags
Reserved. Must be zero.

Return Value

Returns one of the following values.
DD_OK
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMShadow2::SetOptions

IDirect3DRMShadow2

Sets the shadow option flags.

Syntax

HRESULT SetOptions(
  DWORD dwOptions);

Parameters

dwOptions
Shadow options. Valid flag is:
D3DRMSHADOW_TRUEALPHA
Creates a shadow that will not have visual artifacts when blended transparency (alpha blending) is enabled. Call IDirect3DRMDevice3::SetRenderMode to enable blended transparency.

Return Value

Returns one of the following values:
DD_OK
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMShadow2::SetPlane

IDirect3DRMShadow2

Sets the shadow plane. The point is relative to the shadow's frame. The normal is in world space.

Syntax

HRESULT SetPlane(
  D3DVALUE dvPX,
  D3DVALUE dvPY,
  D3DVALUE dvPZ,
  D3DVALUE dvNX,
  D3DVALUE dvNY,
  D3DVALUE dvNZ,
  DWORD dwFlags);

Parameters

dvPX, dvPY, dvPZ
Point on the shadow plane relative to the shadow's frame, specified as a D3DVALUE data type.
dvNX, dvNY, dvNZ
Normal to the shadow plane as a world space vector, specified as a D3DVALUE data type.
dwFlags
Reserved. Must be zero.

Return Value

Returns one of the following values.
DD_OK
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMShadow2::SetVisual

IDirect3DRMShadow2

Sets the visual to be shadowed.

Syntax

HRESULT SetVisual(
    LPDIRECT3DRMVISUAL lpDirect3DRMVisual,
    DWORD dwFlags);

Parameters

lpDirect3DRMVisual
Visual to be shadowed.
dwFlags
Reserved. Must be zero.

Return Value

Returns one of the following values.
DD_OK
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS

Remarks

This method was introduced with DirectX version 6.0.


IDirect3DRMTexture3

Microsoft DirectX version 6.0 introduced the IDirect3DRMTexture3 interface. IDirect3DRMTexture3 extends the older IDirect3DRMTexture2 and IDirect3DRMTexture interfaces that it replaces and it allows finer control over texture management. For a conceptual overview, see Textures. For a history of the Direct3D Retained Mode interfaces, see Interface Changes.

IDirect3DRMTexture3 extends the functionality of the Changed method by allowing you to specify the changed region of the texture. It also provides the texture management caching methods GetCacheOptions and SetCacheOptions. GetSurface, SetDownSampleCallback, and SetValidationCallback are the other new methods IDirect3DRMTexture3 provides.

Previously new methods, added by the older IDirect3DRMTexture2, and also supported by IDirect3DRMTexture3 include InitFromResource2, which allows resources to be loaded from DLLs and executables other than the currently executing file. The InitFromImage method creates a texture from an image in memory. This method is equivalent to the IDirect3DRM3::CreateTexture method. The GenerateMIPMap method generates a mipmap from a source image.

To avoid unnecessary delays when creating textures, hold onto textures you want to use again, instead of creating them each time they're needed. For optimal performance, use a texture surface format that is supported by the device you are using. This will avoid a costly format conversion when the texture is created and any time it changes.

See the remarks in IDirect3DRM3::LoadTexture for an example showing how to keep a reference to textures loaded in a texture callback through IDirect3DRM3::LoadTexture.

The methods of the IDirect3DRMTexture3 interface can be organized into the following groups:
Color | GetColors
 | SetColors
Decals | GetDecalOrigin
 | GetDecalScale
 | GetDecalSize
 | GetDecalTransparency
 | GetDecalTransparentColor
 | SetDecalOrigin
 | SetDecalScale
 | SetDecalSize
 | SetDecalTransparency
 | SetDecalTransparentColor
Images | GetImage
Initialization | InitFromFile
 | InitFromImage
 | InitFromResource2
 | InitFromSurface
Mipmap generation | GenerateMIPMap
Miscellaneous | GetCacheOptions
 | GetSurface
 | SetCacheOptions
 | SetDownsampleCallback
 | SetValidationCallback
Renderer notification | Changed
Shading | GetShades
 | SetShades

The IDirect3DRMTexture3 interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:
AddRef
QueryInterface
Release

In addition, the IDirect3DRMTexture3 interface inherits the following methods from the IDirect3DRMObject interface:
AddDestroyCallback
Clone
DeleteDestroyCallback
GetAppData
GetClassName
GetName
SetAppData
SetName

You can create an IDirect3DRMTexture3 object by calling IDirect3DRM3::CreateTexture or IDirect3DRM3::CreateTextureFromSurface.

IDirect3DRMTexture3::Changed

IDirect3DRMTexture3

Enables the application to specify which region of the texture has changed.

Syntax

HRESULT Changed(
  DWORD dwFlags,
  DWORD dwcRects,
  LPRECT pRects);

Parameters

dwFlags
The following flags are defined:
D3DRMTEXTURE_CHANGEDPIXELS
Indicates that the pixel values have changed.
D3DRMTEXTURE_CHANGEDPALETTE
Indicates that the palette has changed.
D3DRMTEXTURE_INVALIDATEONLY
Indicates that the texture regions are invalidated but do not need to be updated by the application. Before Direct3D Retained Mode renders the texture, it calls the application to update the primary source. This callback is set by SetValidationCallback.
dwcRects
Number of RECT structures pointed to by pRects. If this value is zero, and dwFlags contains D3DRMTEXTURE_CHANGEDPIXELS or D3DRMTEXTURE_INVALIDATEONLY, the whole texture is updated.
pRects
Array of RECT structures describing the regions of pixels that have changed. The pRects parameter is only valid if dwFlags contains D3DRMTEXTURE_CHANGEDPIXELS or D3DRMTEXTURE_INVALIDATEONLY.

Return Value

Returns one of the following values:
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0. This method replaces the old IDirect3DRMTexture::Changed method. This old method has two Boolean parameters that indicate whether the application has changed the pixels or the palette of a texture.

IDirect3DRMTexture3::GenerateMIPMap

IDirect3DRMTexture3

Generates a mipmap from a single image source.

Syntax

HRESULT GenerateMIPMap(
  DWORD dwFlags
  );

Parameters

dwFlags
Should be set to zero.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

This method can be called any time after a texture is created. It will generate a mipmap of the source image down to a resolution of 1×1 by using bilinear filtering between levels. Once a mipmap has been generated, it will always be available and will be updated whenever IDirect3DRMTexture3::Changed is called. When using mipmapping, remember to change the texture quality to D3DRMTEXTURE_MIPNEAREST, D3DRMTEXTURE_MIPLINEAR, D3DRMTEXTURE_LINEARMIPNEAREST, or D3DRMTEXTURE_LINEARMIPLINEAR using IDirect3DRMDevice3::SetTextureQuality. Extra mipmap levels will not be put into video memory for hardware devices unless the texture quality includes a mipmapping type and the hardware device supports mipmapping.

See Also

Mipmaps

IDirect3DRMTexture3::GetCacheOptions

IDirect3DRMTexture3

Retrieves information about how texture management treats the current texture if texture memory is restricted.

Syntax

HRESULT GetCacheOptions(
  LPLONG lplImportance,
  LPDWORD lpdwFlags);

Parameters

lplImportance
A signed value that indicates the relative importance of a texture. The default is zero. Higher values indicate a greater importance. This value is used to calculate which textures should be downsampled last if texture memory is restricted.
lpdwFlags
Flags that control the texture management system with respect to the current texture. The currently defined flags are:
D3DRMTEXTURE_FORCERESIDENT
Indicates that the texture should be kept in video memory (in a hardware scenario).
D3DRMTEXTURE_STATIC
Indicates that the texture will not change. The application guarantees not to use the Changed method.
D3DRMTEXTURE_DOWNSAMPLEPOINT
Indicates that when the texture is downsampled, point filtering will be used.
D3DRMTEXTURE_DOWNSAMPLEBILINEAR
Indicates that when the texture is downsampled, bilinear filtering will be used.
D3DRMTEXTURE_DOWNSAMPLEREDUCEDEPTH
Indicates that when the texture is downsampled, the pixel depth will be reduced.
D3DRMTEXTURE_DOWNSAMPLENONE
Indicates that the texture should never be downsampled.

Return Value

Returns one of the following values:
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMTexture3::GetColors

IDirect3DRMTexture3

Retrieves the maximum number of colors used for rendering a Direct3DRMTexture2 object.

Syntax

DWORD GetColors( );

Return Value

Returns the number of colors.

Remarks

This method returns the number of colors that the Direct3DRMTexture2 object has been quantized to, not the number of colors in the image from which the Direct3DRMTexture2 object was created. Consequently, the number of colors that are returned usually matches the colors that were set by calling the IDirect3DRM3::SetDefaultTextureColors method, unless you used the IDirect3DRMTexture3::SetColors method explicitly to change the colors for the Direct3DRMTexture2 object.

See Also

IDirect3DRMTexture3::SetColors

IDirect3DRMTexture3::GetDecalOrigin

IDirect3DRMTexture3

Retrieves the current origin of the decal.

Syntax

HRESULT GetDecalOrigin(
  LONG  *lplX,
  LONG  *lplY
  );

Parameters

lplX and lplY
Addresses of variables that will be filled with the origin of the decal when the method returns.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMTexture3::SetDecalOrigin

IDirect3DRMTexture3::GetDecalScale

IDirect3DRMTexture3

Retrieves the scaling property of the given decal.

Syntax

DWORD GetDecalScale( );

Return Value

Returns the scaling property if successful, or -1 otherwise.

See Also

IDirect3DRMTexture3::SetDecalScale

IDirect3DRMTexture3::GetDecalSize

IDirect3DRMTexture3

Retrieves the size of the decal.

Syntax

HRESULT GetDecalSize(
  D3DVALUE *lprvWidth,
  D3DVALUE *lprvHeight
  );

Parameters

lprvWidth and lprvHeight
Addresses of variables that will be filled with the width and height of the decal when the method returns.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMTexture3::SetDecalSize

IDirect3DRMTexture3::GetDecalTransparency

IDirect3DRMTexture3

Retrieves the transparency property of the decal.

Syntax

BOOL GetDecalTransparency( );

Return Value

Returns TRUE if the decal has a transparent color, FALSE otherwise.

See Also

IDirect3DRMTexture3::SetDecalTransparency

IDirect3DRMTexture3::GetDecalTransparentColor

IDirect3DRMTexture3

Retrieves the transparent color of the decal.

Syntax

D3DCOLOR GetDecalTransparentColor( );

Return Value

Returns the value of the transparent color.

See Also

IDirect3DRMTexture3::SetDecalTransparentColor

IDirect3DRMTexture3::GetImage

IDirect3DRMTexture3

Returns an address of the image that the texture was created with.

Syntax

D3DRMIMAGE  *GetImage( );

Return Value

Returns the address of the D3DRMIMAGE structure that the current Direct3DRMTexture2 object was created with.

IDirect3DRMTexture3::GetShades

IDirect3DRMTexture3

Retrieves the number of shades used for each color in the texture when rendering.

Syntax

DWORD GetShades( );

Return Value

Returns the number of shades.

See Also

IDirect3DRMTexture3::SetShades

IDirect3DRMTexture3::GetSurface

IDirect3DRMTexture3

Retrieves the DirectDraw surface that was used to create the texture. This only retrieves a surface if CreateTextureFromSurface or InitFromSurface was used to create the texture.

Syntax

HRESULT GetSurface(
  DWORD dwFlags,
  LPDIRECTDRAWSURFACE *lplpDDS);

Parameters

dwFlags
Flag value. Must be zero.
lplpDDS
Address of a variable that receives a pointer to the interface of the corresponding DirectDraw surface. Note that the interface's reference count is incremented before the interface is handed to the caller.

Return Value

Returns one of the following values:
D3DRMERR_NOTCREATEDFROMDDS
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMTexture3::InitFromFile

IDirect3DRMTexture3

Initializes a Direct3DRMTexture2 object using the information in a given file.

Syntax

HRESULT InitFromFile(
  LPCSTR filename
  );

Parameters

filename
A string that specifies the file from which the texture initialization information is drawn.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

You must have created the Direct3DRMTexture2 object to be initialized using the IDirect3DRM3::CreateTexture or IDirect3DRM3::CreateTextureFromSurface methods.

See Also

IDirect3DRMTexture3::InitFromImage, IDirect3DRMTexture3::InitFromResource2, IDirect3DRMTexture3::InitFromSurface

IDirect3DRMTexture3::InitFromImage

IDirect3DRMTexture3

Initializes a texture from an image in memory.

Syntax

HRESULT InitFromImage(
  LPD3DRMIMAGE lpImage
  );

Parameters

lpImage
Address of a D3DRMIMAGE structure describing the source of the texture.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

You must have created the IDirect3DRMTexture3 object to be initialized using the IDirect3DRM3::CreateTexture or IDirect3DRM3::CreateTextureFromSurface methods.

See Also

IDirect3DRMTexture3::InitFromFile, IDirect3DRMTexture3::InitFromResource2, IDirect3DRMTexture3::InitFromSurface

IDirect3DRMTexture3::InitFromResource2

IDirect3DRMTexture3

Initializes a Direct3DRMTexture2 object from a specified resource.

Syntax

HRESULT InitFromResource2(
  HModule hModule,
  LPCTSTR strName,
  LPCTSTR strType
  );

Parameters

hModule
Handle of the specified resource.
strName
The name of the resource to be used to initialize the texture.
strType
The type name of the resource used to initialize the texture. Textures can be stored in RT_BITMAP and RT_RCDATA resource types, or user-defined types. If the resource type is user-defined, this method passes the resource module handle, the resource name, and the resource type to the FindResource Win32 API.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

You must have created the IDirect3DRMTexture3 object to be initialized using the IDirect3DRM3::CreateTexture or IDirect3DRM3::CreateTextureFromSurface methods.

See Also

IDirect3DRMTexture3::InitFromFile, IDirect3DRMTexture3::InitFromImage, IDirect3DRMTexture3::InitFromSurface

IDirect3DRMTexture3::InitFromSurface

IDirect3DRMTexture3

Initializes a Direct3DRMTexture2 object by using the data from a given DirectDraw surface. This method performs the same as IDirect3DRMTexture3::InitFromSurface.

Syntax

HRESULT InitFromSurface(
  LPDIRECTDRAWSURFACE lpDDS
  );

Parameters

lpDDS
Address of a DirectDraw surface from which initialization information is drawn.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

When you create a texture from a DirectDraw surface, it is best to create the surface in system memory. This enables optimal performance for software devices and allows Direct3D Retained Mode to manage the use of video memory more effectively for hardware devices.

See Also

IDirect3DRMTexture3::InitFromFile, IDirect3DRMTexture3::InitFromImage, IDirect3DRMTexture3::InitFromResource2

IDirect3DRMTexture3::SetCacheOptions

IDirect3DRMTexture3

Provides information about how texture management should treat this texture if texture memory is restricted.

Syntax

HRESULT SetCacheOptions(
  LONG lImportance,
  DWORD dwFlags);

Parameters

lImportance
A signed value that indicates the relative importance of a texture. The default value is zero. Higher values indicate a greater importance. This value is used to calculate which textures should be downsampled last if texture memory is restricted.
dwFlags
Flags that control the texture-management system with respect to the current texture. The currently defined flags are:
D3DRMTEXTURE_FORCERESIDENT
Indicates that the texture should be kept in video memory (in a hardware scenario).
D3DRMTEXTURE_STATIC
Indicates that the texture will not change.
D3DRMTEXTURE_DOWNSAMPLEPOINT
Indicates that when the texture is downsampled, point filtering should be used.
D3DRMTEXTURE_DOWNSAMPLEBILINEAR
Indicates that when the texture is downsampled, bilinear filtering should be used.
D3DRMTEXTURE_DOWNSAMPLEREDUCEDEPTH
Indicates that when the texture is downsampled, the pixel depth should be reduced. If no lower bit depth is available, the size of the texture will be reduced.
D3DRMTEXTURE_DOWNSAMPLENONE
Indicates that the texture should never be downsampled. The default value is D3DRMTEXTURE_DOWNSAMPLEPOINT.

Return Value

Returns one of the following values:
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMTexture3::SetColors

IDirect3DRMTexture3

Sets the maximum number of colors used for rendering a Direct3DRMTexture2 object. This method is required only in the ramp color model.

Syntax

HRESULT SetColors(
  DWORD ulColors
  );

Parameters

ulColors
Number of colors. The default value is 8.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMTexture3::GetColors

IDirect3DRMTexture3::SetDecalOrigin

IDirect3DRMTexture3

Sets the origin of the decal as an offset from the top left of the decal.

Syntax

HRESULT SetDecalOrigin(
  LONG lX,
  LONG lY
  );

Parameters

lX and lY
New origin, in decal coordinates, for the decal. The default origin is [0, 0].

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

The decal's origin is mapped to its frame's position when rendering. For example, the origin of a decal of a cross would be set to the middle of the decal, and the origin of an arrow pointing down would be set to midway along the bottom edge.

This method is also used to add a decal origin key to a Direct3DRMTextureInterpolator object.

See Also

IDirect3DRMTexture3::GetDecalOrigin

IDirect3DRMTexture3::SetDecalScale

IDirect3DRMTexture3

Sets the scaling property for a decal.

Syntax

HRESULT SetDecalScale(
  DWORD dwScale
  );

Parameters

dwScale
If this parameter is TRUE, depth is taken into account when the decal is scaled and, when the decal is a texture on a frame in a scene, the decal will be scaled smaller when it is farther from the viewer and larger when it closer to the viewer. If this parameter is FALSE, depth information is ignored, and the decal will be the same size whether it is close to or far from the viewer. The default value is TRUE.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMTexture3::GetDecalScale

IDirect3DRMTexture3::SetDecalSize

IDirect3DRMTexture3

Sets the size of the decal to be used if the decal is being scaled according to its depth in the scene.

Syntax

HRESULT SetDecalSize(
  D3DVALUE rvWidth,
  D3DVALUE rvHeight
  );

Parameters

rvWidth and rvHeight
New width and height, in model coordinates, of the decal. The default size is [1, 1].

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

This method is also used to add a decal size key to a Direct3DRMTextureInterpolator object.

See Also

IDirect3DRMTexture3::GetDecalSize

IDirect3DRMTexture3::SetDecalTransparency

IDirect3DRMTexture3

Sets the transparency property of the decal.

Syntax

HRESULT SetDecalTransparency(
  BOOL bTransp
  );

Parameters

bTransp
If this parameter is TRUE, the decal has a transparent color. If it is FALSE, it has an opaque color. The default value is FALSE.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMTexture3::GetDecalTransparency

IDirect3DRMTexture3::SetDecalTransparentColor

IDirect3DRMTexture3

Sets the transparent color for a decal.

Syntax

HRESULT SetDecalTransparentColor(
  D3DCOLOR rcTransp
  );

Parameters

rcTransp
New transparent color. The default transparent color is black.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

Remarks

This method is also used to add a decal transparent color key to a Direct3DRMTextureInterpolator object.

See Also

IDirect3DRMTexture3::GetDecalTransparentColor

IDirect3DRMTexture3::SetDownsampleCallback

IDirect3DRMTexture3

Specifies a callback that texture management will use when a texture is to be downsampled, rather than using the D3DRM built-in method. If a callback has already been specified, the new callback replaces the old one. If the callback is NULL, the current callback is removed.

Syntax

typedef HRESULT (CDECL *D3DRMDOWNSAMPLECALLBACK)
  (LPVOID pArg,
  LPDIRECTDRAWSURFACE pDDSSrc,
  LPDIRECTDRAWSURFACE pDDSDst);

HRESULT SetDownsampleCallback(
  LPDIRECT3DRMTEXTURE3 lpDirect3DRMTexture,
  D3DRMDOWNSAMPLECALLBACK pCallback,
  LPVOID pArg);

Parameters

pCallback
Pointer to a callback function that will be invoked to perform the downsampling. A value of NULL indicates that the current callback is to be removed.
pArg
Application-specific data that will be passed to the callback upon invocation.

Return Value

Returns one of the following values:
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

Downsampling is done when the video memory is getting overloaded and the texture surfaces need to be reduced in size. Direct3D Retained Mode provides default methods for reducing texture sizes, such as DirectDraw blitting and bilinear filtering, but users can define a callback with their own method to scale down texture size.

This method was introduced with DirectX version 6.0.

See Also

D3DRMDOWNSAMPLECALLBACK

IDirect3DRMTexture3::SetShades

IDirect3DRMTexture3

Sets the maximum number of shades to use for each color for the Direct3DRMTexture2 object when rendering. This method is required only in the ramp color model.

Syntax

HRESULT SetShades(
  DWORD ulShades
  );

Parameters

ulShades
New number of shades. This value must be a power of 2. The default value is 16.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible return codes, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMTexture3::GetShades

IDirect3DRMTexture3::SetValidationCallback

IDirect3DRMTexture3

Sets the callback function that will validate and update the primary source texture.

Syntax

typedef HRESULT (CDECL *D3DRMVALIDATIONCALLBACK)
  (LPVOID pArg,
  DWORD dwFlags,
  DWORD dwcRects,
  LPRECT pRects);

HRESULT SetValidationCallback(
  LPDIRECT3DRMTEXTURE3 lpDirect3DRMTexture,
  D3DRMVALIDATIONCALLBACK pCallback,
  LPVOID pArg);

Parameters

pCallback
Pointer to a callback function that will be invoked to perform the validation. If a callback has already been specified, the new callback replaces the old one. Specify NULL to remove the current callback.
pArg
Application-specific data that will be passed to the callback upon invocation.

Return Value

Returns one of the following values:
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

Direct3D Retained Mode calls the texture validation callback when a texture region that has previously been marked as invalid, meaning it has changed but not been updated, now needs to be updated. The application updates the primary source and returns.

This method was introduced with DirectX version 6.0.

See Also

D3DRMVALIDATIONCALLBACK


IDirect3DRMUserVisual

Applications use the IDirect3DRMUserVisual interface to initialize Direct3DRMUserVisual objects. Note that this initialization is not necessary if the application uses the IDirect3DRM3::CreateUserVisual method; it is required only if the application uses the IDirect3DRM3::CreateObject method to create the user-visual object. An application that calls IDirect3DRM3::CreateObject then calls the IDirect3DRMUserVisual::Init method to initialize the object.

User-visual objects are application-defined data that an application can add to a scene and then render, typically by using a customized rendering module. For example, an application could add sound as a user-visual object in a scene, and then render the sound during playback. If an application changes the render state during the D3DRMUSERVISUALCALLBACK callback function it should also restore the render state before that function returns.

The IDirect3DRMUserVisual interface supports the Init method.

The IDirect3DRMUserVisual interface, like all Component Object Model (COM) interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:
AddRef
QueryInterface
Release

In addition, the IDirect3DRMUserVisual interface inherits the following methods from the IDirect3DRMObject interface:
AddDestroyCallback
Clone
DeleteDestroyCallback
GetAppData
GetClassName
GetName
SetAppData
SetName

The Direct3DRMUserVisual object is obtained by using the IDirect3DRM3::CreateUserVisual method.

IDirect3DRMUserVisual::Init

IDirect3DRMUserVisual

Initializes a Direct3DRMUserVisual object.

Syntax

HRESULT Init(
  D3DRMUSERVISUALCALLBACK d3drmUVProc,
  void  *lpArg
  );

Parameters

d3drmUVProc
Application-defined D3DRMUSERVISUALCALLBACK callback function.
lpArg
Application-defined data to be passed to the callback function.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

Applications can use the IDirect3DRM3::CreateUserVisual method to create and initialize a user-visual object at the same time. It is necessary to use IDirect3DRMUserVisual::Init only when the application has created the user-visual object by using the IDirect3DRM3::CreateObject method.


IDirect3DRMViewport2

Applications use the methods of the IDirect3DRMViewport2 interface to work with viewport objects. For a conceptual overview, see Viewports. Microsoft DirectX version 6.0 introduced the IDirect3DRMViewport2 interface. IDirect3DRMViewport2 extends the older IDirect3DRMViewport interface that it replaces by adding a flag parameter to the Clear method to indicate what should be cleared. For a history of the Direct3D Retained Mode interfaces, see Interface Changes.

The methods of the IDirect3DRMViewport2 interface can be organized into the following groups:

Camera | GetCamera
 | SetCamera
Clipping planes | GetBack
 | GetFront
 | GetPlane
 | SetBack
 | SetFront
 | SetPlane
Dimensions | GetHeight
 | GetWidth
Field of view | GetField
 | SetField
Initialization | Init
Miscellaneous | Clear
 | Configure
 | ForceUpdate
 | GetDevice
 | GetDirect3DViewport
 | Pick
 | Render
Offsets | GetX
 | GetY
Projection types | GetProjection
 | SetProjection
Scaling | GetUniformScaling
 | SetUniformScaling
Transformations | InverseTransform
 | InverseTransformVectors
 | Transform
 | TransformVectors

The IDirect3DRMViewport2 interface, like all Component Object Model (COM) interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:
AddRef
QueryInterface
Release

In addition, the IDirect3DRMViewport2 interface inherits the following methods from the IDirect3DRMObject interface:
AddDestroyCallback
Clone
DeleteDestroyCallback
GetAppData
GetClassName
GetName
SetAppData
SetName

The Direct3DRMViewport object is obtained by using the IDirect3DRM3::CreateViewport method.

IDirect3DRMViewport2::Clear

IDirect3DRMViewport2

Clears the given viewport to the current background color. This is an enhanced version of IDirect3DRMViewport::Clear that provides flags that indicate what should be cleared. IDirect3DRMViewport::Clear takes no parameters.

Syntax

HRESULT Clear(
  DWORD dwFlags);

Parameters

dwFlags
The following flags are currently defined and can be logically combined.
D3DRMCLEAR_TARGET
Clear only the destination rendering surface.
D3DRMCLEAR_ZBUFFER
Clear only the z-buffer surface.
D3DRMCLEAR_DIRTYRECTS
Clear only the dirty rectangle list.
D3DRMCLEAR_ALL
Clear the target, z-buffer, and dirty rectangle list. This flag is analogous to using IDirect3DRMViewport::Clear.

Return Value

Returns one of the following values:
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMViewport2::Configure

IDirect3DRMViewport2

Reconfigures the origin and dimensions of a viewport.

Syntax

HRESULT Configure(
  LONG lX,
  LONG lY,
  DWORD dwWidth,
  DWORD dwHeight
  );

Parameters

lX and lY
New position of the viewport.
dwWidth and dwHeight
New width and height of the viewport.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

This method returns D3DRMERR_BADVALUE if lX + dwWidth or lY + dwHeight are greater than the width or height of the device, or if any value of lX, lY, dwWidth, or dwHeight is less than zero.

IDirect3DRMViewport2::ForceUpdate

IDirect3DRMViewport2

Forces an area of the viewport to be updated. The specified area will be copied to the screen at the next call to the IDirect3DRMDevice3::Update method.

Syntax

HRESULT ForceUpdate(
  DWORD dwX1,
  DWORD dwY1,
  DWORD dwX2,
  DWORD dwY2
  );

Parameters

dwX1 and dwY1
Upper-left corner of area to be updated.
dwX2 and dwY2
Lower-right corner of area to be updated.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

The system might update any region that is larger than the specified rectangle, possibly including the entire window.

IDirect3DRMViewport2::GetBack

IDirect3DRMViewport2

Retrieves the position of the back clipping plane for a viewport.

Syntax

D3DVALUE GetBack( );

Return Value

Returns a value describing the distance between the back clipping plane and the camera.

See Also

IDirect3DRMViewport2::SetBack, Viewing Frustum

IDirect3DRMViewport2::GetCamera

IDirect3DRMViewport2

Retrieves the camera for a viewport.

Syntax

HRESULT GetCamera(
  LPDIRECT3DRMFRAME3 *lpCamera
  );

Parameters

lpCamera
Pointer to the Direct3DRMFrame object representing the camera.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMViewport2::SetCamera, Camera

IDirect3DRMViewport2::GetDevice

IDirect3DRMViewport2

Retrieves the device associated with a viewport.

Syntax

HRESULT GetDevice(
  LPDIRECT3DRMDEVICE3 *lpD3DRMDevice
  );

Parameters

lpD3DRMDevice
Address of a variable that represents the device object. For more information about devices, see Output Devices.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMViewport2::GetDirect3DViewport

IDirect3DRMViewport2

Retrieves the Direct3D viewport corresponding to the current Direct3DRMViewport.

Syntax

HRESULT GetDirect3DViewport(
  LPDIRECT3DVIEWPORT  *lplpD3DViewport
  );

Parameters

lplpD3DViewport
Address of a pointer that is initialized with a pointer to the Direct3DViewport object.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMViewport2::GetField

IDirect3DRMViewport2

Retrieves the field of view for a viewport.

Syntax

D3DVALUE GetField( );

Return Value

Returns a value describing the field of view.

See Also

IDirect3DRMViewport2::SetField, Viewing Frustum

IDirect3DRMViewport2::GetFront

IDirect3DRMViewport2

Retrieves the position of the front clipping plane for a viewport.

Syntax

D3DVALUE GetFront( );

Return Value

Returns a value describing the distance from the camera to the front clipping plane.

See Also

IDirect3DRMViewport2::SetFront, Viewing Frustum

IDirect3DRMViewport2::GetHeight

IDirect3DRMViewport2

Retrieves the height, in pixels, of the viewport.

Syntax

DWORD GetHeight( );

Return Value

Returns the pixel height.

IDirect3DRMViewport2::GetPlane

IDirect3DRMViewport2

Retrieves the dimensions of the viewport on the front clipping plane.

Syntax

HRESULT GetPlane(
  D3DVALUE *lpd3dvLeft,
  D3DVALUE *lpd3dvRight,
  D3DVALUE *lpd3dvBottom,
  D3DVALUE *lpd3dvTop
  );

Parameters

lpd3dvLeft, lpd3dvRight, lpd3dvBottom, and lpd3dvTop
Addresses of variables that will be filled with the dimensions of the viewport on the front clipping plane.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMViewport2::SetPlane

IDirect3DRMViewport2::GetProjection

IDirect3DRMViewport2

Retrieves the viewport's projection type. A viewport can use either orthographic or perspective projection.

Syntax

D3DRMPROJECTIONTYPE GetProjection( );

Return Value

Returns one of the members of the D3DRMPROJECTIONTYPE enumerated type.

See Also

IDirect3DRMViewport2::SetProjection

IDirect3DRMViewport2::GetUniformScaling

IDirect3DRMViewport2

Retrieves the scaling property used to scale the viewing volume into the larger window dimension.

Syntax

BOOL GetUniformScaling( );

Return Value

Returns TRUE if the viewport scales uniformly, or FALSE otherwise.

See Also

IDirect3DRMViewport2::SetUniformScaling

IDirect3DRMViewport2::GetWidth

IDirect3DRMViewport2

Retrieves the width, in pixels, of the viewport.

Syntax

DWORD GetWidth( );

Return Value

Returns the pixel width.

IDirect3DRMViewport2::GetX

IDirect3DRMViewport2

Retrieves the x-offset of the start of the viewport on a device.

Syntax

LONG GetX( );

Return Value

Returns the x-offset.

IDirect3DRMViewport2::GetY

IDirect3DRMViewport2

Retrieves the y-offset of the start of the viewport on a device.

Syntax

LONG GetY( );

Return Value

Returns the y-offset.

IDirect3DRMViewport2::Init

IDirect3DRMViewport2

Initializes a Direct3DRMViewport object.

Syntax

HRESULT Init(
  LPDIRECT3DRMDEVICE3 lpD3DRMDevice,
  LPDIRECT3DRMFRAME3 lpD3DRMFrameCamera,
  DWORD xpos,
  DWORD ypos,
  DWORD width,
  DWORD height
  );

Parameters

lpD3DRMDevice
Address of the device object associated with this viewport. For more information about devices, see Output Devices.
lpD3DRMFrameCamera
Address of the camera frame associated with this viewport.
xpos and ypos
The x- and y-coordinates of the upper-left corner of the viewport.
width and height
Width and height of the viewport.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMViewport2::InverseTransform

IDirect3DRMViewport2

Transforms the vector in the lprvSrc parameter in screen coordinates to world coordinates, and returns the result in the lprvDst parameter.

Syntax

HRESULT InverseTransform(
  D3DVECTOR  *lprvDst,
  D3DRMVECTOR4D  *lprvSrc
  );

Parameters

lprvDst
Address of a D3DVECTOR structure that will be filled with the result of the operation when the method returns.
lprvSrc
Address of a D3DRMVECTOR4D structure that represents the source of the operation.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMViewport2::InverseTransformVectors, IDirect3DRMViewport2::Transform

IDirect3DRMViewport2::InverseTransformVectors

IDirect3DRMViewport2

This transforms an array of vectors in the lpSrcVectors parameter in screen coordinates to world coordinates, and returns the result in the lprvDstVectors parameter

Syntax

HRESULT InverseTransformVectors(
   DWORD dwNumVectors,
   LPD3DVECTOR	lpDstVectors,
   LPD3DRMVECTOR4D lpSrcVectors);

Parameters

dwNumVectors
The number of vectors whose coordinates are to be transformed.
lpDstVectors
Destination of the transformation.
lpSrcVectors
Array of D3DRMVECTOR4D structures representing the vectors to transform.

Return Value

Returns one of the following values:
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

See Also

IDirect3DRMViewport2::TransformVectors, IDirect3DRMViewport2::InverseTransform

IDirect3DRMViewport2::Pick

IDirect3DRMViewport2

Finds a depth-sorted list of objects (and faces, if relevant) that includes the path taken in the hierarchy from the root down to the frame that contained the object.

Syntax

HRESULT Pick(
  LONG lX,
  LONG lY,
  LPDIRECT3DRMPICKEDARRAY *lplpVisuals
  );

Parameters

lX and lY
Coordinates used for picking.
lplpVisuals
Address of a pointer that is initialized with a valid pointer to the IDirect3DRMPickedArray interface if the call succeeds.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMViewport2::Render

IDirect3DRMViewport2

Renders a frame hierarchy to the given viewport. Only those visuals on the given frame and any frames below it in the hierarchy are rendered.

Syntax

HRESULT Render(
  LPDIRECT3DRMFRAME lpD3DRMFrame
  );

Parameters

lpD3DRMFrame
Address of a variable that represents the Direct3DRMFrame object that represents the frame hierarchy to be rendered.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values. This method returns an error if you try to use the IDirect3DRM3::SetOptions method to indicate right-handed support and at the same time use the older means (IDirect3DRMViewport2::SetProjection) for providing right-handed support.

IDirect3DRMViewport2::SetBack

IDirect3DRMViewport2

Sets the position of the back clipping plane for a viewport.

Syntax

HRESULT SetBack(
  D3DVALUE rvBack
  );

Parameters

rvBack
Distance between the camera and the back clipping plane. The default value is 100.0. Reasonable values depend on other viewing frustrum settings. For more information, see Viewports.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

This method is also used to add a back clipping plane position key to a Direct3DRMViewportInterpolator object.

See Also

IDirect3DRMViewport2::GetBack, IDirect3DRMViewport2::SetFront, Viewing Frustum

IDirect3DRMViewport2::SetCamera

IDirect3DRMViewport2

Sets a camera for a viewport.

Syntax

HRESULT SetCamera(
  LPDIRECT3DRMFRAME3 lpCamera
  );

Parameters

lpCamera
Address of a variable that represents the Direct3DRMFrame object that represents the camera.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

This method sets a viewport's position, direction, and orientation to that of the given camera frame. The view is oriented along the positive z-axis of the camera frame, with the up direction being in the direction of the positive y-axis.

See Also

IDirect3DRMViewport2::GetCamera, Camera

IDirect3DRMViewport2::SetField

IDirect3DRMViewport2

Sets the field of view for a viewport.

Syntax

HRESULT SetField(
  D3DVALUE rvField
  );

Parameters

rvField
New field of view. This value is a fraction of the viewing angle. The default value is 0.5. If this value is less than or equal to zero, this method returns the D3DRMERR_BADVALUE error. The viewing angle is defined as the 2 times the arctangent of the front clipping plane over the distance from the camera. See Viewing Frustum for more information on the viewing angle. An rvField value of 0.5 would be one-half the viewing angle A shown in the Viewing Frustum section.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

This method is also used to add a field of view key to a Direct3DRMViewportInterpolator object.

See Also

IDirect3DRMViewport2::GetField, Viewing Frustum

IDirect3DRMViewport2::SetFront

IDirect3DRMViewport2

Sets the position of the front clipping plane for a viewport.

Syntax

HRESULT SetFront(
  D3DVALUE rvFront
  );

Parameters

rvFront
Distance from the camera to the front clipping plane. The default value is 1.0. Reasonable values depend on other viewing frustrum settings. For more information, see Viewports.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

If the value passed is less than or equal to zero, this method returns the D3DRMERR_BADVALUE error.

This method is also used to add a front clipping plane position key to a Direct3DRMViewportInterpolator object.

See Also

IDirect3DRMViewport2::GetFront, Viewing Frustum

IDirect3DRMViewport2::SetPlane

IDirect3DRMViewport2

Sets the dimensions of the viewport on the front clipping plane, relative to the camera's z-axis.

Syntax

HRESULT SetPlane(
  D3DVALUE rvLeft,
  D3DVALUE rvRight,
  D3DVALUE rvBottom,
  D3DVALUE rvTop
  );

Parameters

rvLeft, rvRight, rvBottom, and rvTop
Minimum x-, maximum x-, minimum y-, and maximum y-coordinates, respectively, of the four sides of the viewport.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

Unlike the IDirect3DRMViewport2::SetField method, which specifies a centered proportional viewport, this method allows you to specify a viewport of arbitrary proportion and position. For example, this method could be used to construct a sheared viewing frustum to implement a right- or left-eye stereo view.

This method is also used to add a plane key to a Direct3DRMViewportInterpolator object.

See Also

IDirect3DRMViewport2::GetPlane, IDirect3DRMViewport2::SetField

IDirect3DRMViewport2::SetProjection

IDirect3DRMViewport2

Sets the projection type for a viewport.

Syntax

HRESULT SetProjection(
  D3DRMPROJECTIONTYPE rptType
  );

Parameters

rptType
One of the members of the D3DRMPROJECTIONTYPE enumerated type.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

With DirectX version 6.0 or later, use IDirect3DRM3::SetOptions to specify right-handed geometry.

See Also

IDirect3DRMViewport2::GetProjection

IDirect3DRMViewport2::SetUniformScaling

IDirect3DRMViewport2

Sets the scaling property used to scale the viewing volume into the larger dimension of the window.

Syntax

HRESULT SetUniformScaling(
  BOOL bScale
  );

Parameters

bScale
New scaling property. If this parameter is TRUE, the same horizontal and vertical scaling factor is used to scale the viewing volume. Otherwise, different scaling factors are used to scale the viewing volume exactly into the window. The default setting is TRUE.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

This method is typically used with the IDirect3DRMViewport2::SetPlane method to support banding.

See Also

IDirect3DRMViewport2::GetUniformScaling

IDirect3DRMViewport2::Transform

IDirect3DRMViewport2

Transforms the vector in the lprvSrc parameter in world coordinates to screen coordinates, and returns the result in the lprvDst parameter.

Syntax

HRESULT Transform(
  D3DRMVECTOR4D  *lprvDst,
  D3DVECTOR  *lprvSrc
  );

Parameters

lprvDst
Address of a D3DRMVECTOR4D structure that acts as the destination for the transformation operation.
lprvSrc
Address of a D3DVECTOR structure that acts as the source for the transformation operation.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

The result of the transformation is a four-element homogeneous vector. The point represented by the resulting vector is visible if the following equations are true:

Equations for testing whether the point is visible

See Also

IDirect3DRMViewport2::TransformVectors, IDirect3DRMViewport2::InverseTransform

IDirect3DRMViewport2::TransformVectors

IDirect3DRMViewport2

Transforms an array of vectors in the lprvSrcVectors parameter in world coordinates to screen coordinates, and returns the result in the lprvDstVectors parameter.

Syntax

HRESULT TransformVectors(
  DWORD dwNumVectors,
  LPD3DRMVECTOR4D lpDstVectors,
  LPD3DVECTOR lpSrcVectors);

Parameters

dwNumVectors
The number of vectors to be transformed.
lpDstVectors
Array of D3DRMVECTOR4D structures representing the vectors transformed to screen coordinates.
lpSrcVectors
Array of vectors to transform.

Return Value

Returns one of the following values:
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

See Also

IDirect3DRMViewport2::Transform, IDirect3DRMViewport2::InverseTransformVectors


IDirect3DRMViewportArray

Applications use the methods of the IDirect3DRMViewportArray interface to organize viewport objects. This section is a reference to the methods of this interface. For a conceptual overview, see Viewports.

The IDirect3DRMViewportArray interface supports the following methods:
GetElement
GetSize

The IDirect3DRMViewportArray interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:
AddRef
QueryInterface
Release

The Direct3DRMViewportArray object is obtained by calling the IDirect3DRMDevice3::GetViewports method.

IDirect3DRMViewportArray::GetElement

IDirect3DRMViewportArray

Retrieves a specified element in a Direct3DRMViewportArray object.

Syntax

HRESULT GetElement(
  DWORD index,
  LPDIRECT3DRMVIEWPORT  *lplpD3DRMViewport
  );

Parameters

index
Element in the array.
lplpD3DRMViewport
Address that will be filled with a pointer to an IDirect3DRMViewport interface.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

You can use QueryInterface to obtain a pointer to the version of IDirect3DRMViewport that you want, for example, IDirect3DRMViewport2. You cannot simply cast the lplpD3DRMViewport parameter to a different version. You must use QueryInterface.

IDirect3DRMViewportArray::GetSize

IDirect3DRMViewportArray

Retrieves the number of elements contained in a Direct3DRMViewportArray object.

Syntax

DWORD GetSize( );

Return Value

Returns the number of elements.


IDirect3DRMVisual

IDirect3DRMVisual does not provide any Microsoft® Direct3D® Retained Mode methods, but the interfaces for the visual objects derive from the IDirect3DRMVisual interface. For a complete interface hierarchy, see the Interface Hierarchy Chart.

Visuals are objects that can be rendered in a scene. Visuals are visible only when they are added to a frame in that scene. An application can add a visual to a frame by using the IDirect3DRMFrame3::AddVisual method. The frame provides the visual with position and orientation for rendering.

The following interfaces derive from IDirect3DRMVisual.

  • IDirect3DRMFrame3
  • IDirect3DRMMesh
  • IDirect3DRMMeshBuilder3
  • IDirect3DRMProgressiveMesh
  • IDirect3DRMShadow2
  • IDirect3DRMTexture3
  • IDirect3DRMUserVisual

The IDirect3DRMVisual interface, like all Component Object Model (COM) interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:
AddRef
QueryInterface
Release


IDirect3DRMVisualArray

Applications use the methods of the IDirect3DRMVisualArray interface to organize groups of visual objects.

Visuals are objects that can be rendered in a scene. Visuals are visible only when they are added to a frame in that scene. An application can add a visual to a frame by using the IDirect3DRMFrame3::AddVisual method. The frame provides the visual with position and orientation for rendering.

Note: although there is a IDirect3DRMVisual COM interface, it has no Direct3D Retained Mode-specific methods.

The most common visual types are Direct3DRMMeshBuilder3 and Direct3DRMTexture objects.

The IDirect3DRMVisualArray interface supports the following methods:
GetElement
GetSize

The IDirect3DRMVisualArray interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:
AddRef
QueryInterface
Release

The Direct3DRMVisualArray object is obtained by calling the IDirect3DRMFrame3::GetVisuals method.

IDirect3DRMVisualArray::GetElement

IDirect3DRMVisualArray

Retrieves a specified element in a Direct3DRMVisualArray object.

Syntax

HRESULT GetElement(
  DWORD index,
  LPDIRECT3DRMVISUAL  *lplpD3DRMVisual
  );

Parameters

index
Element in the array.
lplpD3DRMVisual
Address that will be filled with a pointer to an IDirect3DRMVisual interface.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMVisualArray::GetSize

IDirect3DRMVisualArray

Retrieves the number of elements contained in a Direct3DRMVisualArray object.

Syntax

DWORD GetSize( );

Return Value

Returns the number of elements.


IDirect3DRMWinDevice

Applications use the methods of the IDirect3DRMWinDevice interface to respond to window messages in a window procedure. This section is a reference to the methods of this interface. For a conceptual overview, see Window Management.

The IDirect3DRMWinDevice interface supports the following methods:
HandleActivate
HandlePaint

The IDirect3DRMWinDevice interface, like all Component Object Model (COM) interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:
AddRef
QueryInterface
Release

The Direct3DRMWinDevice object is obtained by calling the IDirect3DRMObject::QueryInterface method and specifying IID_IDirect3DRMWinDevice, or by calling a method such as IDirect3DRM3::CreateDeviceFromD3D. The IDirect3DRMWinDevice methods are inherited from the IDirect3DRMDevice3 interface.

IDirect3DRMWinDevice::HandleActivate

IDirect3DRMWinDevice

Responds to a Microsoft® Windows®w WM_ACTIVATE message. This ensures that the colors are correct in the active rendering window.

Syntax

HRESULT HandleActivate(
  WORD wParam
  );

Parameters

wParam
WPARAM parameter passed to the message-processing procedure with the WM_ACTIVATE message.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMWinDevice::HandlePaint

IDirect3DRMWinDevice

Responds to a Windows WM_PAINT message. The hDC parameter should be taken from the PAINTSTRUCT structure given to the Windows BeginPaint function. This method should be called before repainting any application areas in the window because it may repaint areas outside the viewports that have been created on the device.

Syntax

HRESULT HandlePaint(
  HDC hDC
  );

Parameters

hDC
Handle of the device context (DC).

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.


IDirect3DRMWrap

Applications use the methods of the IDirect3DRMWrap interface to work with wrap objects. This section is a reference to the methods of this interface. For a conceptual overview, see Wraps.

The methods of the IDirect3DRMWrap interface can be organized into the following groups:
Initialization | Init
Wrap | Apply
 | ApplyRelative

The IDirect3DRMWrap interface, like all Component Object Model (COM) interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:
AddRef
QueryInterface
Release

In addition, the IDirect3DRMWrap interface inherits the following methods from the IDirect3DRMObject interface:
AddDestroyCallback
Clone
DeleteDestroyCallback
GetAppData
GetClassName
GetName
SetAppData
SetName

The Direct3DRMWrap object is obtained by using the IDirect3DRM3::CreateWrap method.

IDirect3DRMWrap::Apply

IDirect3DRMWrap

Applies a Direct3DRMWrap object to its destination object. The destination object is typically a face or a mesh.

Syntax

HRESULT Apply(
  LPDIRECT3DRMOBJECT lpObject
  );

Parameters

lpObject
Address of the destination object.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRM3::CreateWrap

IDirect3DRMWrap::ApplyRelative

IDirect3DRMWrap

Applies the wrap to the vertices of the object, first transforming each vertex by the frame's world transformation and the inverse world transformation of the wrap's reference frame.

Syntax

HRESULT ApplyRelative(
  LPDIRECT3DRMFRAME frame,
  LPDIRECT3DRMOBJECT mesh
  );

Parameters

frame
Direct3DRMFrame object containing the object to wrap.
mesh
Direct3DRMWrap object to apply.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRM3::CreateWrap

IDirect3DRMWrap::Init

IDirect3DRMWrap

Initializes a Direct3DRMWrap object.

Syntax

HRESULT Init(
  D3DRMWRAPTYPE d3drmwt,
  LPDIRECT3DRMFRAME lpd3drmfRef,
  D3DVALUE ox,
  D3DVALUE oy,
  D3DVALUE oz,
  D3DVALUE dx,
  D3DVALUE dy,
  D3DVALUE dz,
  D3DVALUE ux,
  D3DVALUE uy,
  D3DVALUE uz,
  D3DVALUE ou,
  D3DVALUE ov,
  D3DVALUE su,
  D3DVALUE sv
  );

Parameters

d3drmwt
One of the members of the D3DRMWRAPTYPE enumerated type.
lpd3drmfRef
Address of a Direct3DRMFrame object representing the reference frame for this Direct3DRMWrap object.
ox, oy, and oz
Origin of the wrap.
dx, dy, and dz
The z-axis of the wrap.
ux, uy, and uz
The y-axis of the wrap.
ou and ov
Origin of the texture.
su and sv
Scale factor of the texture.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRM3::CreateWrap


C++ Nonmember Functions

The Microsoft® Direct3D® Retained Mode nonmember functions for C++ are:

  • D3DRMColorGetAlpha
  • D3DRMColorGetBlue
  • D3DRMColorGetGreen
  • D3DRMColorGetRed
  • D3DRMCreateColorRGB
  • D3DRMCreateColorRGBA
  • D3DRMMatrixFromQuaternion
  • D3DRMQuaternionFromRotation
  • D3DRMQuaternionMultiply
  • D3DRMQuaternionSlerp
  • D3DRMVectorAdd
  • D3DRMVectorCrossProduct
  • D3DRMVectorDotProduct
  • D3DRMVectorModulus
  • D3DRMVectorNormalize
  • D3DRMVectorRandom
  • D3DRMVectorReflect
  • D3DRMVectorRotate
  • D3DRMVectorScale
  • D3DRMVectorSubtract
  • Direct3DRMCreate

D3DRMColorGetAlpha

Retrieves the alpha component of a color.

Syntax

D3DVALUE D3DRMColorGetAlpha(
  D3DCOLOR d3drmc
  );

Parameters

d3drmc
Color from which the alpha component is retrieved. A value between 0 and 255.

Return Value

Returns the alpha value if successful, or zero otherwise.

See Also

D3DRMColorGetBlue, D3DRMColorGetGreen, D3DRMColorGetRed

D3DRMColorGetBlue

Retrieves the blue component of a color.

Syntax

D3DVALUE D3DRMColorGetBlue(
  D3DCOLOR d3drmc
  );

Parameters

d3drmc
Color from which the blue component is retrieved. A value between 0 and 255.

Return Value

Returns the blue value if successful, or zero otherwise.

See Also

D3DRMColorGetAlpha, D3DRMColorGetGreen, D3DRMColorGetRed

D3DRMColorGetGreen

Retrieves the green component of a color.

Syntax

D3DVALUE D3DRMColorGetGreen(
  D3DCOLOR d3drmc
  );

Parameters

d3drmc
Color from which the green component is retrieved. A value between 0 and 255.

Return Value

Returns the green value if successful, or zero otherwise.

See Also

D3DRMColorGetAlpha, D3DRMColorGetBlue, D3DRMColorGetRed

D3DRMColorGetRed

Retrieves the red component of a color.

Syntax

D3DVALUE D3DRMColorGetRed(
  D3DCOLOR d3drmc
  );

Parameters

d3drmc
Color from which the red component is retrieved.

Return Value

Returns the red value if successful, or zero otherwise.

See Also

D3DRMColorGetAlpha, D3DRMColorGetBlue, D3DRMColorGetGreen

D3DRMCreateColorRGB

Creates an RGB color from supplied red, green, and blue components.

Syntax

D3DCOLOR D3DRMCreateColorRGB(
  D3DVALUE red,
  D3DVALUE green,
  D3DVALUE blue
  );

Parameters

red, green, and blue
Components of the RGB color.

Return Value

Returns the new RGB value if successful, or zero otherwise.

See Also

D3DRMCreateColorRGBA

D3DRMCreateColorRGBA

Creates an RGBA color from supplied red, green, blue, and alpha components.

Syntax

D3DCOLOR D3DRMCreateColorRGBA(
  D3DVALUE red,
  D3DVALUE green,
  D3DVALUE blue,
  D3DVALUE alpha
  );

Parameters

red, green, blue, and alpha
Components of the RGBA color. Values between 0 and 1.

Return Value

Returns the new RGBA value if successful, or zero otherwise.

See Also

D3DRMCreateColorRGB

D3DRMMatrixFromQuaternion

Calculates the matrix for the rotation that a unit quaternion represents.

Syntax

void D3DRMMatrixFromQuaternion (
  D3DRMMATRIX4D mat,
  LPD3DRMQUATERNION lpquat
  );

Parameters

mat
Address that will contain the calculated matrix when the function returns. (The D3DRMMATRIX4D type is an array.)
lpquat
Address of the D3DRMQUATERNION structure.

Return Value

No return value.

D3DRMQuaternionFromRotation

Retrieves a unit quaternion that represents a rotation of a specified number of radians around the given axis.

Syntax

LPD3DRMQUATERNION D3DRMQuaternionFromRotation(
  LPD3DRMQUATERNION lpquat,
  LPD3DVECTOR lpv,
  D3DVALUE theta
  );

Parameters

lpquat
Address of a D3DRMQUATERNION structure that will contain the result of the operation.
lpv
Address of a D3DVECTOR structure specifying the axis of rotation.
theta
Number of radians to rotate around the axis specified by the lpv parameter.

Return Value

Returns the address of the unit quaternion that was passed as the first parameter if successful, or zero otherwise.

D3DRMQuaternionMultiply

Calculates the product of two quaternion structures.

Syntax

LPD3DRMQUATERNION D3DRMQuaternionMultiply(
  LPD3DRMQUATERNION lpq,
  LPD3DRMQUATERNION lpa,
  LPD3DRMQUATERNION lpb
  );

Parameters

lpq
Address of the D3DRMQUATERNION structure that will contain the product of the multiplication.
lpa and lpb
Addresses of the D3DRMQUATERNION structures that will be multiplied together.

Return Value

Returns the address of the quaternion that was passed as the first parameter if successful, or zero otherwise.

D3DRMQuaternionSlerp

Interpolates between two quaternion structures, using spherical linear interpolation.

Syntax

LPD3DRMQUATERNION D3DRMQuaternionSlerp(
  LPD3DRMQUATERNION lpq,
  LPD3DRMQUATERNION lpa,
  LPD3DRMQUATERNION lpb,
  D3DVALUE alpha
  );

Parameters

lpq
Address of the D3DRMQUATERNION structure that will contain the interpolation.
lpa and lpb
Addresses of the D3DRMQUATERNION structures that are used as the starting and ending points for the interpolation, respectively.
alpha
Value between 0 and 1 that specifies how far to interpolate between lpa and lpb.

Return Value

Returns the address of the quaternion that was passed as the first parameter if successful, or zero otherwise.

D3DRMVectorAdd

Adds two vectors.

Syntax

LPD3DVECTOR D3DRMVectorAdd(
  LPD3DVECTOR lpd,
  LPD3DVECTOR lps1,
  LPD3DVECTOR lps2
  );

Parameters

lpd
Address of a D3DVECTOR structure that will contain the result of the addition.
lps1 and lps2
Addresses of the D3DVECTOR structures that will be added together.

Return Value

Returns the address of the vector that was passed as the first parameter if successful, or zero otherwise.

D3DRMVectorCrossProduct

Calculates the cross product of the two vector arguments.

Syntax

LPD3DVECTOR D3DRMVectorCrossProduct(
  LPD3DVECTOR lpd,
  LPD3DVECTOR lps1,
  LPD3DVECTOR lps2
  );

Parameters

lpd
Address of a D3DVECTOR structure that will contain the result of the cross product.
lps1 and lps2
Addresses of the D3DVECTOR structures from which the cross product is produced.

Return Value

Returns the address of the vector that was passed as the first parameter if successful, or zero otherwise.

D3DRMVectorDotProduct

Returns the vector dot product.

Syntax

D3DVALUE D3DRMVectorDotProduct(
  LPD3DVECTOR lps1,
  LPD3DVECTOR lps2
  );

Parameters

lps1 and lps2
Addresses of the D3DVECTOR structures from which the dot product is produced.

Return Value

Returns the result of the dot product if successful, or zero otherwise.

D3DRMVectorModulus

Returns the length of a vector according to the following formula:

Square root of x squared plus y squared plus z squared

Syntax

D3DVALUE D3DRMVectorModulus(
  LPD3DVECTOR lpv
  );

Parameters

lpv
Address of the D3DVECTOR structure whose length is returned.

Return Value

Returns the length of the D3DVECTOR structure if successful, or zero otherwise.

D3DRMVectorNormalize

Scales a vector so that its modulus is 1.

Syntax

LPD3DVECTOR D3DRMVectorNormalize(
  LPD3DVECTOR lpv
  );

Parameters

lpv
Address of a D3DVECTOR structure that will contain the result of the scaling operation.

Return Value

Returns the address of the vector that was passed as the first parameter if successful, or zero if an error occurs. An example of an error is if a zero vector were passed.

D3DRMVectorRandom

Returns a random unit vector.

Syntax

LPD3DVECTOR D3DRMVectorRandom(
  LPD3DVECTOR lpd
  );

Parameters

lpd
Address of a D3DVECTOR structure that will contain a random unit vector.

Return Value

Returns the address of the vector that was passed as the first parameter if successful, or zero otherwise.

D3DRMVectorReflect

Reflects a ray about a given normal.

Syntax

LPD3DVECTOR D3DRMVectorReflect(
  LPD3DVECTOR lpd,
  LPD3DVECTOR lpRay,
  LPD3DVECTOR lpNorm
  );

Parameters

lpd
Address of a D3DVECTOR structure that will contain the result of the operation.
lpRay
Address of a D3DVECTOR structure that will be reflected about a normal.
lpNorm
Address of a D3DVECTOR structure specifying the normal about which the vector specified in lpRay is reflected.

Return Value

Returns the address of the vector that was passed as the first parameter if successful, or zero otherwise.

D3DRMVectorRotate

Rotates a vector around a given axis. Returns a normalized vector if successful.

Syntax

LPD3DVECTOR D3DRMVectorRotate(
  LPD3DVECTOR lpr,
  LPD3DVECTOR lpv,
  LPD3DVECTOR lpaxis,
  D3DVALUE theta
  );

Parameters

lpr
Address of a D3DVECTOR structure that will contain the normalized result of the operation.
lpv
Address of a D3DVECTOR structure that will be rotated around the given axis.
lpaxis
Address of a D3DVECTOR structure that is the axis of rotation.
theta
The amount of rotation in radians.

Return Value

Returns the address of the vector that was passed as the first parameter if successful, or zero otherwise. This vector is normalized.

D3DRMVectorScale

Scales a vector uniformly in all three axes.

Syntax

LPD3DVECTOR D3DRMVectorScale(
  LPD3DVECTOR lpd,
  LPD3DVECTOR lps,
  D3DVALUE factor
  );

Parameters

lpd
Address of a D3DVECTOR structure that will contain the result of the operation.
lps
Address of a D3DVECTOR structure that this function scales.
factor
Scaling factor. A value of 1 does not change the scaling; a value of 2 doubles it, and so on.

Return Value

Returns the address of the vector that was passed as the first parameter if successful, or zero otherwise.

D3DRMVectorSubtract

Subtracts two vectors.

Syntax

LPD3DVECTOR D3DRMVectorSubtract(
  LPD3DVECTOR lpd,
  LPD3DVECTOR lps1,
  LPD3DVECTOR lps2
  );

Parameters

lpd
Address of a D3DVECTOR structure that will contain the result of the operation.
lps1
Address of the D3DVECTOR structure from which lps2 is subtracted.
lps2
Address of the D3DVECTOR structure that is subtracted from lps1.

Return Value

Returns the address of the vector that was passed as the first parameter if successful, or zero otherwise.

Direct3DRMCreate

Creates an instance of a Direct3DRM object.

Syntax

HRESULT Direct3DRMCreate(
  LPDIRECT3DRM FAR  *lplpD3DRM
  );

Parameters

lplpD3DRM
Address of a pointer that will be initialized with a valid Direct3DRM pointer if the call succeeds.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMObject


C++ Constants

Microsoft® Direct3D® Retained Mode includes other type definitions for C++, not included in structures or enumerated types. These are:

  • D3DRMANIMATIONOPTIONS
  • D3DRMCOLORMODEL
  • D3DRMINTERPOLATIONOPTIONS
  • D3DRMLOADOPTIONS
  • D3DRMMAPPING
  • D3DRMMATRIX4D
  • D3DRMSAVEOPTIONS

D3DRMANIMATIONOPTIONS

Specifies values used by the IDirect3DRMAnimation2::GetOptions and IDirect3DRMAnimation2::SetOptions methods and the D3DRMANIMATIONKEY structure to define how animations are played.

Syntax

typedef DWORD D3DRMANIMATIONOPTIONS;
#define D3DRMANIMATION_CLOSED             0x02L
#define D3DRMANIMATION_LINEARPOSITION     0x04L
#define D3DRMANIMATION_OPEN               0x01L
#define D3DRMANIMATION_POSITION           0x00000020L
#define D3DRMANIMATION_SCALEANDROTATION   0x00000010L
#define D3DRMANIMATION_SPLINEPOSITION     0x08L

Parameters

D3DRMANIMATION_CLOSED
Animation plays continually, looping back to the beginning when it reaches the end. In a closed animation, if you want a smooth transition from the end to the beginning, the last key in the animation should be a repeat of the first. This repeated key is used to indicate the time difference between the last and first keys in the looping animation. However, if the last key is not a repeat of the first, it is no longer being ignored in the new interfaces (IDirect3DRMAnimation2, IDirect3DRMAnimationSet2). It takes effect, and then the animation jumps immediately back to the beginning.
D3DRMANIMATION_LINEARPOSITION
Animation's position is set linearly.
D3DRMANIMATION_OPEN
Animation plays once and stops.
D3DRMANIMATION_POSITION
Animation's position matrix should overwrite any transformation matrices that could be set by other methods.
D3DRMANIMATION_SCALEANDROTATION
Animation's scale and rotation matrix should overwrite any transformation matrices that could be set by other methods.
D3DRMANIMATION_SPLINEPOSITION
Animation's position is set using splines.

D3DRMCOLORMODEL

Describes the color model implemented by the device. For more information, see the D3DCOLORMODEL enumerated type.

Syntax

typedef D3DCOLORMODEL D3DRMCOLORMODEL;

See Also

D3DCOLORMODEL

D3DRMINTERPOLATIONOPTIONS

Defines options for the IDirect3DRMInterpolator::Interpolate method. These options modify how the object is loaded.

Syntax

typedef DWORD D3DRMINTERPOLATIONOPTIONS;
#define D3DRMINTERPOLATION_OPEN 0x01L
#define D3DRMINTERPOLATION_CLOSED 0x02L
#define D3DRMINTERPOLATION_NEAREST 0x0100L
#define D3DRMINTERPOLATION_LINEAR 0x04L
#define D3DRMINTERPOLATION_SPLINE 0x08L
#define D3DRMINTERPOLATION_VERTEXCOLOR 0x40L
#define D3DRMINTERPOLATION_SLERPNORMALS 0x80L

Parameters

D3DRMINTERPOLATION_OPEN
First and last keys of each key chain will fix the interpolated values outside of the index span.
D3DRMINTERPOLATION_CLOSED
The interpolation is cyclic. The keys effectively repeat infinitely with a period equal to the index span. For compatibility with animations, any key with an index equal to the end of the span is ignored.
D3DRMINTERPOLATION_NEAREST
Nearest key value is used for determining in-between values on each key chain (execution thread).
D3DRMINTERPOLATION_LINEAR
Linear interpolation between the two nearest keys is used for determining in-between values on each key chain.
D3DRMINTERPOLATION_SPLINE
B-spline blending function on the four nearest keys is used for determining in-between values on each key chain.
D3DRMINTERPOLATION_VERTEXCOLOR
Specifies that vertex colors should be interpolated. Only affects the interpolation of IDirect3DRMMesh::SetVertices.
D3DRMINTERPOLATION_SLERPNORMALS
Specifies that vertex normals should be spherically interpolated (not currently implemented). Only affects the interpolation of IDirect3DRMMesh::SetVertices.

D3DRMLOADOPTIONS

Defines options for the IDirect3DRM3::Load, IDirect3DRMAnimationSet2::Load, IDirect3DRMFrame3::Load, IDirect3DRMMeshBuilder3::Load, and IDirect3DRMProgressiveMesh::Load methods. These options modify how the object is loaded.

Syntax

typedef DWORD D3DRMLOADOPTIONS;
#define D3DRMLOAD_FROMFILE             0x00L
#define D3DRMLOAD_FROMRESOURCE         0x01L
#define D3DRMLOAD_FROMMEMORY           0x02L
#define D3DRMLOAD_FROMURL              0x08L
#define D3DRMLOAD_BYNAME               0x10L
#define D3DRMLOAD_BYPOSITION           0x20L
#define D3DRMLOAD_BYGUID               0x30L
#define D3DRMLOAD_FIRST                0x40L
#define D3DRMLOAD_INSTANCEBYREFERENCE  0x100L
#define D3DRMLOAD_INSTANCEBYCOPYING    0x200L
#define D3DRMLOAD_ASYNCHRONOUS         0x400L

Parameters

Source flags
D3DRMLOAD_FROMFILE
Load from a file. This is the default setting.
D3DRMLOAD_FROMRESOURCE
Load from a resource. If this flag is specified, the lpvObjSource parameter of the calling Load method must point to a D3DRMLOADRESOURCE structure.
D3DRMLOAD_FROMMEMORY
Load from memory. If this flag is specified, the lpvObjSource parameter of the calling Load method must point to a D3DRMLOADMEMORY structure.
D3DRMLOAD_FROMURL
Load from an URL.
Identifier flags
D3DRMLOAD_BYNAME
Load any object by using a specified name.
D3DRMLOAD_BYPOSITION
Load a stand-alone object based on a given zero-based position (that is, the nth object in the file). Stand-alone objects can contain other objects, but are not contained by any other objects.
D3DRMLOAD_BYGUID
Load any object by using a specified globally unique identifier (GUID).
D3DRMLOAD_FIRST
The default setting. Load the first stand-alone object of the given type (for example, a mesh if the application uses IDirect3DRMMeshBuilder3::Load). Stand-alone objects can contain other objects, but are not contained by any other objects.
Instance flags
D3DRMLOAD_INSTANCEBYREFERENCE
Check whether an object already exists with the same name as specified and, if so, use an instance of that object instead of creating a new one.
D3DRMLOAD_INSTANCEBYCOPYING
Check whether an object already exists with the same name as specified and, if so, copy that object.
Source flags
D3DRMLOAD_ASYNCHRONOUS
The Load call will return immediately. It is up to the application to use events to find out how the load is progressing. By default, loading is done synchronously, and the Load call will not return until all data has been loaded or an error occurs.

Remarks

Each of the Load methods uses an lpvObjSource parameter to specify the source of the object and an lpvObjID parameter to identify the object. The system interprets the contents of the lpvObjSource parameter based on the choice of source flags, and it interprets the contents of the lpvObjID parameter based on the choice of identifier flags.

The instance flags do not change the interpretation of any of the parameters. By using the D3DRMLOAD_INSTANCEBYREFERENCE flag, it is possible for an application to load the same file twice without creating any new objects. If an object does not have a name, setting the D3DRMLOAD_INSTANCEBYREFERENCE flag has the same effect as setting the D3DRMLOAD_INSTANCEBYCOPYING flag—the loader creates each unnamed object as a new one, even if some of the objects are identical.

D3DRMMAPPING

Specifies values used by the IDirect3DRMMesh::GetGroupMapping and IDirect3DRMMesh::SetGroupMapping methods to define how textures are mapped to a group.

Syntax

typedef DWORD D3DRMMAPPING, D3DRMMAPPINGFLAG;
static const D3DRMMAPPINGFLAG D3DRMMAP_WRAPU = 1;
static const D3DRMMAPPINGFLAG D3DRMMAP_WRAPV = 2;
static const D3DRMMAPPINGFLAG D3DRMMAP_PERSPCORRECT = 4;

Parameters

D3DRMMAPPINGFLAG
Type equivalent to D3DRMMAPPING.
D3DRMMAP_WRAPU
Texture wraps in the u-direction.
D3DRMMAP_WRAPV
Texture wraps in the v-direction.
D3DRMMAP_PERSPCORRECT
Texture wrapping is perspective-corrected.

Remarks

The D3DRMMAP_WRAPU and D3DRMMAP_WRAPV flags determine how the rasterizer interprets texture coordinates. The rasterizer always interpolates the shortest distance between texture coordinates; that is, a line. The path taken by this line, and the valid values for the u- and v-coordinates, varies with the use of the wrapping flags. If either or both flags are set, the line can wrap around the texture edge in the u- or v- direction, as if the texture had a cylindrical or toroidal topology. For more information, see Wraps.

See Also

Wraps, IDirect3DRMMesh::GetGroupMapping, IDirect3DRMMesh::SetGroupMapping

D3DRMMATRIX4D

Expresses a transformation as an array. The organization of the matrix entries is D3DRMMATRIX4D[row][column].

Syntax

typedef D3DVALUE D3DRMMATRIX4D[4][4];

See Also

IDirect3DRMFrame3::AddTransform, IDirect3DRMFrame3::GetTransform

D3DRMSAVEOPTIONS

Defines options for the IDirect3DRMMeshBuilder3::Save method.

Syntax

typedef DWORD D3DRMSAVEOPTIONS;
#define D3DRMXOFSAVE_NORMALS 1
#define D3DRMXOFSAVE_TEXTURECOORDINATES 2
#define D3DRMXOFSAVE_MATERIALS 4
#define D3DRMXOFSAVE_TEXTURENAMES 8
#define D3DRMXOFSAVE_ALL 15
#define D3DRMXOFSAVE_TEMPLATES 16
#define D3DRMSAVE_TEXTURETOPOLOGY 32

Parameters

D3DRMXOFSAVE_NORMALS
Save normal vectors in addition to the basic geometry.
D3DRMXOFSAVE_TEXTURECOORDINATES
Save texture coordinates in addition to the basic geometry.
D3DRMXOFSAVE_MATERIALS
Save materials in addition to the basic geometry.
D3DRMXOFSAVE_TEXTURENAMES
Save texture names in addition to the basic geometry.
D3DRMXOFSAVE_ALL
Save normal vectors, texture coordinates, materials, and texture names in addition to the basic geometry.
D3DRMXOFSAVE_TEMPLATES
Save templates with the file. By default, templates are not saved.
D3DRMSAVE_TEXTURETOPOLOGY
Save the mesh's face wrap values (set by IDirect3DRMMeshBuilder3::SetTextureTopology or IDirect3DRMFace2::SetTextureTopology). This flag is not included when you pass D3DRMXOFSAVE_ALL to the Save method. You should pass D3DRMSAVE_TEXTURETOPOLOGY|D3DRMXOFSAVE_ALL if you want to save everything. You only need to pass this flag when you have called IDirect3DRMMeshBuilder3::SetTextureTopology or IDirect3DRMFace2::SetTextureTopology and want to preserve the values you set.


C++ Enumerated Types

The Microsoft® Direct3D® Retained Mode enumerated types for C++ are:

  • D3DRMCOLORSOURCE
  • D3DRMCOMBINETYPE
  • D3DRMFILLMODE
  • D3DRMFOGMODE
  • D3DRMFRAMECONSTRAINT
  • D3DRMLIGHTMODE
  • D3DRMLIGHTTYPE
  • D3DRMMATERIALMODE
  • D3DRMPALETTEFLAGS
  • D3DRMPROJECTIONTYPE
  • D3DRMRENDERQUALITY
  • D3DRMSHADEMODE
  • D3DRMSORTMODE
  • D3DRMTEXTUREQUALITY
  • D3DRMUSERVISUALREASON
  • D3DRMWRAPTYPE
  • D3DRMXOFFORMAT
  • D3DRMZBUFFERMODE

D3DRMCOLORSOURCE

Describes the color source of a Direct3DRMMeshBuilder3 object. You can set the color source by using the IDirect3DRMMeshBuilder3::SetColorSource method. To retrieve it, use the IDirect3DRMMeshBuilder3::GetColorSource method.

Syntax

typedef enum _D3DRMCOLORSOURCE{
    D3DRMCOLOR_FROMFACE,
    D3DRMCOLOR_FROMVERTEX
} D3DRMCOLORSOURCE;

Values

D3DRMCOLOR_FROMFACE
Object's color source is a face.
D3DRMCOLOR_FROMVERTEX
Object's color source is a vertex.

See Also

IDirect3DRMMeshBuilder3::SetColorSource, IDirect3DRMMeshBuilder3::GetColorSource

D3DRMCOMBINETYPE

Specifies how to combine two matrices.

Syntax

typedef enum _D3DRMCOMBINETYPE{
    D3DRMCOMBINE_REPLACE,
    D3DRMCOMBINE_BEFORE,
    D3DRMCOMBINE_AFTER
} D3DRMCOMBINETYPE;

Values

D3DRMCOMBINE_REPLACE
Supplied matrix replaces the frame's current matrix.
D3DRMCOMBINE_BEFORE
Supplied matrix is multiplied with the frame's current matrix and precedes the current matrix in the calculation.
D3DRMCOMBINE_AFTER
Supplied matrix is multiplied with the frame's current matrix and follows the current matrix in the calculation.

Remarks

The order of the supplied and current matrices when they are multiplied is important because matrix multiplication is not commutative.

See Also

IDirect3DRMFrame3::AddRotation, IDirect3DRMFrame3::AddScale, IDirect3DRMFrame3::AddTransform, IDirect3DRMFrame3::AddTranslation

D3DRMFILLMODE

Used to define the D3DRMRENDERQUALITY type.

Syntax

typedef enum _D3DRMFILLMODE {
    D3DRMFILL_POINTS    = 0 *D3DRMLIGHT_MAX,
    D3DRMFILL_WIREFRAME = 1 *D3DRMLIGHT_MAX,
    D3DRMFILL_SOLID     = 2 *D3DRMLIGHT_MAX,
    D3DRMFILL_MASK      = 7 *D3DRMLIGHT_MAX,
    D3DRMFILL_MAX       = 8 *D3DRMLIGHT_MAX
} D3DRMFILLMODE;

Values

D3DRMFILL_POINTS
Fills points only; minimum fill mode.
D3DRMFILL_WIREFRAME
Fill wire frames.
D3DRMFILL_SOLID
Fill solid objects.
D3DRMFILL_MASK
Fill using a mask.
D3DRMFILL_MAX
Maximum value for fill mode.

See Also

D3DRMLIGHTMODE, D3DRMSHADEMODE, D3DRMRENDERQUALITY

D3DRMFOGMODE

Contains values that specify how rapidly and in what ways the fog effect intensifies with increasing distance from the camera.

In monochromatic (ramp) lighting mode, fog works properly only when the fog color is black. (If there is no lighting, any fog color will work, since in this case any fog color is effectively black.)

Syntax

typedef enum _D3DRMFOGMODE{
    D3DRMFOG_LINEAR,
    D3DRMFOG_EXPONENTIAL,
    D3DRMFOG_EXPONENTIALSQUARED
} D3DRMFOGMODE;

Values

D3DRMFOG_LINEAR
Fog effect intensifies linearly between the start and end points, according to the following formula:

Equation showing linear increase of fog effect with distance

This is the only fog mode currently supported.

D3DRMFOG_EXPONENTIAL
Fog effect intensifies exponentially, according to the following formula:

Equation showing exponential increase of fog effect with distance

D3DRMFOG_EXPONENTIALSQUARED
Fog effect intensifies exponentially with the square of the distance, according to the following formula:

Equation showing exponential increase of fog effect with distance squared

Remarks

Note that fog can be considered a measure of visibility—the lower the fog value produced by one of the fog equations, the less visible an object is.

You can specify the fog's density and start and end points by using the IDirect3DRMFrame3::SetSceneFogParams method. In the formulas for the exponential fog modes, e is the base of the natural logarithms; its value is approximately 2.71828.

See Also

IDirect3DRMFrame3::SetSceneFogMode, IDirect3DRMFrame3::SetSceneFogParams

D3DRMFRAMECONSTRAINT

Describes the axes of rotation to constrain when viewing a Direct3DRMFrame object. The IDirect3DRMFrame3::LookAt method uses this enumerated type.

Syntax

typedef enum _D3DRMFRAMECONSTRAINT {
    D3DRMCONSTRAIN_Z,
    D3DRMCONSTRAIN_Y,
    D3DRMCONSTRAIN_X
} D3DRMFRAMECONSTRAINT;

Values

D3DRMCONSTRAIN_Z
Use only x- and y- rotations.
D3DRMCONSTRAIN_Y
Use only x- and z- rotations.
D3DRMCONSTRAIN_X
Use only y- and z- rotations.

See Also

IDirect3DRMFrame3::LookAt

D3DRMLIGHTMODE

Used to define the D3DRMRENDERQUALITY type.

Syntax

typedef enum _D3DRMLIGHTMODE {
    D3DRMLIGHT_OFF      = 0 *D3DRMSHADE_MAX,
    D3DRMLIGHT_ON       = 1 *D3DRMSHADE_MAX,
    D3DRMLIGHT_MASK     = 7 *D3DRMSHADE_MAX,
    D3DRMLIGHT_MAX      = 8 *D3DRMSHADE_MAX
} D3DRMLIGHTMODE;

Values

D3DRMLIGHT_OFF
Lighting is off.
D3DRMLIGHT_ON
Lighting is on.
D3DRMLIGHT_MASK
Lighting uses a mask.
D3DRMLIGHT_MAX
Maximum lighting mode.

See Also

D3DRMFILLMODE, D3DRMSHADEMODE, D3DRMRENDERQUALITY

D3DRMLIGHTTYPE

Defines the light type in uses to the IDirect3DRM3::CreateLight method.

Syntax

typedef enum _D3DRMLIGHTTYPE{
    D3DRMLIGHT_AMBIENT,
    D3DRMLIGHT_POINT,
    D3DRMLIGHT_SPOT,
    D3DRMLIGHT_DIRECTIONAL,
    D3DRMLIGHT_PARALLELPOINT
} D3DRMLIGHTTYPE;

Values

D3DRMLIGHT_AMBIENT
Light is an ambient source.
D3DRMLIGHT_POINT
Light is a point source.
D3DRMLIGHT_SPOT
Light is a spotlight source.
D3DRMLIGHT_DIRECTIONAL
Light is a directional source.
D3DRMLIGHT_PARALLELPOINT
Light is a parallel point source.

D3DRMMATERIALMODE

Describes the source of material information for visuals rendered with a frame.

Syntax

typedef enum _D3DRMMATERIALMODE{
    D3DRMMATERIAL_FROMMESH,
    D3DRMMATERIAL_FROMPARENT,
    D3DRMMATERIAL_FROMFRAME
} D3DRMMATERIALMODE;

Values

D3DRMMATERIAL_FROMMESH
Material information is retrieved from the visual object (the mesh) itself. This is the default setting.
D3DRMMATERIAL_FROMPARENT
Material information, along with color or texture information, is inherited from the parent frame.
D3DRMMATERIAL_FROMFRAME
Material information is retrieved from the frame, overriding any previous material information that the visual object may have possessed.

See Also

IDirect3DRMFrame3::GetMaterialMode, IDirect3DRMFrame3::SetMaterialMode

D3DRMPALETTEFLAGS

Used to define how a color can be used in the D3DRMPALETTEENTRY structure.

Syntax

typedef enum _D3DRMPALETTEFLAGS {
    D3DRMPALETTE_FREE,
    D3DRMPALETTE_READONLY,
    D3DRMPALETTE_RESERVED
} D3DRMPALETTEFLAGS;

Values

D3DRMPALETTE_FREE
Renderer can use this entry freely.
D3DRMPALETTE_READONLY
Fixed but can be used by renderer.
D3DRMPALETTE_RESERVED
Cannot be used by renderer.

See Also

D3DRMPALETTEENTRY

D3DRMPROJECTIONTYPE

Defines the type of projection used in a Direct3DRMViewport object. The IDirect3DRMViewport2::GetProjection and IDirect3DRMViewport2::SetProjection methods use this enumerated type. The right-hand types enable right-handed projection.

Note: With DirectX version 6.0 or later, use IDirect3DRM3::SetOptions to specify right-handed geometry.

The axes of the camera (see IDirect3DRMFrame3::SetAxes) are used in both left-handed and right-handed projection to determine what direction the camera is facing.

Syntax

typedef enum _D3DRMPROJECTIONTYPE{
    D3DRMPROJECT_PERSPECTIVE,
    D3DRMPROJECT_ORTHOGRAPHIC,
    D3DRMPROJECT_RIGHTHANDPERSPECTIVE,
    D3DRMPROJECT_RIGHTHANDORTHOGRAPHIC
} D3DRMPROJECTIONTYPE;

Values

D3DRMPROJECT_PERSPECTIVE
Projection is perspective and left-handed.
D3DRMPROJECT_ORTHOGRAPHIC
Projection is orthographic and left-handed.
D3DRMPROJECT_RIGHTHANDPERSPECTIVE
Projection is perspective and right-handed.
D3DRMPROJECT_RIGHTHANDORTHOGRAPHIC
Projection is orthographic and right-handed.

See Also

IDirect3DRMViewport2::GetProjection, IDirect3DRMViewport2::SetProjection

D3DRMRENDERQUALITY

Combines descriptions of the shading mode, lighting mode, and filling mode for a Direct3DRMMesh object.

Syntax

typedef enum _D3DRMSHADEMODE {
    D3DRMSHADE_FLAT        = 0,
    D3DRMSHADE_GOURAUD     = 1,
    D3DRMSHADE_PHONG       = 2,
    D3DRMSHADE_MASK        = 7,
    D3DRMSHADE_MAX         = 8
} D3DRMSHADEMODE;
typedef enum _D3DRMLIGHTMODE {
    D3DRMLIGHT_OFF          = 0 *D3DRMSHADE_MAX,
    D3DRMLIGHT_ON           = 1 *D3DRMSHADE_MAX,
    D3DRMLIGHT_MASK         = 7 *D3DRMSHADE_MAX,
    D3DRMLIGHT_MAX          = 8 *D3DRMSHADE_MAX
} D3DRMLIGHTMODE;
typedef enum _D3DRMFILLMODE {
    D3DRMFILL_POINTS        = 0 *D3DRMLIGHT_MAX,
    D3DRMFILL_WIREFRAME     = 1 *D3DRMLIGHT_MAX,
    D3DRMFILL_SOLID         = 2 *D3DRMLIGHT_MAX,
    D3DRMFILL_MASK          = 7 *D3DRMLIGHT_MAX,
    D3DRMFILL_MAX           = 8 *D3DRMLIGHT_MAX
} D3DRMFILLMODE;

typedef DWORD D3DRMRENDERQUALITY;

#define D3DRMRENDER_WIREFRAME   (D3DRMSHADE_FLAT+D3DRMLIGHT_OFF+D3DRMFILL_WIREFRAME)
#define D3DRMRENDER_UNLITFLAT   (D3DRMSHADE_FLAT+D3DRMLIGHT_OFF+D3DRMFILL_SOLID)
#define D3DRMRENDER_FLAT        (D3DRMSHADE_FLAT+D3DRMLIGHT_ON+D3DRMFILL_SOLID)
#define D3DRMRENDER_GOURAUD     (D3DRMSHADE_GOURAUD+D3DRMLIGHT_ON+D3DRMFILL_SOLID)
#define D3DRMRENDER_PHONG       (D3DRMSHADE_PHONG+D3DRMLIGHT_ON+D3DRMFILL_SOLID)

Values

D3DRMSHADEMODE, D3DRMLIGHTMODE, and D3DRMFILLMODE
These enumerated types describe the shade, light, and fill modes for Direct3DRMMesh objects.

D3DRMRENDER_WIREFRAME
Display only the edges.
D3DRMRENDER_UNLITFLAT
Flat shaded without lighting.
D3DRMRENDER_FLAT
Flat shaded.
D3DRMRENDER_GOURAUD
Gouraud shaded.
D3DRMRENDER_PHONG
Phong shaded. Phong shading is not currently supported.

See Also

IDirect3DRMMesh::GetGroupQuality, IDirect3DRMMesh::SetGroupQuality,IDirect3DRMDevice3::SetRenderMode

D3DRMSHADEMODE

Used to define the D3DRMRENDERQUALITY type.

Syntax

typedef enum _D3DRMSHADEMODE {
    D3DRMSHADE_FLAT     = 0,
    D3DRMSHADE_GOURAUD  = 1,
    D3DRMSHADE_PHONG    = 2,
    D3DRMSHADE_MASK     = 7,
    D3DRMSHADE_MAX      = 8
} D3DRMSHADEMODE;

See Also

D3DRMFILLMODE, D3DRMLIGHTMODE, D3DRMRENDERQUALITY

D3DRMSORTMODE

Describes how child frames are sorted in a scene.

Syntax

typedef enum _D3DRMSORTMODE {
    D3DRMSORT_FROMPARENT,
    D3DRMSORT_NONE,
    D3DRMSORT_FRONTTOBACK,
    D3DRMSORT_BACKTOFRONT
} D3DRMSORTMODE;

Values

D3DRMSORT_FROMPARENT
Child frames inherit the sorting order of their parents. This is the default setting.
D3DRMSORT_NONE
Child frames are not sorted.
D3DRMSORT_FRONTTOBACK
Child frames are sorted front-to-back.
D3DRMSORT_BACKTOFRONT
Child frames are sorted back-to-front.

See Also

IDirect3DRMFrame3::GetSortMode, IDirect3DRMFrame3::SetSortMode

D3DRMTEXTUREQUALITY

Describes how a device interpolates between pixels in a texture and pixels in a viewport. This enumerated type is used by the IDirect3DRMDevice3::SetTextureQuality and IDirect3DRMDevice3::GetTextureQuality methods.

Syntax

typedef enum _D3DRMTEXTUREQUALITY{
    D3DRMTEXTURE_NEAREST,
    D3DRMTEXTURE_LINEAR,
    D3DRMTEXTURE_MIPNEAREST,
    D3DRMTEXTURE_MIPLINEAR,
    D3DRMTEXTURE_LINEARMIPNEAREST,
    D3DRMTEXTURE_LINEARMIPLINEAR
} D3DRMTEXTUREQUALITY;

Values

D3DRMTEXTURE_NEAREST
Choose the nearest pixel in the texture. Does not support mipmapping.
D3DRMTEXTURE_LINEAR
Linearly interpolate the four nearest pixels. Does not support mipmapping.
D3DRMTEXTURE_MIPNEAREST
Similar to D3DRMTEXTURE_NEAREST, but uses the appropriate mipmap instead of the texture. Pixel sampling and mipmapping are both nearest.
D3DRMTEXTURE_MIPLINEAR
Similar to D3DRMTEXTURE_LINEAR, but uses the appropriate mipmap instead of the texture. Pixel sampling is linear; mipmapping is nearest.
D3DRMTEXTURE_LINEARMIPNEAREST
Similar to D3DRMTEXTURE_MIPNEAREST, but interpolates between the two nearest mipmaps. Pixel sampling is nearest; mipmapping is linear.
D3DRMTEXTURE_LINEARMIPLINEAR
Similar to D3DRMTEXTURE_MIPLINEAR, but interpolates between the two nearest mipmaps. Both pixel sampling and mipmapping are linear.

D3DRMUSERVISUALREASON

Defines the reason the system has used the D3DRMUSERVISUALCALLBACK callback function.

Syntax

typedef enum _D3DRMUSERVISUALREASON {
    D3DRMUSERVISUAL_CANSEE,
    D3DRMUSERVISUAL_RENDER
} D3DRMUSERVISUALREASON;

Values

D3DRMUSERVISUAL_CANSEE
Callback function should return TRUE if the user-visual object is visible in the viewport.
D3DRMUSERVISUAL_RENDER
Callback function should render the user-visual object.

See Also

D3DRMUSERVISUALCALLBACK

D3DRMWRAPTYPE

Defines the type of Direct3DRMWrap object created by the IDirect3DRM3::CreateWrap method. You can also use this enumerated type to initialize a Direct3DRMWrap object in a call to the IDirect3DRMWrap::Init method.

Syntax

typedef enum _D3DRMWRAPTYPE{
    D3DRMWRAP_FLAT,
    D3DRMWRAP_CYLINDER,
    D3DRMWRAP_SPHERE,
    D3DRMWRAP_CHROME
} D3DRMWRAPTYPE;

Values

D3DRMWRAP_FLAT
Wrap is flat.
D3DRMWRAP_CYLINDER
Wrap is cylindrical.
D3DRMWRAP_SPHERE
Wrap is spherical.
D3DRMWRAP_CHROME
Wrap allocates texture coordinates so that the texture appears to be reflected onto the objects.

See Also

IDirect3DRM3::CreateWrap, IDirect3DRMWrap::Init, Wraps

D3DRMXOFFORMAT

Defines the file type used by the IDirect3DRMMeshBuilder3::Save method.

Syntax

typedef enum _D3DRMXOFFORMAT{
    D3DRMXOF_BINARY,
    D3DRMXOF_COMPRESSED,
    D3DRMXOF_TEXT
} D3DRMXOFFORMAT;

Values

D3DRMXOF_BINARY
File is in binary format. This is the default setting.
D3DRMXOF_COMPRESSED
Not currently supported.
D3DRMXOF_TEXT
File is in text format.

Remarks

The D3DRMXOF_BINARY and D3DRMXOF_TEXT settings are mutually exclusive.

See Also

IDirect3DRMMeshBuilder3::Save

D3DRMZBUFFERMODE

Describes whether z-buffering is enabled.

Syntax

typedef enum _D3DRMZBUFFERMODE {
    D3DRMZBUFFER_FROMPARENT,
    D3DRMZBUFFER_ENABLE,
    D3DRMZBUFFER_DISABLE
} D3DRMZBUFFERMODE;

Values

D3DRMZBUFFER_FROMPARENT
The frame inherits the z-buffer setting from its parent frame. This is the default setting.
D3DRMZBUFFER_ENABLE
Z-buffering is enabled.
D3DRMZBUFFER_DISABLE
Z-buffering is disabled.

See Also

IDirect3DRMFrame3::GetZbufferMode, IDirect3DRMFrame3::SetZbufferMode


C++ Structures

The Microsoft® Direct3D® Retained Mode structures for C++ are:

  • D3DRMANIMATIONKEY
  • D3DRMBOX
  • D3DRMIMAGE
  • D3DRMLOADMEMORY
  • D3DRMLOADRESOURCE
  • D3DRMMATERIALOVERRIDE
  • D3DRMPALETTEENTRY
  • D3DRMPICKDESC
  • D3DRMPICKDESC2
  • D3DRMPMESHLOADSTATUS
  • D3DRMQUATERNION
  • D3DRMRAY
  • D3DRMVECTOR4D
  • D3DRMVERTEX

D3DRMANIMATIONKEY

Defines the keys used by the IDirect3DRMAnimation2::AddKey, GetKeys, and ModifyKey methods.

Syntax

typedef struct _D3DRMANIMATIONKEY
{
    DWORD dwSize;
    DWORD dwKeyType;
    D3DVALUE dvTime;
    DWORD dwId ;
    union
    {
        D3DRMQUATERNION dqRotateKey;
        D3DVECTOR dvScaleKey;
        D3DVECTOR dvPositionKey;
    };
} D3DRMANIMATIONKEY;
typedef D3DRMANIMATIONKEY *LPD3DRMANIMATIONKEY;

Members

dwSize
Size of the animation.
dwKeyType
Type of key. One of the following values:
D3DRMANIMATION_ROTATEKEY = 0x01
D3DRMANIMATION_SCALEKEY = 0x02
D3DRMANIMATION_POSITIONKEY = 0x03
dvTime
Time value in arbitrary units and a member of the D3DVALUE type.
dwId
Key identifier.
dqRotateKey
Value of the D3DRMQUATERNION structure type defining the rotation.
dvScaleKey
Value of the D3DVECTOR structure type defining the scale.
dvPositionKey
Value of the D3DVECTOR structure type defining the position.

D3DRMBOX

Defines the bounding box retrieved by the IDirect3DRMMesh::GetBox and IDirect3DRMMeshBuilder3::GetBox methods.

Syntax

typedef struct _D3DRMBOX {
    D3DVECTOR min, max;
}D3DRMBOX;
typedef D3DRMBOX *LPD3DRMBOX;

Members

min and max
Values defining the bounds of the box. These values are D3DVECTOR structures.

See Also

D3DVECTOR, IDirect3DRMMesh::GetBox, IDirect3DRMMeshBuilder3::GetBox

D3DRMIMAGE

Describes an image that is attached to a texture by the IDirect3DRM3::CreateTexture method. IDirect3DRMTexture3::GetImage returns the address of this image.

Syntax

typedef struct _D3DRMIMAGE {
    int                width, height;
    int                aspectx, aspecty;
    int                depth;
    int                rgb;
    int                bytes_per_line;
    void              *buffer1;
    void              *buffer2;
    unsigned long      red_mask;
    unsigned long      green_mask;
    unsigned long      blue_mask;
    unsigned long      alpha_mask;
    int                palette_size;
    D3DRMPALETTEENTRY *palette;
}D3DRMIMAGE;
typedef D3DRMIMAGE, *LPD3DRMIMAGE;

Members

width and height
Width and height of the image, in pixels.
aspectx and aspecty
Aspect ratio for nonsquare pixels.
depth
Number of bits that specify each pixel.
rgb
A flag that indicates whether pixels are RGB values or palette indices. If this member is FALSE, pixels are indices into a palette. Otherwise, pixels encode RGB values.
bytes_per_line
Number of bytes of memory for a scan line. This value must be a multiple of four.
buffer1
Memory to render into (first buffer).
buffer2
Second rendering buffer for double buffering. Set this member to NULL for single buffering.
red_mask, green_mask, blue_mask, and alpha_mask
A mask for RGB pixels or pixel palette indices. If rgb is TRUE, these members are masks for the red, green, and blue parts of a pixel. Otherwise, they are masks for the significant bits of the red, green, and blue elements in the palette. For example, most Super VGA (SVGA) displays use 64 intensities of red, green, and blue, so the masks should all be set to 0xfc.
palette_size
Number of entries in the palette.
palette
A pointer to a D3DRMPALETTEENTRY structure describing the color palette to be used. This structure is only used if the D3DRMIMAGE rgb member is FALSE.

See Also

IDirect3DRM3::CreateTexture, IDirect3DRMTexture3::GetImage

D3DRMLOADMEMORY

Identifies a resource to be loaded when an application uses the IDirect3DRM3::Load method (or one of the other Load methods) and specifies D3DRMLOAD_FROMMEMORY.

Syntax

typedef struct _D3DRMLOADMEMORY {
    LPVOID lpMemory;
    DWORD  dSize;
} D3DRMLOADMEMORY, *LPD3DRMLOADMEMORY;

Members

lpMemory
Address of a block of memory to be loaded.
dSize
Size, in bytes, of the block of memory to be loaded.

See Also

IDirect3DRM3::Load, IDirect3DRMAnimationSet2::Load, IDirect3DRMFrame3::Load, IDirect3DRMMeshBuilder3::Load, D3DRMLOADOPTIONS, D3DRMLOADRESOURCE

D3DRMLOADRESOURCE

Identifies a resource to be loaded when an application uses the IDirect3DRM3::Load method (or one of the other Load methods) and specifies D3DRMLOAD_FROMRESOURCE.

Syntax

typedef struct _D3DRMLOADRESOURCE {
    HMODULE hModule;
    LPCTSTR lpName;
    LPCTSTR lpType;
} D3DRMLOADRESOURCE, *LPD3DRMLOADRESOURCE;

Members

hModule
Handle of the module containing the resource to be loaded. If this member is NULL, the resource must be attached to the executable file or dynamic-link library (DLL) that uses the resource.

lpName
Name of the resource to be loaded. For example, if the resource is a mesh, this member should specify the name of the mesh file.
lpType
User-defined type identifying the resource.

Remarks

If the high-order word of the lpName or lpType member is zero, the low-order word specifies the integer identifier of the name or type of the given resource. Otherwise, those parameters are long pointers to null-terminated strings. If the first character of the string is a number sign (#), the remaining characters represent a decimal number that specifies the integer identifier of the resource's name or type. For example, the string "#258" represents the integer identifier 258. An application should reduce the amount of memory required for the resources by referring to them by integer identifier instead of by name.

When an application uses a Load method and specifies D3DRMLOAD_FROMRESOURCE, it does not need to find or unlock any resources; the system handles this automatically.

See Also

IDirect3DRM3::Load, IDirect3DRMAnimationSet2::Load, IDirect3DRMFrame3::Load, IDirect3DRMMeshBuilder3::Load, D3DRMLOADMEMORY, D3DRMLOADOPTIONS

D3DRMMATERIALOVERRIDE

Describes the overrides for IDirect3DRMFrame3::SetMaterialOverride and IDirect3DRMFrame3::GetMaterialOverride methods.

Syntax

typedef struct _D3DRMMATERIALOVERRIDE
{
    DWORD         dwSize;
    DWORD         dwFlags;
    D3DCOLORVALUE dcDiffuse;
    D3DCOLORVALUE dcAmbient;
    D3DCOLORVALUE dcEmissive;
    D3DCOLORVALUE dcSpecular;
    D3DVALUE      dvPower;
    LPUNKNOWN     lpD3DRMTex;
} D3DRMMATERIALOVERRIDE, *LPD3DRMMATERIALOVERRIDE;

Members

dwSize
Size of this structure, in bytes.
dwFlags
Logical combination of flags, indicating which fields in this structure are valid. Possible values include the following:
D3DRMMATERIALOVERRIDE_DIFFUSE_ALPHAONLY
D3DRMMATERIALOVERRIDE_DIFFUSE_RGBONLY
D3DRMMATERIALOVERRIDE_DIFFUSE
D3DRMMATERIALOVERRIDE_AMBIENT
D3DRMMATERIALOVERRIDE_EMISSIVE
D3DRMMATERIALOVERRIDE_SPECULAR
D3DRMMATERIALOVERRIDE_POWER
D3DRMMATERIALOVERRIDE_TEXTURE
D3DRMMATERIALOVERRIDE_ALL
dcDiffuse
Diffuse RGBA color setting of type D3DCOLORVALUE.
dcAmbient
Ambient RGB color setting of type D3DCOLORVALUE.
dcEmissive
Emissive RGB color setting of type D3DCOLORVALUE.
dcSpecular
Specular RGB color setting of type D3DCOLORVALUE.
dvPower
Power setting of type D3DVALUE.
lpD3DRMTex
Pointer to the texture interface.

D3DRMPALETTEENTRY

Describes the color palette used in a D3DRMIMAGE structure. This structure is used only if the rgb member of the D3DRMIMAGE structure is FALSE. (If it is TRUE, RGB values are used.)

Syntax

typedef struct _D3DRMPALETTEENTRY {
    unsigned char red;
    unsigned char green;
    unsigned char blue;
    unsigned char flags;
}D3DRMPALETTEENTRY;
typedef D3DRMPALETTEENTRY, *LPD3DRMPALETTEENTRY;

Members

red, green, and blue
Values defining the primary color components that define the palette. These values can range from 0 through 255.
flags
Value defining how the palette is used by the renderer. This value is one of the members of the D3DRMPALETTEFLAGS enumerated type.

See Also

D3DRMIMAGE, D3DRMPALETTEFLAGS

D3DRMPICKDESC

Contains the pick position and face and group identifiers of the objects retrieved by the IDirect3DRMPickedArray::GetPick method.

Syntax

typedef struct _D3DRMPICKDESC {
    ULONG       ulFaceIdx;
    LONG        lGroupIdx;
    D3DVECTOR   vPosition;
} D3DRMPICKDESC, *LPD3DRMPICKDESC;

Members

ulFaceIdx
Face index of the retrieved object.
lGroupIdx
Group index of the retrieved object.
vPosition
Value describing the position of the retrieved object. This value is a D3DVECTOR structure.

See Also

D3DVECTOR, IDirect3DRMPickedArray::GetPick

D3DRMPICKDESC2

Contains the face and group identifiers, pick position, horizontal and vertical texture coordinates for the vertex, vertex normal, and color of the objects retrieved by the IDirect3DRMPicked2Array::GetPick method.

Syntax

typedef struct _D3DRMPICKDESC2
{
    ULONG	ulFaceIdx;
    LONG	lGroupIdx;
    D3DVECTOR	dvPosition;
    D3DVALUE	tu;
    D3DVALUE	tv;
    D3DVECTOR	dvNormal;
    D3DCOLOR	dcColor;

} D3DRMPICKDESC2, *LPD3DRMPICKDESC2;

Members

ulFaceIdx
Face index of the retrieved object.
lGroupIdx
Group index of the retrieved object.
vPosition
Value describing the position of the retrieved object. This value is a D3DVECTOR structure.
tu and tv
Horizontal and vertical texture coordinates, respectively, for the vertex.
dvNormal
Normal vector for the vertex.
dcColor
Vertex color.

D3DRMPMESHLOADSTATUS

Contains the loading status of a progressive mesh loaded with the IDirect3DRMProgressiveMesh::Load method. This structure can be retrieved with the IDirect3DRMProgressiveMesh::GetLoadStatus method.

Syntax

typedef struct _D3DRMPMESHLOADSTATUS {
    DWORD dwSize;
    DWORD dwPMeshSize;
    DWORD dwBaseMeshSize;
    DWORD dwBytesLoaded;
    DWORD dwVerticesLoaded;
    DWORD dwFacesLoaded;
    DWORD dwFlags;
} D3DRMPMESHLOADSTATUS;
typedef D3DRMPMESHLOADSTATUS *LPD3DRMPMESHLOADSTATUS;

Members

dwSize
Size of the structure.
dwPMeshSize
Size of the total progressive mesh in bytes.
dwBaseMeshSize
Size of the base mesh in bytes.
dwBytesLoaded
Number of total bytes loaded.
dwVerticesLoaded
Number of vertices loaded.
dwFacesLoaded
Number of faces loaded.
dwFlags
Flags that indicate the status of the progressive mesh loading. Can be one of the following values:

D3DRMPMESHSTATUS_VALID — The progressive mesh object contains valid data.
D3DRMPMESHSTATUS_INTERRUPTED — The download was interrupted either because the application used IDirect3DRMProgressiveMesh::Abort or because the connection was lost.
D3DRMPMESHSTATUS_BASEMESHCOMPLETE — The base mesh has been downloaded.
D3DRMPMESHSTATUS_COMPLETE — All data has been downloaded.
D3DRMPMESHSTATUS_RENDERABLE — It is now possible to render the mesh.

See Also

IDirect3DRMProgressiveMesh::GetLoadStatus, IDirect3DRMProgressiveMesh::Load

D3DRMQUATERNION

Describes the rotation used by the IDirect3DRMAnimation2::AddRotateKey method, and the quaternion used in IDirect3DRMFrame3::SetQuaternion. It is also used in several of the Direct3D mathematical functions.

Syntax

typedef struct _D3DRMQUATERNION {
    D3DVALUE   s;
    D3DVECTOR  v;
}D3DRMQUATERNION;
typedef D3DRMQUATERNION, *LPD3DRMQUATERNION;

See Also

IDirect3DRMAnimation2::AddRotateKey, IDirect3DRMFrame3::SetQuaternion, D3DRMQuaternionFromRotation, D3DRMQuaternionMultiply, D3DRMQuaternionSlerp, D3DRMMatrixFromQuaternion

D3DRMRAY

Defines the direction and starting position of the ray in IDirect3DRMFrame3::RayPick.

Syntax

typedef struct _D3DRMRAY
{   D3DVECTOR dvDir;
    D3DVECTOR dvPos;
} D3DRMRAY, *LPD3DRMRAY;

Members

dvDir
Direction of the ray used in a ray pick.
dvPos
Starting position of the ray used in a ray pick.

D3DRMVECTOR4D

Describes the screen coordinates used as the destination of a transformation by the IDirect3DRMViewport2::Transform and IDirect3DRMViewport2::TransformVectors methods and as the source of a transformation by the IDirect3DRMViewport2::InverseTransform and IDirect3DRMViewport2::InverseTransformVectors methods.

Syntax

typedef struct _D3DRMVECTOR4D {
    D3DVALUE x;
    D3DVALUE y;
    D3DVALUE z;
    D3DVALUE w;
}D3DRMVECTOR4D;
typedef D3DRMVECTOR4D, *LPD3DRMVECTOR4D;

Members

x, y, z, and w
Values of the D3DVALUE type describing homogeneous values. These values define the result of the transformation.

See Also

IDirect3DRMViewport2::Transform, IDirect3DRMViewport2::TransformVectors, IDirect3DRMViewport2::InverseTransform, IDirect3DRMViewport2::InverseTransformVectors

D3DRMVERTEX

Describes a vertex in a Direct3DRMMesh object.

Syntax

typedef struct _D3DRMVERTEX{
    D3DVECTOR position;
    D3DVECTOR normal;
    D3DVALUE  tu, tv;
    D3DCOLOR  color;
} D3DRMVERTEX;

Members

position
Position of the vertex.
normal
Normal vector for the vertex.
tu and tv
Horizontal and vertical texture coordinates, respectively, for the vertex.
color
Vertex color.

See Also

IDirect3DRMMesh::GetVertices, IDirect3DRMMesh::SetVertices


C++ Return Values

The methods of the Microsoft® Direct3D® Retained Model (COM) interfaces can return the following values.

D3DRM_OK
No error. Equivalent to DD_OK.
D3DRMERR_BADALLOC
Out of memory.
D3DRMERR_BADCACHEFILE
An X file could not be opened because of a bad cache file. A cache file contains data retrieved from the network, cached on the hard disk, and retrieved in subsequent requests.
D3DRMERR_BADDEVICE
Device is not compatible with renderer.
D3DRMERR_BADFILE
Data file is corrupt.
D3DRMERR_BADMAJORVERSION
Bad DLL major version.
D3DRMERR_BADMINORVERSION
Bad DLL minor version.
D3DRMERR_BADOBJECT
Object expected in argument.
D3DRMERR_BADPMDATA
The data in the .x file is corrupted. The conversion to a progressive mesh succeeded but produced an invalid progressive mesh in the .x file.
D3DRMERR_BADTYPE
Bad argument type passed.
D3DRMERR_BADVALUE
Bad argument value passed.
D3DRMERR_BOXNOTSET
An attempt was made to access a bounding box (for example, with IDirect3DRMFrame3::GetBox) when no bounding box was set on the frame.
D3DRMERR_CLIENTNOTREGISTERED
Client has not been registered. Call IDirect3DRM3::RegisterClient.
D3DRMERR_CONNECTIONLOST
Data connection was lost during a load, clone, or duplicate.
D3DRMERR_ELEMENTINUSE
Element can't be modified or deleted while in use. To empty a submesh, call Empty() against its parent.
D3DRMERR_ENTRYINUSE
Vertex or normal entries are in use by a face and cannot be deleted.
D3DRMERR_FACEUSED
Face already used in a mesh.
D3DRMERR_FILENOTFOUND
File cannot be opened.
D3DRMERR_INCOMPATIBLEKEY
Specified animation key is incompatible. The key cannot be modified.
D3DRMERR_INVALIDLIBRARY
Specified libary is invalid.
D3DRMERR_INVALIDOBJECT
Method received an object that is invalid.
D3DRMERR_INVALIDPARAMS
At least one of the parameters passed to the method is invalid.
D3DRMERR_LIBRARYNOTFOUND
Specified libary not found.
D3DRMERR_LOADABORTED
Load aborted by user.
D3DRMERR_NOINTERNET
Downloading from a URL failed, or Urlmon.dll could not be found or was corrupt.
D3DRMERR_NOSUCHKEY
Specified animation key does not exist.
D3DRMERR_NOTAGGREGATED
An attempt was made to access IDirect3DRMObject methods through an external visual object, but the external visual was not created with IDirect3DRM::Load or IDirect3DRM::CreateObject, and is not aggregated with IDirect3DRMObject.
D3DRMERR_NOTCREATEDFROMDDS
Specified texture was not created from a DirectDraw Surface.
D3DRMERR_NOTDONEYET
Unimplemented.
D3DRMERR_NOTENOUGHDATA
Not enough data has been loaded to perform the requested operation.
D3DRMERR_NOTFOUND
Object not found in specified place.
D3DRMERR_OUTOFRANGE
Specified value is out of range.
D3DRMERR_PENDING
Data required to supply the requested information has not finished loading.
D3DRMERR_REQUESTTOOLARGE
Attempt was made to set a level of detail in a progressive mesh greater than the maximum available.
D3DRMERR_REQUESTTOOSMALL
Attempt was made to set the minimum rendering detail of a progressive mesh smaller than the detail in the base mesh (the minimum for rendering).
D3DRMERR_TEXTUREFORMATNOTFOUND
Texture format could not be found that meets the specified criteria and that the underlying Immediate Mode device supports.
D3DRMERR_UNABLETOEXECUTE
Unable to carry out procedure.
DD_OK
The request completed successfully. Equivalent to D3DRM_OK.
DDERR_INVALIDOBJECT
Received pointer that was an invalid object.
DDERR_INVALIDPARAMS
One or more of the parameters passed to the method are incorrect.
DDERR_NOTFOUND
The requested item was not found.
DDERR_NOTINITIALIZED
An attempt was made to call an interface method of an object created by CoCreateInstance before the object was initialized.
DDERR_OUTOFMEMORY
DirectDraw does not have enough memory to perform the operation.


Further Reading for C++/COM Programmers

This section contains information about the following topics related to the Microsoft® Direct3D® Retained Mode C++/COM Reference.

  • Color Keying
  • D3DCOLOR_MONO
  • D3DCOLOR_RGB
  • D3DCOLORMODEL
  • D3DCOLORVALUE
  • D3DDEVICEDESC
  • D3DENUMDEVICESCALLBACK
  • D3DMATRIX
  • D3DPRIMCAPS
  • D3DRECT
  • D3DTRIANGLE
  • D3DVALUE
  • D3DVECTOR
  • DirectDrawCreate
  • DirectDrawCreateClipper
  • DrawPrimitive
  • IDirect3D3
  • IDirectDrawClipper
  • IUnknown Interface
  • Mipmaps
  • Texture Map Formats

Color Keying
A color key is typically a single uncommon color that the artist does not use for anything but transparency, but it can also be a specified range of colors. Using the IDirectDrawSurface3::SetColorKey method, you can set the color key for a surface. After the color key is set, subsequent calls to IDirectDrawSurface3::BltFast take advantage of that color key, ignoring the pixels that match it. This type of color key is known as a source color key. Because the source color key prevents "transparent" pixels from being written to the destination, the original background pixels are preserved in these places, making it look like a sprite is a non-rectangular object passing over the background. You can also use a color key that effects the destination surface (a destination color key).

A destination color key is a color on a surface that is used for pixels that can be overwritten by a sprite. Again, the artist chooses an arbitrary color that is not used elsewhere in the image, reserving it as a portion of the image where you are allowed to blit. When you blit a sprite to the destination surface with a destination color key specified, the sprite's pixels will only be blitted to pixels on the destination that are using the destination color key. Because the normal destination pixels are preserved, it looks like the sprite passes behind the image on the destination surface. For more information, see Transparent Blitting and Color Keys in the ""Surfaces" topic in the "DirectDraw Essentials" section of the DirectX Foundation SDK.

D3DCOLOR_MONO
A value of the D3DRMCOLORMODEL constant that tells the system to use a monochromatic model (or ramp model). In this model, the blue component of a vertex color is used to define the brightness of a lit vertex.
D3DCOLOR_RGB
A value of the D3DRMCOLORMODEL constant that tells the system to use a full RGB model.
D3DCOLORMODEL
A constant that defines the color model in which the system will run.
typedef enum _D3DCOLORMODEL {
    D3DCOLOR_MONO = 1,
    D3DCOLOR_RGB  = 2,
} D3DCOLORMODEL;
D3DCOLORVALUE
A structure that describes color values. dvR, dvG, dvB, and dvA are values of the D3DVALUE type specifying the red, green, blue, and alpha components of a color. These values generally range from 0.0 to 1.0, with 0.0 specifying black.
typedef struct _D3DCOLORVALUE {
    union {
        D3DVALUE r;
        D3DVALUE dvR;
    };
    union {
        D3DVALUE g;
        D3DVALUE dvG;
    };
    union {
        D3DVALUE b;
        D3DVALUE dvB;
    };
    union {
        D3DVALUE a;
        D3DVALUE dvA;
    };
} D3DCOLORVALUE;
D3DDEVICEDESC
A structure that contains a description of the current device. For more information, see D3DDEVICEDESC in the "Structures" section of the DirectX Foundation Immediate Mode Reference.
D3DENUMDEVICESCALLBACK
The prototype definition for the callback function to enumerate installed Direct3D devices. For more information, see Callback Functions in the DirectX Foundation Immediate Mode Reference.
typedef HRESULT (FAR PASCAL *LPD3DENUMDEVICESCALLBACK)
  (LPGUID lpGuid,
  LPSTR lpDeviceDescription,
  LPSTR lpDeviceName,
  LPD3DDEVICEDESC lpD3DHWDeviceDesc,
  LPD3DDEVICEDESC lpD3DHELD9eviceDesc,
  LPVOID lpUserArg
);
D3DMATRIX
A structure that describes a matrix.
typedef struct _D3DMATRIX {
    D3DVALUE _11, _12, _13, _14;
    D3DVALUE _21, _22, _23, _24;
    D3DVALUE _31, _32, _33, _34;
    D3DVALUE _41, _42, _43, _44;
} D3DMATRIX, *LPD3DMATRIX;
D3DPRIMCAPS
A structure that defines the capabilities for each primitive type. Used by IDirect3DRM3::CreateDeviceFromClipper to set these default capabilities:

D3DPCMPCAPS_LESSEQUAL — Pass the z-buffer comparison if the new z-value is less than or equal to the current z-value.

D3DPMISCCAPS_CULLCCW — The driver supports counterclockwise culling through the D3DRENDERSTATE_CULLMODE state. (This applies only to triangle primitives.)

D3DPRASTERCAPS_FOGVERTEX — The device calculates the fog value during the lighting operation, places the value into the alpha component of the D3DCOLOR value given for the specular member of the D3DTLVERTEX structure, and interpolates the fog value during rasterization.

D3DPSHADECAPS_ALPHAFLATSTIPPLED — The device can support an alpha component for flat blended and stippled transparency, respectively (the D3DSHADE_FLAT state for the D3DSHADEMODE enumerated type). In these modes, the alpha color component for a primitive is provided as part of the color for the first vertex of the primitive.

D3DPTADDRESSCAPS_WRAP — The device can wrap textures to addresses.

D3DPTBLENDCAPS_COPY | D3DPTBLENDCAPS_MODULATE — The copy texture-blending mode (D3DTBLEND_COPY from the D3DTEXTUREBLEND enumerated type) and the modulate texture-blending mode (D3DTBLEND_MODULATE from the D3DTEXTUREBLEND enumerated type) are supported.

D3DPTEXTURECAPS_PERSPECTIVE | D3DPTEXTURECAPS_TRANSPARENCY — Perspective correction and texture transparency are supported.

D3DPTFILTERCAPS_NEAREST — The texel (a single element of a texture) with coordinates nearest to the desired pixel value is used. This applies to both zooming in and zooming out. If either zooming in or zooming out is supported, then both must be supported.

D3DRECT
A structure that is a rectangle definition.
typedef struct _D3DRECT {
    union {
        LONG x1;
        LONG lX1;  //upper left x
    };
    union {
        LONG y1;
        LONG lY1;  //upper left y
    };
    union {
        LONG x2;
        LONG lX2; //lower right x
    };
    union {
        LONG y2;
        LONG lY2;  //lower right y
    };
} D3DRECT, *LPD3DRECT;
D3DTRIANGLE
The structure that describes the base type for all triangles. The triangle is the main rendering primitive.
D3DVALUE
The fundamental Direct3D fractional data type.
typedef float D3DVALUE, *LPD3DVALUE;
D3DVECTOR
The structure that defines a vector for many Direct3D and Direct3D Retained Mode methods and structures.
typedef struct _D3DVECTOR {
    union {
        D3DVALUE x;
        D3DVALUE dvX;
    };
    union {
        D3DVALUE y;
        D3DVALUE dvY;
    };
    union {
        D3DVALUE z;
        D3DVALUE dvZ;
    };
} D3DVECTOR, *LPD3DVECTOR;
DirectDrawCreate
A function that creates an instance of a DirectDraw object. For more information, see DirectDrawCreate in the "Functions" section of the DirectX Foundation DirectDraw Reference.
DirectDrawCreateClipper
A function that creates an instance of a DirectDrawClipper object not associated with a DirectDraw object. For more information, see DirectDrawCreateClipper in the "Functions" topic of the DirectX Foundation DirectDraw Reference.
DrawPrimitive
The IDirect3DDevice3::DrawPrimitive method renders the specified array of vertices as a sequence of geometric primitives of the specified type (for example, points, lines, triangles, triangle fans, and triangle strips).
IDirect3D3
Applications use the methods of the IDirect3D3 interface to create Direct3D objects and to set up the environment. For more information, see IDirect3D3 in the "Interfaces" topic in the DirectX Foundation Immediate Mode Reference.
IDirect3D3::EnumDevices — This method enumerates all Direct3D device drivers installed on the system.
IDirect3D3::FindDevice — This method finds a device with the specified characteristics and retrieves a description of it.
IDirectDrawClipper
Applications use the methods of the IDirectDrawClipper interface to manage clip lists. For more information, see IDirectDrawClipper in the "Interfaces" topic of the DirectX Foundation DirectDraw Reference.
IDirectDrawClipper::SetHWnd — This method sets the window handle that will obtain the clipping information.
IUnknown Interface
All Component Object Model (COM) interfaces are derived from the IUnknown interface. This interface provides control of the object's lifetime and the ability to navigate multiple interfaces. IUnknown has three methods: AddRef, which increments the object's reference count by 1 when an interface or another application binds itself to the object; QueryInterface, which queries the object about the features it supports by requesting pointers to a specific interface; Release, which decrements the object's reference count by 1. When the count reaches 0, the object is deallocated.

IUnknown::AddRef and IUnknown::Release — These IUnknown methods maintain an object's reference count. For example, if you create a DirectPlay object (with CoCreateInstance, for example), the object's reference count is set to 1. Every time a function returns a pointer to an interface for that object, the function must call AddRef through that pointer to increment the reference count. You must match each AddRef call with a call to Release. Before the pointer can be destroyed, you must call Release through that pointer. After an object's reference count reaches 0, the object is destroyed and all interfaces to it become invalid.
IUnknown::QueryInterface — This IUnknown method determines whether an object supports a specific interface. If an object supports the interface, QueryInterface returns a pointer to that interface. You then can use the methods contained in that interface to communicate with the object. If QueryInterface successfully returns a pointer to an interface, it implicitly calls AddRef to increment the reference count, so your application must call Release to decrement the reference count before destroying the pointer to the interface.
Mipmaps
A mipmap is a sequence of textures, each of which is a progressively lower resolution, prefiltered representation of the same image. Each prefiltered image, or level, in the mipmap is a power of two smaller than the previous level. A high-resolution level is used for objects that are close to the viewer. Lower-resolution levels are used as the object moves farther away. Mipmapping is a computationally low-cost way of improving the quality of rendered textures. For more information, see Mipmaps in the "Textures" topic in the "Direct3D Immediate-Mode Essentials" section of the DirectX Foundation SDK.
Texture Map Formats
A wide range of texture pixel formats are supported by the Microsoft® DirectX® hardware-emulation layer. The table in Texture Map Formats in the "Pixel Format Masks" topic in the DirectX Foundation DirectDraw Reference shows these formats.


Reference

Visual Basic Reference

The Microsoft® Direct3D® Retained Mode reference for Microsoft Visual Basic® provides detailed information about the interfaces, classes, methods, and callback interfaces, with syntax, parameter descriptions, and flag descriptions. It describes the members of Direct3D Retained Mode types, enumerations, other defined types, and the possible error values that can be returned. This section contains the following topics.

Interfaces

  • Callback Interfaces
  • Interfaces

Data Types

  • Enumerations
  • Types

Other Topics

  • Error Values
  • Further Reading


Visual Basic Callback Interfaces

The Microsoft® Direct3D® Retained Mode callback interfaces for Microsoft Visual Basic® are:

  • Direct3DRMCallback
  • Direct3DRMDeviceUpdateCallback3
  • Direct3DRMEnumerateObjectsCallback
  • Direct3DRMFrameMoveCallback3
  • Direct3DRMLoadCallback
  • Direct3DRMLoadTextureCallback3

To use the callback interfaces, for example Direct3DRMDeviceUpdateCallback3, perform the following steps.

  1. Copy the following line into the Code Editor window.
    Implements Direct3DRMDeviceUpdateCallback3
  2. Press ENTER.
  3. Select Direct3DRMDeviceUpdateCallback3 from the Object list box. The syntax block for the Direct3DRMDeviceUpdateCallback3 interface appears on your form.
    Private Sub Direct3DRMDeviceUpdateCallback3_CallbackRMUpdate(
    ByVal f As DxVBLib.Direct3DRMDevice3, ByVal arg As Object,
    ByVal n As Long, Update As DxVBLib.D3DRECT)
    'do something
End Sub

Direct3DRMCallback.CallbackRMDestroyObject

Removes an object.

Syntax

object_CallbackRMDestroyObject(ByVal args As Object)

Parts

object
Object expression that resolves to a Direct3DRMCallback object.
args
Application-defined data passed to this callback.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMDeviceUpdateCallback3.CallbackRMUpdate

Alerts the application when the device changes. This callback is application-defined.

Syntax

object_CallbackRMUpdate(ByVal f As DxVBLib.Direct3DRMDevice3,
  ByVal arg As Object,
  ByVal n As Long,
  Update As DxVBLib.D3DRECT)

Parts

object
Object expression that resolves to a Direct3DRMDeviceUpdateCallback3 object.
f
Direct3DRMDevice3 object to which this callback applies.
arg
Application-defined data passed to this callback.
n
Number of rectangles specified in the Update parameter.
Update
D3DRECT type that describes the area to be updated. The coordinates are specified in device units.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMEnumerateObjectsCallback.CallbackRMEnumerateObjects

Enumerates objects in response to a call to the Direct3DRM3.EnumerateObjects method. This callback is application-defined.

Syntax

object_CallbackRMEnumerateObjects(ByVal Object As DxVBLib.Direct3DRMObject,
  ByVal userArgument As Object)

Parts

object
Object expression that resolves to a Direct3DRMEnumerateObjectsCallback object.
object
Direct3DRMObject object.
userArgument
Application-defined data passed to this callback.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFrameMoveCallback3.CallbackRMFrameMove

Enables an application to apply customized algorithms when a frame is moved or updated. You can use this callback to compensate for changing frame rates. This callback is application-defined.

Syntax

object_CallbackRMFrameMove(ByVal f As DxVBLib.Direct3DRMFrame3,
  ByVal arg As Object,
  ByVal delta As Single)

Parts

object
Object expression that resolves to a Direct3DRMFrameMoveCallback3 object.
f
Direct3DRMFrame3 object that is being moved.
arg
Application-defined data passed to this callback.
delta
Amount of change to apply to the movement. There are two components to the change in position of a frame: linear and rotational. The change in each component is equal to velocity_of_component × delta. Although either or both of these velocities can be set relative to any frame, the system automatically converts them to velocities relative to the parent frame for the purpose of applying time deltas.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Your application can synthesize the acceleration of a frame relative to its parent frame. To do so, on each tick your application should set the velocity of the child frame relative to itself to (a units per tick) × 1 tick, where a is the required acceleration. This is equal to a × delta units per tick. Internally, a × delta units per tick relative to the child frame is converted to (v + (a × delta)) units per tick relative to the parent frame, where v is the current velocity of the child relative to the parent.

You can add and remove this callback from your application by using the Direct3DRMFrame3.AddMoveCallback and Direct3DRMFrame3.DeleteMoveCallback methods.

When determining the order in which to use callbacks, the system searches the objects highest in the hierarchy first, and then uses their callbacks in the order in which they were created.

Direct3DRMLoadCallback.CallbackRMLoad

Loads objects named in a call to the Direct3DRM3.LoadFromFile method. This callback is application-defined.

Syntax

object_CallbackRMLoad(Obj As DxVBLib.Direct3DRMObject,
  ByVal guid As String,
  ByVal userArgument As Object)

Parts

object
Object expression that resolves to a Direct3DRMLoadCallback object.
Obj
Direct3DRMObject object being loaded.
guid
Globally unique identifier (GUID) of the object being loaded.
userArgument
Application-defined data passed to this callback.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

When determining the order in which to use callbacks, the system searches the objects highest in the hierarchy first, and then uses their callbacks in the order in which they were created.

See Also

Direct3DRM3.LoadFromFile

Direct3DRMLoadTextureCallback3.CallbackRMLoadTexture

Loads texture maps from a file or resource named in a call to one of the LoadFromFile methods. Textures must have a width and length divisible by 2. This callback is application-defined.

Syntax

object_CallbackRMLoadTexture(ByVal textureName As String,
  ByVal userArgument As Object) As DxVBLib.Direct3DRMTexture3

Parts

object
Object expression that resolves to a Direct3DRMLoadTextureCallback3 object.
textureName
String containing the name of the texture.
userArgument
Application-defined data passed to this callback.

Return Value

Returns a Direct3DRMTexture3 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Applications can use this callback to implement support for textures that are not in the Microsoft® Windows® bitmap (.bmp) or Portable Pixelmap bitmap (.ppm) P6 format. The P6 format is a binary file format for color images.

When determining the order in which to use callbacks, the system searches the objects highest in the hierarchy first, and then uses their callbacks in the order in which they were created.

See Also

Direct3DRM3.LoadFromFile, Direct3DRMAnimationSet2.LoadFromFile, Direct3DRMFrame3.LoadFromFile, Direct3DRMMeshBuilder3.LoadFromFile


Visual Basic Interfaces

The Microsoft® Direct3D® Retained Mode interfaces for Microsoft Visual Basic® are:

  • Direct3DRM3
  • Direct3DRMAnimation2
  • Direct3DRMAnimationArray
  • Direct3DRMAnimationSet2
  • Direct3DRMClippedVisual
  • Direct3DRMDevice3
  • Direct3DRMDeviceArray
  • Direct3DRMFace2
  • Direct3DRMFaceArray
  • Direct3DRMFrame3
  • Direct3DRMFrameArray
  • Direct3DRMFrameInterpolator
  • Direct3DRMLight
  • Direct3DRMLightArray
  • Direct3DRMLightInterpolator
  • Direct3DRMMaterial2
  • Direct3DRMMaterialInterpolator
  • Direct3DRMMesh
  • Direct3DRMMeshBuilder3
  • Direct3DRMMeshInterpolator
  • Direct3DRMObject
  • Direct3DRMObjectArray
  • Direct3DRMPick2Array
  • Direct3DRMPickArray
  • Direct3DRMProgressiveMesh
  • Direct3DRMShadow2
  • Direct3DRMTexture3
  • Direct3DRMTextureInterpolator
  • Direct3DRMViewport2
  • Direct3DRMViewportArray
  • Direct3DRMViewportInterpolator
  • Direct3DRMVisual
  • Direct3DRMVisualArray
  • Direct3DRMWrap


Direct3DRM3

Applications use the Direct3DRM3 interface to create Direct3DRM3 objects and work with system-level variables.

The methods of the Direct3DRM3 interface create the following objects.

  • Animations and animation sets
  • Clipped visuals
  • Devices
  • Faces
  • Frames
  • Generic uninitialized objects
  • Lights
  • Materials
  • Meshes and mesh builders
  • Shadows
  • Textures
  • Viewports
  • Wraps

Applications use the Direct3DRMDevice3 interface to interact with the output device. For more information about the capabilities of the output device when you create it by using the Direct3DRM3 interface, see Direct3DRMDevice3.

The methods of the Direct3DRM3 interface can be organized into the following groups.

Animation | CreateAnimation
CreateAnimationSet
Clipped visuals | CreateClippedVisual
Devices | CreateDeviceFromClipper
CreateDeviceFromD3D
CreateDeviceFromSurface
GetDevices
Enumeration | EnumerateObjects
Faces | CreateFace
Frames | CreateFrame
Interpolators | CreateInterpolatorFrame
CreateInterpolatorLight
CreateInterpolatorMaterial
CreateInterpolatorMesh
CreateInterpolatorTexture
CreateInterpolatorViewport
Lights | CreateLight
CreateLightRGB
Materials | CreateMaterial
Meshes | CreateMesh
CreateMeshBuilder
Miscellaneous | GetNamedObject
GetOptions
LoadFromFile
SetOptions
Tick
Progressive meshes | CreateProgressiveMesh
Search paths | AddSearchPath
GetSearchPath
SetSearchPath
Shadows | CreateShadow
Textures | CreateTextureFromSurface
LoadTexture
SetDefaultTextureColors
SetDefaultTextureShades
Viewports | CreateViewport
Wraps | CreateWrap

Direct3DRM3.AddSearchPath

Direct3DRM3

Adds a list of directories to the end of the current file search path.

Syntax

object.AddSearchPath(name As String)

Parts

object
Object expression that resolves to a Direct3DRM3 object.
name
String specifying the path to add to the current search path.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

For Microsoft® Windows®, the path should be a list of directories separated by semicolons (;).

See Also

Direct3DRM3.SetSearchPath

Direct3DRM3.CreateAnimation

Direct3DRM3

Creates an empty Direct3DRMAnimation2 object.

Syntax

object.CreateAnimation( ) As Direct3DRMAnimation2

Parts

object
Object expression that resolves to a Direct3DRM3 object.

Return Value

Returns a Direct3DRMAnimation2 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRM3.CreateAnimationSet

Direct3DRM3

Creates an empty Direct3DRMAnimationSet2 object.

Syntax

object.CreateAnimationSet( ) As Direct3DRMAnimationSet2

Parts

object
Object expression that resolves to a Direct3DRM3 object.

Return Value

Returns a Direct3DRMAnimationSet2 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRM3.CreateClippedVisual

Direct3DRM3

Creates a Direct3DRMClippedVisual object.

Syntax

object.CreateClippedVisual(vis As Direct3DRMVisual)
  As Direct3DRMClippedVisual

Parts

object
Object expression that resolves to a Direct3DRM3 object.
vis
Direct3DRMVisual object, such as a Direct3DRMMeshBuilder3 object.

Return Value

Returns a Direct3DRMClippedVisual object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRM3.CreateDeviceFromClipper

Direct3DRM3

Creates a Direct3DRMDevice3 object by using a specified DirectDrawClipper object.

Syntax

object.CreateDeviceFromClipper(DDClipper As DirectDrawClipper,
  guid As String,
  width As Long,
  height As Long) As Direct3DRMDevice3

Parts

object
Object expression that resolves to a Direct3DRM3 object.
DDClipper
DirectDrawClipper object.
guid
Globally unique identifier (GUID). This parameter can be "".
width, height
Width and height of the device to be created, in pixels.

Return Value

Returns a Direct3DRMDevice3 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

If the guid parameter is "", the system searches for a device with a default set of device capabilities. This is the recommended way to create a Retained Mode device because it always works, even if the user installs new hardware.

The system describes the default settings by using a D3DPRIMCAPS type in internal device-enumeration calls.

If a hardware device is not found, the monochromatic (ramp) software driver is loaded. An application should enumerate devices instead of specifying "" in the guid parameter if it has special needs that are not met by this list of default settings. Specifying "" in the guid parameter will chose a hardware device if one is available and default to a software rasterizer if one is not.

To specify a device, locate the appropriate GUID by getting a Direct3D3 object through DirectDraw4 by calling the GetDirect3D method. Then, call GetDevicesEnum on the Direct3D3 object to get a Direct3DEnumDevices object. From the Direct3DEnumDevices, object you can match GUIDs to device descriptions and capabilities.

For more information about devices, see Direct3DRMDevice3.

Direct3DRM3.CreateDeviceFromD3D

Direct3DRM3

Creates a Direct3D Retained Mode Windows device by using specified Direct3D objects.

Syntax

object.CreateDeviceFromD3D(D3D As Direct3D3,
  dev As Direct3DDevice3) As Direct3DRMDevice3

Parts

object
Object expression that resolves to a Direct3DRM3 object.
D3D
Instance of a Direct3D3 Immediate Mode object.
dev
Direct3DDevice3 Immediate Mode device object.

Return Value

Returns a Direct3DRMDevice3 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

For more information about devices, see Direct3DRMDevice3.

Direct3DRM3.CreateDeviceFromSurface

Direct3DRM3

Creates a Direct3D Retained Mode Windows device for rendering from the specified DirectDraw surfaces.

Syntax

object.CreateDeviceFromSurface(g As String,
  dd As DirectDraw4,
  ddS As DirectDrawSurface4,
  flags As CONST_D3DRMCREATEDEVICEFLAGS) As Direct3DRMDevice3

Parts

object
Object expression that resolves to a Direct3DRM3 object.
g
Globally unique identifier (GUID) used as the required device driver. If this parameter is "", the default device driver is used.
dd
DirectDraw4 object that is the source of the DirectDraw surface.
ddS
DirectDrawSurface4 object that represents the back buffer.
flags
One or more values from the CONST_D3DRMCREATEDEVICEFLAGS enumerated type.

Return Value

Returns a Direct3DRMDevice3 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

For more information about devices, see Direct3DRMDevice3.

Direct3DRM3.CreateFace

Direct3DRM3

Creates an instance of the Direct3DRMFace2 interface.

Syntax

object.CreateFace( ) As Direct3DRMFace2

Parts

object
Object expression that resolves to a Direct3DRM3 object.

Return Value

Returns a Direct3DRMFace2 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRM3.CreateFrame

Direct3DRM3

Creates a new child frame of the given parent frame.

Syntax

object.CreateFrame(parent As Direct3DRMFrame3) As Direct3DRMFrame3

Parts

object
Object expression that resolves to a Direct3DRM3 object.
parent
Direct3DRMFrame3 object that will be the parent of the new frame.

Return Value

Returns a Direct3DRMFrame3 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

The child frame inherits the motion attributes of its parent. For example, if the parent is moving with a given velocity, the child frame will also move with that velocity. Furthermore, if the parent is set to rotate, the child frame will rotate about the origin of the parent. Frames that have no parent are called scenes. To create a scene, specify NOTHING as the parent. An application can create a frame with no parent and then associate it with a parent frame later by using the Direct3DRMFrame3.AddChild method.

If an application calls Direct3DRM3.SetOptions to set right-handed geometry, the default axes for root frames becomes v = (0, 0, -1) and u = (0, 1, 0). (Note: to create a root frame, the parent should be NOTHING.) Therefore, Direct3DRMFrame3.GetOrientation and Direct3DRMFrame3.SetOrientation work correctly in right-handed mode.

Direct3DRM3.CreateInterpolatorFrame

Direct3DRM3

Creates an instance of a Direct3DRMFrameInterpolator interface.

Syntax

object.CreateInterpolatorFrame( ) As Direct3DRMFrameInterpolator

Parts

object
Object expression that resolves to a Direct3DRM3 object.

Return Value

Returns a Direct3DRMFrameInterpolator object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRM3.CreateInterpolatorLight

Direct3DRM3

Creates an instance of a Direct3DRMLightInterpolator interface.

Syntax

object.CreateInterpolatorLight( ) As Direct3DRMLightInterpolator

Parts

object
Object expression that resolves to a Direct3DRM3 object.

Return Value

Returns a Direct3DRMLightInterpolator object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRM3.CreateInterpolatorMaterial

Direct3DRM3

Creates an instance of a Direct3DRMMaterialInterpolator interface.

Syntax

object.CreateInterpolatorMaterial( ) As Direct3DRMMaterialInterpolator

Parts

object
Object expression that resolves to a Direct3DRM3 object.

Return Value

Returns a Direct3DRMMaterialInterpolator object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRM3.CreateInterpolatorMesh

Direct3DRM3

Creates an instance of a Direct3DRMMeshInterpolator interface.

Syntax

object.CreateInterpolatorMesh( ) As Direct3DRMMeshInterpolator

Parts

object
Object expression that resolves to a Direct3DRM3 object.

Return Value

Returns a Direct3DRMMeshInterpolator object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRM3.CreateInterpolatorTexture

Direct3DRM3

Creates an instance of a Direct3DRMTextureInterpolator interface.

Syntax

object.CreateInterpolatorTexture( ) As Direct3DRMTextureInterpolator

Parts

object
Object expression that resolves to a Direct3DRM3 object.

Return Value

Returns a Direct3DRMTextureInterpolator object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRM3.CreateInterpolatorViewport

Direct3DRM3

Creates an instance of a Direct3DRMViewportInterpolator interface.

Syntax

object.CreateInterpolatorViewport( ) As Direct3DRMViewportInterpolator

Parts

object
Object expression that resolves to a Direct3DRM3 object.

Return Value

Returns a Direct3DRMViewportInterpolator object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRM3.CreateLight

Direct3DRM3

Creates a new light source with the given type and color.

Syntax

object.CreateLight(lt As CONST_D3DRMLIGHTTYPE,
  color As Long) As Direct3DRMLight

Parts

object
Object expression that resolves to a Direct3DRM3 object.
lt
One of the lighting types given in the CONST_D3DRMLIGHTTYPE enumerated type.
color
Long value packed with 4 bytes representing the color of the light. The last 3 bytes represent the RGB components of the color. You can use CreateColorRGB from the DirectX 7 object to return a Long color value. For a description of different light types, see the Overviews section in the Direct3D Retained Mode C++ documentation.

Return Value

Returns a Direct3DRMLight object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRM3.CreateLightRGB

Direct3DRM3

Creates a new light source with the given red, green, and blue components.

Syntax

object.CreateLightRGB(lt As CONST_D3DRMLIGHTTYPE,
  vred As Single,
  vgreen As Single,
  vblue As Single) As Direct3DRMLight

Parts

object
Object expression that resolves to a Direct3DRM3 object.
lt
One of the lighting types given in the CONST_D3DRMLIGHTTYPE enumerated type.
vred, vgreen, vblue
Color of the light. Each component of the color should be in the range 0.0 to 1.0.

Return Value

Returns a Direct3DRMLight object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRM3.CreateMaterial

Direct3DRM3

Creates a material with the given specular property.

Syntax

object.CreateMaterial(d As Single) As Direct3DRMMaterial2

Parts

object
Object expression that resolves to a Direct3DRM3 object.
d
Sharpness of the reflected highlights, with a value of 5 giving a metallic look and higher values giving a more plastic look to the rendered surface.

Return Value

Returns a Direct3DRMMaterial2 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRM3.CreateMesh

Direct3DRM3

Creates a new mesh object with no faces. The mesh is not visible until it is added to a frame.

Syntax

object.CreateMesh( ) As Direct3DRMMesh

Parts

object
Object expression that resolves to a Direct3DRM3 object.

Return Value

Returns a Direct3DRMMesh object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRM3.CreateMeshBuilder

Direct3DRM3

Creates a new mesh builder object.

Syntax

object.CreateMeshBuilder( ) As Direct3DRMMeshBuilder3

Parts

object
Object expression that resolves to a Direct3DRM3 object.

Return Value

Returns a Direct3DRMMeshBuilder3 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

By default, perspective correction is on.

Direct3DRM3.CreateProgressiveMesh

Direct3DRM3

Creates a new progressive mesh object with no faces. The mesh is not visible until it is added to a frame.

Syntax

object.CreateProgressiveMesh( ) As Direct3DRMProgressiveMesh

Parts

object
Object expression that resolves to a Direct3DRM3 object.

Return Value

Returns a Direct3DRMProgressiveMesh object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRM3.CreateShadow

Direct3DRM3

Creates a shadow by using the specified visual and light, projecting the shadow onto the specified plane. The shadow is a visual that should be added to the frame that contains the visual.

Syntax

object.CreateShadow(visual As Direct3DRMVisual,
  light As Direct3DRMLight,
  px As Single,
  py As Single,
  pz As Single,
  nx As Single,
  ny As Single,
  nz As Single) As Direct3DRMShadow2

Parts

object
Object expression that resolves to a Direct3DRM3 object.
visual
Direct3DRMVisual object.
light
Direct3DRMLight object that is the light source.
px, py, pz
Plane that the shadow will be projected on.
nx, ny, nz
Normal to the plane that the shadow will be projected on.

Return Value

Returns a Direct3DRMShadow2 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRM3.CreateTextureFromSurface

Direct3DRM3

Creates a texture from a specified DirectDraw surface.

Syntax

object.CreateTextureFromSurface(
    ddS As DirectDrawSurface4)
    As Direct3DRMTexture3

Parts

object
Object expression that resolves to a Direct3DRM3 object.
ddS
DirectDrawSurface4 object containing the texture.

Return Value

Returns a Direct3DRMTexture3 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRM3.CreateViewport

Direct3DRM3

Creates a viewport on a device with device coordinates (x, y) to (x + w, y + h).

Syntax

object.CreateViewport(dev As Direct3DRMDevice3,
  fr As Direct3DRMFrame3,
  x As Long,
  y As Long,
  w As Long,
  h As Long) As Direct3DRMViewport2

Parts

object
Object expression that resolves to a Direct3DRM3 object.
dev
Direct3DRMDevice3 object on which the viewport will be created.
fr
Direct3DRMFrame3 object that describes the position and direction of the view.
x, y, w, h
Position and size of the viewport, in device coordinates. The viewport size cannot be larger than the physical device or the method will fail.

Return Value

Returns a Direct3DRMViewport2 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

The viewport displays objects in the scene that contain the camera (fr), with the view direction and up vector taken from the camera.

For more information about devices, see Direct3DRMDevice3.

Direct3DRM3.CreateWrap

Direct3DRM3

Creates a wrapping function that you can use to assign texture coordinates to faces and meshes.

Syntax

object.CreateWrap(t As CONST_D3DRMWRAPTYPE,
  f As Direct3DRMFrame3,
  ox As Single,
  oy As Single,
  oz As Single,
  dx As Single,
  dy As Single,
  dz As Single,
  ux As Single,
  uy As Single,
  uz As Single,
  ou As Single,
  ov As Single,
  su As Single,
  sv As Single) As Direct3DRMWrap

Parts

object
Object expression that resolves to a Direct3DRM3 object.
t
One of the members of the CONST_D3DRMWRAPTYPE enumerated type.
f
Reference Direct3DRMFrame3 object for the wrap.
ox, oy, oz
Origin of the wrap.
dx, dy, dz
The z-axis of the wrap.
ux, uy, uz
The y-axis of the wrap.
ou, ov
Origin in the texture.
su, sv
Scale factor in the texture.

Return Value

Returns a Direct3DRMWrap object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

For a description of wraps, see the Overviews section in the Direct3D Retained Mode C++ documentation.

Direct3DRM3.EnumerateObjects

Direct3DRM3

Uses the specified callback interface on each of the active Direct3D Retained Mode objects.

Syntax

object.EnumerateObjects(
    enumerateObjectsImplementation As Direct3DRMEnumerateObjectsCallback,
    userArgument As object)

Parts

object
Object expression that resolves to a Direct3DRM3 object.
enumerateObjectsImplementation
Application-defined Direct3DRMEnumerateObjectsCallback callback interface to use with each Direct3DRMObject object and the application-defined argument.
userArgument
Application-defined data passed to the callback.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRM3.GetDevices

Direct3DRM3

Retrieves all the Direct3D Retained Mode devices that have been created in the system.

Syntax

object.GetDevices( ) As Direct3DRMDeviceArray

Parts

object
Object expression that resolves to a Direct3DRM3 object.

Return Value

Returns a Direct3DRMDeviceArray object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRM3.GetNamedObject

Direct3DRM3

Finds the Direct3DRMObject object with a specified name.

Syntax

object.GetNamedObject(name As String) As Direct3DRMObject

Parts

object
Object expression that resolves to a Direct3DRM3 object.
name
Name of the object to search for.

Return Value

Returns a Direct3DRMObject object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

If the system does not find an object with the name specified in the name parameter, this method returns D3DRM_OK but the name parameter is "".

Example

Set O = rm.GetNamedObject("object")
If O is Nothing then
    Debug.Print "Object not found"
End If

Direct3DRM3.GetOptions

Direct3DRM3

Retrieves whether Direct3D Retained Mode uses left-handed or right-handed geometry.

Syntax

object.GetOptions( ) As CONST_D3DRMHANDEDNESS

Parts

object
Object expression that resolves to a Direct3DRM3 object.

Return Value

Returns a value from the CONST_D3DRMHANDEDNESS enumerated type that indicates the current Direct3D Retained Mode options.

Error Values

If an error occurs, this method returns DDERR_INVALIDOBJECT or DDERR_INVALIDPARAMS.

See Also

Direct3DRM3.SetOptions

Direct3DRM3.GetSearchPath

Direct3DRM3

Retrieves the current search path. For Windows, the path is a list of directories separated by semicolons (;).

Syntax

object.GetSearchPath( ) As String

Parts

object
Object expression that resolves to a Direct3DRM3 object.

Return Value

Returns the current search path as a string.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRM3.SetSearchPath

Direct3DRM3.LoadFromFile

Direct3DRM3

Loads an object.

Syntax

object.LoadFromFile(filename As String,
  id As String,
  guidArray() As String,
  count As Long,
  options As CONST_D3DRMLOADFLAGS,
  loadCallbackImplementation As Direct3DRMLoadCallback,
  loadArgument As object,
  loadTextureImplementation As Direct3DRMLoadTextureCallback3,
  loadTextureArgument As object,
  parentFrame As Direct3DRMFrame3)

Parts

object
Object expression that resolves to a Direct3DRM3 object.
filename
Full path to the file.
id
Object name or position to be loaded. If id is "", you must set the options parameter to D3DRMLOAD_FIRST. Note that Microsoft Visual Basic® will accept an Integer in the id parameter, indicating the position of the item to be loaded, even though a String data type is specified. For example, placing 1 in the id parameter will load the object in the first position.
guidArray
Interface identifier to load. For example, if this parameter is a two-element array containing IID_Direct3DRMMeshBuilder3 and IID_Direct3DRMAnimationSet2, this method loads all the animation sets and mesh-builder objects. Possible GUIDs must be one or more of the following: IID_Direct3DRMProgressiveMesh, IID_Direct3DRMMeshBuilder3, IID_Direct3DRMAnimationSet2, IID_Direct3DRMAnimation2, or IID_Direct3DRMFrame3. See Remarks.
count
Number of elements specified in the guidArray parameter.
options
One or more values from the CONST_D3DRMLOADFLAGS enumeration describing the load options.
loadCallbackImplementation
Direct3DRMLoadCallback callback interface used when the system reads the specified object.
loadArgument
Application-defined data passed to the Direct3DRMLoadCallback callback interface.
loadTextureImplementation
Direct3DRMLoadTextureCallback3 callback interface used to load any textures used by an object that require special formatting. Textures must have a width and length divisible by 2. This parameter can be NOTHING.
loadTextureArgument
Application-defined data passed to the Direct3DRMLoadTextureCallback3 callback interface.
parentFrame
Parent Direct3DRMFrame3 object. This argument only affects the loading of animation sets. When an animation that is loaded from an .x file references an unparented frame in the .x file, the unparented frame's parent is set to the parent frame at f. However, if you use LoadFromFile to load any frames in the .x file, the parent frame at parentFrame will not be used as the parent frame for frames in the .x file with no parent. That is, parentFrame is used only when you load animation sets. The f parameter can be NOTHING.

Error Values

For a list of possible return codes, see Direct3D Retained Mode Error Values.

Remarks

By default, perspective correction is on.

Each of the LoadFromFile methods uses a filename parameter to specify the source of the object and an id parameter to identify the object. The system interprets the contents of filename based on the choice of source flags, and it interprets the contents of id based on the choice of identifier flags.

The instance flags do not change the interpretation of any of the members. By using the D3DRMLOAD_INSTANCEBYREFERENCE flag, an application can load the same file twice without creating any new objects. If an object does not have a name, setting the D3DRMLOAD_INSTANCEBYREFERENCE flag has the same effect as setting the D3DRMLOAD_INSTANCEBYCOPYING flag—the loader creates each unnamed object as a new one, even if some of the objects are identical.

Remarks

With a count value of 3, guidArray could be filled as follows.

Dim guidArray(3) As String

guidArray(0)="IID_Direct3DRMMeshBuilder3"
guidArray(1)="IID_Direct3DRMFrame3"
guidArray(2)="IID_Direct3DRMAnimationSet2"

Direct3DRM3.LoadTexture

Direct3DRM3

Loads a Direct3DRMTexture3 texture from the specified file. This texture can have 8, 24, or 32 bits per pixel, and it should be in either the Windows bitmap (.bmp) or Portable Pixmap (.ppm) P6 format.

Syntax

object.LoadTexture(name As String) As Direct3DRMTexture3

Parts

object
Object expression that resolves to a Direct3DRM3 object.
name
Name of the required .bmp or .ppm file.

Return Value

Returns a Direct3DRMTexture3 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

LoadTexture checks whether the texture is in BMP or PPM format, which are the formats it can load.

Direct3DRM3.SetDefaultTextureColors

Direct3DRM3

Sets the default colors to be used for a Direct3DRMTexture3 object.

Syntax

object.SetDefaultTextureColors(numTextureColors As Long)

Parts

object
Object expression that resolves to a Direct3DRM3 object.
numTextureColors
Number of colors.

Error Values

For a list of possible return codes, see Direct3D Retained Mode Error Values.

Remarks

This method affects the texture colors only when it is used before the Direct3DRM3.CreateTextureFromSurface method; it has no effect on textures that have already been created.

Direct3DRM3.SetDefaultTextureShades

Direct3DRM3

Sets the default shades to be used for a Direct3DRMTexture3 object.

Syntax

object.SetDefaultTextureShades(numTextureShades As Long)

Parts

object
Object expression that resolves to a Direct3DRM3 object.
numTextureShades
Number of shades.

Error Values

For a list of possible return codes, see Direct3D Retained Mode Error Values.

Remarks

This method affects the texture shades only when it is used before the Direct3DRM3.CreateTextureFromSurface method; it has no effect on textures that have already been created.

Direct3DRM3.SetOptions

Direct3DRM3

Sets whether Direct3D Retained Mode uses left-handed or right-handed geometry.

Syntax

object.SetOptions(options As CONST_D3DRMHANDEDNESS)

Parts

object
Object expression that resolves to a Direct3DRM3 object.
options
Value from the CONST_D3DRMHANDEDNESS that indicates the current Direct3D Retained Mode options.

Error Values

For a list of possible return codes, see Direct3D Retained Mode Error Values.

See Also

Direct3DRM3.GetOptions

Direct3DRM3.SetSearchPath

Direct3DRM3

Sets the current file search path from a list of directories. For Windows, the path should be a list of directories separated by semicolons (;).

Syntax

object.SetSearchPath(name As String)

Parts

object
Object expression that resolves to a Direct3DRM3 object.
name
String specifying the path to set as the current search path.

Error Values

For a list of possible return codes, see Direct3D Retained Mode Error Values.

See Also

Direct3DRM3.GetSearchPath

Direct3DRM3.Tick

Direct3DRM3

Performs the Direct3D Retained Mode system heartbeat. When this method is used, the positions of all moving frames are updated according to their current motion attributes, the scene is rendered to the current device, and relevant callbacks are used at their appropriate times. Control is returned when the rendering cycle is complete.

Syntax

object.Tick(tic As Single)

Parts

object
Object expression that resolves to a Direct3DRM3 object.
tic
Value representing arbitrary units. For example, if you set a velocity of 1,0,0 (see Direct3DRMFrame3.SetVelocity) and a tick value (tic) of 1, the animation will move 1 unit in the x-direction.

Error Values

For a list of possible return codes, see Direct3D Retained Mode Error Values.

Remarks

You can implement this method by using other Retained Mode methods to allow more flexibility in rendering a scene:

  • Direct3DRMFrame3.SetRotation
  • Direct3DRMFrame3.SetVelocity
  • Direct3DRMFrame3.Move


Direct3DRMAnimation2

Applications use the methods of the Direct3DRMAnimation2 interface to animate the position, orientation, and scaling of visuals, lights, and viewports.

An animation in Retained Mode is defined by a set of keys. A key is a time value associated with a scaling operation, an orientation, or a position. A Direct3DRMAnimation object defines how a transformation is modified according to the time value. The animation can be set to operate on a Direct3DRMFrame object, so it could be used to animate the position, orientation, and scaling of Direct3DRMVisual, Direct3DRMLight, and Direct3DRMViewport objects.

The Direct3DRMAnimation2.AddPositionKey, AddRotateKey, and AddScaleKey methods each specify a time value whose units are arbitrary. If an application adds a position key with a time value of 99, for example, a new position key with a time value of 49 would occur exactly halfway between the (zero-based) beginning of the animation and the first position key.

The animation is driven by calling the Direct3DRMAnimation2.SetTime method. This sets the visual object's transformation to the interpolated position, orientation, and scale of the nearby keys in the animation. As with the methods that add animation keys, the time value for SetTime is an arbitrary value, based on the positions of keys the application has already added.

The methods of the Direct3DRMAnimation2 interface can be organized into the following groups.

Keys | AddKey
 | AddPositionKey
 | AddRotateKey
 | AddScaleKey
 | DeleteKey
 | DeleteKeyByID
 | GetKeys
 | GetKeysCount
 | ModifyKey
Miscellaneous | GetFrame
 | SetFrame
 | SetTime
Options | GetOptions
 | SetOptions

The Direct3DRMAnimation2 interface inherits the following methods from the Direct3DRMObject interface:

  • AddDestroyCallback
  • CloneObject
  • DeleteDestroyCallback
  • GetAppData
  • GetClassName
  • GetName
  • SetAppData
  • SetName

The Direct3DRMAnimation object is obtained by calling the Direct3DRM3.CreateAnimation method.

Direct3DRMAnimation2.AddKey

Direct3DRMAnimation2

Adds a new key.

Syntax

object.AddKey(key As D3DRMANIMATIONKEY)

Parts

object
Object expression that resolves to a Direct3DRMAnimation2 object.
key
D3DRMANIMATIONKEY type that defines a new key. The id member of the type is ignored and is filled in with the ID of the new key upon return.

Error Values

If an error occurs, this method returns DDERR_INVALIDOBJECT or DDERR_INVALIDPARAMS.

Direct3DRMAnimation2.AddPositionKey

Direct3DRMAnimation2

Adds a position key to the animation.

Syntax

object.AddPositionKey(time As Single,
  x As Single,
  y As Single,
  z As Single)

Parts

object
Object expression that resolves to a Direct3DRMAnimation2 object.
time
Time in the animation to store the position key. The time units are arbitrary and zero-based; a key whose time value is 49 occurs exactly in the middle of an animation whose last key has an time value of 99.
x, y, and z
Coordinates for the position key added to the animation.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

The transformation applied by this method is a translation, translating the point (x, y, z) to a new point (x', y', z'):

Matrix that translates a point.

See Also

Direct3DRMAnimation2.DeleteKey

Direct3DRMAnimation2.AddRotateKey

Direct3DRMAnimation2

Adds a rotate key to the animation.

Syntax

object.AddRotateKey(time As Single,
  q As D3DRMQUATERNION)

Parts

object
Object expression that resolves to a Direct3DRMAnimation2 object.
time
Time in the animation to store the rotate key. The time units are arbitrary and zero-based; a key whose time value is 49 occurs exactly in the middle of an animation whose last key has a time value of 99.
q
D3DRMQUATERNION type representing the rotation.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method applies a rotation transformation.

See Also

Direct3DRMAnimation2.DeleteKey

Direct3DRMAnimation2.AddScaleKey

Direct3DRMAnimation2

Adds a scale key to the animation.

Syntax

object.AddScaleKey(time As Single,
  x As Single,
  y As Single,
  z As Single)

Parts

object
Object expression that resolves to a Direct3DRMAnimation2 object.
time
Time in the animation to store the scale key. The time units are arbitrary and zero-based; a key whose time value is 49 occurs exactly in the middle of an animation whose last key has a time value of 99.
x, y, and z
Coordinates for the scale key added to the animation.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method applies a scaling transformation.

See Also

Direct3DRMAnimation2.DeleteKey

Direct3DRMAnimation2.DeleteKey

Direct3DRMAnimation2

Removes all the keys with the given time from an animation. For example, if an animation has a scale key with time t and a rotation key with time t then both keys will be deleted.

Syntax

object.DeleteKey(time As Single)

Parts

object
Object expression that resolves to a Direct3DRMAnimation2 object.
time
Time identifying the key that will be removed from the animation.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMAnimation2.DeleteKeyByID

Direct3DRMAnimation2

Deletes the key corresponding to a particular ID.

Syntax

object.DeleteKeyByID(id As Long)

Parts

object
Object expression that resolves to a Direct3DRMAnimation2 object.
id
ID of the key to delete.

Error Values

If an error occurs, the method returns one of the following values.

  • D3DRMERR_NOSUCHKEY
  • DDERR_INVALIDOBJECT
  • DDERR_INVALIDPARAMS

Direct3DRMAnimation2.GetFrame

Direct3DRMAnimation2

Retrieves the frame corresponding to the animation.

Syntax

object.GetFrame( ) As Direct3DRMFrame3

Parts

object
Object expression that resolves to a Direct3DRMAnimation2 object.

Return Value

Returns the interface of the current Direct3DRMFrame object that the animation references.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMAnimation2.GetKeys

Direct3DRMAnimation2

Retrieves the keys corresponding to a particular time.

Syntax

object.GetKeys(timeMin As Single,
  timeMax As Single,
  keyArray() As D3DRMANIMATIONKEY)

Parts

object
Object expression that resolves to a Direct3DRMAnimation2 object.
timeMin
Minimum time value of keys to be returned.
timeMax
Maximum time value of keys to be returned.
keyArray
Array of D3DRMANIMATIONKEY types that will be filled in with the key value.

Error Values

If an error occurs, the method returns one of the following values.

  • D3DRMERR_NOSUCHKEY
  • DDERR_INVALIDOBJECT
  • DDERR_INVALIDPARAMS
  • DD_OK

Direct3DRMAnimation2.GetKeysCount

Direct3DRMAnimation2

Retrieves the keys between two particular times.

Syntax

object.GetKeysCount(timeMin As Single,
  timeMax As Single) As Long

Parts

object
Object expression that resolves to a Direct3DRMAnimation2 object.
timeMin
Minimum time value of keys to be returned.
timeMax
Maximum time value of keys to be returned.

Return Value

Returns the number of keys between timeMin and timeMax.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMAnimation2.GetOptions

Direct3DRMAnimation2

Retrieves animation options.

Syntax

object.GetOptions( ) As CONST_D3DRMANIMATIONFLAGS

Parts

object
Object expression that resolves to a Direct3DRMAnimation2 object.

Return Value

Returns a value from the CONST_D3DRMANIMATIONFLAGS enumeration describing the animation options.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMAnimation2.SetOptions

Direct3DRMAnimation2.ModifyKey

Direct3DRMAnimation2

Modifies the value of a key.

Syntax

object.ModifyKey(key As D3DRMANIMATIONKEY)

Parts

object
Object expression that resolves to a Direct3DRMAnimation2 object.
key
D3DRMANIMATIONKEY type that defines an existing key's value. The id member of the structure must be an existing key.

Error Values

If an error occurs, the method returns one of the following values.

  • D3DRMERR_INCOMPATIBLEKEY
  • D3DRMERR_NOSUCHKEY
  • DDERR_INVALIDOBJECT
  • DDERR_INVALIDPARAMS

Remarks

You cannot modify a key's type. To change a key's type you must delete the original key and then add a new key. You can modify a key's time and position, rotation, and scale values.

Direct3DRMAnimation2.SetFrame

Direct3DRMAnimation2

Sets the frame for the animation.

Syntax

object.SetFrame(frame As Direct3DRMFrame3)

Parts

object
Object expression that resolves to a Direct3DRMAnimation2 object.
frame
Variable representing the Direct3DRMFrame3 object to set for the animation.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMAnimation2.SetOptions

Direct3DRMAnimation2

Sets the animation options.

Syntax

object.SetOptions(flags As CONST_D3DRMANIMATIONFLAGS)

Parts

object
Object expression that resolves to a Direct3DRMAnimation2 object.
flags
One or more values from the CONST_D3DRMANIMATIONFLAGS enumeration describing the animation options.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMAnimation2.GetOptions

Direct3DRMAnimation2.SetTime

Direct3DRMAnimation2

Sets the current time for this animation.

Syntax

object.SetTime(time As Single)

Parts

object
Object expression that resolves to a Direct3DRMAnimation2 object.
time
New current time for the animation. The time units are arbitrary and zero-based; a key whose time value is 49 occurs exactly in the middle of an animation whose last key has an time value of 99.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.


Direct3DRMAnimationArray

The Direct3DRMAnimationArray interface enables you to retrieve the number of animations in the array and request the interface for an animation. The animation array is zero based (0 to N-1).

This interface supports the GetElement and GetSize methods.

Direct3DRMAnimationArray.GetElement

Direct3DRMAnimationArray

Retrieves an interface for the requested animation.

Syntax

object.GetElement( ) As Direct3DRMAnimation2

Parts

object
Object expression that resolves to a Direct3DRMAnimationArray object.

Return Value

Returns the Direct3DRMAnimation2 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMAnimationArray.GetSize

Direct3DRMAnimationArray

Retrieves the number of animations in the array.

Syntax

object.GetSize( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMAnimationArray object.

Return Value

Returns the number of animations.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.


Direct3DRMAnimationSet2

A Direct3DRMAnimationSet2 object enables you to group Direct3DRMAnimation2 objects. This enables all the animations in an animation set to share the same time parameter, simplifying the playback of complex articulated animation sequences. An application can add an animation to an animation set by using the Direct3DRMAnimationSet2.AddAnimation method, and can remove one by using the Direct3DRMAnimationSet2.DeleteAnimation method. Animation sets are driven by calling the Direct3DRMAnimationSet2.SetTime method.

The methods of the Direct3DRMAnimationSet2 interface can be organized into the following groups.

Adding, removing, retrieving, and loading | AddAnimation
DeleteAnimation
GetAnimations
LoadFromFile
Time | SetTime

The Direct3DRMAnimationSet2 interface inherits the following methods from the Direct3DRMObject interface.

AddDestroyCallback
CloneObject
DeleteDestroyCallback
GetAppData
GetClassName
GetName
SetAppData
SetName

The Direct3DRMAnimationSet2 object is obtained by calling the Direct3DRM3.CreateAnimationSet method.

Direct3DRMAnimationSet2.AddAnimation

Direct3DRMAnimationSet2

Adds an animation to the animation set.

Syntax

object.AddAnimation(aid As Direct3DRMAnimation2)

Parts

object
Object expression that resolves to a Direct3DRMAnimationSet2 object.
aid
Direct3DRMAnimation2 object to be added to the animation set.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMAnimationSet2.DeleteAnimation

Direct3DRMAnimationSet2

Removes a previously added animation from the animation set.

Syntax

object.DeleteAnimation(aid As Direct3DRMAnimation2)

Parts

object
Object expression that resolves to a Direct3DRMAnimationSet2 object.
aid
Direct3DRMAnimation2 object to be removed from the animation set.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMAnimationSet2.GetAnimations

Direct3DRMAnimationSet2

Retrieves an array containing the animations in the animation set.

Syntax

object.GetAnimations( ) As Direct3DRMAnimationArray

Parts

object
Object expression that resolves to a Direct3DRMAnimationSet2 object.

Return Value

Returns a Direct3DRMAnimationArray interface providing access to the animations in the animation set.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMAnimationSet2.LoadFromFile

Direct3DRMAnimationSet2

Loads an animation set.

Syntax

object.LoadFromFile(filename As String,
  id As String,
  options As CONST_D3DRMLOADFLAGS,
  loadTextureImplementation As Direct3DRMLoadTextureCallback3,
  userArgument As object,
  parentFrame As Direct3DRMFrame3)

Parts

object
Object expression that resolves to a Direct3DRMAnimationSet2 object.
filename
Source for the object to be loaded. This source can be a file, resource, memory block, or stream, depending on the source flags specified in the flags parameter.
id
Object name or position to be loaded. If id is "", you must set the options parameter to D3DRMLOAD_FIRST. Note that Microsoft Visual Basic® will accept an Integer in the id parameter, indicating the position of the item to be loaded, even though a String data type is specified. For example, placing 1 in the id parameter will load the object in the first position.
options
One or more values from the CONST_D3DRMLOADFLAGS enumerated type describing the load options.
loadTextureImplementation
Direct3DRMLoadTextureCallback3 interface used to load any textures used by the object that require special formatting. Textures must have a width and length divisible by 2. This parameter can be NOTHING.
userArgument
Application-defined data passed to the Direct3DRMLoadTextureCallback3 interface.
parentFrame
Parent Direct3DRMFrame object. This parameter affects only the loading of animation sets. When an animation that is loaded from an .x file references an unparented frame in the .x file, the frame's parent is set to this parent frame argument. However, if you use LoadFromFile to load any frames in the .x file, the parent frame argument will not be used as the parent frame for frames in the .x file with no parent. That is, the parent frame argument is used only when you load animation sets. The value of this argument can be NOTHING.

Error Values

For a list of possible error codes, see Direct3D Retained Mode Error Values.

Remarks

By default, this method loads the first animation set in the file specified by the filename parameter. By default, perspective correction is on.

Direct3DRMAnimationSet2.SetTime

Direct3DRMAnimationSet2

Sets the time for this animation set.

Syntax

object.SetTime(time As Single)

Parts

object
Object expression that resolves to a Direct3DRMAnimationSet2 object.
time
New time.

Error Values

For a list of possible error codes, see Direct3D Retained Mode Error Values.


Direct3DRMClippedVisual

The Direct3DRMClippedVisual interface allows applications to clip visual objects against arbitrary planes, specified in world space, before rendering. You create a clipped visual from another visual in much the same way you create a shadow from another visual. For example, you can create a clipped visual from a sphere and pass a clipping plane straight through the middle of the sphere to have only half of the sphere render. Create clipped visual objects by calling the Direct3DRM3.CreateClippedVisual method. Then add the clipped visual to the scene by using the Direct3DRMFrame3.AddVisual method.

Direct3DRMClippedVisual inherits from Direct3DRMVisual, as the other visual interfaces do. When the reference frame moves, the clipping plane does not move (see the AddPlane method for more information).

The Direct3DRMClippedVisual interface supports the following methods.

  • AddPlane
  • DeletePlane
  • GetPlane
  • GetPlaneIds
  • GetPlaneIdsCount
  • SetPlane

The Direct3DRMClippedVisual interface inherits the following methods from the Direct3DRMObject interface.

  • AddDestroyCallback
  • CloneObject
  • DeleteDestroyCallback
  • GetAppData
  • GetClassName
  • GetName
  • SetAppData
  • SetName

You can create a Direct3DRMClippedVisual object by using the Direct3DRM3 interface.

Direct3DRMClippedVisual.AddPlane

Direct3DRMClippedVisual

Adds a clipping plane.

Syntax

object.AddPlane(ref As Direct3DRMFrame3,
  point As D3DVECTOR,
  normal As D3DVECTOR) As Long

Parts

object
Object expression that resolves to a Direct3DRMClippedVisual object.
ref
Reference frame for the point and normal parameters.
point
Point on the plane relative to the reference frame.
normal
Vector normal to the plane relative to the reference frame.

Return Value

Returns a unique ID number for the plane on successful return.

Error Values

If an error occurs, the method can return DDERR_INVALIDPARAMS.

For a list of possible error codes, see Direct3D Retained Mode Error Values.

Remarks

Clipping planes are stored internally as world coordinates. When the reference frame moves, the clipping plane does not move. Use the SetPlane method to update the position and orientation of the clipping plane, as needed.

See Also

D3DVECTOR

Direct3DRMClippedVisual.DeletePlane

Direct3DRMClippedVisual

Deletes a clipping plane.

Syntax

object.DeletePlane(id As Long)

Parts

object
Object expression that resolves to a Direct3DRMClippedVisual object.
id
ID number of the plane to delete.

Error Values

For a list of possible error codes, see Direct3D Retained Mode Error Values.

Direct3DRMClippedVisual.GetPlane

Direct3DRMClippedVisual

Retrieves information about a clipping plane.

Syntax

object.GetPlane(id As Long,
  ref As Direct3DRMFrame3,
  point As D3DVECTOR,
  normal As D3DVECTOR)

Parts

object
Object expression that resolves to a Direct3DRMClippedVisual object.
id
ID of the plane.
ref
Reference Direct3DRMFrame3 object for this operation.
point
Point on the plane relative to the "reference frame" on successful return.
normal
Vector normal to the plane, relative to the "reference frame" on successful return.

Error Values

For a list of possible error codes, see Direct3D Retained Mode Error Values.

See Also

D3DVECTOR

Direct3DRMClippedVisual.GetPlaneIds

Direct3DRMClippedVisual

Retrieves an array of IDs.

Syntax

object.GetPlaneIds(count As Long,
  arrayOfIds() As Long)

Parts

object
Object expression that resolves to a Direct3DRMClippedVisual object.
count
Size of the arrayOfIds array, in bytes.
arrayOfIds
Array of all the plane ID numbers. On successful return, contains the IDs of the planes.

Error Values

For a list of possible error codes, see Direct3D Retained Mode Error Values.

Direct3DRMClippedVisual.GetPlaneIdsCount

Direct3DRMClippedVisual

Retrieves the number of planes.

Syntax

object.GetPlaneIdsCount( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMClippedVisual object.

Return Value

Returns the number of planes.

Error Values

For a list of possible error codes, see Direct3D Retained Mode Error Values.

Direct3DRMClippedVisual.SetPlane

Direct3DRMClippedVisual

Changes the parameters of a clipping plane that has already been added.

Syntax

object.SetPlane(id As Long,
  ref As Direct3DRMFrame3,
  point As D3DVECTOR,
  normal As D3DVECTOR)

Parts

object
Object expression that resolves to a Direct3DRMClippedVisual object.
id
ID number of the plane to be changed.
ref
Reference Direct3DRMFrame3 object for the point and normal parameters. If this parameter is NOTHING, point and normal are in world space.
point
Point on the plane relative to the "reference frame."
normal
Vector normal to the plane, relative to the "reference frame."

Error Values

For a list of possible error codes, see Direct3D Retained Mode Error Values.

See Also

D3DVECTOR


Direct3DRMDevice3

When you create the Direct3DRMDevice3 interface from the Direct3DRM3 interface, the interface works with a Direct3DDevice3 Immediate Mode device. The Direct3DDevice3 device executes buffers, and is required for progressive meshes, for alpha blending and sorting of transparent objects.

The methods of the Direct3DRMDevice3 interface can be organized into the following groups.

Buffer counts | GetBufferCount
SetBufferCount
Color models | GetColorModel
Dithering | GetDither
SetDither
Miscellaneous | GetDirect3DDevice3
GetHeight
GetTrianglesDrawn
GetViewports
GetWidth
GetWireframeOptions
Update
Notifications | AddUpdateCallback
DeleteUpdateCallback
Rendering quality | GetQuality
SetQuality
Shading | GetShades
SetShades
Textures | FindPreferredTextureFormat
GetTextureQuality
SetTextureQuality
Transparency | GetRenderMode
SetRenderMode

The Direct3DRMDevice3 interface inherits the following methods from the Direct3DRMObject interface.

  • AddDestroyCallback
  • CloneObject
  • DeleteDestroyCallback
  • GetAppData
  • GetClassName
  • GetName
  • SetAppData
  • SetName

The Direct3DRMDevice3 object can be obtained by calling the Direct3DRM3.CreateDeviceFromClipper, Direct3DRM3.CreateDeviceFromD3D, or Direct3DRM3.CreateDeviceFromSurface methods.

Direct3DRMDevice3.AddUpdateCallback

Direct3DRMDevice3

Adds a callback that alerts the application when a change occurs to the device. The system uses this callback when the application uses the Direct3DRMDevice3.Update method.

Syntax

object.AddUpdateCallback(
    updateCallbackImplementation As Direct3DRMDeviceUpdateCallback3,
    userArgument As object)

Parts

object
Object expression that resolves to a Direct3DRMDevice3 object.
updateCallbackImplementation
Application-defined callback interface, Direct3DRMDeviceUpdateCallback3.
userArgument
Private data to be passed to the update callback.

Error Values

For a list of possible error values, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMDevice3.DeleteUpdateCallback

Direct3DRMDevice3.DeleteUpdateCallback

Direct3DRMDevice3

Removes an update callback that was added by using the Direct3DRMDevice3.AddUpdateCallback method.

Syntax

object.DeleteUpdateCallback(
    updateCallbackImplementation As Direct3DRMDeviceUpdateCallback3,
    userArgument As Object)

Parts

object
Object expression that resolves to a Direct3DRMDevice3 object.
updateCallbackImplementation
Application-defined callback, Direct3DRMDeviceUpdateCallback3.
userArgument
Private data that was passed to the update callback.

Error Values

For a list of possible error values, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMDevice3.Update

Direct3DRMDevice3.FindPreferredTextureFormat

Direct3DRMDevice3

Finds a texture format that meets the user criteria and that the underlying Immediate Mode device supports. For optimal performance of the texture cache, use this method to choose the pixel format of texture surfaces.

Syntax

object.FindPreferredTextureFormat(bitDepth As CONST_DDBITDEPTHFLAGS,
  flags As CONST_D3DRMFPTFFLAGS,
  ddpf As DDPIXELFORMAT)

Parts

object
Object expression that resolves to a Direct3DRMDevice3 object.
CONST_DDBITDEPTHFLAGS
Requested texture format bit depth. Specify zero to indicate that any bit depth is acceptable. Specify other values, using a logical combination of one or more of the following Microsoft® DirectDraw® bit-depth flags.
  • DDBD_4
  • DDBD_8
  • DDBD_16
  • DDBD_24
  • DDBD_32
flags
One or more values from the CONST_D3DRMFPTFFLAGS enumerated type.
ddpf
Variable to receive the texture format.

Error Values

If an error occurs, this method returns one of the following values.

  • D3DRMERR_TEXTUREFORMATNOTFOUND
  • DDERR_INVALIDOBJECT
  • DDERR_INVALIDPARAMS

This method returns D3DRMERR_TEXTUREFORMATNOTFOUND if it does not find an acceptable format.

Direct3DRMDevice3.GetBufferCount

Direct3DRMDevice3

Retrieves the value set in a call to the Direct3DRMDevice3.SetBufferCount method.

Syntax

object.GetBufferCount( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMDevice3 object.

Return Value

Returns the number of buffers—one for single-buffering, two for double-buffering, and so on.

Error Values

For a list of possible error codes, see Direct3D Retained Mode Error Values.

Direct3DRMDevice3.GetColorModel

Direct3DRMDevice3

Retrieves the color model of a device.

Syntax

object.GetColorModel( ) As CONST_D3DCOLORMODEL

Parts

object
Object expression that resolves to a Direct3DRMDevice3 object.

Return Value

Returns a value from the CONST_D3DCOLORMODEL enumerated type that describes the Direct3D color model (RGB or monochrome). For more information on the CONST_D3DCOLORMODEL enumerated type and its possible settings, see CONST_D3DCOLORMODEL in Further Reading.

Error Values

For a list of possible error codes, see Direct3D Retained Mode Error Values.

Direct3DRMDevice3.GetDirect3DDevice3

Direct3DRMDevice3

Retrieves a Direct3DDevice3 Immediate Mode device.

Syntax

object.GetDirect3DDevice3( ) As Direct3DDevice3

Parts

object
Object expression that resolves to a Direct3DRMDevice3 object.

Return Value

Returns a Direct3DDevice3 Immediate Mode device object.

Error Values

For a list of possible error codes, see Direct3D Retained Mode Error Values.

Remarks

The Direct3DDevice3 device will support the Microsoft DirectX® DrawPrimitive interface and execute buffers and is required for progressive meshes and for alpha blending and sorting of transparent objects.

Direct3DRMDevice3.GetDither

Direct3DRMDevice3

Retrieves the dither flag for the device.

Syntax

object.GetDither( ) As CONST_DBOOLFLAGS

Parts

object
Object expression that resolves to a Direct3DRMDevice3 object.

Return Value

Returns –1 if the dither flag is set, or zero otherwise.

Error Values

For a list of possible error codes, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMDevice3.SetDither

Direct3DRMDevice3.GetHeight

Direct3DRMDevice3

Retrieves the height of a device. This method is a convenience function.

Syntax

object.GetHeight( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMDevice3 object.

Return Value

Returns the height, in pixels.

Error Values

For a list of possible error codes, see Direct3D Retained Mode Error Values.

Direct3DRMDevice3.GetQuality

Direct3DRMDevice3

Retrieves the rendering quality for the device.

Syntax

object.GetQuality( ) As CONST_D3DRMRENDERQUALITY

Parts

object
Object expression that resolves to a Direct3DRMDevice3 object.

Return Value

Returns one or more of the values from the CONST_D3DRMRENDERQUALITY enumerated type.

Error Values

For a list of possible error codes, see Direct3D Retained Mode Error Values.

Remarks

The rendering quality is the maximum quality at which rendering can take place on the rendering surface of that device.

An object's quality has three components: shade mode (flat or Gouraud), lighting type (on or off), and fill mode (point, wire frame, or solid).

After this method returns the quality, q, you can query to determine if lighting is on, ((q And D3DRMLIGHT_MASK) = D3DRMLIGHT_ON), query to determine shading use, ((q And D3DRMSHADE_MASK)= D3DRMSHADE_PHONG), and query to determine fill use, ((q And D3DRMFILL_MASK)=D3DRMFILL_SOLID).

See Also

Direct3DRMDevice3.SetQuality

Direct3DRMDevice3.GetRenderMode

Direct3DRMDevice3

Retrieves the current transparency flags.

Syntax

object.GetRenderMode( ) As CONST_D3DRMRENDERMODEFLAGS

Parts

object
Object expression that resolves to a Direct3DRMDevice3 object.

Return Value

Returns a value from the CONST_D3DRMRENDERMODEFLAGS enumerated type.

Error Values

For a list of possible error codes, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMDevice3.SetRenderMode

Direct3DRMDevice3.GetShades

Direct3DRMDevice3

Retrieves the number of shades in a ramp of colors used for shading in the monochromatic (or ramp) model.

Syntax

object.GetShades( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMDevice3 object.

Return Value

Returns the number of shades.

Error Values

For a list of possible error codes, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMDevice3.SetShades

Direct3DRMDevice3.GetTextureQuality

Direct3DRMDevice3

Retrieves the current texture quality parameter for the device. Texture quality is relevant only for an RGB device.

Syntax

object.GetTextureQuality( ) As CONST_D3DRMTEXTUREQUALITY

Parts

object
Object expression that resolves to a Direct3DRMDevice3 object.

Return Value

Returns one of the members of the CONST_D3DRMTEXTUREQUALITY enumerated type.

Error Values

For a list of possible error codes, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMDevice3.SetTextureQuality

Direct3DRMDevice3.GetTrianglesDrawn

Direct3DRMDevice3

Retrieves the number of triangles drawn to a device since its creation. This method is a convenience function.

Syntax

object.GetTrianglesDrawn( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMDevice3 object.

Return Value

Returns the number of triangles.

Error Values

For a list of possible error codes, see Direct3D Retained Mode Error Values.

Remarks

The number of triangles includes those that were passed to the renderer but were not drawn because they were back-facing (facing away from the camera). The number does not include triangles that were rejected for lying outside the viewing frustum.

Direct3DRMDevice3.GetViewports

Direct3DRMDevice3

Constructs an Direct3DRMViewportArray object that represents the viewports currently constructed from the device.

Syntax

object.GetViewports( ) As Direct3DRMViewportArray

Parts

object
Object expression that resolves to a Direct3DRMDevice3 object.

Return Value

Returns a Direct3DRMViewportArray object if the call succeeds.

Error Values

For a list of possible return codes, see Direct3D Retained Mode Error Values.

Direct3DRMDevice3.GetWidth

Direct3DRMDevice3

Retrieves the width of a device. This method is a convenience function.

Syntax

object.GetWidth( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMDevice3 object.

Return Value

Returns the width of the device, in pixels.

Error Values

For a list of possible error codes, see Direct3D Retained Mode Error Values.

Direct3DRMDevice3.GetWireframeOptions

Direct3DRMDevice3

Retrieves the wire-frame options of a given device.

Syntax

object.GetWireframeOptions( ) As CONST_D3DRMWIREFRAMEFLAGS

Parts

object
Object expression that resolves to a Direct3DRMDevice3 object.

Return Value

Returns a value from the CONST_D3DRMWIREFRAMEFLAGS enumerated type.

Error Values

For a list of possible error codes, see Direct3D Retained Mode Error Values.

Direct3DRMDevice3.SetBufferCount

Direct3DRMDevice3

Sets the number of buffers being used by the application.

Syntax

object.SetBufferCount(count As Long)

Parts

object
Object expression that resolves to a Direct3DRMDevice3 object.
count
Number of buffers—one for single-buffering, two for double-buffering, and so on. The default value is one, which is correct only for a single-buffered window operation.

Error Values

For a list of possible error codes, see Direct3D Retained Mode Error Values.

Remarks

An application that employs double-buffering or triple-buffering must use this method to inform the system of how many buffers it is using so that the system can calculate how much of the window to clear and update on each frame.

See Also

Direct3DRMDevice3.GetBufferCount

Direct3DRMDevice3.SetDither

Direct3DRMDevice3

Sets the dither flag for the device.

Syntax

object.SetDither(ditherEnabled As CONST_DBOOLFLAGS)

Parts

object
Object expression that resolves to a Direct3DRMDevice3 object.
ditherEnabled
New dithering mode for the device. Specify D_TRUE to enable dithering; otherwise, specify D_FALSE. The default is D_TRUE.

Error Values

For a list of possible error codes, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMDevice3.GetDither

Direct3DRMDevice3.SetQuality

Direct3DRMDevice3

Sets the rendering quality of a device.

Syntax

object.SetQuality(q As CONST_D3DRMRENDERQUALITY)

Parts

object
Object expression that resolves to a Direct3DRMDevice3 object.
q
One or more of the values from the CONST_D3DRMRENDERQUALITY enumerated type.

Error Values

For a list of possible error codes, see Direct3D Retained Mode Error Values.

Remarks

The rendering quality is the maximum quality at which rendering can take place on the rendering surface of that device.

An object's quality has three components: shade mode (flat or Gouraud; Phong is not yet implemented and will default to Gouraud shading), lighting type (on or off), and fill mode (point, wire frame, or solid).

The shade mode, lighting type, and fill mode, are specified with members of the CONST_D3DRMRENDERQUALITY enumeration.

You can set the quality of a Direct3DRMProgressiveMesh or Direct3DRMMeshBuilder3 object with their respective SetQuality methods. By default, the quality of these objects is D3DRMRENDER_GOURAUD. Note that D3DRMRENDER_GOURAUD is equal to D3DRMLIGHT_ON or D3DRMFILL_SOLID or D3DRMSHADE_GOURAUD.

Tip: Gouraud shading gets better performance on progressive mesh objects that change level of detail often or quickly.

Direct3D Retained Mode renders an object at the lowest quality setting based on the device and the object's current setting for each individual component. For example, if the object's current quality setting is D3DRMRENDER_GOURAUD, and the device is D3DRMRENDER_FLAT, the object will be rendered with flat shading, solid fill, and lights on.

These rules apply to Direct3DRMMeshBuilder3 objects and Direct3DRMProgressiveMesh objects. However, Direct3DRMMesh objects do not follow these rules. Mesh objects ignore the device's quality settings and use the group quality setting (which defaults to D3DRMRENDER_GOURAUD).

See Also

Direct3DRMDevice3.GetQuality

Direct3DRMDevice3.SetRenderMode

Direct3DRMDevice3

Sets the transparency mode, which determines how transparent objects will be rendered.

Syntax

object.SetRenderMode(flags As CONST_D3DRMRENDERMODEFLAGS)

Parts

object
Object expression that resolves to a Direct3DRMDevice3 object.
flags
One or more values from the CONST_D3DRMRENDERMODEFLAGS enumerated type, indicating the transparency mode.

Error Values

For a list of possible error codes, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMDevice3.GetRenderMode

Direct3DRMDevice3.SetShades

Direct3DRMDevice3

Sets the number of shades in a ramp of colors used for shading in the monochromatic (or ramp) model.

Syntax

object.SetShades(numShades As Long)

Parts

object
Object expression that resolves to a Direct3DRMDevice3 object.
numShades
New number of shades. This parameter must be a power of two. The default is 32.

Error Values

For a list of possible error codes, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMDevice3.GetShades

Direct3DRMDevice3.SetTextureQuality

Direct3DRMDevice3

Sets the texture quality for the device.

Syntax

object.SetTextureQuality(d As CONST_D3DRMTEXTUREQUALITY)

Parts

object
Object expression that resolves to a Direct3DRMDevice3 object.
d
One of the members of the CONST_D3DRMTEXTUREQUALITY enumerated type. The default is D3DRMTEXTURE_NEAREST.

Error Values

For a list of possible error codes, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMDevice3.GetTextureQuality

Direct3DRMDevice3.Update

Direct3DRMDevice3

Copies the image that has been rendered to the display. It also provides a heartbeat function to the device driver, letting it know when to update the image.

Syntax

object.Update( )

Parts

object
Object expression that resolves to a Direct3DRMDevice3 object.

Error Values

For a list of possible error codes, see Direct3D Retained Mode Error Values.

Remarks

Each call to this method causes the system to call an application-defined callback interface, D3DRMDeviceUpdateCallback3. To add a callback, use the Direct3DRMDevice3.AddUpdateCallback method.


Direct3DRMDeviceArray

Applications use the methods of the Direct3DRMDeviceArray interface to organize device objects. This section is a reference to the following methods of this interface.

The device array is zero based (0 to N-1).

  • GetElement
  • GetSize

The Direct3DRMDeviceArray object is obtained by calling the Direct3DRM3.GetDevices method.

Direct3DRMDeviceArray.GetElement

Direct3DRMDeviceArray

Retrieves a specified element in a Direct3DRMDeviceArray object.

Syntax

object.GetElement(index As Long) As Direct3DRMDevice3

Parts

object
Object expression that resolves to a Direct3DRMDeviceArray object.
index
Element in the array.

Return Value

Returns the element specified by the index parameter in a Direct3DRMDeviceArray object.

Error Values

For a list of possible error codes, see Direct3D Retained Mode Error Values.

Direct3DRMDeviceArray.GetSize

Direct3DRMDeviceArray

Retrieves the number of elements contained in a Direct3DRMDeviceArray object.

Syntax

object.GetSize( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMDeviceArray object.

Return Value

Returns the number of elements.

Error Values

For a list of possible error codes, see Direct3D Retained Mode Error Values.


Direct3DRMFace2

Applications use the methods of the Direct3DRMFace2 interface to interact with a face. A face represents a single polygon in a mesh. An application can set the color, texture, and material of the face by using the Direct3DRMFace2.SetColor, Direct3DRMFace2.SetColorRGB, Direct3DRMFace2.SetTexture, and Direct3DRMFace2.SetMaterial methods.

Faces are constructed from vertices by using the Direct3DRMFace2.AddVertex and Direct3DRMFace2.AddVertexAndNormalIndexed methods. An application can read the vertices of a face by using the Direct3DRMFace2.GetVertices and Direct3DRMFace2.GetVertex methods.

In Direct3DRMFace2, the SetTexture method can now specify a texture whose width and height are not a power of two.

The methods of the Direct3DRMFace2 interface can be organized into the following groups.

Color | GetColor
SetColor
SetColorRGB
Materials | GetMaterial
SetMaterial
Textures | GetTexture
GetTextureCoordinateIndex
GetTextureCoordinates
GetTextureTopology
SetTexture
SetTextureCoordinates
SetTextureTopology
Vertices and normals | AddVertex
AddVertexAndNormalIndexed
GetNormal
GetVertex
GetVertexCount
GetVertexIndex
GetVertices

The Direct3DRMFace2 interface inherits the following methods from the Direct3DRMObject interface.

  • AddDestroyCallback
  • CloneObject
  • DeleteDestroyCallback
  • GetAppData
  • GetClassName
  • GetName
  • SetAppData
  • SetName

The Direct3DRMFace2 object is obtained by using the Direct3DRM3.CreateFace method.

Direct3DRMFace2.AddVertex

Direct3DRMFace2

Adds a vertex to a Direct3DRMFace2 object.

Syntax

object.AddVertex(x As Single,
  y As Single,
  z As Single)

Parts

object
Object expression that resolves to a Direct3DRMFace2 object.
x, y, and z
The x, y, and z components of the new vertex position.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFace2.AddVertexAndNormalIndexed

Direct3DRMFace2

Adds a vertex and a normal to a Direct3DRMFace2 object, using an index for the vertex and an index for the normal in the containing mesh builder. The face, vertex, and normal must already be part of a Direct3DRMMeshBuilder3 object.

Syntax

object.AddVertexAndNormalIndexed(vertexIndex As Long,
  normalIndex As Long)

Parts

object
Object expression that resolves to a Direct3DRMFace2 object.
vertexIndex and normal
Indexes of the vertex and normal to add.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFace2.GetColor

Direct3DRMFace2

Retrieves the color of a Direct3DRMFace2 object.

Syntax

object.GetColor( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMFace2 object.

Return Value

Returns the color.

Error Values

For a list of possible error codes, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMFace2.SetColor

Direct3DRMFace2.GetMaterial

Direct3DRMFace2

Retrieves the material of a Direct3DRMFace2 object.

Syntax

object.GetMaterial( ) As Direct3DRMMaterial2

Parts

object
Object expression that resolves to a Direct3DRMFace2 object.

Return Value

Returns the Direct3DRMMaterial object applied to the face.

Error Values

For a list of possible error codes, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMFace2.SetMaterial

Direct3DRMFace2.GetNormal

Direct3DRMFace2

Retrieves the normal vector of a Direct3DRMFace2 object.

Syntax

object.GetNormal(val As D3DVECTOR)

Parts

object
Object expression that resolves to a Direct3DRMFace2 object.
val
D3DVECTOR type that will be filled with the normal vector of the face.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFace2.GetTexture

Direct3DRMFace2

Retrieves the Direct3DRMTexture3 object applied to a Direct3DRMFace2 object.

Syntax

object.GetTexture( ) As Direct3DRMTexture3

Parts

object
Object expression that resolves to a Direct3DRMFace2 object.

Return Value

Returns a Direct3DRMTexture3 object.

Error Values

For a list of possible error codes, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMFace2.SetTexture

Direct3DRMFace2.GetTextureCoordinateIndex

Direct3DRMFace2

Retrieves the index of the vertex for texture coordinates in the face's mesh.

Syntax

object.GetTextureCoordinateIndex(which As Long) As Long

Parts

object
Object expression that resolves to a Direct3DRMFace2 object.
which
Index within the face of the vertex whose corresponding mesh vertex index is being retrieved.

Return Value

Returns the face's mesh-relative vertex index.

Error Values

For a list of possible error codes, see Direct3D Retained Mode Error Values.

Direct3DRMFace2.GetTextureCoordinates

Direct3DRMFace2

Retrieves the texture coordinates of a vertex in a Direct3DRMFace2 object.

Syntax

object.GetTextureCoordinates(Vertex As Long,
  u As Single,
  v As Single)

Parts

object
Object expression that resolves to a Direct3DRMFace2 object.
Vertex
Index of the vertex.
u and v
Variables that are filled with the texture coordinates of the vertex.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFace2.GetTextureTopology

Direct3DRMFace2

Retrieves the texture topology of a Direct3DRMFace2 object.

Syntax

object.GetTextureTopology(u As Long,
  v As Long)

Parts

object
Object expression that resolves to a Direct3DRMFace2 object.
u and v
Variables filled with texture coordinates.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFace2.GetVertex

Direct3DRMFace2

Retrieves the position and normal of a vertex in a Direct3DRMFace2 object.

Syntax

object.GetVertex(idx As Long,
  vert As D3DVECTOR,
  norm As D3DVECTOR)

Parts

object
Object expression that resolves to a Direct3DRMFace2 object.
idx
Index of the vertex.
vert and norm
D3DVECTOR types that will be filled with the position and normal of the vertex, respectively.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFace2.GetVertexCount

Direct3DRMFace2

Retrieves the number of vertices in a Direct3DRMFace2 object.

Syntax

object.GetVertexCount( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMFace2 object.

Return Value

Returns the number of vertices.

Error Values

For a list of possible error codes, see Direct3D Retained Mode Error Values.

Direct3DRMFace2.GetVertexIndex

Direct3DRMFace2

Retrieves the index of the vertex in the face's mesh.

Syntax

object.GetVertexIndex(which As Long) As Long

Parts

object
Object expression that resolves to a Direct3DRMFace2 object.
which
Index within the face of the vertex whose corresponding mesh vertex index is being retrieved.

Return Value

Returns the mesh-relative vertex index.

Error Values

For a list of possible error codes, see Direct3D Retained Mode Error Values.

Direct3DRMFace2.GetVertices

Direct3DRMFace2

Retrieves the position and normal vector of each vertex in a Direct3DRMFace2 object.

Syntax

object.GetVertices(vertexCount As Long,
  coord() As D3DVECTOR,
  normals() As D3DVECTOR)

Parts

object
Object expression that resolves to a Direct3DRMFace2 object.
vertexCount
Variable filled with the number of vertices. This parameter cannot be NOTHING.
coord and normals
An array of D3DVECTOR types that will be filled with the positions and normal vectors of the vertices, respectively.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Use GetVertexCount to determine vertexCount and make both coord and normals that size.

Direct3DRMFace2.SetColor

Direct3DRMFace2

Sets a Direct3DRMFace2 object to a given color.

Syntax

object.SetColor(c As Long)

Parts

object
Object expression that resolves to a Direct3DRMFace2 object.
c
Color to set. Make sure to set the alpha component as well as the red, green, and blue color components or your objects might not be visible. Colors are represented by a Long, consisting of 4 bytes. The high byte is the alpha component and the subsequent bytes define red, green, and blue. Use CreateColorRGBA from the DirectX7 object to more easily construct a color or use SetColorRGB if you only want full alpha.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMFace2.GetColor

Direct3DRMFace2.SetColorRGB

Direct3DRMFace2

Sets the red, green, and blue color components of a Direct3DRMFace2 object.

Syntax

object.SetColorRGB(r As Single,
  g As Single,
  b As Single)

Parts

object
Object expression that resolves to a Direct3DRMFace2 object.
r, g, and b
Red, green, and blue components of the color.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFace2.SetMaterial

Direct3DRMFace2

Sets the material of a Direct3DRMFace2 object.

Syntax

object.SetMaterial(ref As Direct3DRMMaterial2)

Parts

object
Object expression that resolves to a Direct3DRMFace2 object.
ref
Direct3DRMMaterial object to use as the material.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMFace2.GetMaterial

Direct3DRMFace2.SetTexture

Direct3DRMFace2

Sets the texture of a Direct3DRMFace2 object.

Syntax

object.SetTexture(ref As Direct3DRMTexture3)

Parts

object
Object expression that resolves to a Direct3DRMFace2 object.
ref
Direct3DRMTexture3 object to use as the texture.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Starting with DirectX Foundation 6, the width and height of the texture are not required to be a power of two.

See Also

Direct3DRMFace2.GetTexture

Direct3DRMFace2.SetTextureCoordinates

Direct3DRMFace2

Sets the texture coordinates of a specified vertex in a Direct3DRMFace2 object.

Syntax

object.SetTextureCoordinates(Vertex As Long,
  u As Single,
  v As Single)

Parts

object
Object expression that resolves to a Direct3DRMFace2 object.
Vertex
Index of the vertex to be set. For example, if the face were a triangle, the possible vertex indices would be 0, 1, and 2.
u and v
Texture coordinates to assign to the specified vertex.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFace2.SetTextureTopology

Direct3DRMFace2

Sets the texture topology of a Direct3DRMFace2 object.

Syntax

object.SetTextureTopology(wrap_u As CONST_DBOOLFLAGS,
  wrap_v As CONST_DBOOLFLAGS)

Parts

object
Object expression that resolves to a Direct3DRMFace2 object.
wrap_u and wrap_v
Specify D_TRUE for either or both of these parameters if you want the texture to have a cylindrical topology in the u- and v-dimensions, respectively; otherwise, specify D_FALSE.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Several interfaces provide SetTextureTopology methods. See Direct3DRMeshBuilder3.SetTextureTopology for more information about the relationship between the SetTextureTopology methods, and for more information about the purpose of the wrap_u and wrap_v parameters.


Direct3DRMFaceArray

Applications use the methods of the Direct3DRMFaceArray interface to organize faces in a mesh. The face array is zero based (0 to N-1). For more information about faces, see Direct3DRMFace2.

The Direct3DRMFaceArray interface supports the following methods.

  • GetElement
  • GetSize

The Direct3DRMFaceArray object is obtained by calling the Direct3DRMMeshBuilder3.GetFaces method.

Direct3DRMFaceArray.GetElement

Direct3DRMFaceArray

Retrieves a specified element in a Direct3DRMFaceArray object.

Syntax

object.GetElement(index As Long) As Direct3DRMFace2

Parts

object
Object expression that resolves to a Direct3DRMFaceArray object.
index
Element in the array.

Return Value

Returns the Direct3DRMFace element specified by the index parameter in a Direct3DRMFaceArray object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFaceArray.GetSize

Direct3DRMFaceArray

Retrieves the number of elements contained in a Direct3DRMFaceArray object.

Syntax

object.GetSize( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMFaceArray object.

Return Value

Returns the number of elements.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.


Direct3DRMFrame3

Applications use the methods of the Direct3DRMFrame3 interface to interact with frames—an object's frame of reference.

Direct3DRMFrame3 provides methods that enable transformation capabilities, setting and retrieving traversal options, and setting and retrieving the scene fogging method. The methods have been divided into two sections: Direct3DRMFrame3 Methods A to M and Direct3DRMFrame3 Methods N to Z.

The methods of the Direct3DRMFrame3 interface can be organized into the following groups.

Axes | GetAxes
GetInheritAxes
SetAxes
SetInheritAxes
Background | GetSceneBackground
GetSceneBackgroundDepth
SetSceneBackground
SetSceneBackgroundDepth
SetSceneBackgroundImage
SetSceneBackgroundRGB
Bounding box | GetBox
GetBoxEnable
GetHierarchyBox
SetBox
SetBoxEnable
Color | GetColor
SetColor
SetColorRGB
Fog | GetSceneFogColor
GetSceneFogEnable
GetSceneFogMethod
GetSceneFogMode
GetSceneFogParams
SetSceneFogColor
SetSceneFogEnable
SetSceneFogMethod
SetSceneFogMode
SetSceneFogParams
Hierarchies | AddChild
DeleteChild
GetChildren
GetParent
GetScene
Lighting | AddLight
DeleteLight
GetLights
Loading | LoadFromFile
Material | GetMaterial
GetMaterialOverride
GetMaterialOverrideTexture
SetMaterial
SetMaterialOverride
SetMaterialOverrideTexture
Material modes | GetMaterialMode
SetMaterialMode
Positioning and movement | AddMoveCallback
AddRotation
AddScale
AddTranslation
DeleteMoveCallback
GetOrientation
GetPosition
GetRotation
GetVelocity
LookAt
Move
SetOrientation
SetPosition
SetQuaternion
SetRotation
SetVelocity
Ray picking | RayPick
Saving | Save
Sorting | GetSortMode
GetZbufferMode
SetSortMode
SetZbufferMode
Textures | GetTexture
SetTexture
Transformations | AddTransform
GetTransform
InverseTransform
InverseTransformVectors
Transform
TransformVectors
Traversal | GetTraversalOptions
SetTraversalOptions
Visual objects | AddVisual
DeleteVisual
GetVisual
GetVisuals
GetVisualCount

The Direct3DRMFrame3 interface inherits the following methods from the Direct3DRMObject interface.

  • AddDestroyCallback
  • CloneObject
  • DeleteDestroyCallback
  • GetAppData
  • GetClassName
  • GetName
  • SetAppData
  • SetName

Obtain the Direct3DRMFrame3 object by using the Direct3DRM3.CreateFrame method.


Direct3DRMFrameArray

Applications use the methods of the Direct3DRMFrameArray interface to organize frame objects. The frame array is zero based (0 to N-1). This section is a reference to the methods of this interface.

The Direct3DRMFrameArray interface supports the following methods.

  • GetElement
  • GetSize

Obtain the Direct3DRMFrameArray object by calling the Direct3DRMPickArray.GetPickFrame, Direct3DRMPick2Array.GetPickFrame, or Direct3DRMFrame3.GetChildren method.

Direct3DRMFrameArray.GetElement

Direct3DRMFrameArray

Retrieves a specified element in a Direct3DRMFrameArray object.

Syntax

object.GetElement(index As Long) As Direct3DRMFrame3

Parts

object
Object expression that resolves to a Direct3DRMFrameArray object.
index
Element in the array.

Return Value

Returns a Direct3DRMFrame3 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFrameArray.GetSize

Direct3DRMFrameArray

Retrieves the number of elements contained in a Direct3DRMFrameArray object.

Syntax

object.GetSize( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMFrameArray object.

Return Value

Returns the number of elements.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.


Direct3DRMFrameInterpolator

Interpolators provide a way of storing actions and applying them to objects with automatic calculation of in-between values. With an interpolator you can blend colors, move objects smoothly between positions, morph meshes, and perform many other transformations.

A Direct3DRMFrame3 object can be attached to a Direct3DRMFrameInterpolator object. For more information on interpolators, see Interpolators in Further Reading.

Direct3DRMFrameInterpolator contains the following methods.

Attaching objects | AttachObject
DetachObject
GetAttachedObjects
Background | SetSceneBackground
SetSceneBackgroundRGB
Color | SetColor
SetColorRGB
Fog | SetSceneFogColor
SetSceneFogParams
Interpolating | GetIndex
Interpolate
SetIndex
Positioning and movement | SetOrientation
SetPosition
SetQuaternion
SetRotation
SetVelocity

In addition, Direct3DRMFrameInterpolator inherits the following methods from the Direct3DRMObject interface.

  • AddDestroyCallback
  • Clone
  • DeleteDestroyCallback
  • GetAppData
  • GetClassName
  • GetName
  • SetAppData
  • SetName

Direct3DRMFrameInterpolator.AttachObject

Direct3DRMFrameInterpolator

Connects an object to the interpolator.

Syntax

object.AttachObject(mObject As Direct3DRMObject)

Parts

object
Object expression that resolves to a Direct3DRMFrameInterpolator object.
mObject
Direct3DRMObject object to attach to the interpolator.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

The attached object can be another interpolator or an object of type x where the interpolator is of type xInterpolator. For example, a Direct3DRMFrame3 object can be attached to a Direct3DRMFrameInterpolator object.

Direct3DRMFrameInterpolator.DetachObject

Direct3DRMFrameInterpolator

Detaches an object from the interpolator.

Syntax

object.DetachObject(mObject As Direct3DRMObject)

Parts

object
Object expression that resolves to a Direct3DRMFrameInterpolator object.
mObject
Direct3DRMObject object to detach from the interpolator.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFrameInterpolator.GetAttachedObjects

Direct3DRMFrameInterpolator

Retrieves the objects currently attached to the interpolator.

Syntax

object.GetAttachedObjects( ) As Direct3DRMObjectArray

Parts

object
Object expression that resolves to a Direct3DRMFrameInterpolator object.

Return Value

Returns a Direct3DRMObjectArray object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFrameInterpolator.GetIndex

Direct3DRMFrameInterpolator

Retrieves the interpolator's current internal index (time).

Syntax

object.GetIndex( ) As Single

Parts

object
Object expression that resolves to a Direct3DRMFrameInterpolator object.

Return Value

Returns a value that contains the interpolator's current internal index.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Every key stored in an interpolator has an index value. When a key is recorded (by using a method), the key is stamped with the current interpolator index value. The key's index value does not change after being stamped.

Direct3DRMFrameInterpolator.Interpolate

Direct3DRMFrameInterpolator

Generates a series of actions by interpolating between keys stored in the interpolator. The actions are then applied to the specified object. If no object is specified, the actions are applied to the currently attached objects.

Syntax

object.Interpolate(val As Single,
  mObject As Direct3DRMObject,
  options As CONST_D3DRMINTERPOLATIONFLAGS)

Parts

object
Object expression that resolves to a Direct3DRMFrameInterpolator object.
val
Value that contains the interpolator's current internal index.
mObject
Direct3DRMObject object that will be assigned interpolated values for all properties stored in the interpolator. Can be NOTHING, in which case the property values of all attached objects will be set to interpolated values.
options
One of the values from the CONST_D3DRMINTERPOLATIONFLAGS enumerated type that controls the kind of interpolation done.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFrameInterpolator.SetColor

Direct3DRMFrameInterpolator

Adds a color key to a Direct3DRMFrameInterpolator object.

Syntax

object.SetColor(c As Long)

Parts

object
Object expression that resolves to a Direct3DRMFrameInterpolator object.
c
New color for the frame. Be sure to set the alpha component as well as the red, green, and blue color components or your objects might not be visible. To specify an object's color, including the alpha component, call the CreateColorRGBA method from the DirectX7 interface on the object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFrameInterpolator.SetColorRGB

Direct3DRMFrameInterpolator

Adds an RGB color key to a Direct3DRMFrameInterpolator object.

Syntax

object.SetColorRGB(r As Single,
  g As Single,
  b As Single)

Parts

object
Object expression that resolves to a Direct3DRMFrameInterpolator object.
r, g, b
New color for the frame. Each component of the color should be in the range 0.0 to 1.0.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFrameInterpolator.SetIndex

Direct3DRMFrameInterpolator

Sets the interpolator's internal index (time) to the specified value. If other interpolators are attached to the interpolator, this method recursively synchronizes their indices to the same value.

Syntax

object.SetIndex(val As Single)

Parts

object
Object expression that resolves to a Direct3DRMFrameInterpolator object.
val
Time to set for the interpolator's internal index.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Every key stored in an interpolator has an index value. When a key is recorded (by using a method), the key is stamped with the current interpolator index value. The key's index value does not change after being stamped.

Direct3DRMFrameInterpolator.SetOrientation

Direct3DRMFrameInterpolator

Adds an orientation key to a Direct3DRMFrameInterpolator object.

Syntax

object.SetOrientation(reference As Direct3DRMFrame3,
  dx As Single,
  dy As Single,
  dz As Single,
  ux As Single,
  uy As Single,
  uz As Single)

Parts

object
Object expression that resolves to a Direct3DRMFrameInterpolator object.
reference
Variable that represents the Direct3DRMFrame3 object to be used as the reference.
dx, dy, dz
New z-axis for the frame. Each component of the vector should be in the range 1.0 to 1.0.
ux, uy, uz
New y-axis for the frame. Each component of the vector should be in the range 1.0 to 1.0.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

The default orientation of a frame has a direction vector of [0, 0, 1] and an up vector of [0, 1, 0].

If [ux, uy, uz] is parallel to [dx, dy, dz], the D3DRMERR_BADVALUE error value is returned; otherwise, the [ux, uy, uz] vector passed is projected onto the plane that is perpendicular to [dx, dy, dz].

Direct3DRMFrameInterpolator.SetPosition

Direct3DRMFrameInterpolator

Adds a position key to a Direct3DRMFrameInterpolator object.

Syntax

object.SetPosition(reference As Direct3DRMFrame3,
  x As Single,
  y As Single,
  z As Single)

Parts

object
Object expression that resolves to a Direct3DRMFrameInterpolator object.
reference
Variable that represents the Direct3DRMFrame3 object to be used as the reference.
x, y, z
New position for the frame. Position has no units. Use the viewing frustum to choose reasonable numbers.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFrameInterpolator.SetQuaternion

Direct3DRMFrameInterpolator

Sets a frame's orientation relative to a reference frame, using a unit quaternion.

Syntax

object.SetQuaternion(reference As Direct3DRMFrame3,
  quat As D3DRMQUATERNION)

Parts

object
Object expression that resolves to a Direct3DRMFrameInterpolator object.
reference
Variable that represents the Direct3DRMFrame3 object to be used as the reference.
quat
D3DRMQUATERNION type used to set the frame's orientation.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

A quaternion is a four-valued vector that can be used to represent any rotation and has properties that are useful when interpolating between orientations. A quaternion is a unit quaternion if s**2 + x**2 + y**2 + z**2 = 1.

Direct3DRMFrameInterpolator.SetRotation

Direct3DRMFrameInterpolator

Sets a frame rotating by the given angle around the given vector at each call to the Direct3DRM3.Tick or Direct3DRMFrame3.Move method. The direction vector [x, y, z] is defined in the reference frame.

Syntax

object.SetRotation(reference As Direct3DRMFrame3,
  x As Single,
  y As Single,
  z As Single,
  theta As Single)

Parts

object
Object expression that resolves to a Direct3DRMFrameInterpolator object.
reference
Variable that represents the Direct3DRMFrame3 object to be used as the reference.
x, y, z
Vector about which rotation occurs. Valid values are in the range 1.0 to 1.0.
theta
Rotation angle, in radians. The larger the angle, the faster an object rotates. The Move and Tick methods scale this value.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

The specified rotation changes the matrix with every render tick.

Direct3DRMFrameInterpolator.SetSceneBackground

Direct3DRMFrameInterpolator

Adds a background color key to a Direct3DRMFrameInterpolator object.

Syntax

object.SetSceneBackground(c As Long)

Parts

object
Object expression that resolves to a Direct3DRMFrameInterpolator object.
c
New color for the background. To specify an object's color, including the alpha component, call the CreateColorRGBA method from the DirectX7 interface on the object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFrameInterpolator.SetSceneBackgroundRGB

Direct3DRMFrameInterpolator

Adds a background RGB color key to a Direct3DRMFrameInterpolator object.

Syntax

object.SetSceneBackgroundRGB(r As Single,
  g As Single,
  b As Single)

Parts

object
Object expression that resolves to a Direct3DRMFrameInterpolator object.
r, g, b
New color for the background. Each red, green, and blue component of the color should be in the range 0.0 to 1.0.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFrameInterpolator.SetSceneFogColor

Direct3DRMFrameInterpolator

Adds a fog color key to a Direct3DRMRFrameInterpolator object.

Syntax

object.SetSceneFogColor(c As Long)

Parts

object
Object expression that resolves to a Direct3DRMFrameInterpolator object.
c
New color for the fog.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFrameInterpolator.SetSceneFogParams

Direct3DRMFrameInterpolator

Adds a fog parameters key to a Direct3DRMRFrameInterpolator object.

Syntax

object.SetSceneFogParams(start As Single,
  End As Single,
  density As Single)

Parts

object
Object expression that resolves to a Direct3DRMFrameInterpolator object.
start, End
Fog start and end points for linear fog mode. These settings determine the distance from the camera at which fog effects first become visible, and the distance at which fog reaches its maximum density.
density
Fog density for the exponential fog modes. This value should be in the range 0 through 1.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFrameInterpolator.SetVelocity

Direct3DRMFrameInterpolator

Sets the velocity of the given frame relative to the reference frame. The frame will be moved by the vector [x, y, z] with respect to the reference frame at each successive call to the Direct3DRM3.Tick or Direct3DRMFrame3.Move method.

Syntax

object.SetVelocity(reference As Direct3DRMFrame3,
  x As Single,
  y As Single,
  z As Single,
  with_rotation As CONST_DBOOLFLAGS)

Parts

object
Object expression that resolves to a Direct3DRMFrameInterpolator object.
reference
Direct3DRMFrame3 object to be used as the reference.
x, y, z
New velocity for the frame. Rotational velocity has no units and can be any value. The Move and Tick methods scale this value.
with_rotation
Flag specifying whether the rotational velocity of the object is taken into account when setting the linear velocity. If set to D_TRUE, the object's rotational velocity is included in the calculation; otherwise, set to D_FALSE.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.


Direct3DRMLight

Applications use the methods of the Direct3DRMLight interface to interact with light objects.

The methods of the Direct3DRMLight interface can be organized into the following groups.

Attenuation | GetConstantAttenuation
GetLinearAttenuation
GetQuadraticAttenuation
SetConstantAttenuation
SetLinearAttenuation
SetQuadraticAttenuation
Color | GetColor
SetColor
SetColorRGB
Enable frames | GetEnableFrame
SetEnableFrame
Light types | GetType
SetType
Range | GetRange
SetRange
Spotlight options | GetPenumbra
GetUmbra
SetPenumbra
SetUmbra

The Direct3DRMLight interface inherits the following methods from the Direct3DRMObject interface.

  • AddDestroyCallback
  • CloneObject
  • DeleteDestroyCallback
  • GetAppData
  • GetClassName
  • GetName
  • SetAppData
  • SetName

Obtain the Direct3DRMLight object by using the Direct3DRM3.CreateLight or Direct3DRM3.CreateLightRGB method.

Direct3DRMLight.GetColor

Direct3DRMLight

Retrieves the color of the current Direct3DRMLight object.

Syntax

object.GetColor( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMLight object.

Return Value

Returns the color.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMLight.SetColor

Direct3DRMLight.GetConstantAttenuation

Direct3DRMLight

Retrieves the constant attenuation factor for the Direct3DRMLight object.

Syntax

object.GetConstantAttenuation( ) As Single

Parts

object
Object expression that resolves to a Direct3DRMLight object.

Return Value

Returns the constant attenuation value.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Lights that have a location (those that are not infinitely far away) can have attenuation factors to calculate the attenuation of the light based on the distance from the light.

The formula for the total attenuation factor is:

1 / [constant_attenuation_factor + distance * linear_attenuation_factor + (distance**2) * quadratic_attenuation_factor]

The total attenuation factor cannot be greater than 1. When attenuation factors are not provided, the default values are 1.0 for the constant attenuation factor, 0.0 for the linear attenuation factor, and 0.0 for the quadratic attenuation factor.

See Also

Direct3DRMLight.SetConstantAttenuation

Direct3DRMLight.GetEnableFrame

Direct3DRMLight

Retrieves the enable frame for a light.

Syntax

object.GetEnableFrame( ) As Direct3DRMFrame3

Parts

object
Object expression that resolves to a Direct3DRMLight object.

Return Value

Returns a Direct3DRMFrame3 object if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMLight.SetEnableFrame

Direct3DRMLight.GetLinearAttenuation

Direct3DRMLight

Retrieves the linear attenuation factor for a light.

Syntax

object.GetLinearAttenuation( ) As Single

Parts

object
Object expression that resolves to a Direct3DRMLight object.

Return Value

Returns the linear attenuation value.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Lights that have a location (those that are not infinitely far away) can have attenuation factors to calculate the attenuation of the light based on distance from the light.

The formula for the total attenuation factor is:

1 / [constant_attenuation_factor + distance * linear_attenuation_factor + (distance**2) * quadratic_attenuation_factor]

The total attenuation factor cannot be greater than 1. When attenuation factors are not provided, the default values are 1.0 for the constant attenuation factor, 0.0 for the linear attenuation factor, and 0.0 for the quadratic attenuation factor.

See Also

Direct3DRMLight.SetLinearAttenuation

Direct3DRMLight.GetPenumbra

Direct3DRMLight

Retrieves the penumbra angle of a spotlight.

Syntax

object.GetPenumbra( ) As Single

Parts

object
Object expression that resolves to a Direct3DRMLight object.

Return Value

Returns the penumbra value in radians.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMLight.SetPenumbra

Direct3DRMLight.GetQuadraticAttenuation

Direct3DRMLight

Retrieves the quadratic attenuation factor for a light.

Syntax

object.GetQuadraticAttenuation( ) As Single

Parts

object
Object expression that resolves to a Direct3DRMLight object.

Return Value

Returns the quadratic attenuation value.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Lights that have a location (those that are not infinitely far away) can have attenuation factors to calculate the attenuation of the light based on distance from the light.

The formula for the total attenuation factor is:

1 / [constant_attenuation_factor + distance * linear_attenuation_factor + (distance**2) * quadratic_attenuation_factor]

The total attenuation factor cannot be greater than 1. When attenuation factors are not provided, the default values are 1.0 for the constant attenuation factor, 0.0 for the linear attenuation factor, and 0.0 for the quadratic attenuation factor.

See Also

Direct3DRMLight.SetQuadraticAttenuation

Direct3DRMLight.GetRange

Direct3DRMLight

Retrieves the range of the current Direct3DRMLight object.

Syntax

object.GetRange( ) As Single

Parts

object
Object expression that resolves to a Direct3DRMLight object.

Return Value

Returns a value describing the range.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMLight.SetRange

Direct3DRMLight.GetType

Direct3DRMLight

Retrieves the type of a given light.

Syntax

object.GetType( ) As CONST_D3DRMLIGHTTYPE

Parts

object
Object expression that resolves to a Direct3DRMLight object.

Return Value

Returns one of the members of the CONST_D3DRMLIGHTTYPE enumerated type.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMLight.SetType

Direct3DRMLight.GetUmbra

Direct3DRMLight

Retrieves the umbra angle of the Direct3DRMLight object. The default is 0.4 radians.

Syntax

object.GetUmbra( ) As Single

Parts

object
Object expression that resolves to a Direct3DRMLight object.

Return Value

Returns the umbra angle in radians.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMLight.SetUmbra

Direct3DRMLight.SetColor

Direct3DRMLight

Sets the color of the given light.

Syntax

object.SetColor(c As Long)

Parts

object
Object expression that resolves to a Direct3DRMLight object.
c
New color for the light. Make sure to set the alpha component as well as the red, green, and blue color components or your objects might not be visible. Colors are represented by a Long, consisting of 4 bytes. The high byte is the alpha component and the subsequent bytes define red, green, and blue. Use CreateColorRGBA from the DirectX7 object to more easily construct a color or use SetColorRGB if you only want full alpha.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method is also used to add a color key to a Direct3DRMLightInterpolator object.

See Also

Direct3DRMLight.GetColor

Direct3DRMLight.SetColorRGB

Direct3DRMLight

Sets the red, green, and blue color components of the given light.

Syntax

object.SetColorRGB(r As Single,
  g As Single,
  b As Single)

Parts

object
Object expression that resolves to a Direct3DRMLight object.
r, g, and b
New color for the light.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method is also used to add an RGB color key to a Direct3DRMLightInterpolator object.

Direct3DRMLight.SetConstantAttenuation

Direct3DRMLight

Sets the constant attenuation factor for a light.

Syntax

object.SetConstantAttenuation(atn As Single)

Parts

object
Object expression that resolves to a Direct3DRMLight object.
atn
New constant attenuation factor.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Lights that have a location (those that are not infinitely far away) can have attenuation factors to calculate the attenuation of the light based on the distance from the light.

The formula for the total attenuation factor is:

1 / [constant_attenuation_factor + distance * linear_attenuation_factor + (distance**2) * quadratic_attenuation_factor]

The total attenuation factor cannot be greater than 1. When attenuation factors are not provided, the default values are 1.0 for the constant attenuation factor, 0.0 for the linear attenuation factor, and 0.0 for the quadratic attenuation factor.

This method is also used to add a constant attenuation key to a Direct3DRMLightInterpolator object.

See Also

Direct3DRMLight.GetConstantAttenuation

Direct3DRMLight.SetEnableFrame

Direct3DRMLight

Sets the enable frame for a light.

Syntax

object.SetEnableFrame(f As Direct3DRMFrame3)

Parts

object
Object expression that resolves to a Direct3DRMLight object.
f
Direct3DRMFrame3 interface for the Direct3DRMLight object. Child frames of this frame are also enabled for this light source.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMLight.GetEnableFrame

Direct3DRMLight.SetLinearAttenuation

Direct3DRMLight

Sets the linear attenuation factor for a light.

Syntax

object.SetLinearAttenuation(atn As Single)

Parts

object
Object expression that resolves to a Direct3DRMLight object.
atn
New linear attenuation factor.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Lights that have a location (those that are not infinitely far away) can have attenuation factors to calculate the attenuation of the light based on distance from the light.

The formula for the total attenuation factor is:

1 / [constant_attenuation_factor + distance * linear_attenuation_factor + (distance**2) * quadratic_attenuation_factor]

The total attenuation factor cannot be greater than 1. When attenuation factors are not provided, the default values are 1.0 for the constant attenuation factor, 0.0 for the linear attenuation factor, and 0.0 for the quadratic attenuation factor.

This method is also used to add a linear attenuation key to a Direct3DRMLightInterpolator object.

See Also

Direct3DRMLight.GetLinearAttenuation

Direct3DRMLight.SetPenumbra

Direct3DRMLight

Sets the angle of the penumbra cone.

Syntax

object.SetPenumbra(p As Single)

Parts

object
Object expression that resolves to a Direct3DRMLight object.
p
New penumbra angle in radians. This angle must be greater than or equal to the angle of the umbra. If you set the penumbra angle to less than the umbra angle, the umbra angle will be set equal to the penumbra angle. The default value is 0.5 radians.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method is also used to add a penumbra angle key to a Direct3DRMLightInterpolator object.

See Also

Direct3DRMLight.GetPenumbra

Direct3DRMLight.SetQuadraticAttenuation

Direct3DRMLight

Sets the quadratic attenuation factor for a light.

Syntax

object.SetQuadraticAttenuation(atn As Single)

Parts

object
Object expression that resolves to a Direct3DRMLight object.
atn
New quadratic attenuation factor.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Lights that have a location (those that are not infinitely far away) can have attenuation factors to calculate the attenuation of the light based on distance from the light.

The formula for the total attenuation factor is:

1 / [constant_attenuation_factor + distance * linear_attenuation_factor + (distance**2) * quadratic_attenuation_factor]

The total attenuation factor cannot be greater than 1. When attenuation factors are not provided, the default values are 1.0 for the constant attenuation factor, 0.0 for the linear attenuation factor, and 0.0 for the quadratic attenuation factor.

This method is also used to add a quadratic attenuation key to a Direct3DRMLightInterpolator object.

See Also

Direct3DRMLight.GetQuadraticAttenuation

Direct3DRMLight.SetRange

Direct3DRMLight

Sets the range of a spotlight. The light affects objects that are within the range only.

Syntax

object.SetRange(mg As Single)

Parts

object
Object expression that resolves to a Direct3DRMLight object.
mg
New range. The default value is 256 modeling-space units.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

The range property is for spotlights only. This method is also used to add a range key to a Direct3DRMLightInterpolator object.

See Also

Direct3DRMLight.GetRange

Direct3DRMLight.SetType

Direct3DRMLight

Changes the light's type.

Syntax

object.SetType(t As CONST_D3DRMLIGHTTYPE)

Parts

object
Object expression that resolves to a Direct3DRMLight object.
t
New light type specified by one of the members of the CONST_D3DRMLIGHTTYPE enumerated type.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMLight.GetType

Direct3DRMLight.SetUmbra

Direct3DRMLight

Sets the angle of the umbra cone.

Syntax

object.SetUmbra(u As Single)

Parts

object
Object expression that resolves to a Direct3DRMLight object.
u
New umbra angle in radians. This angle must be less than or equal to the angle of the penumbra. If you set the umbra angle to greater than the penumbra angle, the penumbra angle will be set equal to the umbra angle. The default value is 0.4 radians.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method is also used to add an umbra angle key to a Direct3DRMLightInterpolator object.

See Also

Direct3DRMLight.GetUmbra


Direct3DRMLightArray

Applications use the methods of the Direct3DRMLightArray interface to organize light objects. The light array is zero based (0 to N-1).

The Direct3DRMLightArray interface supports the following methods.

  • GetElement
  • GetSize

Obtain the Direct3DRMLightArray object by calling the Direct3DRMFrame3.GetLights method.

Direct3DRMLightArray.GetElement

Direct3DRMLightArray

Retrieves a specified element in a Direct3DRMLightArray object.

Syntax

object.GetElement(index As Long) As Direct3DRMLight

Parts

object
Object expression that resolves to a Direct3DRMLightArray object.
index
Element in the array.

Return Value

Returns a Direct3DRMLight object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMLightArray.GetSize

Direct3DRMLightArray

Retrieves the number of elements contained in a Direct3DRMLightArray object.

Syntax

object.GetSize( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMLightArray object.

Return Value

Returns the number of elements.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.


Direct3DRMLightInterpolator

Interpolators provide a way of storing actions and applying them to objects with automatic calculation of in-between values. With an interpolator you can blend colors, move objects smoothly between positions, morph meshes, and perform many other transformations.

A Direct3DRMLight object can be attached to a Direct3DRMLightInterpolator object. For more information on interpolators, see Interpolators in Further Reading.

The Direct3DRMLightInterpolator interface contains the following methods.

Attaching objects | AttachObject
DetachObject
GetAttachedObjects
Attenuation | SetConstantAttenuation
SetLinearAttenuation
SetQuadraticAttenuation
Color | SetColor
SetColorRGB
Interpolating | GetIndex
Interpolate
SetIndex
Range | SetRange
Spotlight options | SetPenumbra
SetUmbra

In addition, Direct3DRMLightInterpolator inherits the following methods from the Direct3DRMObject interface.

  • AddDestroyCallback
  • Clone
  • DeleteDestroyCallback
  • GetAppData
  • GetClassName
  • GetName
  • SetAppData
  • SetName

Direct3DRMLightInterpolator.AttachObject

Direct3DRMLightInterpolator

Connects an object to the interpolator.

Syntax

object.AttachObject(mObject As Direct3DRMObject)

Parts

object
Object expression that resolves to a Direct3DRMLightInterpolator object.
mObject
Direct3DRMObject object to attach to the interpolator.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

The attached object can be another interpolator or an object of type x where the interpolator is of type xInterpolator. For example, a Direct3DRMLight object can be attached to a Direct3DRMLightInterpolator object.

Direct3DRMLightInterpolator.DetachObject

Direct3DRMLightInterpolator

Detaches an object from the interpolator.

Syntax

object.DetachObject(mObject As Direct3DRMObject)

Parts

object
Object expression that resolves to a Direct3DRMLightInterpolator object.
mObject
Direct3DRMObject object to detach from the interpolator.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMLightInterpolator.GetAttachedObjects

Direct3DRMLightInterpolator

Retrieves the objects currently attached to the interpolator.

Syntax

object.GetAttachedObjects( ) As Direct3DRMObjectArray

Parts

object
Object expression that resolves to a Direct3DRMLightInterpolator object.

Return Value

Returns a Direct3DRMObjectArray object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMLightInterpolator.GetIndex

Direct3DRMLightInterpolator

Retrieves the interpolator's current internal index (time).

Syntax

object.GetIndex( ) As Single

Parts

object
Object expression that resolves to a Direct3DRMLightInterpolator object.

Return Value

Returns a value that contains the interpolator's current internal index.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Every key stored in an interpolator has an index value. When a key is recorded (by using a method), the key is stamped with the current interpolator index value. The key's index value does not change after being stamped.

Direct3DRMLightInterpolator.Interpolate

Direct3DRMLightInterpolator

Generates a series of actions by interpolating between keys stored in the interpolator. The actions are then applied to the specified object. If no object is specified, the actions are applied to the currently attached objects.

Syntax

object.Interpolate(val As Single,
  mObject As Direct3DRMObject,
  options As CONST_D3DRMINTERPOLATIONFLAGS)

Parts

object
Object expression that resolves to a Direct3DRMLightInterpolator object.
val
Value that contains the interpolator's current internal index.
mObject
Direct3DRMObject object that will be assigned interpolated values for all properties stored in the interpolator. Can be NOTHING, in which case the property values of all attached objects will be set to interpolated values.
options
One of the values from the CONST_D3DRMINTERPOLATIONFLAGS enumerated type that controls the kind of interpolation done.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMLightInterpolator.SetColor

Direct3DRMLightInterpolator

Adds a color key to a Direct3DRMLightInterpolator object.

Syntax

object.SetColor(c As Long)

Parts

object
Object expression that resolves to a Direct3DRMLightInterpolator object.
c
New color for the light. Make sure to set the alpha component as well as the red, green, and blue color components or your objects might not be visible. Colors are represented by a Long, consisting of 4 bytes. The high byte is the alpha component and the subsequent bytes define red, green, and blue. Use CreateColorRGBA from the DirectX7 object to more easily construct a color or use SetColorRGB if you only want full alpha.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMLightInterpolator.SetColorRGB

Direct3DRMLightInterpolator

Adds an RGB color key to a Direct3DRMLightInterpolator object.

Syntax

object.SetColorRGB(r As Single,
  g As Single,
  b As Single)

Parts

object
Object expression that resolves to a Direct3DRMLightInterpolator object.
r, g, and b
New red, green, and blue color components for the light.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMLightInterpolator.SetConstantAttenuation

Direct3DRMLightInterpolator

Adds a constant attenuation key to a Direct3DRMLightInterpolator object.

Syntax

object.SetConstantAttenuation(atn As Single)

Parts

object
Object expression that resolves to a Direct3DRMLightInterpolator object.
atn
New constant attenuation factor.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Lights that have a location (those that are not infinitely far away) can have attenuation factors to calculate the attenuation of the light based on the distance from the light.

The formula for the total attenuation factor is:

1 / [constant_attenuation_factor + distance * linear_attenuation_factor + (distance**2) * quadratic_attenuation_factor]

The total attenuation factor cannot be greater than 1. When attenuation factors are not provided, the default values are 1.0 for the constant attenuation factor, 0.0 for the linear attenuation factor, and 0.0 for the quadratic attenuation factor.

Direct3DRMLightInterpolator.SetIndex

Direct3DRMLightInterpolator

Sets the interpolator's internal index (time) to the specified value. If other interpolators are attached to the interpolator, this method recursively synchronizes their indices to the same value.

Syntax

object.SetIndex(val As Single)

Parts

object
Object expression that resolves to a Direct3DRMLightInterpolator object.
val
Time to set for the interpolator's internal index.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Every key stored in an interpolator has an index value. When a key is recorded (by using a method), the key is stamped with the current interpolator index value. The key's index value does not change after being stamped.

Direct3DRMLightInterpolator.SetLinearAttenuation

Direct3DRMLightInterpolator

Adds a linear attenuation key to a Direct3DRMLightInterpolator object.

Syntax

object.SetLinearAttenuation(atn As Single)

Parts

object
Object expression that resolves to a Direct3DRMLightInterpolator object.
atn
New linear attenuation factor.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Lights that have a location (those that are not infinitely far away) can have attenuation factors to calculate the attenuation of the light based on distance from the light.

The formula for the total attenuation factor is:

1 / [constant_attenuation_factor + distance * linear_attenuation_factor + (distance**2) * quadratic_attenuation_factor]

The total attenuation factor cannot be greater than 1. When attenuation factors are not provided, the default values are 1.0 for the constant attenuation factor, 0.0 for the linear attenuation factor, and 0.0 for the quadratic attenuation factor.

Direct3DRMLightInterpolator.SetPenumbra

Direct3DRMLightInterpolator

Adds a penumbra angle key to a Direct3DRMLightInterpolator object.

Syntax

object.SetPenumbra(p As Single)

Parts

object
Object expression that resolves to a Direct3DRMLightInterpolator object.
p
New penumbra angle, in radians. This angle must be greater than or equal to the angle of the umbra. If you set the penumbra angle to less than the umbra angle, the umbra angle will be set equal to the penumbra angle. The default value is 0.5 radians.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMLightInterpolator.SetQuadraticAttenuation

Direct3DRMLightInterpolator

Adds a quadratic attenuation key to a Direct3DRMLightInterpolator object.

Syntax

object.SetQuadraticAttenuation(atn As Single)

Parts

object
Object expression that resolves to a Direct3DRMLightInterpolator object.
atn
New quadratic attenuation factor.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Lights that have a location (those that are not infinitely far away) can have attenuation factors to calculate the attenuation of the light based on distance from the light.

The formula for the total attenuation factor is:

1 / [constant_attenuation_factor + distance * linear_attenuation_factor + (distance**2) * quadratic_attenuation_factor]

The total attenuation factor cannot be greater than 1. When attenuation factors are not provided, the default values are 1.0 for the constant attenuation factor, 0.0 for the linear attenuation factor, and 0.0 for the quadratic attenuation factor.

See Also

Direct3DRMLight.GetQuadraticAttenuation

Direct3DRMLightInterpolator.SetRange

Direct3DRMLightInterpolator

Adds a range key to a Direct3DRMLightInterpolator object.

Syntax

object.SetRange(mg As Single)

Parts

object
Object expression that resolves to a Direct3DRMLightInterpolator object.
mg
New range. The default value is 256 modeling-space units.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

The range property is for spotlights only.

Direct3DRMLightInterpolator.SetUmbra

Direct3DRMLightInterpolator

Adds an umbra angle key to a Direct3DRMLightInterpolator object.

Syntax

object.SetUmbra(u As Single)

Parts

object
Object expression that resolves to a Direct3DRMLightInterpolator object.
u
New umbra angle, in radians. This angle must be less than or equal to the angle of the penumbra. If you set the umbra angle to greater than the penumbra angle, the penumbra angle will be set equal to the umbra angle. The default value is 0.4 radians.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.


Direct3DRMMaterial2

Applications use the methods of the Direct3DRMMaterial2 interface to interact with material objects.

A material defines how a surface reflects light. A material has two components: an emissive property and a specular property, whose brightness is determined by a power setting. The value of the power determines the sharpness of the reflected highlights, with a value of 5 giving a metallic appearance and higher values giving a more plastic appearance.

An application can control the emission of a material by using the GetEmissive and SetEmissive methods, the specular component by using the GetSpecular and SetSpecular methods, and the power by using the GetPower and SetPower methods.

A Direct3DRMMaterial2 object uses the object's face color as the ambient color until SetAmbient is called.

The methods of the Direct3DRMMaterial2 interface can be organized into the following groups.

Ambient | GetAmbient
SetAmbient
Emission | GetEmissive
SetEmissive
Power for specular exponent | GetPower
SetPower
Specular | GetSpecular
SetSpecular

The Direct3DRMMaterial2 interface inherits the following methods from the Direct3DRMObject interface.

  • AddDestroyCallback
  • CloneObject
  • DeleteDestroyCallback
  • GetAppData
  • GetClassName
  • GetName
  • SetAppData
  • SetName

Obtain the Direct3DRMMaterial object by using the Direct3DRM3.CreateMaterial method.

Direct3DRMMaterial2.GetAmbient

Direct3DRMMaterial2

Retrieves the current ambient value for the material.

Syntax

object.GetAmbient(r As Single,
  g As Single,
  b As Single)

Parts

object
Object expression that resolves to a Direct3DRMMaterial2 object.
r
Red component of the ambient color.
g
Green component of the ambient color.
b
Blue component of the ambient color.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMaterial2.GetEmissive

Direct3DRMMaterial2

Retrieves the setting for the emissive property of a material. The setting of this property is the color and intensity of the light the object emits.

Syntax

object.GetEmissive(r As Single,
  g As Single,
  b As Single)

Parts

object
Object expression that resolves to a Direct3DRMMaterial2 object.
r, g, and b
Red, green, and blue components of the emissive color.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMMaterial2.SetEmissive

Direct3DRMMaterial2.GetPower

Direct3DRMMaterial2

Retrieves the power used for the specular exponent in the given material.

Syntax

object.GetPower( ) As Single

Parts

object
Object expression that resolves to a Direct3DRMMaterial2 object.

Return Value

Returns the value specifying the power of the specular exponent.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMMaterial2.SetPower

Direct3DRMMaterial2.GetSpecular

Direct3DRMMaterial2

Retrieves the color of the specular highlights of a material.

Syntax

object.GetSpecular(r As Single,
  g As Single,
  b As Single)

Parts

object
Object expression that resolves to a Direct3DRMMaterial2 object.
r, g, and b
Red, green, and blue components of the color of the specular highlights when the method returns.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMMaterial2.SetSpecular

Direct3DRMMaterial2.SetAmbient

Direct3DRMMaterial2

Sets the ambient value for the material. The default is the diffuse color.

Syntax

object.SetAmbient(r As Single,
  g As Single,
  b As Single)

Parts

object
Object expression that resolves to a Direct3DRMMaterial2 object.
r
Red component of the ambient color.
g
Green component of the ambient color.
b
Blue component of the ambient color.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMaterial2.SetEmissive

Direct3DRMMaterial2

Sets the emissive property of a material.

Syntax

object.SetEmissive(r As Single,
  g As Single,
  b As Single)

Parts

object
Object expression that resolves to a Direct3DRMMaterial2 object.
r, g, and b
Red, green, and blue components of the emissive color.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method is also used to add an emissive property key to a Direct3DRMMaterialInterpolator object.

See Also

Direct3DRMMaterial2.GetEmissive

Direct3DRMMaterial2.SetPower

Direct3DRMMaterial2

Sets the power used for the specular exponent in a material.

Syntax

object.SetPower(power As Single)

Parts

object
Object expression that resolves to a Direct3DRMMaterial2 object.
power
New specular exponent.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method is also used to add a spectral power key to a Direct3DRMMaterialInterpolator object.

See Also

Direct3DRMMaterial2.GetPower

Direct3DRMMaterial2.SetSpecular

Direct3DRMMaterial2

Sets the color of the specular highlights for a material.

Syntax

object.SetSpecular(r As Single,
  g As Single,
  b As Single)

Parts

object
Object expression that resolves to a Direct3DRMMaterial2 object.
r, g, and b
Red, green, and blue components of the color of the specular highlights.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method is also used to add a spectral color key to a Direct3DRMMaterialInterpolator object.

See Also

Direct3DRMMaterial2.GetSpecular


Direct3DRMMaterialInterpolator

Interpolators provide a way of storing actions and applying them to objects with automatic calculation of in-between values. With an interpolator you can blend colors, move objects smoothly between positions, morph meshes, and perform many other transformations.

A Direct3DRMMaterial2 object can be attached to a Direct3DRMMaterialInterpolator object. For more information on interpolators, see Interpolators in Further Reading.

Direct3DRMMaterialInterpolator contains the following methods.

Attaching objects | AttachObject
DetachObject
GetAttachedObjects
Emission | SetEmissive
Interpolating | GetIndex
Interpolate
SetIndex
Power for specular exponent | SetPower
Specular | SetSpecular

In addition, Direct3DRMMaterialInterpolator inherits the following methods from the Direct3DRMObject interface.

  • AddDestroyCallback
  • Clone
  • DeleteDestroyCallback
  • GetAppData
  • GetClassName
  • GetName
  • SetAppData
  • SetName

Direct3DRMMaterialInterpolator.AttachObject

Direct3DRMMaterialInterpolator

Connects an object to the interpolator.

Syntax

object.AttachObject(mObject As Direct3DRMObject)

Parts

object
Object expression that resolves to a Direct3DRMMaterialInterpolator object.
mObject
Direct3DRMObject object to attach to the interpolator.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

The attached object can be another interpolator or an object of type x where the interpolator is of type xInterpolator. For example, a Direct3DRMMaterial2 object can be attached to a Direct3DRMMaterialInterpolator object.

Direct3DRMMaterialInterpolator.DetachObject

Direct3DRMMaterialInterpolator

Detaches an object from the interpolator.

Syntax

object.DetachObject(mObject As Direct3DRMObject)

Parts

object
Object expression that resolves to a Direct3DRMMaterialInterpolator object.
mObject
Direct3DRMObject object to detach from the interpolator.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMaterialInterpolator.GetAttachedObjects

Direct3DRMMaterialInterpolator

Retrieves the objects currently attached to the interpolator.

Syntax

object.GetAttachedObjects( ) As Direct3DRMObjectArray

Parts

object
Object expression that resolves to a Direct3DRMMaterialInterpolator object.

Return Value

Returns a Direct3DRMObjectArray object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMaterialInterpolator.GetIndex

Direct3DRMMaterialInterpolator

Retrieves the interpolator's current internal index (time).

Syntax

object.GetIndex( ) As Single

Parts

object
Object expression that resolves to a Direct3DRMMaterialInterpolator object.

Return Value

Returns a value that contains the interpolator's current internal index.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Every key stored in an interpolator has an index value. When a key is recorded (by using a method), the key is stamped with the current interpolator index value. The key's index value does not change after being stamped.

Direct3DRMMaterialInterpolator.Interpolate

Direct3DRMMaterialInterpolator

Generates a series of actions by interpolating between keys stored in the interpolator. The actions are then applied to the specified object. If no object is specified, the actions are applied to the currently attached objects.

Syntax

object.Interpolate(val As Single,
  mObject As Direct3DRMObject,
  options As CONST_D3DRMINTERPOLATIONFLAGS)

Parts

object
Object expression that resolves to a Direct3DRMMaterialInterpolator object.
val
Value that contains the interpolator's current internal index.
mObject
Direct3DRMObject object that will be assigned interpolated values for all properties stored in the interpolator. Can be NOTHING, in which case the property values of all attached objects will be set to interpolated values.
options
One of the values from the CONST_D3DRMINTERPOLATIONFLAGS enumerated type that controls the kind of interpolation done.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMaterialInterpolator.SetEmissive

Direct3DRMMaterialInterpolator

Adds an emissive property key to a Direct3DRMMaterialInterpolator object.

Syntax

object.SetEmissive(r As Single,
  g As Single,
  b As Single)

Parts

object
Object expression that resolves to a Direct3DRMMaterialInterpolator object.
r, g, and b
Red, green, and blue components of the emissive color.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMaterialInterpolator.SetIndex

Direct3DRMMaterialInterpolator

Sets the interpolator's internal index (time) to the specified value. If other interpolators are attached to the interpolator, this method recursively synchronizes their indices to the same value.

Syntax

object.SetIndex(val As Single)

Parts

object
Object expression that resolves to a Direct3DRMMaterialInterpolator object.
val
Time to set for the interpolator's internal index.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Every key stored in an interpolator has an index value. When a key is recorded (by using a method), the key is stamped with the current interpolator index value. The key's index value does not change after being stamped.

Direct3DRMMaterialInterpolator.SetPower

Direct3DRMMaterialInterpolator

Adds a spectral power key to a Direct3DRMMaterialInterpolator object.

Syntax

object.SetPower(power As Single)

Parts

object
Object expression that resolves to a Direct3DRMMaterialInterpolator object.
power
New specular exponent.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

In the specular property of a material, the value of the power parameter will determine the sharpness of specular highlights. A value of 5 gives a metallic appearance, and higher values give a more plastic appearance.

Direct3DRMMaterialInterpolator.SetSpecular

Direct3DRMMaterialInterpolator

Adds a spectral color key to a Direct3DRMMaterialInterpolator object.

Syntax

object.SetSpecular(r As Single,
  g As Single,
  b As Single)

Parts

object
Object expression that resolves to a Direct3DRMMaterialInterpolator object.
r, g, and b
Red, green, and blue components of the color of the specular highlights.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.


Direct3DRMMesh

Applications use the methods of the Direct3DRMMesh interface to interact with groups of meshes. A mesh is a visual object made up of a set of polygonal faces. A mesh defines a set of vertices and a set of faces (the faces are defined in terms of the vertices and normals of the mesh). Changing a vertex or normal that is used by several faces changes the appearance of all faces sharing it.

The vertices of a mesh define the positions of faces in the mesh, and they can also be used to define 2-D coordinates within a texture map.

You can manipulate meshes in Microsoft® Direct3D® Retained Mode by using Direct3DRMMesh and Direct3DRMMeshBuilder3.

If an application needs to assign the same characteristics (such as material or texture) to several vertices or faces, it can use the Direct3DRMMesh interface to combine them in a group. If the application needs to share vertices between two different groups (for example, if neighboring faces in a mesh are different colors), the vertices must be duplicated in both groups. The Direct3DRMMesh.AddGroup method assigns a group identifier to a collection of faces. This identifier is used to refer to the group in subsequent calls.

The Direct3DRMMeshBuilder3 and Direct3DRMMesh interfaces enable an application to create faces with more than three sides. They also automatically split a mesh into multiple buffers if, for example, the hardware the application is rendering to has a limit of 64 KB and a mesh is larger than that size. These features set the Direct3DRMMesh and Direct3DRMMeshBuilder3 API apart from the Direct3D API.

You can define individual color, texture, and material properties for each face in the mesh, or for all faces in the mesh at once, by using the Direct3DRMMesh.SetGroupColor, SetGroupColorRGB, SetGroupTexture, and SetGroupMaterial methods.

For a mesh to be rendered, you must first add it to a frame by using the Direct3DRMFrame3.AddVisual method. You can add a single mesh to multiple frames to create multiple instances of that mesh.

Your application can use flat and Gouraud shade modes, as specified by a call to the Direct3DRMMesh.SetGroupQuality method. (Phong shading is not yet available, however.)

The methods of the Direct3DRMMesh interface can be organized into the following groups.

Color | GetGroupColor
SetGroupColor
SetGroupColorRGB
Creation and information | AddGroup
GetBox
GetGroupCount
GetGroupData
GetSizes
GetGroupDataSize
Materials | GetGroupMaterial
SetGroupMaterial
Miscellaneous | Scale
Translate
Rendering quality | GetGroupQuality
SetGroupQuality
Texture mapping | GetGroupMapping
SetGroupMapping
Textures | GetGroupTexture
SetGroupTexture
Vertex positions | GetVertex
GetVertexCount
GetVertices
SetVertex
SetVertices

The Direct3DRMMesh interface inherits the following methods from the Direct3DRMObject interface.

  • AddDestroyCallback
  • Clone
  • DeleteDestroyCallback
  • GetAppData
  • GetClassName
  • GetName
  • SetAppData
  • SetName

Obtain a Direct3DRMMesh object by using the Direct3DRM3.CreateMesh method.

Direct3DRMMesh.AddGroup

Direct3DRMMesh

Groups a collection of faces and retrieves an identifier for the group. The first group added to a mesh always has index 0. The index of each successive group increases by 1.

Syntax

object.AddGroup(vertexCount As Long,
  faceCount As Long,
  verticesPerFace As Long,
  fdata() As Long) As Long

Parts

object
Object expression that resolves to a Direct3DRMMesh object.
vertexCount and faceCount
Number of vertices and faces in the group.
verticesPerFace
Number of vertices per face in the group, if all faces have the same vertex count. If the group contains faces with varying vertex counts, this parameter should be zero.
fdata
Face data. If the verticesPerFace parameter specifies a value, this data is simply a list of indices into the group's vertex array. If verticesPerFace is zero, the vertex indices should be preceded by an integer specifying the number of vertices in that face. For example, if verticesPerFace is zero and the group is made up of triangular and quadrilateral faces, the data might be in the following form: 3 index index index 4 index index index index 3 index index index ...

Return Value

Returns the value that identifies the group.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

A newly added group has the following default properties.

  • White
  • No texture
  • No specular reflection
  • Position, normal, and color of each vertex in the vertex array equal to zero

To set the positions of the vertices, use the Direct3DRMMesh.SetVertices method.

Direct3DRMMesh.GetBox

Direct3DRMMesh

Retrieves the bounding box containing a Direct3DRMMesh object. The bounding box gives the minimum and maximum model coordinates in each dimension.

Syntax

object.GetBox(vector As D3DRMBOX)

Parts

object
Object expression that resolves to a Direct3DRMMesh object.
vector
D3DRMBOX type filled with the bounding box coordinates.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMesh.GetGroupColor

Direct3DRMMesh

Retrieves the color for a group.

Syntax

object.GetGroupColor(id As Long) As Long

Parts

object
Object expression that resolves to a Direct3DRMMesh object.
id
Identifier of the group. This identifier must be produced by using the Direct3DRMMesh.AddGroup method.

Return Value

Returns a value specifying the color if successful, or zero otherwise.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMMesh.SetGroupColor, Direct3DRMMesh.SetGroupColorRGB

Direct3DRMMesh.GetGroupCount

Direct3DRMMesh

Retrieves the number of groups for a given Direct3DRMMesh object.

Syntax

object.GetGroupCount( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMMesh object.

Return Value

Returns the number of groups if successful, or zero otherwise.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMesh.GetGroupData

Direct3DRMMesh

Retrieves the face data associated with a specified group.

Syntax

object.GetGroupData(id As Long,
  psa() As Long)

Parts

object
Object expression that resolves to a Direct3DRMMesh object.
id
Identifier of the group. This identifier must be produced by using the Direct3DRMMesh.AddGroup method.
psa
Array to be filled with face data. This data is a list of indices into the group's vertex array preceded by an integer specifying the number of vertices in that face. For example, if the group is made up of triangular and quadrilateral faces, the data might be in the following form: 3 index index index 4 index index index index 3 index index index ...

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMesh.GetGroupDataSize

Direct3DRMMesh

Retrieves the number of elements in the data array associated with a particular group.

Syntax

object.GetGroupDataSize(id As Long) As Long

Parts

object
Object expression that resolves to a Direct3DRMMesh object.
id
Identifier of the group. This identifier must be produced by using the Direct3DRMMesh.AddGroup method.

Return Value

Returns the number of elements.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMesh.GetGroupMapping

Direct3DRMMesh

Retrieves a description of how textures are mapped to a group in a Direct3DRMMesh object.

Syntax

object.GetGroupMapping(id As Long) As CONST_D3DRMMAPPINGFLAGS

Parts

object
Object expression that resolves to a Direct3DRMMesh object.
id
Identifier of the group. This identifier must be produced by using the Direct3DRMMesh.AddGroup method.

Return Value

Returns one of the following values from the CONST_D3DRMMAPPINGFLAGS enumerated type describing how textures are mapped to a group.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMMesh.SetGroupMapping

Direct3DRMMesh.GetGroupMaterial

Direct3DRMMesh

Retrieves the material associated with a group in a Direct3DRMMesh object.

Syntax

object.GetGroupMaterial(id As Long) As Direct3DRMMaterial2

Parts

object
Object expression that resolves to a Direct3DRMMesh object.
id
Identifier of the group. This identifier must be produced by using the Direct3DRMMesh.AddGroup method.

Return Value

Returns a Direct3DRMMaterial2 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMMesh.SetGroupMaterial

Direct3DRMMesh.GetGroupQuality

Direct3DRMMesh

Retrieves the rendering quality for a specified group in a Direct3DRMMesh object.

Syntax

object.GetGroupQuality(id As Long) As CONST_D3DRMRENDERQUALITY

Parts

object
Object expression that resolves to a Direct3DRMMesh object.
id
Identifier of the group. This identifier must be produced by using the Direct3DRMMesh.AddGroup method.

Return Value

Returns values from the CONST_D3DRMRENDERQUALITY enumerated type specifying render quality if successful, or zero otherwise.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

The rendering quality is the maximum quality at which rendering can take place on the rendering surface of that device.

An object's quality has three components: shade mode (flat or Gouraud), lighting type (on or off), and fill mode (point, wire frame, or solid).

See Also

Direct3DRMMesh.SetGroupQuality

Direct3DRMMesh.GetGroupTexture

Direct3DRMMesh

Retrieves the texture associated with a group in a Direct3DRMMesh object.

Syntax

object.GetGroupTexture(id As Long) As Direct3DRMTexture3

Parts

object
Object expression that resolves to a Direct3DRMMesh object.
id
Identifier of the group. This identifier must be produced by using the Direct3DRMMesh.AddGroup method.

Return Value

Returns a Direct3DRMTexture3 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMMesh.SetGroupTexture

Direct3DRMMesh.GetSizes

Direct3DRMMesh

Retrieves information for a specified group in a Direct3DRMMesh object.

Syntax

object.GetSizes(id As Long, cnt1 As Long,
  cnt2 As Long,
  cnt3 As Long,
  cnt4 As Long)

Parts

object
Object expression that resolves to a Direct3DRMMesh object.
id
Identifier of the group. This identifier must have been produced by using the Direct3DRMMesh.AddGroup method.
cnt1
Filled with the number of vertices in the group.
cnt2
Filled with the number of faces in the group.
cnt3
Filled with the number of vertices per face in the group, if all faces have the same vertex count. If the group contains faces with varying vertex counts, this parameter is filled with zero.
cnt4
Filled with the required size of psa required by GetGroupData.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMMesh.SetVertices

Direct3DRMMesh.GetVertex

Direct3DRMMesh

Retrieves a single vertex from a particular group.

Syntax

object.GetVertex(id As Long,
  idx As Long,
  ret As D3DRMVERTEX)

Parts

object
Object expression that resolves to a Direct3DRMMesh object.
id
Identifier of the group. This identifier must have been produced by using the Direct3DRMMesh.AddGroup method.
idx
Index into the array of D3DRMVERTEX types at which to begin returning vertex positions.
ret
D3DRMVERTEX type that will contain the vertex information (vertex positions, colors, texture coordinates, and so on) when the method returns.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMMesh.SetVertices

Direct3DRMMesh.GetVertexCount

Direct3DRMMesh

Retrieves the number of vertices for a given Direct3DRMMesh object.

Syntax

object.GetVertexCount(id As Long) As Long

Parts

object
Object expression that resolves to a Direct3DRMMesh object.
id
Identifier of the group. This identifier must have been produced by using the Direct3DRMMesh.AddGroup method.

Return Value

Returns the number of vertices if successful, or zero otherwise.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMMesh.SetVertices

Direct3DRMMesh.GetVertices

Direct3DRMMesh

Retrieves vertex information for a specified group in a Direct3DRMMesh object.

Syntax

object.GetVertices(id As Long,
  idx As Long,
  cnt As Long,
  vertexArray() As D3DRMVERTEX)

Parts

object
Object expression that resolves to a Direct3DRMMesh object.
id
Identifier of the group. This identifier must have been produced by using the Direct3DRMMesh.AddGroup method.
idx
Index into the array of D3DRMVERTEX types at which to begin returning vertex positions.
cnt
Number of D3DRMVERTEX types (vertices) to retrieve following the index given in the idx parameter. This parameter cannot be NOTHING. To retrieve the number of vertices in a group, use the Direct3DRMMesh.GetVertexCount method.
vertexArray
An array of D3DRMVERTEX types that will contain the vertex information (vertex positions, colors, texture coordinates, and so on) when the method returns.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMMesh.SetVertices

Direct3DRMMesh.Scale

Direct3DRMMesh

Scales a Direct3DRMMesh object by the given scaling factors, parallel to the x-, y-, and z-axes in model coordinates.

Syntax

object.Scale(sx As Single,
  sy As Single,
  sz As Single)

Parts

object
Object expression that resolves to a Direct3DRMMesh object.
sx, sy, and sz
Scaling factors that are applied along the x-, y-, and z-axes.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMesh.SetGroupColor

Direct3DRMMesh

Sets the color of a group in a Direct3DRMMesh object.

Syntax

object.SetGroupColor(id As Long,
  val As Long)

Parts

object
Object expression that resolves to a Direct3DRMMesh object.
id
Identifier of the group. This identifier must be produced by using the Direct3DRMMesh.AddGroup method.
val
Color of the group.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method is also used to add a group color key to a Direct3DRMMeshInterpolator object.

See Also

Direct3DRMMesh.GetGroupColor, Direct3DRMMesh.SetGroupColorRGB

Direct3DRMMesh.SetGroupColorRGB

Direct3DRMMesh

Sets the color of a group in a Direct3DRMMesh object, using individual RGB values.

Syntax

object.SetGroupColorRGB(id As Long,
  r As Single,
  g As Single,
  b As Single)

Parts

object
Object expression that resolves to a Direct3DRMMesh object.
id
Identifier of the group. This identifier must be produced by using the Direct3DRMMesh.AddGroup method.
r, g, and b
Red, green, and blue components of the group color.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method is also used to add a group RGB key to a Direct3DRMMeshInterpolator object.

See Also

Direct3DRMMesh.GetGroupColor, Direct3DRMMesh.SetGroupColor

Direct3DRMMesh.SetGroupMapping

Direct3DRMMesh

Sets the mapping for a group in a Direct3DRMMesh object. The mapping controls how textures are mapped to a surface.

Syntax

object.SetGroupMapping(id As Long,
  value As CONST_D3DRMMAPPINGFLAGS)

Parts

object
Object expression that resolves to a Direct3DRMMesh object.
id
Identifier of the group. This identifier must be produced by using the Direct3DRMMesh.AddGroup method.
value
Value from the CONST_D3DRMMAPPINGFLAGS enumerated type that describes the mapping for the group.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMMesh.GetGroupMapping

Direct3DRMMesh.SetGroupMaterial

Direct3DRMMesh

Sets the material associated with a group in a Direct3DRMMesh object.

Syntax

object.SetGroupMaterial(id As Long,
  val As Direct3DRMMaterial2)

Parts

object
Object expression that resolves to a Direct3DRMMesh object.
id
Identifier of the group. This identifier must be produced by using the Direct3DRMMesh.AddGroup method.
val
Direct3DRMMaterial2 interface for the Direct3DRMMesh object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMMesh.GetGroupMaterial

Direct3DRMMesh.SetGroupQuality

Direct3DRMMesh

Sets the rendering quality for a specified group in a Direct3DRMMesh object.

Syntax

object.SetGroupQuality(id As Long,
  value As CONST_D3DRMRENDERQUALITY)

Parts

object
Object expression that resolves to a Direct3DRMMesh object.
id
Identifier of the group. This identifier must be produced by using the Direct3DRMMesh.AddGroup method.
value
Values from the CONST_D3DRMRENDERQUALITY enumerated type identifying the rendering quality. These values include the shading, lighting, and fill modes for the object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

The rendering quality is the maximum quality at which rendering can take place on the rendering surface of that device.

An object's quality has three components: shade mode (flat or Gouraud), lighting type (on or off), and fill mode (point, wire frame, or solid).

See Also

Direct3DRMMesh.GetGroupQuality

Direct3DRMMesh.SetGroupTexture

Direct3DRMMesh

Sets the texture associated with a group in a Direct3DRMMesh object.

Syntax

object.SetGroupTexture(id As Long,
  val As Direct3DRMTexture3)

Parts

object
Object expression that resolves to a Direct3DRMMesh object.
id
Identifier of the group. This identifier must be produced by using the Direct3DRMMesh.AddGroup method.
val
Direct3DRMTexture3 interface for the Direct3DRMMesh object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMMesh.GetGroupTexture

Direct3DRMMesh.SetVertex

Direct3DRMMesh

Modifies the geometry of an existing group in a Direct3DRMMesh object.

Syntax

object.SetVertex(id As Long,
  idx As Long,
  values As D3DRMVERTEX)

Parts

object
Object expression that resolves to a Direct3DRMMesh object.
id
Identifier of the group. This identifier must be produced by using the Direct3DRMMesh.AddGroup method.
idx
Index of the first vertex in the mesh group to be modified.
values
D3DRMVERTEX type specifying the vertex positions to be set.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Vertices are local to the group. If an application needs to share vertices between two different groups (for example, if neighboring faces in a mesh are different colors), the vertices must be duplicated in both groups.

This method is also used to add a vertex position key to a Direct3DRMMeshInterpolator object.

See Also

Direct3DRMMesh.GetVertices

Direct3DRMMesh.SetVertices

Direct3DRMMesh

Sets the vertex positions for a specified group in a Direct3DRMMesh object.

Syntax

object.SetVertices(id As Long,
  idx As Long,
  count As Long,
  vertexArray() As D3DRMVERTEX)

Parts

object
Object expression that resolves to a Direct3DRMMesh object.
id
Identifier of the group. This identifier must be produced by using the Direct3DRMMesh.AddGroup method.
idx
Index of the first vertex in the mesh group to be modified.
count
Number of consecutive vertices to set. The vertexArray parameter must contain at least the number of count elements.
vertexArray
n array of D3DRMVERTEX types specifying the vertex positions to be set.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Vertices are local to the group. If an application needs to share vertices between two different groups (for example, if neighboring faces in a mesh are different colors), the vertices must be duplicated in both groups.

This method is also used to add a vertex position key to a Direct3DRMMeshInterpolator object.

See Also

Direct3DRMMesh.GetVertices

Direct3DRMMesh.Translate

Direct3DRMMesh

Adds the specified offsets to the vertex positions of a Direct3DRMMesh object.

Syntax

object.Translate(tx As Single,
  ty As Single,
  tz As Single)

Parts

object
Object expression that resolves to a Direct3DRMMesh object.
tx, ty, and tz
Offsets that are added to the x-, y-, and z-coordinates, respectively, of each vertex position.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.


Direct3DRMMeshBuilder3

Applications use the methods of the Direct3DRMMeshBuilder3 interface to interact with mesh objects. For more information about meshes, see Direct3DRMMesh.

You can add vertices and faces individually to a mesh by using the Direct3DRMMeshBuilder3.AddVertex, AddFace, and AddFaces methods. You can retrieve an individual face with the GetFace method.

You can set normals (which should be unit vectors), or normals can be calculated by averaging the face normals of the surrounding faces by using the GenerateNormals method.

Direct3DRMMeshBuilder3 methods retrieve normals, the number of normals, faces, one or more vertices, and the state (enabled or disabled) of the meshbuilder. This interface enables you to set vertices and normals, and to create and retrieve new submeshes and parent meshes of the meshbuilder. Direct3DRMMeshBuilder3 also enables the application to add new triangles (as opposed to general polygons) to the Direct3DRMMeshBuilder3 object and, in the process, implicitly create new faces by using the AddTriangles method.

In Retained Mode 6.x, you can create a Direct3DRMMeshBuilder3 object by using the Direct3DRM3 interface, in which case the Direct3DRMMeshBuilder3 object uses the Immediate Mode DrawPrimitive interface for its implementation.

The methods of the Direct3DRMMeshBuilder3 interface can be organized into the following groups.

Color | GetColorSource
SetColor
SetColorRGB
SetColorSource
Creation | GetBox
Faces | AddFace
AddFaces
AddFacesIndexed
CreateFace
DeleteFace
GetFaceCount
GetFaceDataSize
GetFace
GetFaces
Loading | LoadFromFile
Meshes | AddMesh
CreateMesh
Miscellaneous | AddFrame
AddMeshBuilder
AddTriangles
Empty
Enable
GetEnable
Optimize
Save
ScaleMesh
SetMaterial
Translate
Normals | AddNormal
GenerateNormals
GetNormals
GetNormalCount
SetNormal
Perspective | GetPerspective
SetPerspective
Rendering quality | GetQuality
SetQuality
SubMeshes | CreateSubMesh
DeleteSubMesh
GetParentMesh
GetSubMeshCount
GetSubMeshes
Textures | GetTextureCoordinates
SetTexture
SetTextureCoordinates
SetTextureTopology
Vertices | AddVertex
GetGeometry
GetVertex
GetVertexColor
GetVertexCount
SetVertex
SetVertexColor
SetVertexColorRGB

The Direct3DRMMeshBuilder3 interface inherits the following methods from the Direct3DRMObject interface.

  • AddDestroyCallback
  • CloneObject
  • DeleteDestroyCallback
  • GetAppData
  • GetClassName
  • GetName
  • SetAppData
  • SetName

Obtain the Direct3DRMMeshBuilder3 object by using the Direct3DRM3.CreateMeshBuilder method.

Direct3DRMMeshBuilder3.AddFace

Direct3DRMMeshBuilder3

Adds a face to a Direct3DRMMeshBuilder3 object.

Syntax

object.AddFace(f As Direct3DRMFace2)

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
f
Direct3DRMFace2 object being added.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Any one face can exist in only one mesh at a time.

Direct3DRMMeshBuilder3.AddFaces

Direct3DRMMeshBuilder3

Adds faces to a Direct3DRMMeshBuilder3 object.

Syntax

object.AddFaces(vc As Long,
  vertexArray() As D3DVECTOR,
  nc As Long,
  normalArray() As D3DVECTOR,
  data() As Long) As Direct3DRMFaceArray

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
vc
Number of vertices.
vertexArray
An array of D3DVECTOR types that store the vertex positions.
nc
Number of normals.
normalArray
An array of D3DVECTOR types that store the normal positions.
data
For each face, this parameter should contain a vertex count followed by the indexes into the vertices array. If nc is not zero, this parameter should contain a vertex count followed by pairs of indexes, with the first index of each pair indexing into the array of vertices, and the second indexing into the array of normals. The list of indexes must terminate with a zero.

Return Value

Returns a Direct3DRMFaceArray interface that will be filled with the newly created faces.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMeshBuilder3.AddFacesIndexed

Direct3DRMMeshBuilder3

Enables a number of faces to be created on the meshbuilder that use pre-existing vertices and normals (optional).

Syntax

object.AddFacesIndexed(flags As CONST_D3DRMADDFACESFLAGS,
  indexArray() As Long) As Long

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
flags
A value from the CONST_D3DRMADDFACESFLAGS enumerated type that specifies how normal indexes should be handled. If the value is D3DRMADDFACES_DEFAULT, indexes of pre-existing normals must be specified in the indexArray parameter. Otherwise, the normal with the corresponding index will be used automatically for each vertex.
indexArray
Contiguous array of integer tuples that specify the following for each face.
  • Number of vertices n, where n is greater than or equal to 3
  • Vertex indexes
  • Normal indexes (optional)

The following table shows the relationship between the value for the flags parameter and the required face tuple format for the indexArray parameter.

flags | Required face tuple format
D3DRMADDFACES_DEFAULT | {<n>, <vIndex0>, <nIndex0>,...,<vIndex n-1>, <nIndex n-1>}
D3DRMADDFACES_VERTICESONLY | {<n>, <vIndex0>,...,<vIndex n-1>}

The vIndex and nIndex values are required to index into previously existing vertices and normals within the meshbuilder. The array of tuples should be terminated with the value 0.

Return Value

Returns the index of the first new face added to the meshbuilder.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMeshBuilder3.AddFrame

Direct3DRMMeshBuilder3

Adds the contents of a frame to a Direct3DRMMeshBuilder3 object.

Syntax

object.AddFrame(f As Direct3DRMFrame3)

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
f
Direct3DRMFrame3 object whose contents are being added.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method adds a copy of all the mesh and meshbuilder faces from the specified frame hierarchy (which can be a subbranch of a larger frame hierarchy) to the Direct3DRMMeshBuilder3 object. The frame tree is specified by passing the root frame. Faces are added with the position and orientation of their containing frame factored in. Transforms of the specified root frame are ignored, even if the root frame has a parent.

The source frame is not modified or referenced by this operation.

Direct3DRMMeshBuilder3.AddMesh

Direct3DRMMeshBuilder3

Adds a mesh to a Direct3DRMMeshBuilder3 object.

Syntax

object.AddMesh(m As Direct3DRMMesh)

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
m
Direct3DRMMesh object being added.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMeshBuilder3.AddMeshBuilder

Direct3DRMMeshBuilder3

Adds the contents of a Direct3DRMMeshBuilder3 object to a Direct3DRMMeshBuilder3 object. All sub-meshbuilders underneath the source Direct3DRMMeshBuilder3 object and the faces they contain are duplicated beneath the target Direct3DRMMeshBuilder3 object.

Syntax

object.AddMeshBuilder(meshbuilder As Direct3DRMMeshBuilder3,
  flags As CONST_D3DRMADDMESHBUILDERFLAGS)

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
meshbuilder
Direct3DRMMeshBuilder3 object whose contents are being added.
flags
One or more values from the CONST_D3DRMADDMESHBUILDERFLAGS enumerated type, indicating the copying options.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

The source Direct3DRMMeshBuilder3 object is not modified or referenced by this operation.

Direct3DRMMeshBuilder3.AddNormal

Direct3DRMMeshBuilder3

Adds a normal to a Direct3DRMMeshBuilder3 object.

Syntax

object.AddNormal(x As Single,
  y As Single,
  z As Single) As Long

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
x, y, and z
The x-, y-, and z-components of the direction of the new normal.

Return Value

Returns the index of the normal.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMeshBuilder3.AddTriangles

Direct3DRMMeshBuilder3

Enables the application to add new triangles (as opposed to general polygons) to the Direct3DRMMeshBuilder3 object, and in the process, to implicitly create new faces.

Syntax

object.AddTriangles(flags As Long,
  format As CONST_D3DRMADDTRIANGLESVT,
  vertexCount As Long,
  data As Any)

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
flags
Must be zero.
format
Logical combination of values from the CONST_D3DRMADDTRIANGLESVT enumerated type that describes the format of the vertex data. If all valid values are included, the vertex data is described by the following D3DRMFLEXVERTEX user-defined type.

Syntax

Type D3DRMFLEXVERTEX
  IType As Long
  color As Long
  normal As D3DVECTOR
  position As D3DVECTOR
  tu As Single
  tv As Single
End Type

Dim verts(100) As D3DRMFLEXVERTEX

AddTriangles(D3DRMFVF_TYPE Or D3DRMFVF_NORMAL Or D3DRMFVF_COLOR Or D3DRMFVF_TEXTURECOORDS, 100, verts(0))

Valid values include a logical combination of any of the following values, which indicate which members of the D3DRMFLEXVERTEX type to include in the description for each element. The position member is always present.

D3DRMFVF_TYPE
Include the IType member. If the IType member is present, it must include one of the following:
D3DRMVERTEX_LIST
Starts a new list or is a member of a previously started list. If the previous vertex (or the vertex previous to that) was not marked with this flag, the following vertices must be marked with this flag until at least one triangle is formed.
D3DRMVERTEX_STRIP
Forms a new triangle in strip format with the previous two vertices.
D3DRMVERTEX_FAN
Forms a new triangle with the previous vertex and the first vertex in the fan.
D3DRMFVF_NORMAL
Include the normal member.
D3DRMFVF_COLOR
Include the color member.
D3DRMFVF_TEXTURECOORDS
Include the tu and tv members.
vertexCount
Vertex number.
data
Data described by format.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method provides flexibility to the application in describing the triangles. The triangles are described by a set of vertices. Each vertex must have a position, but can optionally have none or any of the following: normal, texture coordinates, or color.

The following table shows the appropriate IType flag for each vertex in the following diagram.

Vertex number | IType flag
0 | D3DRMVERTEX_STRIP
1 | D3DRMVERTEX_STRIP
2 | D3DRMVERTEX_STRIP
3 | D3DRMVERTEX_STRIP
4 | D3DRMVERTEX_STRIP
5 | D3DRMVERTEX_FAN
6 | D3DRMVERTEX_FAN
7 | D3DRMVERTEX_FAN
8 | D3DRMVERTEX_LIST
9 | D3DRMVERTEX_LIST
10 | D3DRMVERTEX_LIST
11 | D3DRMVERTEX_LIST
12 | D3DRMVERTEX_LIST
13 | D3DRMVERTEX_LIST

Direct3DRMMeshBuilder3.AddVertex

Direct3DRMMeshBuilder3

Adds a vertex to a Direct3DRMMeshBuilder3 object.

Syntax

object.AddVertex(x As Single,
  y As Single,
  z As Single) As Long

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
x, y, and z
The x-, y-, and z-components of the position of the new vertex.

Return Value

Returns the index of the vertex.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMeshBuilder3.CreateFace

Direct3DRMMeshBuilder3

Creates a new face with no vertices and adds it to a Direct3DRMMeshBuilder3 object.

Syntax

object.CreateFace( ) As Direct3DRMFace2

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.

Return Value

Returns a Direct3DRMFace2 object that will be filled with the newly created face.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMeshBuilder3.CreateMesh

Direct3DRMMeshBuilder3

Creates a new mesh from a Direct3DRMMeshBuilder3 object.

Syntax

object.CreateMesh( ) As Direct3DRMMesh

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.

Return Value

Returns a Direct3DRMMesh object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMeshBuilder3.CreateSubMesh

Direct3DRMMeshBuilder3

Creates a new submesh for the current Direct3DRMMeshBuilder3 object.

Syntax

object.CreateSubMesh( ) As Direct3DRMMeshBuilder3

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.

Return Value

Returns a Direct3DRMMeshBuilder3 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

A submesh is similar to a meshbuilder object in that it supports the Direct3DRMMeshBuilder3 interface, and can itself have submeshes. The difference between submeshes and meshbuilders is that all submeshes share the vertices and normals with the greatest ancestor in the chain of submeshes. Meshbuilders do not share vertices and normals.

See Also

Direct3DRMMeshBuilder3.DeleteSubMesh, Direct3DRMMeshBuilder3.GetSubMesh, Direct3DRMMeshBuilder3.GetParentMesh

Direct3DRMMeshBuilder3.DeleteFace

Direct3DRMMeshBuilder3

Deletes a face from the Direct3DRMMeshBuilder3 object.

Syntax

object.DeleteFace(face As Direct3DRMFace2)

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
face
Interface of a Direct3DRMFace2 object to remove from the Direct3DRMMeshBuilder3 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMeshBuilder3.DeleteSubMesh

Direct3DRMMeshBuilder3

Deletes a submesh. The submesh must be an immediate child of the current Direct3DRMMeshBuilder3 object.

Syntax

object.DeleteSubMesh(mesh As Direct3DRMMeshBuilder3)

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
mesh
Direct3DRMMeshBuilder3 interface of the submesh to delete.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMMeshBuilder3.CreateSubMesh, Direct3DRMMeshBuilder3.GetSubMesh and Direct3DRMMeshBuilder3.GetParentMesh

Direct3DRMMeshBuilder3.Empty

Direct3DRMMeshBuilder3

Removes all faces, vertices, and normals from the Direct3DRMMeshBuilder3 object.

Syntax

object.Empty( )

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMeshBuilder3.Enable

Direct3DRMMeshBuilder3

Specifies whether this Direct3DRMMeshBuilder3 object should be enabled or disabled for rendering and picking.

Syntax

object.Enable(flags As CONST_D3DRMADDMESHBUILDERFLAGS)

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
flags
One or more values from the CONST_D3DRMMESHBUILDERENABLEFLAGS enumerated type indicating whether rendering and picking are enabled.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMMeshBuilder3.GetEnable

Direct3DRMMeshBuilder3.GenerateNormals

Direct3DRMMeshBuilder3

Processes the Direct3DRMMeshBuilder3 object and generates normals for each vertex in a mesh by averaging the face normals for each face that shares the vertex. New normals are generated if the faces sharing a vertex have an angle between them greater than the crease angle.

Syntax

object.GenerateNormals(angle As Single,
  flags As CONST_D3DRMGENERATENORMALSFLAGS)

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
angle
Least angle, in radians, that faces can have between them and have a new normal generated.
flags
One or more of the values from the CONST_D3DRMGENERATENORMALSFLAGS enumerated type.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

If you specify the D3DRMGENERATENORMALS_PRECOMPACT flag, the precompact pass searches all the vertices in the mesh and merges any that are the same. This is a good way of compacting a mesh that has been loaded. Some meshes have multiple vertices if they have multiple normals at that vertex. This is not necessary in Direct3D Retained Mode. Specifying this flag is the way to get rid of the multiple vertices.

After compacting, the normals are generated. The edges between faces are examined, and if the angle the faces make at the edge is less than the crease angle, the face normals are averaged to generate the vertex normal. If the angle is greater than the crease angle, a new normal is generated. Note that a new vertex is not generated.

Direct3DRMMeshBuilder3.GetBox

Direct3DRMMeshBuilder3

Retrieves the bounding box containing a Direct3DRMMeshBuilder3 object. The bounding box gives the minimum and maximum model coordinates in each dimension.

Syntax

object.GetBox(retV As D3DRMBOX)

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
retV
D3DRMBOX type that will be filled with the bounding box coordinates.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMeshBuilder3.GetColorSource

Direct3DRMMeshBuilder3

Retrieves the color source of a Direct3DRMMeshBuilder3 object. The color source can be either a face or a vertex.

Syntax

object.GetColorSource( ) As CONST_D3DRMCOLORSOURCE

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.

Return Value

Returns a member of the CONST_D3DRMCOLORSOURCE enumerated type.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMMeshBuilder3.SetColorSource

Direct3DRMMeshBuilder3.GetEnable

Direct3DRMMeshBuilder3

Retrieves a value that indicates whether this Direct3DRMMeshBuilder3 object should be enabled or disabled.

Syntax

object.GetEnable( ) As CONST_D3DRMADDMESHBUILDERFLAGS

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.

Return Value

Returns a value from the CONST_D3DRMMESHBUILDERENABLEFLAGS enumerated type indicating the current enable status of this Direct3DRMMeshBuilder3 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMMeshBuilder3.Enable

Direct3DRMMeshBuilder3.GetFace

Direct3DRMMeshBuilder3

Retrieves a single face of a Direct3DRMMeshBuilder3 object.

Syntax

object.GetFace(id As Long) As Direct3DRMFace2

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
id
ID of the mesh face to be retrieved. The face must already be part of a Direct3DRMMeshBuilder3 object.

Return Value

Returns a Direct3DRMFace2 interface that is filled with the face.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMeshBuilder3.GetFaceCount

Direct3DRMMeshBuilder3

Retrieves the number of faces in a Direct3DRMMeshBuilder3 object.

Syntax

object.GetFaceCount( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.

Return Value

Returns the number of faces.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMeshBuilder3.GetFaceDataSize

Direct3DRMMeshBuilder3

Retrieves the size of the face data array for a Direct3DRMMeshBuilder3 object.

Syntax

object.GetFaceDataSize( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.

Return Value

Returns the value of the sizeData argument required by GetGeometry.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method retrieves the size of the faceData array required by Direct3DRMMeshBuilder3.GetGeometry.

Direct3DRMMeshBuilder3.GetFaces

Direct3DRMMeshBuilder3

Retrieves the faces of a Direct3DRMMeshBuilder3 object.

Syntax

object.GetFaces( ) As Direct3DRMFaceArray

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.

Return Value

Returns a Direct3DRMFaceArray object that is filled with the faces.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMeshBuilder3.GetGeometry

Direct3DRMMeshBuilder3

Retrieves the vertices, normals, and face data for a Direct3DRMMeshBuilder3 object.

Syntax

object.GetGeometry(vertexCount As Long,
  vertexArray() As D3DVECTOR,
  normalCount As Long,
  normalArray() As D3DVECTOR,
  sizeData As Long,
  faceData() As Long)

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
vertexCount
Number of vertices in vertexArray.
vertexArray
Array of D3DVECTOR types that will contain the vertices for the Direct3DRMMeshBuilder3 object. Use GetVertexCount to determine the minimum size for this array.
normalCount
Number of normals in normalArray.
normalArray
Array of D3DVECTOR types that will contain the normals for the Direct3DRMMeshBuilder3 object. Use GetNormalCount to determine the size of the array.
sizeData
Value specifying the number of elements in faceData.
faceData
Face data for the Direct3DRMMeshBuilder3 object. This data is in the same format as specified in the Direct3DRMMeshBuilder3.AddFaces method except that it is null-terminated. Call GetFaceDataSize to determine the size of the array.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMeshBuilder3.GetNormal

Direct3DRMMeshBuilder3

Retrieves a normal vector.

Syntax

object.GetNormal(index As Long,
  desc As D3DVECTOR)

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
index
Index of the normal to return.
desc
D3DVECTOR type that will be filled in with the x-, y-, and z-coordinates of the normal.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMeshBuilder3.GetNormalCount

Direct3DRMMeshBuilder3

Retrieves the number of normals in a Direct3DRMMeshBuilder3 object.

Syntax

object.GetNormalCount( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.

Return Value

Returns the number of normals in the Direct3DRMMeshBuilder3 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMMeshBuilder3.GetNormal and Direct3DRMMeshBuilder3.SetNormal

Direct3DRMMeshBuilder3.GetParentMesh

Direct3DRMMeshBuilder3

Retrieves a parent mesh of this Direct3DRMMeshBuilder3 object.

Syntax

object.GetParentMesh(
    flags As CONST_D3DRMPARENTINGFLAGS)
    As Direct3DRMMeshBuilder3

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
flags
One or more values from the CONST_D3DRMPARENTINGFLAGS enumerated type, defining which Direct3DRMMeshBuilder3 object to retrieve.

Return Value

Returns a Direct3DRMMeshBuilder3 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMMeshBuilder3.GetSubMesh

Direct3DRMMeshBuilder3.GetPerspective

Direct3DRMMeshBuilder3

Determines whether perspective correction is on for a Direct3DRMMeshBuilder3 object.

Syntax

object.GetPerspective( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.

Return Value

Returns –1 if perspective correction is on, or zero otherwise.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMeshBuilder3.GetQuality

Direct3DRMMeshBuilder3

Retrieves the rendering quality of a Direct3DRMMeshBuilder3 object.

Syntax

object.GetQuality( ) As CONST_D3DRMRENDERQUALITY

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.

Return Value

Returns a value from the CONST_D3DRMRENDERQUALITY enumerated type that specifies the rendering quality of the mesh.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

The rendering quality is the maximum quality at which rendering can take place on the rendering surface of that device.

An object's quality has three components: shade mode (flat or Gouraud), lighting type (on or off), and fill mode (point, wire frame, or solid).

See Also

Direct3DRMMeshBuilder3.SetQuality

Direct3DRMMeshBuilder3.GetSubMeshCount

Direct3DRMMeshBuilder3

Retrieves the number of submeshes that this Direct3DRMMeshBuilder3 object contains.

Syntax

object.GetSubMeshCount( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.

Return Value

Returns the number of submeshes.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMMeshBuilder3.GetParentMesh

Direct3DRMMeshBuilder3.GetSubMeshes

Direct3DRMMeshBuilder3

Retrieves a list of the submeshes that this Direct3DRMMeshBuilder3 object contains.

Syntax

object.GetSubMeshes(count As Long,
  arrayOfMeshBuilders() As Direct3DRMMeshBuilder3)

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
count
Number of submeshes expected to be returned. The value pointed to by count receives the number of submeshes actually retrieved.
arrayOfMeshBuilders
Array of Direct3DRMMeshBuilder3 objects containing child submeshes.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMMeshBuilder3.GetParentMesh

Direct3DRMMeshBuilder3.GetTextureCoordinates

Direct3DRMMeshBuilder3

Retrieves the texture coordinates of a specified vertex in a Direct3DRMMeshBuilder3 object.

Syntax

object.GetTextureCoordinates(idx As Long,
  u As Single,
  v As Single)

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
idx
Index of the vertex.
u and v
Returned texture coordinates of the vertex.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMMeshBuilder3.SetTextureCoordinates

Direct3DRMMeshBuilder3.GetVertex

Direct3DRMMeshBuilder3

Retrieves a vertex vector.

Syntax

object.GetVertex(id As Long,
  vec As D3DVECTOR)

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
id
ID of the vertex to return.
vec
D3DVECTOR type that will be filled with the x-, y-, and z-coordinates of the vertex.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMeshBuilder3.GetVertexColor

Direct3DRMMeshBuilder3

Retrieves the color of a specified vertex in a Direct3DRMMeshBuilder3 object.

Syntax

object.GetVertexColor(index As Long) As Long

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
index
Index of the vertex.

Return Value

Returns the color.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMMeshBuilder3.SetVertexColor

Direct3DRMMeshBuilder3.GetVertexCount

Direct3DRMMeshBuilder3

Retrieves the number of vertices in a Direct3DRMMeshBuilder3 object.

Syntax

object.GetVertexCount( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.

Return Value

Returns the number of vertices.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMeshBuilder3.LoadFromFile

Direct3DRMMeshBuilder3

Loads a Direct3DRMMeshBuilder3 object.

Syntax

object.LoadFromFile(filename As String,
  id As String,
  options As CONST_D3DRMLOADFLAGS,
  loadTextureImplementation As Direct3DRMLoadTextureCallback3,
  userArgument As Object)

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
filename
Source for the object to be loaded. This source can be a file, resource, memory block, or stream, depending on the source flags specified in the flags parameter.
id
Object name or position to be loaded. If id is "", you must set the options parameter to D3DRMLOAD_FIRST. Note that Microsoft Visual Basic® will accept an Integer in the id parameter, indicating the position of the item to be loaded, even though a String data type is specified. For example, placing 1 in the id parameter will load the object in the first position.
options
One or more values from the CONST_D3DRMLOADFLAGS enumerated type describing the load options.
loadTextureImplementation
Direct3DRMLoadTextureCallback3 callback interface used to load any textures used by an object that require special formatting. Textures must have a width and length divisible by 2. This parameter can be NOTHING.
userArgument
Application-defined data passed to the callback.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

By default, this method loads the first mesh from the source specified in the filename parameter.

This method respects the right-handed and left-handed geometry options as set by Direct3DRM3.SetOptions.

You can load more than one object into a Direct3DRMMeshBuilder3 object by calling its load method multiple times.

Each of the LoadFromFile methods uses a filename parameter to specify the source of the object and an id parameter to identify the object. The system interprets the contents of the filename parameter based on the choice of source flags, and it interprets the contents of the id parameter based on the choice of identifier flags.

The instance flags do not change the interpretation of any of the members. By using the D3DRMLOAD_INSTANCEBYREFERENCE flag, an application can load the same file twice without creating any new objects. If an object does not have a name, setting the D3DRMLOAD_INSTANCEBYREFERENCE flag has the same effect as setting the D3DRMLOAD_INSTANCEBYCOPYING flag—the loader creates each unnamed object as a new one, even if some of the objects are identical.

Direct3DRMMeshBuilder3.Optimize

Direct3DRMMeshBuilder3

Optimizes the Direct3DRMMeshBuilder3 object for the current device. This can be an expensive operation.

Syntax

object.Optimize( )
object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMeshBuilder3.Save

Direct3DRMMeshBuilder3

Saves a Direct3DRMMeshBuilder3 object.

Syntax

object.Save(fname As String,
  xFormat As CONST_D3DRMXOFFORMAT,
  Save As CONST_D3DRMSAVEFLAGS)

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
fname
Name of the created file. This file must have the .x file name extension.
xFormat
D3DRMXOF_TEXT value from the CONST_D3DRMXOFFORMAT enumerated type.
Save
One or more values from the CONST_D3DRMSAVEFLAGS enumerated type describing the save options.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMeshBuilder3.ScaleMesh

Direct3DRMMeshBuilder3

Scales a Direct3DRMMeshBuilder3 object by the given scaling factors, parallel to the x-, y-, and z-axes in model coordinates.

Syntax

object.ScaleMesh(sx As Single,
  sy As Single,
  sz As Single)

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
sx, sy, and sz
Scaling factors that are applied along the x-, y-, and z-axes.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMeshBuilder3.SetColor

Direct3DRMMeshBuilder3

Sets all the faces of a Direct3DRMMeshBuilder3 object to a given color.

Syntax

object.SetColor(col As Long)

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
col
Color of the faces. Make sure to set the alpha component as well as the red, green, and blue color components or your objects might not be visible. Colors are represented by a Long, consisting of 4 bytes. The high byte is the alpha component and the subsequent bytes define red, green, and blue. Use CreateColorRGBA from the DirectX7 object to more easily construct a color or use SetColorRGB if you only want full alpha.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMeshBuilder3.SetColorRGB

Direct3DRMMeshBuilder3

Sets the red, green, and blue color components of all the faces of a Direct3DRMMeshBuilder3 object.

Syntax

object.SetColorRGB(red As Single,
  green As Single,
  blue As Single)

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
red, green, and blue
Red, green, and blue components of the color.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMeshBuilder3.SetColorSource

Direct3DRMMeshBuilder3

Sets the color source of a Direct3DRMMeshBuilder3 object.

Syntax

object.SetColorSource(val As CONST_D3DRMCOLORSOURCE)

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
val
Member of the CONST_D3DRMCOLORSOURCE enumerated type that specifies the new color source to use.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMMeshBuilder3.GetColorSource

Direct3DRMMeshBuilder3.SetMaterial

Direct3DRMMeshBuilder3

Sets the material of all the faces of a Direct3DRMMeshBuilder3 object.

Syntax

object.SetMaterial(mat As Direct3DRMMaterial2)

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
mat
Direct3DRMMaterial2 interface for the Direct3DRMMeshBuilder3 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMeshBuilder3.SetNormal

Direct3DRMMeshBuilder3

Sets the normal vector of a specified vertex in a Direct3DRMMeshBuilder3 object.

Syntax

object.SetNormal(idx As Long,
  x As Single,
  y As Single,
  z As Single)

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
idx
Index of the normal to be set.
x, y, and z
The x-, y-, and z-components of the vector to assign to the specified normal.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMeshBuilder3.SetPerspective

Direct3DRMMeshBuilder3

Enables or disables perspective-correct texture mapping for a Direct3DRMMeshBuilder3 object.

Syntax

object.SetPerspective(perspectiveEnabled As CONST_DBOOLFLAGS)

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
perspectiveEnabled
D_TRUE if the mesh should be texture-mapped with perspective correction, or D_FALSE otherwise.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMeshBuilder3.SetQuality

Direct3DRMMeshBuilder3

Sets the rendering quality of a Direct3DRMMeshBuilder3 object.

Syntax

object.SetQuality(q As CONST_D3DRMRENDERQUALITY)

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
q
Member of the CONST_D3DRMRENDERQUALITY enumerated type that specifies the new rendering quality to use.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

An object's quality has three components: shade mode (flat or Gouraud; Phong shading is not yet implemented and will default to Gouraud shading), lighting type (on or off), and fill mode (point, wire frame, or solid).

You can set the quality of a device with Direct3DRMDevice3.SetQuality. By default it is D3DRMRENDER_FLAT (flat shading, lights on, and solid fill).

You can set the quality of a Direct3DRMMeshBuilder3 object with the SetQuality method. By default, a Direct3DRMMeshBuilder3 object's quality is D3DRMRENDER_GOURAUD (Gouraud shading, lights on, and solid fill).

Tip: Gouraud shading performs better than Phong shading on progressive mesh objects that change their level of detail often or quickly.

Direct3D Retained Mode renders an object at the lowest quality setting based on the device and object's current setting for each individual component. For example, if the object's current quality setting is D3DRMRENDER_GOURAUD, and the device is D3DRMRENDER_FLAT then the object will be rendered with flat shading, solid fill and lights on.

If the object's current quality setting is D3DRMSHADE_GOURAUD|D3DRMLIGHT_OFF|D3DRMFILL_WIREFRAME and the device's quality setting is D3DRMSHADE_FLAT|D3DRMLIGHT_ON|D3DRMFILL_POINT, then the object will be rendered with flat shading, lights off, and point fill mode.

These rules apply to Direct3DRMMeshBuilder3 objects and Direct3DRMProgressiveMesh objects. However, Direct3DRMMesh objects do not follow these rules. Mesh objects ignore the device's quality settings and use the group quality setting (which defaults to D3DRMRENDER_GOURAUD).

See Also

Direct3DRMMeshBuilder3.GetQuality

Direct3DRMMeshBuilder3.SetTexture

Direct3DRMMeshBuilder3

Sets the texture of all the faces of a Direct3DRMMeshBuilder3 object.

Syntax

object.SetTexture(tex As Direct3DRMTexture3)

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
tex
Required Direct3DRMTexture3 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMeshBuilder3.SetTextureCoordinates

Direct3DRMMeshBuilder3

Sets the texture coordinates of a specified vertex in a Direct3DRMMeshBuilder3 object.

Syntax

object.SetTextureCoordinates(idx As Long,
  u As Single,
  v As Single)

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
idx
Index of the vertex to set.
u and v
Texture coordinates to assign to the specified mesh vertex.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMMeshBuilder3.GetTextureCoordinates

Direct3DRMMeshBuilder3.SetTextureTopology

Direct3DRMMeshBuilder3

Sets the texture topology of a Direct3DRMMeshBuilder3 object.

Syntax

object.SetTextureTopology(wrap_u As CONST_DBOOLFLAGS,
  wrap_v As CONST_DBOOLFLAGS)

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
wrap_u and wrap_v
Value indicating the texture topology. Specify D_TRUE for either or both of these parameters if you want the texture to have a cylindrical topology in the u- and v-dimensions, respectively; otherwise, specify D_FALSE.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

The texture topology flags, wrap_u and wrap_v, control the settings of the Direct3D Immediate Mode render states D3DRENDERSTATE_WRAPU and D3DRENDERSTATE_WRAPV. When a wrap flag is set to D_TRUE, the rasterizer will cross from one edge of the texture to the opposite edge (toroidal mapping) if it is the shorter path between two texture coordinates.

Consider a triangle that has v coordinates ranging from 0.1 and 0.9 along one edge. If WRAPV is D_FALSE, nearly the full length of the texture will be rendered along the triangle. If WRAPV is D_TRUE, a sliver from the top of the texture and one from the bottom will be rendered. Additionally, when a wrap flag is D_TRUE, only the fractional part of a texture coordinate is considered for values greater than 1.0, which means textures will not be tiled across a face when wrap is D_TRUE.

Controlling the wrapping behavior is necessary for proper interpretation of texture coordinates. If you have a single texture wrapped across many faces, set the wrap_u and wrap_v parameters to D_TRUE. If a model has one texture per face or you want multiple copies of the texture to be tiled across a single face by using texture coordinates greater than 1, set wrap_u and wrap_v to D_FALSE.

Several interfaces expose a SetTextureTopology method. Direct3DRMMeshBuilder3.SetTextureTopology updates the topology on all component faces, overriding any settings made by Direct3DRMFace2.SetTextureTopology. By default, Direct3DRMFrame3.SetTextureTopology reads from the mesh because the default material mode is D3DRMMATERIAL_FROMMESH. If the material mode is not D3DRMMATERIAL_FROMMESH, Direct3DRMFrame3.SetTextureTopology overrides settings made by Direct3DRMMeshBuilder3.SetTextureTopology.

Direct3DRMMeshBuilder3.SetVertex

Direct3DRMMeshBuilder3

Sets the position of a specified vertex in a Direct3DRMMeshBuilder3 object.

Syntax

object.SetVertex(idx As Long,
  x As Single,
  y As Single,
  z As Single)

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
idx
Index of the vertex to be set.
x, y, and z
The x-, y-, and z-components of the position to assign to the specified vertex.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMeshBuilder3.SetVertexColor

Direct3DRMMeshBuilder3

Sets the color of a specified vertex in a Direct3DRMMeshBuilder3 object.

Syntax

object.SetVertexColor(idx As Long,
  c As Long)

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
idx
Index of the vertex to be set.
c
Color to assign to the specified vertex.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMMeshBuilder3.GetVertexColor

Direct3DRMMeshBuilder3.SetVertexColorRGB

Direct3DRMMeshBuilder3

Sets red, green, and blue color components of a specified vertex in a Direct3DRMMeshBuilder3 object.

Syntax

object.SetVertexColorRGB(idx As Long,
  r As Single,
  g As Single,
  b As Single)

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
idx
Index of the vertex to be set.
r, g, and b
Red, green, and blue components of the color to assign to the specified vertex.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMeshBuilder3.Translate

Direct3DRMMeshBuilder3

Adds the specified offsets to the vertex positions of a Direct3DRMMeshBuilder3 object.

Syntax

object.Translate(tx As Single,
  ty As Single,
  tz As Single)

Parts

object
Object expression that resolves to a Direct3DRMMeshBuilder3 object.
tx, ty, and tz
Offsets that are added to the x-, y-, and z-coordinates, respectively, of each vertex position.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.


Direct3DRMMeshInterpolator

Interpolators provide a way of storing actions and applying them to objects with automatic calculation of in-between values. With an interpolator you can blend colors, move objects smoothly between positions, morph meshes, and perform many other transformations.

A Direct3DRMMesh object can be attached to a Direct3DRMMeshInterpolator object. For more information on interpolators, see Interpolators in Further Reading.

The Direct3DRMMeshInterpolator interface contains the following methods.

Attaching objects | AttachObject
DetachObject
GetAttachedObjects
Color | SetGroupColor
SetGroupColorRGB
Interpolating | GetIndex
Interpolate
SetIndex
Miscellaneous | Translate
Vertex positions | SetVertices

In addition, Direct3DRMMeshInterpolator inherits the following methods from the Direct3DRMObject interface.

  • AddDestroyCallback
  • Clone
  • DeleteDestroyCallback
  • GetAppData
  • GetClassName
  • GetName
  • SetAppData
  • SetName

Direct3DRMMeshInterpolator.AttachObject

Direct3DRMMeshInterpolator

Connects an object to the interpolator.

Syntax

object.AttachObject(mObject As Direct3DRMObject)

Parts

object
Object expression that resolves to a Direct3DRMMeshInterpolator object.
mObject
Direct3DRMObject object to attach to the interpolator.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

The attached object can be another interpolator or an object of type x where the interpolator is of type xInterpolator. For example, a Direct3DRMMesh object can be attached to a Direct3DRMMeshInterpolator object.

Direct3DRMMeshInterpolator.DetachObject

Direct3DRMMeshInterpolator

Detaches an object from the interpolator.

Syntax

object.DetachObject(mObject As Direct3DRMObject)

Parts

object
Object expression that resolves to a Direct3DRMMeshInterpolator object.
mObject
Direct3DRMObject object to detach from the interpolator.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMeshInterpolator.GetAttachedObjects

Direct3DRMMeshInterpolator

Retrieves the objects currently attached to the interpolator.

Syntax

object.GetAttachedObjects( ) As Direct3DRMObjectArray

Parts

object
Object expression that resolves to a Direct3DRMMeshInterpolator object.

Return Value

Returns a Direct3DRMObjectArray object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMeshInterpolator.GetIndex

Direct3DRMMeshInterpolator

Retrieves the interpolator's current internal index (time).

Syntax

object.GetIndex( ) As Single

Parts

object
Object expression that resolves to a Direct3DRMMeshInterpolator object.

Return Value

Returns a value that contains the interpolator's current internal index.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Every key stored in an interpolator has an index value. When a key is recorded (by using a method), the key is stamped with the current interpolator index value. The key's index value does not change after being stamped.

Direct3DRMMeshInterpolator.Interpolate

Direct3DRMMeshInterpolator

Generates a series of actions by interpolating between keys stored in the interpolator. The actions are then applied to the specified object. If no object is specified, the actions are applied to the currently attached objects.

Syntax

object.Interpolate(val As Single,
  mObject As Direct3DRMObject,
  options As CONST_D3DRMINTERPOLATIONFLAGS)

Parts

object
Object expression that resolves to a Direct3DRMMeshInterpolator object.
val
Value that contains the interpolator's current internal index.
mObject
Direct3DRMObject object that will be assigned interpolated values for all properties stored in the interpolator. Can be NOTHING, in which case the property values of all attached objects will be set to interpolated values.
options
One of the values from the CONST_D3DRMINTERPOLATIONFLAGS enumerated type that controls the kind of interpolation done.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMeshInterpolator.SetGroupColor

Direct3DRMMeshInterpolator

Adds a group color key to a Direct3DRMMeshInterpolator object.

Syntax

object.SetGroupColor(id As Long,
  val As Long)

Parts

object
Object expression that resolves to a Direct3DRMMeshInterpolator object.
id
Identifier of the group. This identifier must be produced by using the Direct3DRMMesh.AddGroup method.
val
Color of the group. Colors are represented by a Long, consisting of 4 bytes. The high byte is the alpha component and the subsequent bytes define red, green, and blue. Use CreateColorRGBA from the DirectX7 object to more easily construct a color or use SetGroupColorRGB if you only want full alpha.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMeshInterpolator.SetGroupColorRGB

Direct3DRMMeshInterpolator

Adds a group RGB key to a Direct3DRMMeshInterpolator object.

Syntax

object.SetGroupColorRGB(id As Long,
  r As Single,
  g As Single,
  b As Single)

Parts

object
Object expression that resolves to a Direct3DRMMeshInterpolator object.
id
Identifier of the group. This identifier must be produced by using the Direct3DRMMesh.AddGroup method.
r, g, and b
Red, green, and blue components of the group color.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMeshInterpolator.SetIndex

Direct3DRMMeshInterpolator

Sets the interpolator's internal index (time) to the specified value. If other interpolators are attached to the interpolator, this method recursively synchronizes their indices to the same value.

Syntax

object.SetIndex(val As Single)

Parts

object
Object expression that resolves to a Direct3DRMMeshInterpolator object.
val
Time to set for the interpolator's internal index.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Every key stored in an interpolator has an index value. When a key is recorded (by using a method), the key is stamped with the current interpolator index value. The key's index value does not change after being stamped.

Direct3DRMMeshInterpolator.SetVertices

Direct3DRMMeshInterpolator

Adds a vertex position key to a Direct3DRMMeshInterpolator object.

Syntax

object.SetVertices(id As Long,
  idx As Long,
  count As Long,
  vertexArray() As D3DRMVERTEX)

Parts

object
Object expression that resolves to a Direct3DRMMeshInterpolator object.
id
Identifier of the group. This identifier must be produced by using the Direct3DRMMesh.AddGroup method.
idx
Index of the first vertex in the mesh group to be modified.
count
Number of consecutive vertices to set. The vertexArray parameter must contain at least the number of count elements.
vertexArray
An array of D3DRMVERTEX types specifying the vertex positions to be set.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMMeshInterpolator.Translate

Direct3DRMMeshInterpolator

Adds the specified offsets to the vertex positions of a Direct3DRMMeshInterpolator object.

Syntax

object.Translate(tx As Single,
  ty As Single,
  tz As Single)

Parts

object
Object expression that resolves to a Direct3DRMMeshInterpolator object.
tx, ty, and tz
Offsets that are added to the x-, y-, and z-coordinates, respectively, of each vertex position.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.


Direct3DRMObject

Applications use the methods of the Direct3DRMObject interface to work with the object superclass of Microsoft® Direct3D® Retained Mode objects.

Direct3DRMObject is the common superclass of all objects in the system. A Direct3DRMObject object has characteristics common to all objects.

To create an object, the application must first have instantiated a Direct3D Retained Mode object. The application then calls the method of the object's interface that creates an object, and it specifies parameters specific to the object. For example, to create a Direct3DRMAnimation object, the application would call the Direct3DRM3.CreateAnimation method. The creation method then creates a new object, initializes some of the object's attributes from data passed in the parameters (leaving all others with their default values), and returns the object. Applications can then specify the interface for this object to modify and use the object.

Any object can store 32 bits of application-specific data. This data is not interpreted or altered by Retained Mode. The application can read this data by using the Direct3DRMObject.GetAppData method, and it can write to it by using the Direct3DRMObject.SetAppData method. Finding this data is simpler if the application keeps a structure for each Direct3DRMFrame object. For example, if calling the Direct3DRMFrame3.GetParent method retrieves a Direct3DRMFrame object, the application can easily retrieve the data by accessing its private structure, possibly avoiding a time-consuming search.

You might also want to assign a name to an object to help you organize an application or as part of your application's user interface. You can use the Direct3DRMObject.SetName and Direct3DRMObject.GetName methods to set and retrieve object names.

Another example of possible uses for application-specific data is when an application needs to group the faces within a mesh into subsets (for example, for front and back faces). You could use the application data in the face to note in which of these groups a face should be included.

An application can specify a method to call when an object is destroyed, such as when the application needs to deallocate memory associated with the object. To do this, use the Direct3DRMObject.AddDestroyCallback method. To remove a function previously registered with this method, use the Direct3DRMObject.DeleteDestroyCallback method.

The callback is called only when the object is destroyed and the system is about to deallocate the memory for the object. If an application kept additional data about an object (so that its dynamics could be implemented, for example), the application could use this callback as a way to notify itself that it can dispose of the data.

The methods of the Direct3DRMObject interface can be organized into the following groups.

Application-specific data | GetAppData
SetAppData
Cloning | CloneObject
Naming | GetClassName
GetName
SetName
Notifications | AddDestroyCallback
DeleteDestroyCallback

All Retained Mode objects inherit the Direct3DRMObject interface methods.

Direct3DRMObject.AddDestroyCallback

Direct3DRMObject

Registers a function that will be called when an object is destroyed.

This method is not implemented.

Syntax

object.AddDestroyCallback(fn As Direct3DRMCallback,
  arg As Variant)

Parts

object
Object expression that resolves to a Direct3DRMObject object.
fn
User-defined Direct3DRMCallback callback interface that will be used when the object is destroyed.
arg
Application-defined data passed to the callback. Because this function is used after the object has been destroyed, you should not use this function with the object as an argument.

Error Values

This method returns E_NOTIMPL.

Direct3DRMObject.CloneObject

Direct3DRMObject

Creates a copy of an object.

Syntax

object.CloneObject( ) As Direct3DRMObject

Parts

object
Object expression that resolves to a Direct3DRMObject object.

Return Value

Returns a copy of the object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMObject.DeleteDestroyCallback

Direct3DRMObject

Removes a function previously registered with the Direct3DRMObject.AddDestroyCallback method.

This method is not implemented.

Syntax

object.DeleteDestroyCallback(fn As Direct3DRMCallback,
  args As Variant)

Parts

object
Object expression that resolves to a Direct3DRMObject object.
fn
User-defined Direct3DRMCallback interface that will be used when the object is destroyed.
args
Application-defined data passed to the callback.

Error Values

This method returns E_NOTIMPL.

Direct3DRMObject.GetAppData

Direct3DRMObject

Retrieves the 32 bits of application-specific data in the object. The default value of the data is 0.

Syntax

object.GetAppData( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMObject object.

Return Value

Returns the data value defined by the application.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMObject.SetAppData

Direct3DRMObject.GetClassName

Direct3DRMObject

Retrieves the name of the object's class.

Syntax

object.GetClassName( ) As String

Parts

object
Object expression that resolves to a Direct3DRMObject object.

Return Value

Returns a string identifying the class name.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMObject.GetName

Direct3DRMObject

Retrieves the object's name.

Syntax

object.GetName( ) As String

Parts

object
Object expression that resolves to a Direct3DRMObject object.

Return Value

Returns a string identifying the object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMObject.SetName

Direct3DRMObject.SetAppData

Direct3DRMObject

Sets the 32 bits of application-specific data in the object.

Syntax

object.SetAppData(data As Long)

Parts

object
Object expression that resolves to a Direct3DRMObject object.
data
User-defined data to be stored with the object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMObject.GetAppData

Direct3DRMObject.SetName

Direct3DRMObject

Sets the object's name.

Syntax

object.SetName(name As String)

Parts

object
Object expression that resolves to a Direct3DRMObject object.
name
User-defined string to name the object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMObject.GetName


Direct3DRMObjectArray

Applications use the methods of the Direct3DRMObjectArray interface to organize Direct3DRMObject objects. The object array is zero based (0 to N-1).

The Direct3DRMObjectArray interface supports the following methods.

  • GetElement
  • GetSize

Obtain the Direct3DRMObjectArray object by calling GetAttachedObjects on an interpolator object.

Direct3DRMObjectArray.GetElement

Direct3DRMObjectArray

Retrieves a specified element in a Direct3DRMObjectArray object.

Syntax

object.GetElement(index As Long) As Direct3DRMObject

Parts

object
Object expression that resolves to a Direct3DRMObjectArray object.
index
Element in the array.

Return Value

Returns a Direct3DRMObject object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMObjectArray.GetSize

Direct3DRMObjectArray

Retrieves the number of elements contained in a Direct3DRMObjectArray object.

Syntax

object.GetSize( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMObjectArray object.

Return Value

Returns the number of elements.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.


Direct3DRMPick2Array

Applications use the methods of the Direct3DRMPick2Array interface to organize pick objects and to return more information about the pick objects. The pick array is zero based (0 to N-1). For more information about picking, see Direct3DRMPickArray.

You can use the Direct3DRMFrame3.RayPick method to retrieve an Direct3DRMPick2Array object, and then call the Direct3DRMPick2Array.GetPickFrame method to retrieve an Direct3DRMFrameArray interface, a visual object, and information about the object intersected by the ray, including the face and group identifiers, pick position, and horizontal and vertical texture coordinates for the vertex, vertex normal, and color of the object. The array of frames is the path through the hierarchy leading to the visual object.

The Direct3DRMPick2Array interface supports the following methods.

  • GetPickFrame
  • GetPickVisual
  • GetSize

Obtain the Direct3DRMPick2Array object by calling the Direct3DRMFrame3.RayPick method.

Direct3DRMPick2Array.GetPickFrame

Direct3DRMPick2Array

Retrieves the Direct3DRMFrameArray object intersected by the specified pick.

Syntax

object.GetPickFrame(index As Long,
  pickDesc As D3DRMPICKDESC2) As Direct3DRMFrameArray

Parts

object
Object expression that resolves to a Direct3DRMPick2Array object.
index
Index into the pick array identifying the pick for which information will be retrieved.
pickDesc
D3DRMPICKDESC2 type specifying the face and group identifiers, pick position, horizontal and vertical texture coordinates for the vertex, vertex normal, and color of the intersected objects.

Return Value

Returns the Direct3DRMFrameArray object associated with the specified pick.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method is similar to Direct3DRMPickedArray.GetPickFrame except that it retrieves the u- and v-values in a D3DRMPICKDESC2 type rather than a D3DRMPICKDESC type.

See Also

Direct3DRMFrame3.RayPick

Direct3DRMPick2Array.GetPickVisual

Direct3DRMPick2Array

Retrieves the Direct3DRMVisual object intersected by the specified pick.

Syntax

object.GetPickVisual(index As Long,
  pickDesc As D3DRMPICKDESC2) As Direct3DRMVisual

Parts

object
Object expression that resolves to a Direct3DRMPick2Array object.
index
Index into the pick array identifying the pick for which information will be retrieved.
pickDesc
D3DRMPICKDESC2 type specifying the face and group identifiers, pick position, horizontal and vertical texture coordinates for the vertex, vertex normal, and color of the intersected objects.

Return Value

Returns the Direct3DRMVisual object associated with the specified pick.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method is similar to Direct3DRMPickArray.GetPickVisual except that it retrieves the u- and v-values in a D3DRMPICKDESC2 type rather than a D3DRMPICKDESC type.

See Also

Direct3DRMFrame3.RayPick

Direct3DRMPick2Array.GetSize

Direct3DRMPick2Array

Retrieves the number of elements contained in a Direct3DRMPick2Array object.

Syntax

object.GetSize( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMPick2Array object.

Return Value

Returns the number of elements.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.


Direct3DRMPickArray

Applications use the methods of the Direct3DRMPickArray interface to organize pick objects. The pick array is zero based (0 to N-1).

Picking is the process of searching for visuals in a scene, given a 2-D coordinate in a viewport or a vector in a frame. For information about ray picking, see the Direct3DRMPick2Array interface.

You can use the Direct3DRMViewport2.Pick method to retrieve an Direct3DRMPickArray object, and then call the Direct3DRMPickArray.GetPickFrame method to retrieve an Direct3DRMFrameArray interface and a visual object. The array of frames is the path through the hierarchy leading to the visual object; that is, a hierarchical list of the visual object's parent frames, with the topmost parent in the hierarchy first in the array.

The Direct3DRMPickArray interface supports the following methods.

  • GetPickFrame
  • GetPickVisual
  • GetSize

Obtain the Direct3DRMPickArray object by calling the Direct3DRMViewport2.Pick method.

Direct3DRMPickArray.GetPickFrame

Direct3DRMPickArray

Retrieves the Direct3DRMFrameArray object intersected by the specified pick.

Syntax

object.GetPickFrame(index As Long,
  pickDesc As D3DRMPICKDESC) As Direct3DRMFrameArray

Parts

object
Object expression that resolves to a Direct3DRMPickArray object.
index
Index into the pick array identifying the pick for which information will be retrieved.
pickDesc
D3DRMPICKDESC type specifying the pick position and face and group identifiers of the objects being retrieved.

Return Value

Returns the Direct3DRMFrameArray object associated with the specified pick.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMViewport2.Pick

Direct3DRMPickArray.GetPickVisual

Direct3DRMPickArray

Retrieves the Direct3DRMVisual object intersected by the specified pick.

Syntax

object.GetPickVisual(index As Long,
  pickDesc As D3DRMPICKDESC) As Direct3DRMVisual

Parts

object
Object expression that resolves to a Direct3DRMPickArray object.
index
Index into the pick array identifying the pick for which information will be retrieved.
pickDesc
D3DRMPICKDESC type specifying the pick position and face and group identifiers of the objects being retrieved.

Return Value

Returns the Direct3DRMVisual object associated with the specified pick.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMViewport2.Pick

Direct3DRMPickArray.GetSize

Direct3DRMPickArray

Retrieves the number of elements contained in a Direct3DRMPickArray object.

Syntax

object.GetSize( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMPickArray object.

Return Value

Returns the number of elements.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.


Direct3DRMProgressiveMesh

A mesh is a visual object that is made up of a set of polygonal faces. A mesh defines a set of vertices and a set of faces. For more information about meshes, see Direct3DRMMesh.

A progressive mesh is a mesh that is stored as a base mesh (a coarse version) and a set of vertex split records that are used to increasingly refine the mesh. In other words, it enables progressive refinement. This enables you to set the level of detail rendered for a mesh and also enables progressive download from remote sources.

The progressive mesh is a visual in Microsoft® Direct3D® Retained Mode and can be used in the standard ways that visuals are used. That is, a progressive mesh can be added to frame hierarchies, instantiated a multiple number of times, and picked.

Using the methods of the Direct3DRMProgressiveMesh interface, you can set the number of vertices or faces to render, and thereby control, the render detail. You can also specify a minimum level of detail required for rendering. Normally, a progressive mesh is rendered when the base mesh is available, but with the Direct3DRMProgressiveMesh.SetMinRenderDetail method you can specify that a greater level of detail is necessary before rendering. You can also build a Direct3DRMMesh object from a particular state of the progressive mesh by using the Direct3DRMProgressiveMesh.CreateMesh method.

You can load a progressive mesh from a file, resource, memory, or URL. Loading can be done synchronously or asynchronously. You can check the status of a download with the Direct3DRMProgressiveMesh.GetLoadStatus method, and terminate a download with the Direct3DRMProgressiveMesh.Abort method. If loading is asynchronous, it is up to the application to use events through the Direct3DRMProgressiveMesh.RegisterEvents and Direct3DRMProgressiveMesh.GetLoadStatus methods to find out how the load is progressing.

The Direct3DRMProgressiveMesh object is created by using the Direct3DRM3.CreateProgressiveMesh method. After creation, the object can be added to a hierarchy, but will not render until at least the base mesh is available.

The methods of the Direct3DRMProgressiveMesh interface can be organized into the following groups.

Creating and Copying Meshes | CreateMesh
 | Duplicate
 | GetBox
Loading | Abort
 | GetLoadStatus
 | LoadFromFile
Setting Quality | SetQuality
 | GetQuality
Managing Details | GetDetail
 | GetFaceDetail
 | GetFaceDetailRange
 | GetVertexDetail
 | GetVertexDetailRange
 | SetDetail
 | SetFaceDetail
 | SetMinRenderDetail
 | SetVertexDetail
Registering Events | RegisterEvents

The Direct3DRMProgressiveMesh interface inherits the following methods from the Direct3DRMObject interface.
AddDestroyCallback
CloneObject
DeleteDestroyCallback
GetAppData
GetClassName
GetName
SetAppData
SetName

Direct3DRMProgressiveMesh.Abort

Direct3DRMProgressiveMesh

Terminates the currently active download.

Syntax

object.Abort( )

Parts

object
Object expression that resolves to a Direct3DRMProgressiveMesh object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

If the base mesh has been downloaded before this method is used, the effect is as if the progressive mesh has loaded, the vertex splits are in a valid state, and the progressive mesh is renderable. The other progressive mesh methods will work. If the base mesh has not been downloaded before the Direct3DRMProgressiveMesh.Abort call and you have added the progressive mesh to a scene, the Direct3DRMViewport2.Render method will succeed, but the progressive mesh will not be rendered. Also, if the base mesh has not been downloaded when you try to use the progressive mesh (to create a mesh or clone, for example) the call will return D3DRMERR_NOTENOUGHDATA.

If there are any outstanding events, they are signaled.

Direct3DRMProgressiveMesh.CreateMesh

Direct3DRMProgressiveMesh

Builds a mesh from the current level of detail.

Syntax

object.CreateMesh( ) As Direct3DRMMesh

Parts

object
Object expression that resolves to a Direct3DRMProgressiveMesh object.

Return Value

Returns the newly generated Direct3DRMMesh object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

If the application has requested a level of detail that is not yet available or if the base mesh is not yet available, this method returns the error D3DRMERR_NOTENOUGHDATA.

Direct3DRMProgressiveMesh.Duplicate

Direct3DRMProgressiveMesh

Creates a copy of the Direct3DRMProgressiveMesh object. The copy shares all geometry and face data with the original, but has a detail level that can be set independently of the original. This enables the same mesh data to be used in different parts of the hierarchy but with different levels of detail. In essence, you almost have two instances of a progressive mesh within the frame hierarchy.

Syntax

object.Duplicate( ) As Direct3DRMProgressiveMesh

Parts

object
Object expression that resolves to a Direct3DRMProgressiveMesh object.

Return Value

Returns the newly generated Direct3DRMProgressiveMesh object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

The progressive mesh being duplicated must have at least its base mesh loaded. If you use this method on a progressive mesh that is currently being asynchronously loaded, the duplicated mesh only has as much detail as the loading progressive mesh had at the time it was duplicated. Any vertex splits loaded after the duplication are not available to the duplicated mesh.

A progressive mesh has a set of data representing the base mesh and a set of data representing the vertex splits. The base mesh data and data describing the current state of the progressive mesh and the current level of detail aren't shared between meshes that are duplicated, but the vertex splits are.

Direct3DRMProgressiveMesh.GetBox

Direct3DRMProgressiveMesh

Retrieves the bounding box containing a Direct3DRMProgressiveMesh object. The bounding box gives the minimum and maximum coordinates relative to a child frame, in each dimension.

Syntax

object.GetBox(box As D3DRMBOX)

Parts

object
Object expression that resolves to a Direct3DRMProgressiveMesh object.
box
A D3DRMBOX type that will be filled with the bounding box coordinates.

Error Values

For a list of possible return codes, see Direct3D Retained Mode Error Values.

Direct3DRMProgressiveMesh.GetDetail

Direct3DRMProgressiveMesh

Returns the current detail level of the progressive mesh normalized between 0.0 and 1.0.

Syntax

object.GetDetail( ) As Single

Parts

object
Object expression that resolves to a Direct3DRMProgressiveMesh object.

Return Value

Returns a value that will be filled with the current detail level of the progressive mesh.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

If the base mesh has not yet downloaded, this method will return D3DRMERR_PENDING. If a requested level of detail has been set, the return value will increase on each subsequent call until the requested level has been met. If no level has been requested, the detail will increase until all vertex splits have been downloaded.

The normalized value 0.0 represents the minimum number of vertices (the number of vertices in the base mesh), and the normalized value 1.0 represents the maximum number of vertices.

Direct3DRMProgressiveMesh.GetFaceDetail

Direct3DRMProgressiveMesh

Retrieves the number of faces in the progressive mesh.

Syntax

object.GetFaceDetail( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMProgressiveMesh object.

Return Value

Returns a value that will be filled in with the number of faces in the progressive mesh.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

If the number of faces is not available, this method returns D3DRMERR_PENDING.

Direct3DRMProgressiveMesh.GetFaceDetailRange

Direct3DRMProgressiveMesh

Retrieves the minimum and maximum face count available in the progressive mesh.

Syntax

object.GetFaceDetailRange(min As Long,
  max As Long)

Parts

object
Object expression that resolves to a Direct3DRMProgressiveMesh object.
min
Value that will be filled in with the minimum number of faces.
max
Value that will be filled in with the maximum number of faces.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

If the face count is not available, this method returns D3DRMERR_PENDING.

Direct3DRMProgressiveMesh.GetLoadStatus

Direct3DRMProgressiveMesh

Allows the application to inquire about the current status of the load.

Syntax

object.GetLoadStatus(loadStatus As D3DRMPMESHLOADSTATUS)

Parts

object
Object expression that resolves to a Direct3DRMProgressiveMesh object.
loadStatus
A D3DRMPMESHLOADSTATUS type that indicates the loading status of the progressive mesh.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMProgressiveMesh.GetQuality

Direct3DRMProgressiveMesh

Retrieves a value indicating the rendering quality of the progressive mesh.

Syntax

object.GetQuality( ) As CONST_D3DRMRENDERQUALITY

Parts

object
Object expression that resolves to a Direct3DRMProgressiveMesh object.

Return Value

Returns a member of the CONST_D3DRMRENDERQUALITY enumerated type that specifies rendering quality.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMProgressiveMesh.SetQuality

Direct3DRMProgressiveMesh.GetVertexDetail

Direct3DRMProgressiveMesh

Retrieves the number of vertices in the progressive mesh.

Syntax

object.GetVertexDetail( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMProgressiveMesh object.

Return Value

Returns a value that will be filled in with the number of vertices in the progressive mesh.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

If the number of vertices is not available, this method returns D3DRMERR_PENDING.

Direct3DRMProgressiveMesh.GetVertexDetailRange

Direct3DRMProgressiveMesh

Retrieves the minimum and maximum vertex count available in the progressive mesh.

Syntax

object.GetVertexDetailRange(min As Long,
  max As Long)

Parts

object
Object expression that resolves to a Direct3DRMProgressiveMesh object.
min
Value that will be filled in with the minimum number of vertices.
max
Value that will be filled in with the maximum number of vertices.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

If the vertex count information is not available, this method returns D3DRMERR_PENDING.

Direct3DRMProgressiveMesh.LoadFromFile

Direct3DRMProgressiveMesh

Loads the progressive mesh object from memory, a file, a resource, or a URL. Loading can be done synchronously or asynchronously.

Syntax

object.LoadFromFile(sFile As String,
  id As String,
  options As CONST_D3DRMLOADFLAGS,
  loadTextureImplementation As Direct3DRMLoadTextureCallback3,
  userArgument As Object)

Parts

object
Object expression that resolves to a Direct3DRMProgressiveMesh object.
sFile
Source for the object to be loaded. This source can be a file, resource, memory block, or stream, depending on the source flags specified in the options parameter.
id
Object name or position to be loaded. If id is "", you must set the options parameter to D3DRMLOAD_FIRST. Note that Microsoft Visual Basic® will accept an Integer in the id parameter, indicating the position of the item to be loaded, even though a String data type is specified. For example, placing 1 in the id parameter will load the object in the first position.
options
One or more values from the CONST_D3DRMLOADFLAGS enumerated type describing how the load is to be performed.
loadTextureImplementation
Direct3DRMLoadTextureCallback3 callback interface that will be used to load any texture encountered. Textures must have a width and length divisible by two. The callback will be used with the texture name as encountered by the loader and the user-defined args parameter. A new thread is not spawned for the callback.
userArgument
User-defined data passed to the callback.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

The progressive mesh is not useful unless it has been initialized. If asynchronous download is specified, the API returns immediately, and a separate thread is spawned to perform the download. It is up to the application to use events with Direct3DRMProgressiveMesh.RegisterEvents and Direct3DRMProgressiveMesh.GetLoadStatus to find out how the load is progressing.

This method and the Direct3DRMProgressiveMesh.Duplicate method initialize a progressive mesh. You can only initialize an object once. Therefore, you cannot clone or duplicate a progressive mesh and then try to load into the cloned or duplicated mesh, nor can you load into a previously loaded mesh.

Direct3DRMProgressiveMesh.RegisterEvents

Direct3DRMProgressiveMesh

Allows the application to register events with the progressive mesh object that will be signaled when the appropriate conditions are met.

Syntax

object.RegisterEvents(hEvent As Long,
  flags As Long,
  reserved As Long)

Parts

object
Object expression that resolves to a Direct3DRMProgressiveMesh object.
hEvent
Event to be signaled when the required condition is met.
flags
One or more values from the CONST_D3DRMPMESHSTATUSFLAGS enumerated type.
reserved
Must be zero.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method can be used to monitor the progress of loads. Events will also be signaled if an error occurs, so your application should always use the Direct3DRMProgressiveMesh.GetLoadStatus method after being signaled.

Direct3DRMProgressiveMesh.SetDetail

Direct3DRMProgressiveMesh

Sets a requested level of detail normalized between 0.0 (minimum detail) and 1.0 (maximum detail).

Syntax

object.SetDetail(detail As Single)

Parts

object
Object expression that resolves to a Direct3DRMProgressiveMesh object.
detail
Requested level of detail.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

If not enough detail has been downloaded yet (but will be available), the request is acknowledged and D3DRMERR_PENDING is returned. This error is informational and indicates that the requested level will be set as soon as enough detail is available.

The normalized value 0.0 represents the minimum number of vertices (the number of vertices in the base mesh), and the normalized value 1.0 represents the maximum number of vertices.

Direct3DRMProgressiveMesh.SetFaceDetail

Direct3DRMProgressiveMesh

Sets the requested level of face detail.

Syntax

object.SetFaceDetail(count As Long)

Parts

object
Object expression that resolves to a Direct3DRMProgressiveMesh object.
count
Number of faces requested.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Sometimes it is not possible to set the progressive mesh to the number of faces requested, though it will always be within one of the requested value. This is because a vertex split can add one or two faces. For example, if you use SetFaceDetail(20), the progressive mesh may only be able to set the face detail to 19 or 21. You can always get the actual number of faces in the progressive mesh by using the Direct3DRMProgressiveMesh.GetFaceDetail method.

If not enough detail has been downloaded yet (but will be available), the request is acknowledged and D3DRMERR_PENDING is returned. This error is informational and indicates that the requested level will be set as soon as enough detail is available. If the detail requested is greater that the detail available in the progressive mesh, D3DRMERR_REQUESTTOOLARGE is returned.

See Also

Direct3DRMProgressiveMesh.GetFaceDetail

Direct3DRMProgressiveMesh.SetMinRenderDetail

Direct3DRMProgressiveMesh

Sets the minimum level of detail that will be rendered during a load from 0.0 (minimum detail) to 1.0 (maximum detail). Normally, the progressive mesh will be rendered after the base mesh is available (and the mesh is in the scene graph).

Syntax

object.SetMinRenderDetail(val As Single)

Parts

object
Object expression that resolves to a Direct3DRMProgressiveMesh object.
val
Requested minimum detail.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method sets the minimum number of faces/vertices that will be rendered during the load. The value is in addition to those that are already rendered in the base mesh.

Any subsequent Direct3DRMProgressiveMesh.SetDetail, Direct3DRMProgressiveMesh.SetFaceDetail, or Direct3DRMProgressiveMesh.SetVertexDetail calls will override this.

Direct3DRMProgressiveMesh.SetQuality

Direct3DRMProgressiveMesh

Sets the rendering quality of a Direct3DRMProgressiveMesh object.

Syntax

object.SetQuality(quality As CONST_D3DRMRENDERQUALITY)

Parts

object
Object expression that resolves to a Direct3DRMProgressiveMesh object.
quality
Member of the CONST_D3DRMRENDERQUALITY enumerated type that specifies the new rendering quality to use.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

An object's quality has three components: shade mode (flat or Gouraud; Phong is not yet implemented and will default to Gouraud shading), lighting type (on or off), and fill mode (point, wireframe, or solid).

You can set the quality of a device with the Direct3DRMDevice3.SetQuality method. By default, the quality is D3DRMRENDER_FLAT (flat shading, lights on, and solid fill).

You can set the quality of a Direct3DRMProgressiveMesh object with the SetQuality method. By default, a Direct3DRMProgressiveMesh object's quality is D3DRMRENDER_GOURAUD (Gouraud shading, lights on, and solid fill).

Tip: Gouraud shading performs better on progressive mesh objects that change their level of detail often or quickly.

Direct3D Retained Mode renders an object at the lowest quality setting, based on the device and object's current setting for each individual component. For example, if the object's current quality setting is D3DRMRENDER_GOURAUD, and the device is D3DRMRENDER_FLAT, the object will be rendered with flat shading, solid fill and lights on.

If the object's current quality setting is D3DRMSHADE_GOURAUD|D3DRMLIGHT_OFF|D3DRMFILL_WIREFRAME and the device's quality setting is D3DRMSHADE_FLAT|D3DRMLIGHT_ON|D3DRMFILL_POINT, the object will be rendered with flat shading, lights off, and point fill mode.

These rules apply to Direct3DRMMeshBuilder3 objects and Direct3DRMProgressiveMesh objects. However, Direct3DRMMesh objects do not follow these rules. Mesh objects ignore the device's quality settings and use the group quality setting (which defaults to D3DRMRENDER_GOURAUD).

See Also

Direct3DRMProgressiveMesh.GetRenderQuality

Direct3DRMProgressiveMesh.SetVertexDetail

Direct3DRMProgressiveMesh

Sets the requested level of vertex detail.

Syntax

object.SetVertexDetail(count As Long)

Parts

object
Object expression that resolves to a Direct3DRMProgressiveMesh object.
count
Number of vertices requested.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

If not enough detail has been downloaded yet (but will be available), the request will be acknowledged and D3DRMERR_PENDING is returned. This error is informational and indicates that the requested level will be set as soon as enough detail is available. If the detail requested is greater than the detail available in the progressive mesh, D3DRMERR_REQUESTTOOLARGE is returned.

See Also

Direct3DRMProgressiveMesh.GetVertexDetail


Direct3DRMShadow2

Applications use the Direct3DRM3.CreateShadow method to initialize Direct3DRMShadow2 objects. These shadow objects are created and added to the frame hierarchy as visuals.

The Direct3DRMShadow2 interface inherits the following methods from the Direct3DRMObject interface.
AddDestroyCallback
CloneObject
DeleteDestroyCallback
GetAppData
GetClassName
GetName
SetAppData
SetName

The Direct3DRMShadow2 object is obtained by using the Direct3DRM3.CreateShadow method.


Direct3DRMTexture3

The Direct3DRMTexture3 interface provides fine control over texture management. The Changed method enables you to specify the changed region of the texture. Direct3DRMTexture3 also provides the texture management caching methods GetCacheFlags, SetCacheOptions, and GetCacheImportance.

The GenerateMIPMap method generates a mipmap from a source image.

To avoid unnecessary delays when creating textures, hold on to textures you want to use again, instead of creating them each time they're needed. For optimal performance, use a texture surface format that is supported by the device you are using. This will avoid a costly format conversion when the texture is created and any time it changes.

The methods of the Direct3DRMTexture3 interface can be organized into the following groups.

Color | GetColors
SetColors
Decals | GetDecalOrigin
GetDecalScale
GetDecalSize
GetDecalTransparency
GetDecalTransparentColor
SetDecalOrigin
SetDecalScale
SetDecalSize
SetDecalTransparency
SetDecalTransparentColor
MIP map generation | GenerateMIPMap
Miscellaneous | GetCacheFlags
GetCacheImportance
GetSurface
SetCacheOptions
Renderer notification | Changed
Shading | GetShades
SetShades

The Direct3DRMTexture3 interface inherits the following methods from the Direct3DRMObject interface.

AddDestroyCallback
CloneObject
DeleteDestroyCallback
GetAppData
GetClassName
GetName
SetAppData
SetName

Call the Direct3DRM3.CreateTextureFromSurface method to create a Direct3DRMTexture3 object.

Direct3DRMTexture3.Changed

Direct3DRMTexture3

Enables the application to specify which region of the texture has changed.

Syntax

object.Changed(flags As CONST_D3DRMTEXTURECHANGEDFLAGS,
  nRects As Long,
  rects() As RECT)

Parts

object
Object expression that resolves to a Direct3DRMTexture3 object.
flags
One or more of the values from the CONST_D3DRMTEXTURECHANGEDFLAGS enumerated type, indicating textural changes.
nRects
Number of RECT types in rects. If this value is zero, and flags contains D3DRMTEXTURE_CHANGEDPIXELS or D3DRMTEXTURE_INVALIDATEONLY, the whole texture is updated.
rects
Array of RECT types describing the regions of pixels that have changed. The rects parameter is only valid if flags contains D3DRMTEXTURE_CHANGEDPIXELS or D3DRMTEXTURE_INVALIDATEONLY. A RECT is a type that is a rectangle definition:
Type RECT
  Bottom As Long
  Left As Long
  Right As Long
  Top As Long
End Type

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMTexture3.GenerateMIPMap

Direct3DRMTexture3

Generates a mipmap from a single image source.

Syntax

object.GenerateMIPMap( )

Parts

object
Object expression that resolves to a Direct3DRMTexture3 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method can be called any time after a texture is created. It will generate a mipmap of the source image down to a resolution of 1 × 1 by using bilinear filtering between levels. After a mipmap has been generated, it will always be available and will be updated whenever Direct3DRMTexture3.Changed is called. When using mipmapping, remember to change the texture quality to D3DRMTEXTURE_MIPNEAREST, D3DRMTEXTURE_MIPLINEAR, D3DRMTEXTURE_LINEARMIPNEAREST, or D3DRMTEXTURE_LINEARMIPLINEAR using Direct3DRMDevice3.SetTextureQuality. Extra mipmap levels will not be put into video memory for hardware devices unless the texture quality includes a mipmapping type and the hardware device supports mipmapping.

Direct3DRMTexture3.GetCacheFlags

Direct3DRMTexture3

Retrieves information about how texture management treats the current texture if texture memory is restricted.

Syntax

object.GetCacheFlags( ) As CONST_D3DRMTEXTURECACHEFLAGS

Parts

object
Object expression that resolves to a Direct3DRMTexture3 object.

Return Value

Returns values from the CONST_D3DRMTEXTURECACHEFLAGS enumerated type.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMTexture3.GetCacheImportance

Direct3DRMTexture3

Retrieves information on the relative importance of a texture if texture memory is restricted.

Syntax

object.GetCacheImportance( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMTexture3 object.

Return Value

Returns a value that indicates the relative importance of a texture. The default is zero. Higher values indicate a greater importance. This value is used to calculate which textures should be downsampled last if texture memory is restricted.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMTexture3.GetColors

Direct3DRMTexture3

Retrieves the maximum number of colors used for rendering a Direct3DRMTexture3 object.

Syntax

object.GetColors( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMTexture3 object.

Return Value

Returns the number of colors.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method returns the number of colors that the Direct3DRMTexture3 object has been quantized to, not the number of colors in the image from which the Direct3DRMTexture3 object was created. Consequently, the number of colors returned usually matches the colors that were set by calling the Direct3DRM3.SetDefaultTextureColors method, unless you used the Direct3DRMTexture3.SetColors method explicitly to change the colors for the Direct3DRMTexture3 object.

Direct3DRMTexture3.GetDecalOrigin

Direct3DRMTexture3

Retrieves the current origin of the decal.

Syntax

object.GetDecalOrigin(x As Long,
  y As Long)

Parts

object
Object expression that resolves to a Direct3DRMTexture3 object.
x and y
The x- and y-coordinates of the decal's origin.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMTexture3.SetDecalOrigin

Direct3DRMTexture3.GetDecalScale

Direct3DRMTexture3

Retrieves the scaling property of the given decal.

Syntax

object.GetDecalScale( ) As CONST_DBOOLFLAGS

Parts

object
Object expression that resolves to a Direct3DRMTexture3 object.

Return Value

Returns –1 if depth is taken into account when the decal is scaled and, when the decal is a texture on a frame in a scene, the decal will be scaled smaller when it is farther from the viewer and larger when it is closer to the viewer. Otherwise, if depth information is ignored, and the decal will be the same size whether it is close to or far from the viewer, zero is returned.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMTexture3.SetDecalScale

Direct3DRMTexture3.GetDecalSize

Direct3DRMTexture3

Retrieves the size of the decal.

Syntax

object.GetDecalSize(w As Single,
  h As Single)

Parts

object
Object expression that resolves to a Direct3DRMTexture3 object.
w and h
Width and height of the decal.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMTexture3.SetDecalSize

Direct3DRMTexture3.GetDecalTransparency

Direct3DRMTexture3

Retrieves the transparency property of the decal.

Syntax

object.GetDecalTransparency( ) As CONST_DBOOLFLAGS

Parts

object
Object expression that resolves to a Direct3DRMTexture3 object.

Return Value

Returns –1 if the decal has a transparent color, or zero otherwise.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMTexture3.SetDecalTransparency

Direct3DRMTexture3.GetDecalTransparentColor

Direct3DRMTexture3

Retrieves the transparent color of the decal.

Syntax

object.GetDecalTransparentColor( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMTexture3 object.

Return Value

Returns the value of the transparent color.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMTexture3.SetDecalTransparentColor

Direct3DRMTexture3.GetShades

Direct3DRMTexture3

Retrieves the number of shades used for each color in the texture when rendering.

Syntax

object.GetShades( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMTexture3 object.

Return Value

Returns the number of shades.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMTexture3.SetShades

Direct3DRMTexture3.GetSurface

Direct3DRMTexture3

Retrieves the Microsoft® DirectDraw® surface that was used to create the texture. This method only retrieves a surface if Direct3DRM3.CreateTextureFromSurface was used to create the texture.

Syntax

object.GetSurface(flags As Long) As DirectDrawSurface4

Parts

object
Object expression that resolves to a Direct3DRMTexture3 object.
flags
Flag value. Must be zero.

Return Value

Returns the corresponding DirectDrawSurface4 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMTexture3.SetCacheOptions

Direct3DRMTexture3

Provides information about how texture management should treat this texture if texture memory is restricted.

Syntax

object.SetCacheOptions(importance As Long
  CONST_D3DRMTEXTURECACHEFLAGS As Long)

Parts

object
Object expression that resolves to a Direct3DRMTexture3 object.
importance
Value that indicates the relative importance of a texture. The default value is zero. Higher values indicate a greater importance. This value is used to calculate which textures should be rendered last if texture memory is restricted.
flags
One or more values from the CONST_D3DRMTEXTURECACHEFLAGS enumerated type.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMTexture3.SetColors

Direct3DRMTexture3

Sets the maximum number of colors used for rendering a Direct3DRMTexture3 object. This method is required only in the ramp color model.

Syntax

object.SetColors(c As Long)

Parts

object
Object expression that resolves to a Direct3DRMTexture3 object.
c
Number of colors. The default value is 8.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMTexture3.GetColors

Direct3DRMTexture3.SetDecalOrigin

Direct3DRMTexture3

Sets the origin of the decal as an offset from the top left of the decal.

Syntax

object.SetDecalOrigin(x As Long,
  y As Long)

Parts

object
Object expression that resolves to a Direct3DRMTexture3 object.
x and y
New origin, in decal coordinates, for the decal. The default origin is (0, 0).

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

The decal's origin is mapped to its frame's position when rendering. For example, the origin of a decal of a cross would be set to the middle of the decal, and the origin of an arrow pointing down would be set to midway along the bottom edge.

This method is also used to add a decal origin key to a Direct3DRMTextureInterpolator object.

See Also

Direct3DRMTexture3.GetDecalOrigin

Direct3DRMTexture3.SetDecalScale

Direct3DRMTexture3

Sets the scaling property for a decal.

Syntax

object.SetDecalScale(considerScale As CONST_DBOOLFLAGS)

Parts

object
Object expression that resolves to a Direct3DRMTexture3 object.
considerScale
Value indicating whether depth information is used when scaling the decal. If this parameter is set to D_TRUE, depth is taken into account when the decal is scaled and, when the decal is a texture on a frame in a scene, the decal will be scaled smaller when it is farther from the viewer and larger when it is closer to the viewer. If this parameter is set to D_FALSE, depth information is ignored, and the decal will be the same size whether it is close to or far from the viewer. The default is D_TRUE.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMTexture3.GetDecalScale

Direct3DRMTexture3.SetDecalSize

Direct3DRMTexture3

Sets the size of the decal to use if the decal is being scaled according to its depth in the scene.

Syntax

object.SetDecalSize(width As Single,
  height As Single)

Parts

object
Object expression that resolves to a Direct3DRMTexture3 object.
width and height
New width and height, in model coordinates, of the decal. The default size is [1, 1].

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method is also used to add a decal size key to a Direct3DRMTextureInterpolator object.

See Also

Direct3DRMTexture3.GetDecalSize

Direct3DRMTexture3.SetDecalTransparency

Direct3DRMTexture3

Sets the transparency property of the decal.

Syntax

object.SetDecalTransparency(transparencyEnabled As CONST_DBOOLFLAGS)

Parts

object
Object expression that resolves to a Direct3DRMTexture3 object.
transparencyEnabled
Value indicating whether the decal has a transparent or opaque color. If set to D_TRUE, the decal has a transparent color; if set to D_FALSE, the decal does not have a transparent color. The default is D_FALSE.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMTexture3.GetDecalTransparency

Direct3DRMTexture3.SetDecalTransparentColor

Direct3DRMTexture3

Sets the transparent color for a decal.

Syntax

object.SetDecalTransparentColor(tcolor As Long)

Parts

object
Object expression that resolves to a Direct3DRMTexture3 object.
tcolor
New transparent color. The default is black. To specify an object's color, including the alpha component, call the CreateColorRGBA method from the DirectX7 interface on the object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method is also used to add a decal transparent color key to a Direct3DRMTextureInterpolator object.

See Also

Direct3DRMTexture3.GetDecalTransparentColor

Direct3DRMTexture3.SetShades

Direct3DRMTexture3

Sets the maximum number of shades to use for each color for the Direct3DRMTexture3 object when rendering. This method is required only in the ramp color model.

Syntax

object.SetShades(numShades As Long)

Parts

object
Object expression that resolves to a Direct3DRMTexture3 object.
numShades
New number of shades. This value must be a power of 2. The default value is 16.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMTexture3.GetShades


Direct3DRMTextureInterpolator

Interpolators provide a way of storing actions and applying them to objects with automatic calculation of in-between values. With an interpolator you can blend colors, move objects smoothly between positions, morph meshes, and perform many other transformations.

A Direct3DRMTexture3 object can be attached to a Direct3DRMTextureInterpolator object. For more information on interpolators, see Interpolators in Further Reading.

The Direct3DRMTextureInterpolator interface contains the following methods.

Attaching objects | AttachObject
DetachObject
GetAttachedObjects
Color | SetDecalOrigin
SetDecalSize
SetDecalTransparentColor
Interpolating | GetIndex
Interpolate
SetIndex

In addition, Direct3DRMTextureInterpolator inherits the following methods from the Direct3DRMObject interface.

  • AddDestroyCallback
  • Clone
  • DeleteDestroyCallback
  • GetAppData
  • GetClassName
  • GetName
  • SetAppData
  • SetName

Direct3DRMTextureInterpolator.AttachObject

Direct3DRMTextureInterpolator

Connects an object to the interpolator.

Syntax

object.AttachObject(mObject As Direct3DRMObject)

Parts

object
Object expression that resolves to a Direct3DRMTextureInterpolator object.
mObject
Direct3DRMObject object to attach to the interpolator.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

The attached object can be another interpolator or an object of type x where the interpolator is of type xInterpolator. For example, a Direct3DRMTexture3 object can be attached to a Direct3DRMTextureInterpolator object.

Direct3DRMTextureInterpolator.DetachObject

Direct3DRMTextureInterpolator

Detaches an object from the interpolator.

Syntax

object.DetachObject(mObject As Direct3DRMObject)

Parts

object
Object expression that resolves to a Direct3DRMTextureInterpolator object.
mObject
Direct3DRMObject object to detach from the interpolator.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMTextureInterpolator.GetAttachedObjects

Direct3DRMTextureInterpolator

Retrieves the objects currently attached to the interpolator.

Syntax

object.GetAttachedObjects( ) As Direct3DRMObjectArray

Parts

object
Object expression that resolves to a Direct3DRMTextureInterpolator object.

Return Value

Returns a Direct3DRMObjectArray object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMTextureInterpolator.GetIndex

Direct3DRMTextureInterpolator

Retrieves the interpolator's current internal index (time).

Syntax

object.GetIndex( ) As Single

Parts

object
Object expression that resolves to a Direct3DRMTextureInterpolator object.

Return Value

Returns a value that contains the interpolator's current internal index.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Every key stored in an interpolator has an index value. When a key is recorded (by using a method), the key is stamped with the current interpolator index value. The key's index value does not change after being stamped.

Direct3DRMTextureInterpolator.Interpolate

Direct3DRMTextureInterpolator

Generates a series of actions by interpolating between keys stored in the interpolator. The actions are then applied to the specified object. If no object is specified, the actions are applied to the currently attached objects.

Syntax

object.Interpolate(val As Single,
  mObject As Direct3DRMObject,
  options As CONST_D3DRMINTERPOLATIONFLAGS)

Parts

object
Object expression that resolves to a Direct3DRMTextureInterpolator object.
val
Value that contains the interpolator's current internal index.
mObject
Direct3DRMObject object that will be assigned interpolated values for all properties stored in the interpolator. Can be NOTHING, in which case the property values of all attached objects will be set to interpolated values.
options
One of the values from the CONST_D3DRMINTERPOLATIONFLAGS enumerated type that controls the kind of interpolation done.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMTextureInterpolator.SetDecalOrigin

Direct3DRMTextureInterpolator

Adds a decal origin key to a Direct3DRMTextureInterpolator object.

Syntax

object.SetDecalOrigin(x As Long,
  y As Long)

Parts

object
Object expression that resolves to a Direct3DRMTextureInterpolator object.
x and y
New origin, in decal coordinates, for the decal. The default origin is [0, 0].

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMTextureInterpolator.SetDecalSize

Direct3DRMTextureInterpolator

Adds a decal size key to a Direct3DRMTextureInterpolator object.

Syntax

object.SetDecalSize(width As Single,
  height As Single)

Parts

object
Object expression that resolves to a Direct3DRMTextureInterpolator object.
width and height
New width and height, in model coordinates, of the decal. The default size is [1, 1].

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMTextureInterpolator.SetDecalTransparentColor

Direct3DRMTextureInterpolator

Adds a decal transparent color key to a Direct3DRMTextureInterpolator object.

Syntax

object.SetDecalTransparentColor(tcolor As Long)

Parts

object
Object expression that resolves to a Direct3DRMTextureInterpolator object.
tcolor
New transparent color. The default is black. To specify an object's color, including the alpha component, call the CreateColorRGBA method from the DirectX7 interface on the object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMTextureInterpolator.SetIndex

Direct3DRMTextureInterpolator

Sets the interpolator's internal index (time) to the specified value. If other interpolators are attached to the interpolator, this method recursively synchronizes their indices to the same value.

Syntax

object.SetIndex(val As Single)

Parts

object
Object expression that resolves to a Direct3DRMTextureInterpolator object.
val
Time to set for the interpolator's internal index.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Every key stored in an interpolator has an index value. When a key is recorded (by using a method), the key is stamped with the current interpolator index value. The key's index value does not change after being stamped.


Direct3DRMViewport2

Applications use the methods of the Direct3DRMViewport2 interface to work with viewport objects. Direct3DRMViewport2 supplies a flag parameter to the Clear method to indicate what should be cleared.

The methods of the Direct3DRMViewport2 interface can be organized into the following groups.

Camera | GetCamera
SetCamera
Clipping planes | GetBack
GetFront
GetPlane
SetBack
SetFront
SetPlane
Dimensions | GetHeight
GetWidth
Field of view | GetField
SetField
Miscellaneous | Clear
Configure
ForceUpdate
GetDevice
GetDirect3DViewport3
Pick
Render
Offsets | GetX
GetY
Projection types | GetProjection
SetProjection
Scaling | GetUniformScaling
SetUniformScaling
Transformations | InverseTransform
Transform

The Direct3DRMViewport2 interface inherits the following methods from the Direct3DRMObject interface.

  • AddDestroyCallback
  • CloneObject
  • DeleteDestroyCallback
  • GetAppData
  • GetClassName
  • GetName
  • SetAppData
  • SetName

Obtain the Direct3DRMViewport object by using the Direct3DRM3.CreateViewport method.

Direct3DRMViewport2.Clear

Direct3DRMViewport2

Clears the given viewport to the current background color.

Syntax

object.Clear(flags As CONST_D3DRMVIEWPORTCLEARFLAGS)

Parts

object
Object expression that resolves to a Direct3DRMViewport2 object.
flags
Logical combination of values from the CONST_D3DRMVIEWPORTCLEARFLAGS enumerated type.

Error Values

If an error occurs, this method can return DDERR_INVALIDOBJECT or DDERR_INVALIDPARAMS.

For a complete list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMViewport2.Configure

Direct3DRMViewport2

Reconfigures the origin and dimensions of a viewport.

Syntax

object.Configure(x As Long,
  y As Long,
  width As Long,
  height As Long)

Parts

object
Object expression that resolves to a Direct3DRMViewport2 object.
x and y
New position of the viewport.
width and height
New width and height of the viewport.

Error Values

This method returns D3DRMERR_BADVALUE if x + width or y + height are greater than the width or height of the device, or if any value of x, y, width, or height is less than zero. For a complete list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMViewport2.ForceUpdate

Direct3DRMViewport2

Forces an area of the viewport to be updated. The specified area will be copied to the screen at the next call to the Direct3DRMDevice3.Update method.

Syntax

object.ForceUpdate(x1 As Long,
  y1 As Long,
  x2 As Long,
  y2 As Long)

Parts

object
Object expression that resolves to a Direct3DRMViewport2 object.
x1 and y1
Upper-left corner of area to be updated.
x2 and y2
Lower-right corner of area to be updated.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

The system might update any region that is larger than the specified rectangle, possibly including the entire window.

Direct3DRMViewport2.GetBack

Direct3DRMViewport2

Retrieves the position of the back clipping plane for a viewport.

Syntax

object.GetBack( ) As Single

Parts

object
Object expression that resolves to a Direct3DRMViewport2 object.

Return Value

Returns a value describing the distance between the back clipping plane and the camera.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMViewport2.SetBack

Direct3DRMViewport2.GetCamera

Direct3DRMViewport2

Retrieves the camera for a viewport.

Syntax

object.GetCamera( ) As Direct3DRMFrame3

Parts

object
Object expression that resolves to a Direct3DRMViewport2 object.

Return Value

Returns the Direct3DRMFrame3 object representing the camera.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMViewport2.SetCamera

Direct3DRMViewport2.GetDevice

Direct3DRMViewport2

Retrieves the device associated with a viewport.

Syntax

object.GetDevice( ) As Direct3DRMDevice3

Parts

object
Object expression that resolves to a Direct3DRMViewport2 object.

Return Value

Returns the Direct3DRMDevice3 object representing the device.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMViewport2.GetDirect3DViewport

Direct3DRMViewport2

Retrieves the Direct3D viewport corresponding to the current Direct3DRMViewport2 object.

Syntax

object.GetDirect3DViewport( ) As Direct3DViewport3

Parts

object
Object expression that resolves to a Direct3DRMViewport2 object.

Return Value

Returns the Direct3DViewport3 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMViewport2.GetField

Direct3DRMViewport2

Retrieves the viewing frustum angle in radians.

Syntax

object.GetField( ) As Single

Parts

object
Object expression that resolves to a Direct3DRMViewport2 object.

Return Value

Returns a value describing the field of view.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMViewport2.SetField

Direct3DRMViewport2.GetFront

Direct3DRMViewport2

Retrieves the position of the front clipping plane for a viewport.

Syntax

object.GetFront( ) As Single

Parts

object
Object expression that resolves to a Direct3DRMViewport2 object.

Return Value

Returns a value describing the distance from the camera to the front clipping plane.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMViewport2.SetFront

Direct3DRMViewport2.GetHeight

Direct3DRMViewport2

Retrieves the height of the viewport.

Syntax

object.GetHeight( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMViewport2 object.

Return Value

Returns the height, in pixels.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMViewport2.GetPlane

Direct3DRMViewport2

Retrieves the dimensions of the viewport on the front clipping plane.

Syntax

object.GetPlane(l As Single,
  r As Single,
  b As Single,
  t As Single)

Parts

object
Object expression that resolves to a Direct3DRMViewport2 object.
l, r, b, and t
Left, right, bottom, and top dimensions of the viewport on the front clipping plane. Measurements are recorded in pixels.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMViewport2.SetPlane

Direct3DRMViewport2.GetProjection

Direct3DRMViewport2

Retrieves the viewport's projection type. A viewport can use either orthographic or perspective projection.

Syntax

object.GetProjection( ) As CONST_D3DRMPROJECTIONTYPE

Parts

object
Object expression that resolves to a Direct3DRMViewport2 object.

Return Value

Returns one of the members of the CONST_D3DRMPROJECTIONTYPE enumerated type.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMViewport2.SetProjection

Direct3DRMViewport2.GetUniformScaling

Direct3DRMViewport2

Retrieves the scaling property used to scale the viewing volume into the larger window dimension.

Syntax

object.GetUniformScaling( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMViewport2 object.

Return Value

Returns –1 if the viewport scales uniformly, or zero value otherwise.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMViewport2.SetUniformScaling

Direct3DRMViewport2.GetWidth

Direct3DRMViewport2

Retrieves the width of the viewport.

Syntax

object.GetWidth( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMViewport2 object.

Return Value

Returns the width, in pixels.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMViewport2.GetX

Direct3DRMViewport2

Retrieves the x-offset of the start of the viewport on a device.

Syntax

object.GetX( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMViewport2 object.

Return Value

Returns the x-offset.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMViewport2.GetY

Direct3DRMViewport2

Retrieves the y-offset of the start of the viewport on a device.

Syntax

object.GetY( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMViewport2 object.

Return Value

Returns the y-offset.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMViewport2.InverseTransform

Direct3DRMViewport2

Transforms the specified vector in screen coordinates to world coordinates, and returns the result.

Syntax

object.InverseTransform(d As D3DVECTOR,
  s As D3DRMVECTOR4D)

Parts

object
Object expression that resolves to a Direct3DRMViewport2 object.
d
D3DVECTOR type that will be filled with the result of the operation when the method returns.
s
D3DRMVECTOR4D type that represents the source of the operation.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMViewport2.Pick

Direct3DRMViewport2

Finds a depth-sorted list of objects (and faces, if relevant) that includes the path taken in the hierarchy from the root down to the frame that contained the object.

Syntax

object.Pick(x As Long,
  y As Long) As Direct3DRMPickArray

Parts

object
Object expression that resolves to a Direct3DRMViewport2 object.
x and y
The x- and y-coordinates used for picking.

Return Value

If the call succeeds, returns a Direct3DRMPickArray interface.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMViewport2.Render

Direct3DRMViewport2

Renders a frame hierarchy to the given viewport. Only those visuals on the given frame and any frames below it in the hierarchy are rendered.

Syntax

object.Render(rootFrame As Direct3DRMFrame3)

Parts

object
Object expression that resolves to a Direct3DRMViewport2 object.
rootFrame
Direct3DRMFrame3 object that represents the frame hierarchy to be rendered.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

This method returns an error if you try to use the Direct3DRM3.SetOptions method to indicate right-handed support and at the same time use the older means (Direct3DRMViewport2.SetProjection) for providing right-handed support.

Direct3DRMViewport2.SetBack

Direct3DRMViewport2

Sets the position of the back clipping plane for a viewport.

Syntax

object.SetBack(v As Single)

Parts

object
Object expression that resolves to a Direct3DRMViewport2 object.
v
Distance between the camera and the back clipping plane. The default value is 100. Reasonable values depend on other viewing frustum settings.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method is also used to add a back clipping plane position key to a Direct3DRMViewportInterpolator object.

See Also

Direct3DRMViewport2.GetBack, Direct3DRMViewport2.SetFront

Direct3DRMViewport2.SetCamera

Direct3DRMViewport2

Sets a camera for a viewport.

Syntax

object.SetCamera(f As Direct3DRMFrame3)

Parts

object
Object expression that resolves to a Direct3DRMViewport2 object.
f
Direct3DRMFrame3 object that represents the camera.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method sets a viewport's position, direction, and orientation to that of the given camera frame. The view is oriented along the positive z-axis of the camera frame, with the up direction being in the direction of the positive y-axis.

See Also

Direct3DRMViewport2.GetCamera

Direct3DRMViewport2.SetField

Direct3DRMViewport2

Sets the viewing frustum angle in radians.

Syntax

object.SetField(v As Single)

Parts

object
Object expression that resolves to a Direct3DRMViewport2 object.
v
New field of view. This value is a fraction of the viewing angle. The default value is 0.5. If this value is less than or equal to zero, this method returns the D3DRMERR_BADVALUE error. The viewing angle is defined as 2 times the arctangent of the front clipping plane over the distance from the camera.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method is also used to add a field of view key to a Direct3DRMViewportInterpolator object.

See Also

Direct3DRMViewport2.GetField

Direct3DRMViewport2.SetFront

Direct3DRMViewport2

Sets the position of the front clipping plane for a viewport.

Syntax

object.SetFront(v As Single)

Parts

object
Object expression that resolves to a Direct3DRMViewport2 object.
v
Distance from the camera to the front clipping plane. The default value is 1.0. Reasonable values depend on other viewing frustum settings.

Error Values

If the value passed is less than or equal to zero, this method returns the D3DRMERR_BADVALUE error. For a complete list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method is also used to add a front clipping plane position key to a Direct3DRMViewportInterpolator object.

See Also

Direct3DRMViewport2.GetFront

Direct3DRMViewport2.SetPlane

Direct3DRMViewport2

Sets the dimensions of the viewport on the front clipping plane, relative to the camera's z-axis.

Syntax

object.SetPlane(Left As Single,
  Right As Single,
  Bottom As Single,
  Top As Single)

Parts

object
Object expression that resolves to a Direct3DRMViewport2 object.
Left, Right, Bottom, and Top
Minimum x-, maximum x-, minimum y-, and maximum y-coordinates, respectively, of the four sides of the viewport.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Unlike the Direct3DRMViewport2.SetField method, which specifies a centered proportional viewport, this method enables you to specify a viewport of arbitrary proportion and position. For example, you could use this method to construct a sheared viewing frustum to implement a right- or left-eye stereo view.

This method is also used to add a plane key to a Direct3DRMViewportInterpolator object.

See Also

Direct3DRMViewport2.GetPlane

Direct3DRMViewport2.SetProjection

Direct3DRMViewport2

Sets the projection type for a viewport.

Syntax

object.SetProjection(val As CONST_D3DRMPROJECTIONTYPE)

Parts

object
Object expression that resolves to a Direct3DRMViewport2 object.
val
One of the members of the CONST_D3DRMPROJECTIONTYPE enumerated type.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Use Direct3DRM3.SetOptions to specify right-handed geometry.

See Also

Direct3DRMViewport2.GetProjection

Direct3DRMViewport2.SetUniformScaling

Direct3DRMViewport2

Sets the scaling property used to scale the viewing volume into the larger dimension of the window.

Syntax

object.SetUniformScaling(flag As CONST_DBOOLFLAGS)

Parts

object
Object expression that resolves to a Direct3DRMViewport2 object.
flag
New scaling property. If this parameter is D_TRUE, the same horizontal and vertical scaling factor is used to scale the viewing volume. Otherwise, if the parameter is set to D_FALSE, different scaling factors are used to scale the viewing volume exactly into the window. The default setting is D_TRUE.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method is typically used with the Direct3DRMViewport2.SetPlane method to support banding.

See Also

Direct3DRMViewport2.GetUniformScaling

Direct3DRMViewport2.Transform

Direct3DRMViewport2

Transforms the specified vector in world coordinates to screen coordinates, and returns the result.

Syntax

object.Transform(d As D3DRMVECTOR4D,
  s As D3DVECTOR)

Parts

object
Object expression that resolves to a Direct3DRMViewport2 object.
d
D3DRMVECTOR4D type that acts as the destination for the transformation operation.
s
D3DVECTOR type that acts as the source for the transformation operation.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

The result of the transformation is a four-element homogeneous vector. The point represented by the resulting vector is visible if the following equations are true.

Equations for testing whether the point is visible

See Also

Direct3DRMViewport2.InverseTransform


Direct3DRMViewportArray

Applications use the methods of the Direct3DRMViewportArray interface to organize viewport objects. The viewport array is zero based (0 to N-1).

The Direct3DRMViewportArray interface supports the following methods.
GetElement
GetSize

The Direct3DRMViewportArray object is obtained by calling the Direct3DRMDevice3.GetViewports method.

Direct3DRMViewportArray.GetElement

Direct3DRMViewportArray

Retrieves a specified element in a Direct3DRMViewportArray object.

Syntax

object.GetElement(index As Long) As Direct3DRMViewport2

Parts

object
Object expression that resolves to a Direct3DRMViewportArray object.
index
Element in the array.

Return Value

An Direct3DRMViewport2 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMViewportArray.GetSize

Direct3DRMViewportArray

Retrieves the number of elements contained in a Direct3DRMViewportArray object.

Syntax

object.GetSize( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMViewportArray object.

Return Value

Returns the number of elements.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.


Direct3DRMViewportInterpolator

Interpolators provide a way of storing actions and applying them to objects with automatic calculation of in-between values. With an interpolator you can blend colors, move objects smoothly between positions, morph meshes, and perform many other transformations.

A Direct3DRMViewport2 object can be attached to a Direct3DRMViewportInterpolator object. For more information on interpolators, see Interpolators in Further Reading.

The Direct3DRMViewportInterpolator interface contains the following methods.

Attaching objects | AttachObject
DetachObject
GetAttachedObjects
Clipping planes | SetBack
SetFront
Field of view | SetField
Interpolating | GetIndex
Interpolate
SetIndex

In addition, Direct3DRMViewportInterpolator inherits the following methods from the Direct3DRMObject interface.

  • AddDestroyCallback
  • Clone
  • DeleteDestroyCallback
  • GetAppData
  • GetClassName
  • GetName
  • SetAppData
  • SetName

Direct3DRMViewportInterpolator.AttachObject

Direct3DRMViewportInterpolator

Connects an object to the interpolator.

Syntax

object.AttachObject(mObject As Direct3DRMObject)

Parts

object
Object expression that resolves to a Direct3DRMViewportInterpolator object.
mObject
Direct3DRMObject object to attach to the interpolator.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

The attached object can be another interpolator or an object of type x where the interpolator is of type xInterpolator. For example, a Direct3DRMViewport2 object can be attached to a Direct3DRMViewportInterpolator object.

Direct3DRMViewportInterpolator.DetachObject

Direct3DRMViewportInterpolator

Detaches an object from the interpolator.

Syntax

object.DetachObject(mObject As Direct3DRMObject)

Parts

object
Object expression that resolves to a Direct3DRMViewportInterpolator object.
mObject
Direct3DRMObject object to detach from the interpolator.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMViewportInterpolator.GetAttachedObjects

Direct3DRMViewportInterpolator

Retrieves the objects currently attached to the interpolator.

Syntax

object.GetAttachedObjects( ) As Direct3DRMObjectArray

Parts

object
Object expression that resolves to a Direct3DRMViewportInterpolator object.

Return Value

Returns a Direct3DRMObjectArray object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMViewportInterpolator.GetIndex

Direct3DRMViewportInterpolator

Retrieves the interpolator's current internal index (time).

Syntax

object.GetIndex( ) As Single

Parts

object
Object expression that resolves to a Direct3DRMViewportInterpolator object.

Return Value

Returns a value that contains the interpolator's current internal index.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Every key stored in an interpolator has an index value. When a key is recorded (by using a method), the key is stamped with the current interpolator index value. The key's index value does not change after being stamped.

Direct3DRMViewportInterpolator.Interpolate

Direct3DRMViewportInterpolator

Generates a series of actions by interpolating between keys stored in the interpolator. The actions are then applied to the specified object. If no object is specified, the actions are applied to the currently attached objects.

Syntax

object.Interpolate(val As Single,
  mObject As Direct3DRMObject,
  options As CONST_D3DRMINTERPOLATIONFLAGS)

Parts

object
Object expression that resolves to a Direct3DRMViewportInterpolator object.
val
Value that contains the interpolator's current internal index.
mObject
Direct3DRMObject object that will be assigned interpolated values for all properties stored in the interpolator. Can be NOTHING, in which case the property values of all attached objects will be set to interpolated values.
options
One of the values from the CONST_D3DRMINTERPOLATIONFLAGS enumerated type that controls the kind of interpolation done.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMViewportInterpolator.SetBack

Direct3DRMViewportInterpolator

Adds a back clipping plane position key to a Direct3DRMViewportInterpolator object.

Syntax

object.SetBack(v As Single)

Parts

object
Object expression that resolves to a Direct3DRMViewportInterpolator object.
v
Distance between the camera and the back clipping plane. The default value is 100. Reasonable values depend on other viewing frustum settings.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMViewportInterpolator.SetField

Direct3DRMViewportInterpolator

Adds a field of view key to a Direct3DRMViewportInterpolator object.

Syntax

object.SetField(v As Single)

Parts

object
Object expression that resolves to a Direct3DRMViewportInterpolator object.
v
New field of view. This value is a fraction of the viewing angle. The default value is 0.5. If this value is less than or equal to zero, this method returns the D3DRMERR_BADVALUE error. The viewing angle is defined as 2 times the arctangent of the front clipping plane over the distance from the camera.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMViewportInterpolator.SetFront

Direct3DRMViewportInterpolator

Adds a front clipping plane position key to a Direct3DRMViewportInterpolator object.

Syntax

object.SetFront(v As Single)

Parts

object
Object expression that resolves to a Direct3DRMViewportInterpolator object.
v
Distance from the camera to the front clipping plane. The default value is 1.0. Reasonable values depend on other viewing frustum settings.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMViewportInterpolator.SetIndex

Direct3DRMViewportInterpolator

Sets the interpolator's internal index (time) to the specified value. If other interpolators are attached to the interpolator, this method recursively synchronizes their indices to the same value.

Syntax

object.SetIndex(val As Single)

Parts

object
Object expression that resolves to a Direct3DRMViewportInterpolator object.
val
Time to set for the interpolator's internal index.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Every key stored in an interpolator has an index value. When a key is recorded (by using a method), the key is stamped with the current interpolator index value. The key's index value does not change after being stamped.


Direct3DRMVisual

Direct3DRMVisual does not provide any Microsoft® Direct3D® Retained Mode methods, but the interfaces for the visual objects derive from the Direct3DRMVisual interface.

Visuals are objects that can be rendered in a scene. Visuals are visible only when they are added to a frame in that scene. An application can add a visual to a frame by using the Direct3DRMFrame3.AddVisual method. The frame provides the visual with position and orientation for rendering.

A visual can be cast through the following code.

Sub test(visual As Direct3DRMVisual)
    Dim mb As Direct3DRMMeshBuilder3
    Dim mesh As Direct3DRMMesh
    Dim pmesh As Direct3DRMProgressiveMesh
    Dim shadow As Direct3DRMShadow2

    Select Case UCase(visual.GetClassName())
        Case "MESHBUILDER"
            Set mb = visual
        Case "MESH"
            Set mesh = visual
        Case "PROGRESSIVEMESH"
            Set pmesh = visual
        Case "SHADOW"
            Set shadow = visual
    End Select

    'Do whatever

End Sub

The following interfaces derive from Direct3DRMVisual.

  • Direct3DRMFrame3
  • Direct3DRMMesh
  • Direct3DRMProgressiveMesh
  • Direct3DRMShadow2
  • Direct3DRMTexture3


Direct3DRMVisualArray

Applications use the methods of the Direct3DRMVisualArray interface to organize groups of visual objects. The visual array is zero based (0 to N-1).

Visuals are objects that can be rendered in a scene. Visuals are visible only when they are added to a frame in that scene. An application can add a visual to a frame by using the Direct3DRMFrame3.AddVisual method. The frame provides the visual with position and orientation for rendering.

The most common visual types are Direct3DRMMeshBuilder3 and Direct3DRMTexture3 objects.

The Direct3DRMVisualArray interface supports the following methods.
GetElement
GetSize

The Direct3DRMVisualArray object is obtained by calling the Direct3DRMFrame3.GetVisuals method.

Direct3DRMVisualArray.GetElement

Direct3DRMVisualArray

Retrieves a specified element in a Direct3DRMVisualArray object.

Syntax

object.GetElement(index As Long) As Direct3DRMVisual

Parts

object
Object expression that resolves to a Direct3DRMVisualArray object.
index
Element in the array.

Return Value

An Direct3DRMVisual object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMVisualArray.GetSize

Direct3DRMVisualArray

Retrieves the number of elements contained in a Direct3DRMVisualArray object.

Syntax

object.GetSize( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMVisualArray object.

Return Value

Returns the number of elements.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.


Direct3DRMWrap

Applications use the methods of the Direct3DRMWrap interface to work with wrap objects. This section is a reference to the methods of this interface.

The Direct3DRMWrap interface supports the following methods.

  • Apply
  • ApplyRelative

The Direct3DRMWrap interface inherits the following methods from the Direct3DRMObject interface.
AddDestroyCallback
CloneObject
DeleteDestroyCallback
GetAppData
GetClassName
GetName
SetAppData
SetName

The Direct3DRMWrap object is obtained by using the Direct3DRM3.CreateWrap method.

Direct3DRMWrap.Apply

Direct3DRMWrap

Applies a Direct3DRMWrap object to its destination object. The destination object is typically a face or a mesh.

Syntax

object.Apply(visual As Direct3DRMObject)

Parts

object
Object expression that resolves to a Direct3DRMWrap object.
visual
Destination object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRM3.CreateWrap

Direct3DRMWrap.ApplyRelative

Direct3DRMWrap

Applies the wrap to the vertices of the object; first transforming each vertex by the frame's world transformation and the inverse world transformation of the wrap's reference frame.

Syntax

object.ApplyRelative(f As Direct3DRMFrame3,
  visual As Direct3DRMObject)

Parts

object
Object expression that resolves to a Direct3DRMWrap object.
f
The Direct3DRMFrame object containing the object to wrap.
visual
Object to apply.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRM3.CreateWrap


Visual Basic Enumerations

The Microsoft® Direct3D® Retained Mode enumerated types for Microsoft Visual Basic® are:

  • CONST_D3DRMADDFACESFLAGS
  • CONST_D3DRMADDMESHBUILDERFLAGS
  • CONST_D3DRMADDTRIANGLESFLAGS
  • CONST_D3DRMADDTRIANGLESVT
  • CONST_D3DRMANIMATIONFLAGS
  • CONST_D3DRMCALLBACKORDERFLAGS
  • CONST_D3DRMCOLORSOURCE
  • CONST_D3DRMCOMBINETYPE
  • CONST_D3DRMCREATEDEVICEFLAGS
  • CONST_D3DRMFOGMETHOD
  • CONST_D3DRMFOGMODE
  • CONST_D3DRMFPTFFLAGS
  • CONST_D3DRMFRAMECONSTRAINT
  • CONST_D3DRMGENERATENORMALSFLAGS
  • CONST_D3DRMHANDEDNESS
  • CONST_D3DRMINTERPOLATIONFLAGS
  • CONST_D3DRMLIGHTTYPE
  • CONST_D3DRMLOADFLAGS
  • CONST_D3DRMMAPPINGFLAGS
  • CONST_D3DRMMATERIALMODE
  • CONST_D3DRMMATERIALOVERRIDEFLAGS
  • CONST_D3DRMMESHBUILDERAGEFLAGS
  • CONST_D3DRMMESHBUILDERENABLEFLAGS
  • CONST_D3DRMPALETTEFLAGS
  • CONST_D3DRMPARENTINGFLAGS
  • CONST_D3DRMPMESHEVENTFLAGS
  • CONST_D3DRMPMESHSTATUSFLAGS
  • CONST_D3DRMPROJECTIONTYPE
  • CONST_D3DRMRAYPICKFLAGS
  • CONST_D3DRMRENDERMODEFLAGS
  • CONST_D3DRMRENDERQUALITY
  • CONST_D3DRMSAVEFLAGS
  • CONST_D3DRMSORTMODE
  • CONST_D3DRMSTATECHANGEFLAGS
  • CONST_D3DRMTEXTURECACHEFLAGS
  • CONST_D3DRMTEXTURECHANGEDFLAGS
  • CONST_D3DRMTEXTUREQUALITY
  • CONST_D3DRMTRAVERALFLAGS
  • CONST_D3DRMVIEWPORTCLEARFLAGS
  • CONST_D3DRMWIREFRAMEFLAGS
  • CONST_D3DRMWRAPTYPE
  • CONST_D3DRMXOFFORMAT
  • CONST_D3DRMZBUFFERMODE

CONST_D3DRMADDFACESFLAGS

Specifies how normal indexes should be handled.

Syntax

Enum CONST_D3DRMADDFACESFLAGS
  D3DRMADDFACES_DEFAULT
  D3DRMADDFACES_VERTICESONLY
End Enum

Values

D3DRMADDFACES_DEFAULT
Indexes of pre-existing normals will be used.
D3DRMADDFACES_VERTICESONLY
The normal with the corresponding index will be used automatically for each vertex.

CONST_D3DRMADDMESHBUILDERFLAGS

Indicates the copying options.

Syntax

Enum CONST_D3DRMADDMESHBUILDERFLAGS
  D3DRMADDMESHBUILDER_DONTCOPYAPPDATA  = 1
  D3DRMADDMESHBUILDER_FLATTENSUBMESHES = 2
  D3DRMADDMESHBUILDER_NOSUBMESHES      = 4
End Enum

Values

D3DRMADDMESHBUILDER_DONTCOPYAPPDATA
By default, Direct3DRMMeshBuilder3.AddMeshBuilder copies the application data of source meshbuilders to the destination. Specifying D3DRMADDMESHBUILDER_DONTCOPYAPPDATA prevents this from occurring.
D3DRMADDMESHBUILDER_FLATTENSUBMESHES
Causes the submesh objects not to be duplicated. Their faces are still copied, but only to the top level of the destination meshbuilder.
D3DRMADDMESHBUILDER_NOSUBMESHES
Causes sub-meshbuilders to be ignored.

CONST_D3DRMADDTRIANGLESFLAGS

Indicates options for the newly formed triangle.

Syntax

Enum CONST_D3DRMADDTRIANGLESFLAGS
  D3DRMVERTEX_STRIP = 1
  D3DRMVERTEX_FAN   = 2
  D3DRMVERTEX_LIST  = 4
End Enum

Values

D3DRMVERTEX_STRIP
Forms a new triangle in strip format with the previous two vertices.
D3DRMVERTEX_FAN
Forms a new triangle with the previous vertex and the first vertex in the fan.
D3DRMVERTEX_LIST
Starts a new list or is a member of a previously started list. If the previous vertex (or the vertex previous to that) was not marked with this flag, the following vertices must be marked with this flag until at least one triangle is formed.

CONST_D3DRMADDTRIANGLESVT

Indicates which methods to include in the description for each element.

Syntax

Enum CONST_D3DRMADDTRIANGLESVT
  D3DRMFVF_TYPE          = 1
  D3DRMFVF_NORMAL        = 2
  D3DRMFVF_COLOR         = 4
  D3DRMFVF_TEXTURECOORDS = 8
End Enum

Values

D3DRMFVF_TYPE
Value from the CONST_D3DRMADDTRIANGLESFLAGS enumerated type.
D3DRMFVF_NORMAL
Include the normal member.
D3DRMFVF_COLOR
Include the color member.
D3DRMFVF_TEXTURECOORDS
Include the tu and tv members.

CONST_D3DRMANIMATIONFLAGS

Sets the animation options.

Syntax

Enum CONST_D3DRMANIMATIONFLAGS
  D3DRMANIMATION_OPEN             = 1
  D3DRMANIMATION_CLOSED           = 2
  D3DRMANIMATION_LINEARPOSITION   = 4
  D3DRMANIMATION_SPLINEPOSITION   = 8
  D3DRMANIMATION_SCALEANDROTATION = 16 (&H10)
  D3DRMANIMATION_POSITION         = 32 (&H20)
End Enum

Values

D3DRMANIMATION_OPEN
Animation plays once and stops.
D3DRMANIMATION_CLOSED
Animation plays continually, looping back to the beginning when it reaches the end. In a closed animation, if you want a smooth transition from the end to the beginning, the last key in the animation should be a repeat of the first. This repeated key indicates the time difference between the last and first keys in the looping animation. However, if the last key is not a repeat of the first, the new interfaces (Direct3DRMAnimation2, Direct3DRMAnimationSet2) will no longer ignore it. It takes effect, and then the animation jumps immediately back to the beginning.
D3DRMANIMATION_LINEARPOSITION
Animation's position is set linearly.
D3DRMANIMATION_SPLINEPOSITION
Animation's position is set using splines.
D3DRMANIMATION_SCALEANDROTATION
Animation's scale and rotation matrix should overwrite any transformation matrices set by other methods.
D3DRMANIMATION_POSITION
Animation's position matrix should overwrite any transformation matrices set by other methods.

CONST_D3DRMCALLBACKORDERFLAGS

Used by the Direct3DRMFrame3.AddMoveCallback method to specify whether callbacks for a frame are used before or after the child frames are traversed.

Syntax

Enum CONST_D3DRMCALLBACKORDERFLAGS
  D3DRMCALLBACK_PREORDER
  D3DRMCALLBACK_POSTORDER
End Enum

Values

D3DRMCALLBACK_PREORDER
The default value. When the Direct3DRMFrame3.Move method traverses the hierarchy, callbacks for a frame are used before any child frames are traversed.
D3DRMCALLBACK_POSTORDER
When Move traverses the hierarchy, callbacks for a frame are used after the child frames are traversed.

CONST_D3DRMCOLORSOURCE

Describes the color source of a Direct3DRMMeshBuilder3 object. You can set the color source by using the Direct3DRMMeshBuilder3.SetColorSource method. To retrieve it, use the Direct3DRMMeshBuilder3.GetColorSource method.

Syntax

Enum CONST_D3DRMCOLORSOURCE
  D3DRMCOLOR_FROMFACE
  D3DRMCOLOR_FROMVERTEX
End Enum

Values

D3DRMCOLOR_FROMFACE
Object's color source is a face.
D3DRMCOLOR_FROMVERTEX
Object's color source is a vertex.

CONST_D3DRMCOMBINETYPE

Specifies how to combine two matrices.

Syntax

Enum CONST_D3DRMCOMBINETYPE
  D3DRMCOMBINE_REPLACE
  D3DRMCOMBINE_BEFORE
  D3DRMCOMBINE_AFTER
End Enum

Values

D3DRMCOMBINE_REPLACE
Supplied matrix replaces the frame's current matrix.
D3DRMCOMBINE_BEFORE
Supplied matrix is multiplied with the frame's current matrix and precedes the current matrix in the calculation.
D3DRMCOMBINE_AFTER
Supplied matrix is multiplied with the frame's current matrix and follows the current matrix in the calculation.

Remarks

The order of the supplied and current matrices when they are multiplied is important because matrix multiplication is not commutative.

See Also

Direct3DRMFrame3.AddRotation, Direct3DRMFrame3.AddScale, Direct3DRMFrame3.AddTransform, Direct3DRMFrame3.AddTranslation

CONST_D3DRMCREATEDEVICEFLAGS

Defines options when creating a Direct3DRMDevice3 object.

Syntax

Enum CONST_D3DRMCREATEDEVICEFLAGS
  D3DRMDEVICE_DEFAULT
  D3DRMDEVICE_NOZBUFFER
End Enum

Values

D3DRMDEVICE_DEFAULT
Use default options.
D3DRMDEVICE_NOZBUFFER
Z-buffering not enabled.

CONST_D3DRMFOGMETHOD

Indicates the current fogging method.

Syntax

Enum CONST_D3DRMFOGMETHOD
  D3DRMFOGMETHOD_VERTEX = 1
  D3DRMFOGMETHOD_TABLE  = 2
  D3DRMFOGMETHOD_ANY    = 4
End Enum

Values

D3DRMFOGMETHOD_VERTEX
Use vertex fog.
D3DRMFOGMETHOD_TABLE
Use table fog.
D3DRMFOGMETHOD_ANY
Direct3D Retained Mode should choose an applicable method.

CONST_D3DRMFOGMODE

Contains values that specify how rapidly and in what ways the fog effect intensifies with increasing distance from the camera.

In monochromatic (ramp) lighting mode, fog works properly only when the fog color is black. (If there is no lighting, any fog color will work, because in this case any fog color is effectively black.)

Syntax

Enum CONST_D3DRMFOGMODE
  D3DRMFOG_LINEAR
  D3DRMFOG_EXPONENTIAL
  D3DRMFOG_EXPONENTIALSQUARED
End Enum

Values

D3DRMFOG_LINEAR
Fog effect intensifies linearly between the start and end points, according to the following formula.

Equation showing linear increase of fog effect with distance

This is the only fog mode currently supported.

D3DRMFOG_EXPONENTIAL
Fog effect intensifies exponentially, according to the following formula.

Equation showing exponential increase of fog effect with distance

D3DRMFOG_EXPONENTIALSQUARED
Fog effect intensifies exponentially with the square of the distance, according to the following formula.

Equation showing exponential increase of fog effect with distance squared

Remarks

Fog can be considered a measure of visibility—the lower the fog value produced by one of the fog equations, the less visible an object will be.

You can specify the fog's density and start and end points by using the Direct3DRMFrame3.SetSceneFogParams method. In the formulas for the exponential fog modes, e is the base of the natural logarithms; its value is approximately 2.71828.

See Also

Direct3DRMFrame3.SetSceneFogMode

CONST_D3DRMFPTFFLAGS

Sets options for the returned texture format.

Syntax

Enum CONST_D3DRMFPTFFLAGS
  D3DRMFPTF_ALPHA         = 1
  D3DRMFPTF_NOALPHA       = 2
  D3DRMFPTF_PALETTIZED    = 4
  D3DRMFPTF_NOTPALETTIZED = 8
End Enum

Values

D3DRMFPTF_ALPHA
The returned texture format must have an alpha channel.
D3DRMFPTF_NOALPHA
The returned texture format must not have an alpha channel. Omit both the D3DRMFPTF_ALPHA and D3DRMFPTF_NOALPHA flags to indicate that the absence of an alpha channel is preferred but not required.
D3DRMFPTF_PALETTIZED
The returned texture format must be palettized.
D3DRMFPTF_NOTPALETTIZED
The returned texture format must not be palettized. Omit both the D3DRMFPTF_PALETTIZED and D3DRMFPTF_NOTPALETTIZED flags to indicate that the absence of a palette is preferred but not required.

CONST_D3DRMFRAMECONSTRAINT

Describes the axes of rotation to constrain when viewing a Direct3DRMFrame3 object. The Direct3DRMFrame3.LookAt method uses this enumerated type.

Syntax

Enum CONST_D3DRMFRAMECONSTRAINT
  D3DRMCONSTRAIN_Z
  D3DRMCONSTRAIN_Y
  D3DRMCONSTRAIN_X
End Enum

Values

D3DRMCONSTRAIN_Z
Use only x-axis and y-axis rotations.
D3DRMCONSTRAIN_Y
Use only x-axis and z-axis rotations.
D3DRMCONSTRAIN_X
Use only y-axis and z-axis rotations.

CONST_D3DRMGENERATENORMALSFLAGS

Specifies values used by the Direct3DRMMeshBuilder3.GenerateNormals method to define how normals are generated.

Syntax

Enum CONST_D3DRMGENERATENORMALSFLAGS
  D3DRMGENERATENORMALS_PRECOMPACT     = 1
  D3DRMGENERATENORMALS_USECREASEANGLE = 2
End Enum

Values

D3DRMGENERATENORMALS_PRECOMPACT
Algorithm should attempt to compact mesh vertices before it generates normals.
D3DRMGENERATENORMALS_USECREASEANGLE
The parameter indicating the crease angle should be used; otherwise it is ignored.

CONST_D3DRMHANDEDNESS

Indicates the current options for the Direct3D Retained Mode coordinate system.

Syntax

Enum CONST_D3DRMHANDEDNESS
  D3DRMOPTIONS_LEFTHANDED  = 1
  D3DRMOPTIONS_RIGHTHANDED = 2
End Enum

Values

D3DRMOPTIONS_LEFTHANDED
Use left-handed geometry. This value is the default.
D3DRMOPTIONS_RIGHTHANDED
Use right-handed geometry.

Remarks

D3DRMOPTIONS_LEFTHANDED and D3DRMOPTIONS_RIGHTHANDED affect picking, ray picking, and the following interfaces.

  • Direct3DRMClippedVisual
  • Direct3DRMMesh
  • Direct3DRMMeshBuilder3
  • Direct3DRMProgressiveMesh
  • Direct3DRMShadow2
  • Direct3DRMTexture3
  • Direct3DRMViewport2

CONST_D3DRMINTERPOLATIONFLAGS

Defines options for the Interpolate method on interpolator objects, modifying how the object is loaded.

Syntax

Enum CONST_D3DRMINTERPOLATIONFLAGS
  D3DRMINTERPOLATION_OPEN         = 1
  D3DRMINTERPOLATION_CLOSED       = 2
  D3DRMINTERPOLATION_LINEAR       = 4
  D3DRMINTERPOLATION_SPLINE       = 8
  D3DRMINTERPOLATION_VERTEXCOLOR  = 64 (&H40)
  D3DRMINTERPOLATION_SLERPNORMALS = 128 (&H80)
  D3DRMINTERPOLATION_NEAREST      = 256 (&H100)
End Enum

Values

D3DRMINTERPOLATION_OPEN
First and last keys of each key chain (execution thread) will fix the interpolated values outside the index span.
D3DRMINTERPOLATION_CLOSED
Interpolation is cyclic. The keys effectively repeat infinitely with a period equal to the index span. For compatibility with animations, any key with an index equal to the end of the span is ignored.
D3DRMINTERPOLATION_LINEAR
Linear interpolation between the two nearest keys is used for determining in-between values on each key chain.
D3DRMINTERPOLATION_SPLINE
B-spline blending function on the four nearest keys is used for determining in-between values on each key chain.
D3DRMINTERPOLATION_VERTEXCOLOR
Vertex colors should be interpolated. Only affects the interpolation of Direct3DRMMesh.SetVertices.
D3DRMINTERPOLATION_SLERPNORMALS
Vertex normals should be spherically interpolated (not currently implemented). Only affects the interpolation of SetVertices.
D3DRMINTERPOLATION_NEAREST
Nearest key value is used for determining in-between values on each key chain.

CONST_D3DRMLIGHTTYPE

Defines the light type used in the Direct3DRM3.CreateLight method.

Syntax

Enum CONST_D3DRMLIGHTTYPE
  D3DRMLIGHT_AMBIENT
  D3DRMLIGHT_POINT
  D3DRMLIGHT_SPOT
  D3DRMLIGHT_DIRECTIONAL
  D3DRMLIGHT_PARALLELPOINT
End Enum

Values

D3DRMLIGHT_AMBIENT
Light is an ambient source.
D3DRMLIGHT_POINT
Light is a point source.
D3DRMLIGHT_SPOT
Light is a spotlight source.
D3DRMLIGHT_DIRECTIONAL
Light is a directional source.
D3DRMLIGHT_PARALLELPOINT
Light is a parallel point source.

CONST_D3DRMLOADFLAGS

Defines options for the Direct3DRM3.LoadFromFile, Direct3DRMAnimationSet2.LoadFromFile, Direct3DRMFrame3.LoadFromFile, Direct3DRMMeshBuilder3.LoadFromFile, and Direct3DRMProgressiveMesh.LoadFromFile methods. These options modify how the object is loaded.

Syntax

Enum CONST_D3DRMLOADFLAGS
  D3DRMLOAD_FROMFILE            = 0
  D3DRMLOAD_FROMRESOURCE        = 1
  D3DRMLOAD_FROMMEMORY          = 2
  D3DRMLOAD_FROMSTREAM          = 4
  D3DRMLOAD_FROMUR              = 8
  D3DRMLOAD_BYNAME              = 16 (&H10)
  D3DRMLOAD_BYPOSITION          = 32 (&H20)
  D3DRMLOAD_BYGUID              = 64 (&H40)
  D3DRMLOAD_FIRST               = 128 (&H80)
  D3DRMLOAD_INSTANCEBYREFERENCE = 256 (&H100)
  D3DRMLOAD_INSTANCEBYCOPYING   = 512 (&H200)
  D3DRMLOAD_ASYNCHRONOUS        = 1024 (&H400)
End Enum

Values

Source flags:

D3DRMLOAD_FROMFILE
Load from a file. This is the default setting.
D3DRMLOAD_FROMRESOURCE
Load from a resource.
D3DRMLOAD_FROMMEMORY
Load from memory.
D3DRMLOAD_FROMSTREAM
Load from stream.
D3DRMLOAD_FROMUR
Load from a URL.

Identifier flags:

D3DRMLOAD_BYNAME
Load any object by using a specified name.
D3DRMLOAD_BYPOSITION
Load a stand-alone object based on a given zero-based position (that is, the nth object in the file). Stand-alone objects can contain other objects, but are not contained by any other objects.
D3DRMLOAD_BYGUID
Load any object by using a specified globally unique identifier (GUID).
D3DRMLOAD_FIRST
Default setting. Load the first stand-alone object of the given type (for example, a mesh if the application uses Direct3DRMMeshBuilder3.LoadFromFile). Stand-alone objects can contain other objects, but are not contained by any other objects.

Instance flags:

D3DRMLOAD_INSTANCEBYREFERENCE
Check whether an object already exists with the same name as specified and, if so, use an instance of that object instead of creating a new one.
D3DRMLOAD_INSTANCEBYCOPYING
Check whether an object already exists with the same name as specified and, if so, copy that object.

Load flag:

D3DRMLOAD_ASYNCHRONOUS
LoadFromFile call will return immediately. It is up to the application to use events to find out how the load is progressing. By default, loading is done synchronously, and the LoadFromFile call will not return until all data has been loaded or an error occurs.

Remarks

Each of the LoadFromFile methods uses a filename parameter to specify the source of the object and an id parameter to identify the object. The system interprets the contents of the filename parameter based on the choice of source flags, and it interprets the contents of the id parameter based on the choice of identifier flags.

The instance flags do not change the interpretation of any of the parameters. By using the D3DRMLOAD_INSTANCEBYREFERENCE flag, an application can load the same file twice without creating any new objects. If an object does not have a name, setting the D3DRMLOAD_INSTANCEBYREFERENCE flag has the same effect as setting the D3DRMLOAD_INSTANCEBYCOPYING flag—the loader creates each unnamed object as a new one, even if some of the objects are identical.

CONST_D3DRMMAPPINGFLAGS

Specifies values used by the Direct3DRMMesh.GetGroupMapping and Direct3DRMMesh.SetGroupMapping methods to define how textures are mapped to a group.

Syntax

Enum CONST_D3DRMMAPPINGFLAGS
  D3DRMMAP_WRAPU        = 1
  D3DRMMAP_WRAPV        = 2
  D3DRMMAP_PERSPCORRECT = 4
End Enum

Values

D3DRMMAP_WRAPU
Texture wraps in the u-direction.
D3DRMMAP_WRAPV
Texture wraps in the v-direction.
D3DRMMAP_PERSPCORRECT
Texture wrapping is perspective-corrected.

Remarks

The D3DRMMAP_WRAPU and D3DRMMAP_WRAPV flags determine how the rasterizer interprets texture coordinates. The rasterizer always interpolates the shortest distance between texture coordinates; that is, a line. The path taken by this line, and the valid values for the u- and v-coordinates, vary with the use of the wrapping flags. Setting these flags causes the line to wrap around the texture edge in the u- or v- direction, as if the texture had a cylindrical or toroidal topology.

If either D3DRMMAP_WRAPU or D3DRMMAP_WRAPV is set, the texture is a cylinder with an infinite length and a circumference of 1.0. Texture coordinates greater than 1.0 are valid only in the dimension that is not wrapped. The shortest distance between texture coordinates varies with the wrapping flag; if D3DRMMAP_WRAPU is set, the shortest line between (0.1, 0.1) and (0.9, 0.9) passes through (0, 0.5).

If both D3DRMMAP_WRAPU and D3DRMMAP_WRAPV are set, the texture is a torus. Because the system is closed, texture coordinates greater that 1.0 are invalid. The shortest line between (0.1, 0.1) and (0.9, 0.9) passes through (0, 0).

CONST_D3DRMMATERIALMODE

Describes the source of material information for visuals rendered with a frame.

Syntax

Enum CONST_D3DRMMATERIALMODE
  D3DRMMATERIAL_FROMMESH
  D3DRMMATERIAL_FROMPARENT
  D3DRMMATERIAL_FROMFRAME
End Enum

Values

D3DRMMATERIAL_FROMMESH
Material information is retrieved from the visual object (the mesh) itself. This is the default setting.
D3DRMMATERIAL_FROMPARENT
Material information, along with color or texture information, is inherited from the parent frame.
D3DRMMATERIAL_FROMFRAME
Material information is retrieved from the frame, overriding any previous material information that the visual object might have possessed.

See Also

Direct3DRMFrame3.GetMaterialMode, Direct3DRMFrame3.SetMaterialMode

CONST_D3DRMMATERIALOVERRIDEFLAGS

Sets specific material attributes.

Syntax

Enum CONST_D3DRMMATERIALOVERRIDEFLAGS
  D3DRMMATERIALOVERRIDE_DIFFUSE_ALPHAONLY     = 1
  D3DRMMATERIALOVERRIDE_DIFFUSE_RGBONLY       = 2
  D3DRMMATERIALOVERRIDE_DIFFUSE               = 3
  D3DRMMATERIALOVERRIDE_AMBIENT               = 4
  D3DRMMATERIALOVERRIDE_EMISSIVE              = 8
  D3DRMMATERIALOVERRIDE_SPECULAR              = 16 (&H10)
  D3DRMMATERIALOVERRIDE_POWER                 = 32 (&H20)
  D3DRMMATERIALOVERRIDE_TEXTURE               = 64 (&H40)
  D3DRMMATERIALOVERRIDE_DIFFUSE_ALPHAMULTIPLY = 128 (&H80)
  D3DRMMATERIALOVERRIDE_ALL                   = 255 (&HFF)
End Enum

Values

D3DRMMATERIALOVERRIDE_DIFFUSE_ALPHAONLY
Override the diffuse alpha value of the material only.
D3DRMMATERIALOVERRIDE_DIFFUSE_RGBONLY
Override the diffuse RGB values of the material only.
D3DRMMATERIALOVERRIDE_DIFFUSE
Override the diffuse property of the material.
D3DRMMATERIALOVERRIDE_AMBIENT
Override the ambient property of the material.
D3DRMMATERIALOVERRIDE_EMISSIVE
Override the emissive property of the material.
D3DRMMATERIALOVERRIDE_SPECULAR
Override the specular property of the material.
D3DRMMATERIALOVERRIDE_POWER
Override the specular power property of the material.
D3DRMMATERIALOVERRIDE_TEXTURE
Override the texture property of the material.
D3DRMMATERIALOVERRIDE_DIFFUSE_ALPHAMULTIPLY
Override the diffuse alpaha multiply property of the material.
D3DRMMATERIALOVERRIDE_ALL
Override all properties of the material.

CONST_D3DRMMESHBUILDERAGEFLAGS

Indicates the the aging options for the meshbuilder. The default value is zero, which indicates that the meshbuilder ages normally (that is, any change to the meshbuilder causes aging).

Syntax

Enum CONST_D3DRMMESHBUILDERAGEFLAGS
  D3DRMMESHBUILDERAGE_GEOMETRY  = 1
  D3DRMMESHBUILDERAGE_MATERIALS = 2
  D3DRMMESHBUILDERAGE_TEXTURES  = 4
End Enum

Values

D3DRMMESHBUILDERAGE_GEOMETRY
The meshbuilder ages whenever the mesh geometry is changed (for example, addition of vertices, faces, or another meshbuilder).
D3DRMMESHBUILDERAGE_MATERIALS
The meshbuilder ages whenever a material-related property of the mesh changes, or when faces or another mesh are added.
D3DRMMESHBUILDERAGE_TEXTURES
The meshbuilder ages whenever a texture-related property of the mesh changes, or when faces or another mesh are added.

CONST_D3DRMMESHBUILDERENABLEFLAGS

Indicates whether rendering and picking are enabled.

Syntax

Enum CONST_D3DRMMESHBUILDERENABLEFLAGS
  D3DRMMESHBUILDER_RENDERENABLE = 1
  D3DRMMESHBUILDER_PICKENABLE   = 2
End Enum

Values

D3DRMMESHBUILDER_RENDERENABLE
Rendering is enabled on the current object. This setting is the default.
D3DRMMESHBUILDER_PICKENABLE
Picking is enabled on the current object. This setting is the default.

CONST_D3DRMPALETTEFLAGS

Defines how a color can be used. When creating a palette through Microsoft DirectDraw® and using it in Direct3D Retained Mode, you can set the palette flags for a palette entry and mark whether this entry can be changed by Retained Mode.

Syntax

Enum CONST_D3DRMPALETTEFLAGS
  D3DRMPALETTE_FREE
  D3DRMPALETTE_READONLY
  D3DRMPALETTE_RESERVED
End Enum

Values

D3DRMPALETTE_FREE
Renderer can use this entry freely.
D3DRMPALETTE_READONLY
Fixed but can be used by renderer.
D3DRMPALETTE_RESERVED
Cannot be used by renderer.

CONST_D3DRMPARENTINGFLAGS

Defines which Direct3DRMMeshBuilder3 object to retrieve.

Syntax

Enum CONST_D3DRMPARENTINGFLAGS
  D3DRMMESHBUILDER_DIRECTPARENT = 1
  D3DRMMESHBUILDER_ROOTMESH     = 2
End Enum

Values

D3DRMMESHBUILDER_DIRECTPARENT
Retrieve the direct parent of the current Direct3DRMMeshBuilder3 object.
D3DRMMESHBUILDER_ROOTMESH
Retrieve the final parent (the parent which itself has no parents) of the current Direct3DRMMeshBuilder3 object.

CONST_D3DRMPMESHEVENTFLAGS

Used by Direct3DRMProgressiveMesh.RegisterEvents either to signal when the base mesh has been downloaded, or to signal when all data has been downloaded.

Syntax

Enum CONST_D3DRMPMESHEVENTFLAGS
  D3DRMPMESHEVENT_BASEMESH = 1
  D3DRMPMESHEVENT_COMPLETE = 2
End Enum

Values

D3DRMPMESHEVENT_BASEMESH
The event is signaled when the base mesh has been downloaded.
D3DRMPMESHEVENT_COMPLETE
The event is signaled when all data has been downloaded.

CONST_D3DRMPMESHSTATUSFLAGS

Defines the state of the mesh as returned in the Direct3DRMProgressiveMesh.GetLoadStatus method.

Syntax

Enum CONST_D3DRMPMESHSTATUSFLAGS
  D3DRMPMESHSTATUS_VALID            = 1
  D3DRMPMESHSTATUS_INTERRUPTED      = 2
  D3DRMPMESHSTATUS_BASEMESHCOMPLETE = 4
  D3DRMPMESHSTATUS_COMPLETE         = 8
  D3DRMPMESHSTATUS_RENDERABLE       = 16 (&H10)
End Enum

Values

D3DRMPMESHSTATUS_VALID
Data is not corrupt.
D3DRMPMESHSTATUS_INTERRUPTED
Download was interrupted.
D3DRMPMESHSTATUS_BASEMESHCOMPLETE
Base mesh has been downloaded.
D3DRMPMESHSTATUS_COMPLETE
Load is complete.
D3DRMPMESHSTATUS_RENDERABLE
Base mesh has been downloaded and the data is not corrupt.

CONST_D3DRMPROJECTIONTYPE

Defines the type of projection used in a Direct3DRMViewport object. The Direct3DRMViewport2.GetProjection and Direct3DRMViewport2.SetProjection methods use this enumerated type. The right-hand types enable right-handed projection.

Note: use Direct3DRM3.SetOptions to specify right-handed geometry.

The axes of the camera (see Direct3DRMFrame3.SetAxes) are used in both left-handed and right-handed projection to determine what direction the camera is facing.

Syntax

Enum CONST_D3DRMPROJECTIONTYPE
  D3DRMPROJECT_PERSPECTIVE
  D3DRMPROJECT_ORTHOGRAPHIC
  D3DRMPROJECT_RIGHTHANDPERSPECTIVE
  D3DRMPROJECT_RIGHTHANDORTHOGRAPHIC
End Enum

Values

D3DRMPROJECT_PERSPECTIVE
Projection is perspective and left-handed.
D3DRMPROJECT_ORTHOGRAPHIC
Projection is orthographic and left-handed.
D3DRMPROJECT_RIGHTHANDPERSPECTIVE
Projection is perspective and right-handed.
D3DRMPROJECT_RIGHTHANDORTHOGRAPHIC
Projection is orthographic and right-handed.

CONST_D3DRMRAYPICKFLAGS

Specifies values used by the DirectDRMFrame3.RayPick method to calculate the intersection between any visuals and a specified ray.

Syntax

Enum CONST_D3DRMRAYPICKFLAGS
  D3DRMRAYPICK_ONLYBOUNDINGBOXES       = 1
  D3DRMRAYPICK_IGNOREFURTHERPRIMITIVES = 2
  D3DRMRAYPICK_INTERPOLATEUV           = 4
  D3DRMRAYPICK_INTERPOLATECOLOR        = 8
  D3DRMRAYPICK_INTERPOLATENORMAL       = 16 (&H10)
End Enum

Values

Optimization flags:

D3DRMRAYPICK_ONLYBOUNDINGBOXES
Only intersections with bounding boxes of the visuals in the hierarchy are calculated. Does not check for exact face intersections.
D3DRMRAYPICK_IGNOREFURTHERPRIMITIVES
Only intersections closest to the visual that intersects the ray are calculated. Ignores visuals farther away than the closest one found in a search.

Interpolation flags:

D3DRMRAYPICK_INTERPOLATEUV
Interpolate texture coordinates.
D3DRMRAYPICK_INTERPOLATECOLOR
Interpolate color.
D3DRMRAYPICK_INTERPOLATENORMAL
Interpolate normal.

CONST_D3DRMRENDERMODEFLAGS

Specifies the transparency mode for transparent objects.

Syntax

Enum CONST_D3DRMRENDERMODEFLAGS
  D3DRMRENDERMODE_BLENDEDTRANSPARENCY      = 1
  D3DRMRENDERMODE_SORTEDTRANSPARENCY       = 2
  D3DRMRENDERMODE_LIGHTINMODELSPACE        = 8
  D3DRMRENDERMODE_VIEWDEPENDENTSPECULAR    = 16 (&H10)
  D3DRMRENDERMODE_DISABLESORTEDALPHAZWRITE = 32 (&H20)
End Enum

Values

D3DRMRENDERMODE_BLENDEDTRANSPARENCY
Sets the transparency mode to alpha blending. Blended transparency combines two images by adding their color values at each pixel.
D3DRMRENDERMODE_SORTEDTRANSPARENCY
Sets the transparency mode so that transparent polygons in the scene are buffered, sorted, and rendered in a second pass. This flag has no effect if the D3DRMRENDERMODE_BLENDEDTRANSPARENCY flag is not also set. Transparent polygons in external visuals or user visuals are not sorted. Only native Retained Mode visuals (such as D3DRMMesh objects and D3DRMMeshBuilder objects) are sorted.
D3DRMRENDERMODE_LIGHTINMODELSPACE
Sets the transparency mode so that light is rendered in model space.
D3DRMRENDERMODE_VIEWDEPENDENTSPECULAR
Sets the transparency mode to view dependent specular.
D3DRMRENDERMODE_DISABLESORTEDALPHAZWRITE
Sets the transparency mode so that sorting is disabled.

Remarks

If the D3DRMRENDERMODE_BLENDEDTRANSPARENCY and D3DRMRENDERMODE_SORTEDTRANSPARENCY flags are set together, it ensures that when two transparent objects are rendered one on top of the other, the image will blend in the correct order to ensure the right visual result.

The D3DRMRENDERMODE_SORTEDTRANSPARENCY flag turns on per-triangle back-to-front sorting of alpha polygons.

The D3DRMRENDERMODE_BLENDEDTRANSPARENCY flag turns on true alpha blending as opposed to stippled alpha. In true alpha blending, the pixels of overlapping triangles are blended together. In stippled alpha, some pixels from the triangle in front are not drawn, revealing the triangle below. When doing stippled alpha, it is not necessary to sort triangles because the result is the same no matter what order triangles are rendered.

CONST_D3DRMRENDERQUALITY

Defines quality options set by the Direct3DRMDevice3.SetQuality, Direct3DRMMeshBuilder3.SetQuality, and Direct3DRMProgressiveMesh.SetQuality methods. Additionally, CONST_D3DRMRENDERQUALITY defines the fill mode, the light mode, and the shade mode.

Syntax

Enum CONST_D3DRMRENDERQUALITY
  D3DRMFILL_POINTS      = 0
  D3DRMFILL_WIREFRAME   = 64(&H40)
  D3DRMFILL_SOLID       = 128(&H80)
  D3DRMFILL_MASK        = 448(&H1C0)
  D3DRMFILL_MAX         = 512(&H200)

  D3DRMLIGHT_OFF        = 0
  D3DRMLIGHT_ON         = 8
  D3DRMLIGHT_MASK       = 56(&H38)
  D3DRMLIGHT_MAX        = 64(&H40)

  D3DRMRENDER_WIREFRAME = 64  (&H40)
  D3DRMRENDER_UNLITFLAT = 128 (&H80)
  D3DRMRENDER_FLAT      = 136 (&H88)
  D3DRMRENDER_GOURAUD   = 137 (&H89)
  D3DRMRENDER_PHONG     = 138 (&H8A)

  D3DRMSHADE_FLAT       = 0
  D3DRMSHADE_GOURAUD    = 1
  D3DRMSHADE_PHONG      = 2
  D3DRMSHADE_MASK       = 7
  D3DRMSHADE_MAX        = 8
End Enum

Values

D3DRMFILL_POINTS
Fill points only; minimum fill mode.
D3DRMFILL_WIREFRAME
Fill wire frames.
D3DRMFILL_SOLID
Fill solid objects.
D3DRMFILL_MASK
Fill using a mask.
D3DRMFILL_MAX
Maximum value for fill mode.
D3DRMLIGHT_OFF
Lighting is off.
D3DRMLIGHT_ON
Lighting is on.
D3DRMLIGHT_MASK
Lighting uses a mask.
D3DRMLIGHT_MAX
Maximum lighting mode.
D3DRMRENDER_WIREFRAME
Specifies wire-frame fill mode.
D3DRMRENDER_UNLITFLAT
Specifies flat shading and lights off.
D3DRMRENDER_FLAT
Specifies flat shading, lights on, and solid fill.
D3DRMRENDER_GOURAUD
Specifies Gouraud shading, lights on, and solid fill.
D3DRMRENDER_PHONG
Not implemented, defaults to Gouraud shading.
D3DRMSHADE_FLAT
Render object with flat shading. This is the default setting.
D3DRMSHADE_GOURAUD
Render object with Gouraud shading.
D3DRMSHADE_PHONG
Render object with Phong shading.
D3DRMSHADE_MASK
Render object with mask shading.
D3DRMSHADE_MAX
Render object with maximum shading.

Remarks

The rendering quality is the maximum quality at which rendering can take place on the rendering surface of that device.

An object's quality has three components: shade mode (flat or Gouraud), lighting type (on or off), and fill mode (point, wire frame, or solid).

CONST_D3DRMSAVEFLAGS

Defines save options for the Direct3DRMMeshBuilder3.Save method.

Syntax

Enum CONST_D3DRMSAVEFLAGS
  D3DRMXOFSAVE_NORMALS            = 1
  D3DRMXOFSAVE_TEXTURECOORDINATES = 2
  D3DRMXOFSAVE_MATERIALS          = 4
  D3DRMXOFSAVE_TEXTURENAMES       = 8
  D3DRMXOFSAVE_ALL                = 15
  D3DRMXOFSAVE_TEMPLATES          = 16 (&H10)
  D3DRMXOFSAVE_TEXTURETOPOLOGY    = 32 (&H20)
End Enum

Values

D3DRMXOFSAVE_NORMALS
Save normal vectors in addition to the basic geometry.
D3DRMXOFSAVE_TEXTURECOORDINATES
Save texture coordinates in addition to the basic geometry.
D3DRMXOFSAVE_MATERIALS
Save materials in addition to the basic geometry.
D3DRMXOFSAVE_TEXTURENAMES
Save texture names in addition to the basic geometry.
D3DRMXOFSAVE_ALL
Save normal vectors, texture coordinates, materials, and texture names in addition to the basic geometry.
D3DRMXOFSAVE_TEMPLATES
Save templates with the file. By default, templates are not saved.
D3DRMSAVE_TEXTURETOPOLOGY
Save the mesh's face wrap values (set by Direct3DRMMeshBuilder3.SetTextureTopology or Direct3DRMFace2.SetTextureTopology). This flag is not included when you pass D3DRMXOFSAVE_ALL to the Save method. You should pass D3DRMSAVE_TEXTURETOPOLOGY and D3DRMXOFSAVE_ALL if you want to save everything. You only need to pass this flag when you have called Direct3DRMMeshBuilder3.SetTextureTopology or Direct3DRMFace2.SetTextureTopology and want to preserve the values you set.

CONST_D3DRMSORTMODE

Describes how child frames are sorted in a scene.

Syntax

Enum CONST_D3DRMSORTMODE
  D3DRMSORT_FROMPARENT
  D3DRMSORT_NONE
  D3DRMSORT_FRONTTOBACK
  D3DRMSORT_BACKTOFRONT
End Enum

Values

D3DRMSORT_FROMPARENT
Child frames inherit the sorting order of their parents. This is the default setting.
D3DRMSORT_NONE
Child frames are not sorted.
D3DRMSORT_FRONTTOBACK
Child frames are sorted front-to-back.
D3DRMSORT_BACKTOFRONT
Child frames are sorted back-to-front.

See Also

Direct3DRMFrame3.GetSortMode, Direct3DRMFrame3.SetSortMode

CONST_D3DRMSTATECHANGEFLAGS

Sets options for state changes.

Syntax

Enum CONST_D3DRMSTATECHANGEFLAGS
  D3DRMSTATECHANGE_UPDATEONLY  = 1
  D3DRMSTATECHANGE_VOLATILE    = 2
  D3DRMSTATECHANGE_NONVOLATILE = 4
  D3DRMSTATECHANGE_RENDER      = 32 (&H20)
  D3DRMSTATECHANGE_LIGHT       = 64 (&H40)
End Enum

Values

D3DRMSTATECHANGE_UPDATEONLY
Flag indicating a state change.
D3DRMSTATECHANGE_VOLATILE
Flag indicating a state change.
D3DRMSTATECHANGE_NONVOLATILE
Flag indicating a state change.
D3DRMSTATECHANGE_RENDER
Flag indicating a state change.
D3DRMSTATECHANGE_LIGHT
Flag indicating a state change.

CONST_D3DRMTEXTURECACHEFLAGS

Controls the texture-management system with respect to the current texture.

Syntax

Enum CONST_D3DRMTEXTURECACHEFLAGS
  D3DRMTEXTURE_FORCERESIDENT         = 1
  D3DRMTEXTURE_STATIC                = 2
  D3DRMTEXTURE_DOWNSAMPLEPOINT       = 4
  D3DRMTEXTURE_DOWNSAMPLEBILINEAR    = 8
  D3DRMTEXTURE_DOWNSAMPLEREDUCEDEPTH = 16 (&H10)
  D3DRMTEXTURE_DOWNSAMPLENONE        = 32 (&H20)
End Enum

Values

D3DRMTEXTURE_FORCERESIDENT
Indicates that the texture should be kept in video memory (in a hardware scenario).
D3DRMTEXTURE_STATIC
Indicates that the texture will not change.
D3DRMTEXTURE_DOWNSAMPLEPOINT
Indicates that when the texture is downsampled, point filtering should be used.
D3DRMTEXTURE_DOWNSAMPLEBILINEAR
Indicates that when the texture is downsampled, bilinear filtering should be used.
D3DRMTEXTURE_DOWNSAMPLEREDUCEDEPTH
Indicates that when the texture is downsampled, the pixel depth should be reduced. If no lower bit depth is available, the size of the texture will be reduced.
D3DRMTEXTURE_DOWNSAMPLENONE
Indicates that the texture should never be downsampled. The default value is D3DRMTEXTURE_DOWNSAMPLEPOINT.

CONST_D3DRMTEXTURECHANGEDFLAGS

Indicates changes in the texture.

Syntax

Enum CONST_D3DRMTEXTURECHANGEDFLAGS
  D3DRMTEXTURE_CHANGEDPIXELS  = 64 (&H40)
  D3DRMTEXTURE_CHANGEDPALETTE = 128 (&H80)
  D3DRMTEXTURE_INVALIDATEONLY = 256 (&H100)
End Enum

Values

D3DRMTEXTURE_CHANGEDPIXELS
Indicates that the pixel values have changed.
D3DRMTEXTURE_CHANGEDPALETTE
Indicates that the palette has changed.
D3DRMTEXTURE_INVALIDATEONLY
Indicates that the texture regions are invalidated but do not need to be updated by the application.

CONST_D3DRMTEXTUREQUALITY

Describes how a device interpolates between pixels in a texture and pixels in a viewport. This enumerated type is used by the Direct3DRMDevice3.SetTextureQuality and Direct3DRMDevice3.GetTextureQuality methods.

Syntax

Enum CONST_D3DRMTEXTUREQUALITY
  D3DRMTEXTURE_NEAREST
  D3DRMTEXTURE_LINEAR
  D3DRMTEXTURE_MIPNEAREST
  D3DRMTEXTURE_MIPLINEAR
  D3DRMTEXTURE_LINEARMIPNEAREST
  D3DRMTEXTURE_LINEARMIPLINEAR
End Enum

Values

D3DRMTEXTURE_NEAREST
Choose the nearest pixel in the texture. Does not support mipmapping.
D3DRMTEXTURE_LINEAR
Linearly interpolate the four nearest pixels. Does not support mipmapping.
D3DRMTEXTURE_MIPNEAREST
Similar to D3DRMTEXTURE_NEAREST, but uses the appropriate mipmap instead of the texture. Pixel sampling and mipmapping are both nearest.
D3DRMTEXTURE_MIPLINEAR
Similar to D3DRMTEXTURE_LINEAR, but uses the appropriate mipmap instead of the texture. Pixel sampling is linear; mipmapping is nearest.
D3DRMTEXTURE_LINEARMIPNEAREST
Similar to D3DRMTEXTURE_MIPNEAREST, but interpolates between the two nearest mipmaps. Pixel sampling is nearest; mipmapping is linear.
D3DRMTEXTURE_LINEARMIPLINEAR
Similar to D3DRMTEXTURE_MIPLINEAR, but interpolates between the two nearest mipmaps. Both pixel sampling and mipmapping are linear.

CONST_D3DRMTRAVERALFLAGS

Indicates the traversal status of the current frame.

Syntax

Enum CONST_D3DRMTRAVERALFLAGS
  D3DRMFRAME_RENDERENABLE        = 1
  D3DRMFRAME_PICKENABLE          = 2
  D3DRMFRAME_RENDERANDPICKENABLE = 3
End Enum

Values

D3DRMFRAME_RENDERENABLE
Render this frame or any children of this frame.
D3DRMFRAME_PICKENABLE
Pick any visuals in this frame or any children of this frame.
D3DRMFRAME_RENDERANDPICKENABLE
Render and pick any visuals in this frame or any children of this frame.

CONST_D3DRMVIEWPORTCLEARFLAGS

Sets the clear options.

Syntax

Enum CONST_D3DRMVIEWPORTCLEARFLAGS
  D3DRMCLEAR_TARGET     = 1
  D3DRMCLEAR_ZBUFFER    = 2
  D3DRMCLEAR_DIRTYRECTS = 4
  D3DRMCLEAR_ALL        = 7
End Enum

Values

D3DRMCLEAR_TARGET
Clear only the destination rendering surface.
D3DRMCLEAR_ZBUFFER
Clear only the z-buffer surface.
D3DRMCLEAR_DIRTYRECTS
Clear only the dirty rectangle list.
D3DRMCLEAR_ALL
Clear the target, z-buffer, and dirty rectangle list. This flag is equivalent to using Direct3DRMViewport.Clear.

CONST_D3DRMWIREFRAMEFLAGS

Set the wire frame options.

Syntax

Enum CONST_D3DRMWIREFRAMEFLAGS
  D3DRMWIREFRAME_CULL       = 1
  D3DRMWIREFRAME_HIDDENLINE = 2
End Enum

Values

D3DRMWIREFRAME_CULL
Back-facing faces are not drawn.
D3DRMWIREFRAME_HIDDENLINE
Wire-frame-rendered lines are obscured by nearer objects.

CONST_D3DRMWRAPTYPE

Defines the type of Direct3DRMWrap object created by the Direct3DRM3.CreateWrap method.

Syntax

Enum CONST_D3DRMWRAPTYPE
  D3DRMWRAP_FLAT
  D3DRMWRAP_CYLINDER
  D3DRMWRAP_SPHERE
  D3DRMWRAP_CHROME
End Enum

Values

D3DRMWRAP_FLAT
Wrap is flat.
D3DRMWRAP_CYLINDER
Wrap is cylindrical.
D3DRMWRAP_SPHERE
Wrap is spherical.
D3DRMWRAP_CHROME
Wrap allocates texture coordinates so that the texture appears to be reflected onto the objects.

CONST_D3DRMXOFFORMAT

Defines the file type used by the Direct3DRMMeshBuilder3.Save method.

Syntax

Enum CONST_D3DRMXOFFORMAT
  D3DRMXOF_BINARY
  D3DRMXOF_COMPRESSED
  D3DRMXOF_TEXT
End Enum

Values

D3DRMXOF_BINARY
File is in binary format. This is the default setting.
D3DRMXOF_COMPRESSED
Not currently supported.
D3DRMXOF_TEXT
File is in text format.

Remarks

The D3DRMXOF_BINARY and D3DRMXOF_TEXT settings are mutually exclusive.

CONST_D3DRMZBUFFERMODE

Indicates whether z-buffering is enabled.

Syntax

Enum CONST_D3DRMZBUFFERMODE
  D3DRMZBUFFER_FROMPARENT
  D3DRMZBUFFER_ENABLE
  D3DRMZBUFFER_DISABLE
End Enum

Values

D3DRMZBUFFER_FROMPARENT
Frame inherits the z-buffer setting from its parent frame. This is the default setting.
D3DRMZBUFFER_ENABLE
Z-buffering is enabled.
D3DRMZBUFFER_DISABLE
Z-buffering is disabled.

See Also

Direct3DRMFrame3.GetZbufferMode, Direct3DRMFrame3.SetZbufferMode


Visual Basic Types

The Microsoft® Direct3D® Retained Mode types for Microsoft Visual Basic® are:

  • D3DRMANIMATIONKEY
  • D3DRMBOX
  • D3DRMMATERIALOVERRIDE
  • D3DRMPICKDESC
  • D3DRMPICKDESC2
  • D3DRMPMESHLOADSTATUS
  • D3DRMQUATERNION
  • D3DRMRAY
  • D3DRMVECTOR4D
  • D3DRMVERTEX

D3DRMANIMATIONKEY

Defines the keys used by the Direct3DRMAnimation2.AddKey, GetKeys, and ModifyKey methods.

Syntax

Type D3DRMANIMATIONKEY
  x As Single
  y As Single
  z As Single
  s As Single
  dvTime As Single
  lID As Long
  lKeyType As Long
End Type

Members

x
The x value to define a vector.
y
The y value to define a vector
z
The z value to define a vector.
s
The angle in radians used for rotation keys.
dvTime
Time value in arbitrary units.
lID
Key identifier.
lKeyType
Type of key, defining how animations should be played.

Remarks

The members x, y, z, and s either represent the members of a D3DRMQUATERNION type [x, y, z, s] or the members of a D3DVECTOR type [x, y, z]. The rotation key is a D3DRMQUATERNION type defining the rotation, the scale key is the value of the D3DVECTOR type defining the scale, and the position key is the value of the D3DVECTOR type defining the position. Only one key is valid for any particular instance.

D3DRMBOX

Defines the bounding box retrieved by the Direct3DRMMesh.GetBox and Direct3DRMMeshBuilder3.GetBox methods.

Syntax

Type D3DRMBOX
  max As D3DVECTOR
  min As D3DVECTOR
End Type

Members

min and max
Values defining the bounds of the box. These values are D3DVECTOR types.

D3DRMMATERIALOVERRIDE

Describes the overrides for Direct3DRMFrame3.SetMaterialOverride and Direct3DRMFrame3.GetMaterialOverride methods.

Syntax

Type D3DRMMATERIALOVERRIDE
  dcAmbient As D3DCOLORVALUE
  dcDiffuse As D3DCOLORVALUE
  dcEmissive As D3DCOLORVALUE
  dcSpecular As D3DCOLORVALUE
  dvPower As Single
  lFlags As Long
End Type

Members

dcAmbient
Ambient RGB color setting of type D3DCOLORVALUE.
dcDiffuse
Diffuse RGBA color setting of type D3DCOLORVALUE.
dcEmissive
Emissive RGB color setting of type D3DCOLORVALUE.
dcSpecular
Specular RGB color setting of type D3DCOLORVALUE.
dvPower
Power setting.
lFlags
Logical combination of flags, indicating which fields in this type are valid. Possible values include the following:
D3DRMMATERIALOVERRIDE_ALL
D3DRMMATERIALOVERRIDE_AMBIENT
D3DRMMATERIALOVERRIDE_DIFFUSE
D3DRMMATERIALOVERRIDE_DIFFUSE_ALPHAONLY
D3DRMMATERIALOVERRIDE_DIFFUSE_RGBONLY
D3DRMMATERIALOVERRIDE_EMISSIVE
D3DRMMATERIALOVERRIDE_POWER
D3DRMMATERIALOVERRIDE_SPECULAR
D3DRMMATERIALOVERRIDE_TEXTURE

D3DRMPICKDESC

Contains the pick position and face and group identifiers of the objects retrieved by the Direct3DRMPickArray.GetPickFrame method.

Syntax

Type D3DRMPICKDESC
  lFaceIdx As Long
  lGroupIdx As Long
  vPosition As D3DVECTOR
End Type

Members

lFaceIdx
Face index of the retrieved object.
lGroupIdx
Group index of the retrieved object.
vPosition
Value describing the position of the retrieved object. This value is a D3DVECTOR type.

D3DRMPICKDESC2

Contains the face and group identifiers, pick position, horizontal and vertical texture coordinates for the vertex, vertex normal, and color of the objects retrieved by the Direct3DRMPick2Array.GetPickFrame method.

Syntax

Type D3DRMPICKDESC2
  lFaceIdx As Long
  lGroupIdx As Long
  vPosition As D3DVECTOR
  tu As Single
  tv As Single
  vNormal As D3DVECTOR
  color As Long
End Type

Members

lFaceIdx
Face index of the retrieved object.
lGroupIdx
Group index of the retrieved object.
vPosition
Value describing the position of the retrieved object. This value is a D3DVECTOR type.
tu and tv
Horizontal and vertical texture coordinates, respectively, for the vertex.
vNormal
Normal vector for the vertex. This value is a D3DVECTOR type.
color
Vertex color. To specify an object's color, including the alpha component, call the CreateColorRGBA method from the DirectX7 interface on the object.

D3DRMPMESHLOADSTATUS

Contains the loading status of a progressive mesh loaded with the Direct3DRMProgressiveMesh.LoadFromFile method. This type can be retrieved with the Direct3DRMProgressiveMesh.GetLoadStatus method.

Syntax

Type D3DRMPMESHLOADSTATUS
  lBytesLoaded As Long
  lVerticesLoaded As Long
  lFacesLoaded As Long
  lFlags As Long
End Type

Members

lBytesLoaded
Number of total bytes loaded.
lVerticesLoaded
Number of vertices loaded.
lFacesLoaded
Number of faces loaded.
lFlags
Flags that indicate the status of the progressive mesh loading. Can be one of the following values.
D3DRMPMESHSTATUS_VALID
The progressive mesh object contains valid data.
D3DRMPMESHSTATUS_INTERRUPTED
The download was interrupted either because the application used Direct3DRMProgressiveMesh.Abort or because the connection was lost.
D3DRMPMESHSTATUS_BASEMESHCOMPLETE
The base mesh has been downloaded.
D3DRMPMESHSTATUS_COMPLETE
All data has been downloaded.
D3DRMPMESHSTATUS_RENDERABLE
It is now possible to render the mesh.

D3DRMQUATERNION

Describes the rotation used by the Direct3DRMAnimation2.AddRotateKey method, and the quaternion used in Direct3DRMFrame3.SetQuaternion. It is also used in several of the Direct3D mathematical functions.

Syntax

Type D3DRMQUATERNION
  s As Single
  v As D3DVECTOR
End Type

Members

s
Angle.
v
This value is a D3DVECTOR type.

D3DRMRAY

Defines the direction and starting position of the ray in the Direct3DRMFrame3.RayPick method.

Syntax

Type D3DRMRAY
  dir As D3DVECTOR
  pos As D3DVECTOR
End Type

Members

dir
Direction of the ray used in a ray pick. This value is a D3DVECTOR type.
pos
Starting position of the ray used in a ray pick. This value is a D3DVECTOR type.

D3DRMVECTOR4D

Describes the screen coordinates used as the destination of a transformation by the Direct3DRMViewport2.Transform method and as the source of a transformation by the Direct3DRMViewport2.InverseTransform method.

Syntax

Type D3DRMVECTOR4D
  x As Single
  y As Single
  z As Single
  w As Single
End Type

Members

x, y, z, and w
Variables describing homogeneous values. These values define the result of the transformation.

D3DRMVERTEX

Describes a vertex in a Direct3DRMMesh object.

Syntax

Type D3DRMVERTEX
  position As D3DVECTOR
  normal As D3DVECTOR
  tu As Single
  tv As Single
  color As Long
End Type

Members

position
Position of the vertex. This value is a D3DVECTOR type.
normal
Normal vector for the vertex. This value is a D3DVECTOR type.
tu and tv
Horizontal and vertical texture coordinates, respectively, for the vertex.
color
Vertex color. To specify an object's color, including the alpha component, call the CreateColorRGBA method from the DirectX7 interface on the object.

See Also

Direct3DRMMesh.GetVertices, Direct3DRMMesh.SetVertices


Visual Basic Error Values

The methods of the Microsoft® Direct3D® Retained Mode interfaces can return the following values in Microsoft Visual Basic®.

D3DRM_OK
No error. Equivalent to DD_OK.
D3DRMERR_BADALLOC
Out of memory.
D3DRMERR_BADDEVICE
Device is not compatible with renderer.
D3DRMERR_BADFILE
Data file is corrupt.
D3DRMERR_BADMAJORVERSION
Bad dynamic-link library (DLL) major version.
D3DRMERR_BADMINORVERSION
Bad DLL minor version.
D3DRMERR_BADOBJECT
Object expected in argument.
D3DRMERR_BADPMDATA
Data in the .x file is corrupted. The conversion to a progressive mesh succeeded but produced an invalid progressive mesh in the .x file.
D3DRMERR_BADTYPE
Bad argument type passed.
D3DRMERR_BADVALUE
Bad argument value passed.
D3DRMERR_BOXNOTSET
An attempt was made to access a bounding box (for example, with Direct3DRMFrame3.GetBox) when no bounding box was set on the frame.
D3DRMERR_CLIENTNOTREGISTERED
Client has not been registered.
D3DRMERR_CONNECTIONLOST
Data connection was lost during a load, clone, or duplicate.
D3DRMERR_ELEMENTINUSE
Element can't be modified or deleted while in use. To empty a submesh, call Direct3DRMMeshBuilder3.Empty against its parent.
D3DRMERR_ENTRYINUSE
Vertex or normal entries are in use by a face and cannot be deleted.
D3DRMERR_FACEUSED
Face already used in a mesh.
D3DRMERR_FILENOTFOUND
File not found in the specified location.
D3DRMERR_INCOMPATIBLEKEY
Specified animation key is incompatible. The key cannot be modified.
D3DRMERR_INVALIDLIBRARY
Specified library is invalid.
D3DRMERR_INVALIDOBJECT
Method received an object that is invalid.
D3DRMERR_INVALIDPARAMS
At least one of the parameters passed to the method is invalid.
D3DRMERR_LIBRARYNOTFOUND
Specified library not found.
D3DRMERR_LOADABORTED
Load aborted by user.
D3DRMERR_NOSUCHKEY
Specified animation key does not exist.
D3DRMERR_NOTCREATEDFROMDDS
Specified texture was not created from a Microsoft DirectDraw® surface.
D3DRMERR_NOTDONEYET
Error flag not implemented.
D3DRMERR_NOTENOUGHDATA
Not enough data has been loaded to perform the requested operation.
D3DRMERR_NOTFOUND
Object not found in specified place.
D3DRMERR_OUTOFRANGE
Specified value is out of range.
D3DRMERR_PENDING
Data required to supply the requested information has not finished loading.
D3DRMERR_REQUESTTOOLARGE
Attempt was made to set a level of detail in a progressive mesh greater than the maximum available.
D3DRMERR_REQUESTTOOSMALL
Attempt was made to set the minimum rendering detail of a progressive mesh smaller than the detail in the base mesh (the minimum for rendering).
D3DRMERR_TEXTUREFORMATNOTFOUND
Texture format could not be found that meets the specified criteria and that the underlying Immediate Mode device supports.
D3DRMERR_UNABLETOEXECUTE
Unable to carry out procedure.
DD_OK
Request completed successfully. Equivalent to D3DRM_OK.
DDERR_INVALIDOBJECT
Received pointer that was an invalid object.
DDERR_INVALIDPARAMS
One or more of the parameters passed to the method are incorrect.
DDERR_NOTFOUND
Requested item was not found.
DDERR_NOTINITIALIZED
An attempt was made to call an interface method of an object before the object was initialized.
DDERR_OUTOFMEMORY
DirectDraw does not have enough memory to perform the operation.


Further Reading for Visual Basic Programmers

This section contains information about the following topics related to the Microsoft® Direct3D® Retained Mode Reference for Microsoft Visual Basic®.

  • Color keying
  • CONST_D3DCOLORMODEL
  • D3DCOLOR_MONO
  • D3DCOLOR_RGB
  • D3DCOLORVALUE
  • D3DMATRIX
  • D3DPRIMCAPS
  • D3DRECT
  • D3DTRIANGLE
  • D3DVECTOR
  • DirectDrawCreate
  • DirectDrawCreateClipper
  • Direct3D3
  • DirectDrawClipper
  • Interpolators
  • Mipmaps
  • Texture map formats

Color keying
A color key is typically a single uncommon color that the artist does not use for anything but transparency, but it can also be a specified range of colors. Using the DirectDrawSurface4.SetColorKey method, you can set the color key for a surface. After the color key is set, subsequent calls to DirectDrawSurface3.BltFast take advantage of that color key, ignoring the pixels that match it. This type of color key is known as a source color key. Because the source color key prevents "transparent" pixels from being written to the destination, the original background pixels are preserved in these places, making it look like a sprite is a nonrectangular object passing over the background. You can also use a color key that effects the destination surface (a destination color key).

A destination color key is a color on a surface that is used for pixels that a sprite can overwrite. Again, the artist chooses an arbitrary color that is not used elsewhere in the image, reserving it as a portion of the image where you are able to blit. When you blit a sprite to the destination surface with a destination color key specified, the sprite's pixels will only be blitted to pixels on the destination that are using the destination color key. Because the normal destination pixels are preserved, it looks like the sprite passes behind the image on the destination surface. For more information, see Transparent Blitting and Color Keys in the "Surfaces" topic in the "DirectDraw Essentials" section of the DirectX Foundation SDK.

CONST_D3DCOLORMODEL
Enumerated type that describes the color model implemented by the device.

Syntax

Enum CONST_D3DCOLORMODEL
  D3DCOLOR_MONO = 1
  D3DCOLOR_RGB  = 2
End Enum
D3DCOLOR_MONO
A value from the CONST_D3DCOLORMODEL enumerated type that tells the system to use a monochromatic model (or ramp model). In this model, the blue component of a vertex color is used to define the brightness of a lit vertex.
D3DCOLOR_RGB
A value from the CONST_D3DCOLORMODEL enumerated type that tells the system to use a full RGB model.
D3DCOLORVALUE
A type that describes color values. The r, g, b, and a values specify the red, green, blue, and alpha components of a color. These values generally range from 0.0 to 1.0, with 0.0 specifying black.

Syntax

Type D3DCOLORVALUE
  r As Single
  g As Single
  b As Single
  a As Single
End Type
D3DMATRIX
A type that describes a matrix.

Syntax

Type D3DMATRIX
  rc11 As Single, rc12 As Single, rc13 As Single, rc14 As Single
  rc21 As Single, rc22 As Single, rc23 As Single, rc24 As Single
  rc31 As Single, rc32 As Single, rc33 As Single, rc34 As Single
  rc41 As Single, rc42 As Single, rc43 As Single, rc44 As Single
End Type
D3DPRIMCAPS
A type that defines the capabilities for each primitive type. See the the DirectX Foundation SDK for more information.
D3DRECT
A type that is a rectangle definition.

Syntax

Type D3DRECT
  x1 As Long
  x2 As Long
  y1 As Long
  y2 As Long
End Type
D3DTRIANGLE
The type that describes the base type for all triangles. The triangle is the main rendering primitive.
D3DVECTOR
The type that defines a vector for many Microsoft® Direct3D® and Direct3D Retained Mode methods and types.

Syntax

Type D3DVECTOR
  x As Single
  y As Single
  z As Single
End Type
DirectDrawCreate
A function that creates an instance of a DirectDraw object.
DirectDrawCreateClipper
A function that creates an instance of a DirectDrawClipper object not associated with a DirectDraw object.
Direct3D3
Applications use the methods of the Direct3D3 interface to create Direct3D objects and to set up the environment.
Direct3D3.GetDevicesEnum
This method retrieves all enumerated Direct3D device drivers installed on the system.
DirectDrawClipper
Applications use the methods of the DirectDrawClipper interface to manage clip lists.
DirectDrawClipper.SetHWnd
This method sets the window handle that will obtain the clipping information.
Interpolators
Interpolators provide a way to store actions and apply them to objects with automatic calculation of in-between values. For example, you can set a scene's background color to red at time zero and green at time 10, and the interpolator will automatically tint successive scenes to blend from red to green. With an interpolator, you can blend colors, move objects smoothly between positions, morph meshes, and perform many other transformations.

In the Direct3D Retained Mode implementation, interpolators are a generalization of the Direct3DRMAnimation2 interface that increases the kinds of object parameters you can animate. While the Direct3DRMAnimation2 interface allows animation of an object's position, size and orientation, the interpolator interfaces further enable animation of colors, meshes, textures, and materials.

Interpolator keys
The actions stored by the interpolator are called keys. A key is a stored procedure call and has an index associated with it. The interpolator automatically calculates between the key values. Keys are stored in the interpolator by calling one of the supported interface methods that can be interpolated. The method and the parameter values passed to it make up the key. Every key stored inside an interpolator has an index value. When the key is recorded, it is stamped with the current interpolator index value. The key's index value never changes once this value is set.
Interpolator Types
Objects can be attached to interpolators of an associated type; for example, a Direct3DRMMesh object can be attached to a Direct3DRMMeshInterpolator object. The interpolator types are:
  • FrameInterpolator
  • LightInterpolator
  • MaterialInterpolator
  • MeshInterpolator
  • TextureInterpolator
  • ViewportInterpolator

Other interpolators can also be attached to an interpolator. When you change the index of an interpolator, it sets the indices of any attached interpolators to the same value.

Note that for Direct3DRMMeshInterpolator, you add a SetVertices key to a Direct3DRMMeshInterpolator object by calling SetVertices on the Direct3DRMMeshInterpolator object's Direct3DRMMesh interface. The group index used with SetVertices must correspond to a valid group index in the Direct3DRMMesh object or objects that the interpolator is applied to.

Interpolator index values
The interpolator covers a span of index values. This index span is dictated by the following rules:
  • The start of the span is the minimum of all key index values and the current index.
  • The end of the span is the maximum of all key index values and the current index.

For information on interpolation options, see the CONST_D3DRMINTERPOLATIONFLAGS enumerated type.

Mipmaps
A mipmap is a sequence of textures, each of which is a progressively lower resolution, prefiltered representation of the same image. Each prefiltered image, or level, in the mipmap is a power of two smaller than the previous level. A high-resolution level is used for objects that are close to the viewer. Lower-resolution levels are used as the object moves farther away. Mipmapping is a computationally low-cost way of improving the quality of rendered textures. For more information, see Mipmaps in the "Textures" topic in the "Direct3D Immediate-Mode Essentials" section of the DirectX Foundation SDK.
Texture map formats
A wide range of texture pixel formats are supported by the Microsoft DirectX® hardware-emulation layer. The table in Texture Map Formats in the "Pixel Format Masks" topic in the DirectX Foundation DirectDraw Reference shows these formats.


Samples Introduction

This section provides information about how to build the Microsoft® Direct3D® Retained Mode samples in Microsoft Developer Studio™, and it provides summaries of the samples to help you determine which sample to look at.

  • Building Samples Using Developer Studio 5.0
  • Samples


Building Samples Using Developer Studio 5.0

Each sample included with the Microsoft® DirectX® Software Development Kit includes a makefile that you can use to build the sample from the command line. You can then run the sample to see what it does. When you find a sample that interests you, you might want to explore further and step through the code yourself. If you want to build and debug samples (or your own code) using Microsoft Developer Studio™, you will want to create a project within Developer Studio. This article discusses how to create a project in Developer Studio version 5.0. The project file must include the necessary source files and libraries, and Developer Studio must be configured with the correct library and include paths so that the compiler can locate the required library and header files.

Note See the readme.txt file in the DirectX SDK Samples directory for information about building samples from the command line.

This article contains the following sections.

  • Tools Options
  • Creating a New Project
  • Project Settings
  • Adding Libraries
  • Setting the Working Directory
  • Adding Files to the Project

Tools Options

You must specify where the header and library files from the DirectX SDK are located when using Developer Studio. These settings are global within Developer Studio and do not need to be repeated for each project.

Perform the following steps to add the DirectX SDK header and library directories to the include and library file search paths.

  1. Within Developer Studio, choose Options from the Tools menu.
  2. Select the Directories tab.
  3. In the Show Directories for dialog box, choose Include files.
  4. Double-click the dotted rectangle below the list of directories and type in the full path for your DirectX SDK include directory. You can also press the "..." (browse) button that appears on the right side of the entry field when you select the rectangle and then navigate to the correct directory. By default, the header (include) files are installed in c:\mssdk\include.
  5. Press the enter key to complete the entry, re-select the new entry if necessary, and then press the Move Item Up button Move Item Up button repeatedly to move the directory up one position at a time, to the top of the directory list. Placing the directory at the top of the list ensures that the DirectX files will come first in the search path and will be used in case of duplicate file names.

    The following screen shot shows the Directories tab of the Tools Options dialog box with the default include directory at the top of the directory list.

    Directories tab of Tools Options dialog box

  6. After you have added the include directory, add the library directory. In the Show directories for dialog box, choose Library files.
  7. Double-click the dotted rectangle below the list of directories and type in the full path (or use the "..." (browse) button to select a path) for your DirectX SDK library directory. By default, the library files are installed in c:\mssdk\lib.
  8. Press the enter key to complete the entry, re-select the new entry if necessary, and then press the Move Item Up button repeatedly to move the directory up one position at a time, to the top of the directory list.

Creating a New Project

Perform the following steps to create a new project.

  1. Choose New from Developer Studio's File menu.
  2. Select the Projects tab.
  3. Select the appropriate project type. "Win32® Application" is appropriate for Windows® applications.
  4. Type in a project name.
  5. Edit the path for project location to point to your desired location, or use the "..." (browse) button to navigate to that directory. Note that the project name is appended to this path.

Project Settings

This section discusses how to add the appropriate libaries to your project and how to set the working directory. Open a project in Developer Studio before proceeding.

Adding Libraries

  1. Choose Settings from Developer Studio's Project menu.
  2. Select the Link tab.
  3. Choose General from the Category dialog box.
  4. Choose All Configurations from the Settings For dialog box.
  5. In the Object/library modules edit control, type the names of the libraries your project requires. You will typically put those libraries at the beginning of the list so definitions will be picked up first from those core libraries.

    The required libraries vary from project to project, depending on the technology the code uses. If in doubt about the libraries required for a particular sample, search the makefile in that sample's directory and include the same library list. The following table lists the most commonly used libraries included with the DirectX SDK. The Winmm.lib library included with the Platform SDK includes additional multimedia functionality as well.
    DirectDraw | ddraw.lib
    Direct3D Retained Mode | d3drm.lib
    DirectSound | dsound.lib
    DirectPlay | dplayx.lib
    DirectInput | dinput.lib

    For example, the Tex1 sample's makefile lists ddraw.lib and d3drm.lib because it uses Microsoft DirectDraw® and Direct3D® Retained Mode.

The following screen shot shows the Link tab of the Project Settings dialog box. It specifies the settings for all configurations and adds multimedia and DirectX libraries to the beginning of Developer Studio's default Object/library modules list.

Link tab of the Project Settings dialog box

Setting the Working Directory

You might need to set the working directory to make sure your program can find certain files. For example, you might need to load an image from the directory in which your program resides. By default, Developer Studio sets the current working directory to the directory in which it resides, rather than to the directory containing your program.

Perform the following steps to set the working directory.

  1. Choose Settings from Developer Studio's Project menu.
  2. Select the Debug tab.
  3. Choose the appropriate configuration ("All Configurations" or "Win32 Debug", for example) from the Settings For dialog box.
  4. Type the full path to your desired working directory in the Working directory edit control.

The following screen shot shows the Debug tab of the Project Settings dialog box. It specifies a working directory for the Win32 Debug configuration.

Debug tab of the Project Settings dialog box

Adding Files to the Project

Perform the following steps to add any required files to your project. Open a project in Developer Studio before proceeding.

  1. Choose Add To Project from Developer Studio's Project menu.
  2. If you are creating a new file, select New, select the type of file, and specify a file name.
  3. If you are opening an existing file, select Files and select the file you want to add to the project.
  4. Repeat the previous steps until you have added all required source files (such as .cpp or .c), resource files (such as .rc), and any other necessary files.
  5. Choose Save All from Developer Studio's File menu to save all files including source code, project files, and the workspace.


Samples

This article summarizes the Microsoft® Direct3D® Retained Mode samples. The summary for each sample lists the default installation directory for that sample in the Microsoft DirectX® Software Development Kit (SDK) and provides a short description of the sample.

All of the Direct3D Retained Mode samples except RMBegin1, RMBegin2, RMEnum and Viewer use the RMMain helper code. All of the samples that use the RMMain helper code depend on the Rmmain.cpp to provide the main application window and Rmmain.rc to provide menus and accelerators. These samples also link to the Ddraw.lib and D3drm.lib libraries. Each sample directory includes a Microsoft Developer Studio project (.dsp) file that you can open in Developer Studio and use to build the sample.

If you are new to Direct3D Retained Mode, you might want to start by looking at the RMBegin1, RMBegin2, RMEnum, Egg, Globe, Hier1, and Tex1 samples.

The following articles provide a detailed walk through of sample code.

  • Rotating an Object: The RMBegin1 Sample
  • Frame Hierarchies: The RMBegin2 Sample
  • Enumerating Devices: The RMEnum Sample

This article contains information on the following samples.

  • Egg
  • Faces
  • Fly
  • Globe
  • Hier1
  • Hier2
  • Morph
  • Quat
  • RMBegin1
  • RMBegin2
  • RMEnum
  • RMMain
  • Shadow
  • Tex1
  • Tex3
  • Tex4
  • Tex5
  • Trans
  • Uvis
  • Viewer

Some of the DirectX Foundation SDK samples demonstrate multiple technologies. You might want to look at those samples to see how the technologies fit together. For example, the DS3dView DirectSound sample is a simple extension of the Direct3D Retained Mode 3-D object Viewer sample. DS3dView enables you to attach sounds to objects and to move the objects in three dimensions. For more information about DS3dView see the DirectX Foundation SDK.

Egg

Path

mssdk\samples\multimedia\d3drm\src\Egg

Description

This sample loads a simple DirectX file of a single mesh object (Egg.x from the Dxsdk\Media directory). The sample initializes the lights in the scene, loads the mesh file, creates the egg frame within the scene, adds the mesh into the frame, and sets up the frame's position, orientation, and rotation. The sample uses methods of IDirect3DRM3 (CreateFrame, CreateLightRGB, CreateMeshBuilder), IDirect3DRMFrame3 (SetPosition, AddLight, SetRotation, AddVisual, SetOrientation), and IDirect3DRMMeshBuilder3 (Load).

Required Libraries

  • Ddraw.lib
  • D3drm.lib

Required RMMain Code

  • Rmmain.cpp
  • Rmmain.rc

Faces

Path

mssdk\samples\multimedia\d3drm\src\Faces

Description

This sample creates mesh objects one face at a time.

Required Libraries

  • Ddraw.lib
  • D3drm.lib.

Required RMMain Code

  • Rmmain.cpp
  • Rmmain.rc

Fly

Path

mssdk\samples\multimedia\d3drm\src\Fly

Description

This sample uses animations to set the position of a spaceship along a curved path.

Required Libraries

  • Ddraw.lib
  • D3drm.lib

Required RMMain Code

  • Rmmain.cpp
  • Rmmain.rc

Globe

Path

mssdk\samples\multimedia\d3drm\src\Globe

Description

This sample loads a simple DirectX file of a single mesh object with textures. It uses methods of:

  • IDirect3DRM3
    • CreateFrame
    • CreateLightRGB
    • CreateMeshBuilder
    • CreateMaterial
    • CreateWrap
    • LoadTexture
    • CreateAnimation
  • IDirect3DRMFrame3
    • GetScene
    • LookAt
    • SetPosition
    • AddLight
    • SetOrientation
    • SetRotation
    • AddVisual
    • AddMoveCallback
    • AddDestroyCallback
  • IDirect3DRMMeshBuilder3
    • Load
    • SetMaterial
    • Scale
    • SetColorRGB
    • GetBox
    • SetTexture
  • IDirect3DRMAnimation
    • SetFrame
    • SetTime
    • SetOptions
    • AddPositionKey
  • IDirect3DRMWrap
    • Apply
  • IDirect3DRMTexture3
    • SetShades

Required Libraries

  • Ddraw.lib
  • D3drm.lib

Required RMMain Code

  • Rmmain.cpp
  • Rmmain.rc

Hier1

Path

mssdk\samples\multimedia\d3drm\src\Hier1

Description

This sample creates a simple hierarchy of two meshes, demonstrating the concept of frames. It initializes the lights in the scene, loads two mesh files, and creates a hierarchy of frames (frames within frames). Hier1 loads a texture and wraps it onto a mesh, adds the mesh into the frame, and sets up the frame's position, orientation, and rotation.

Required Libraries

  • Ddraw.lib
  • D3drm.lib

Required RMMain Code

  • Rmmain.cpp
  • Rmmain.rc

See Also

Hier2

Hier2

Path

mssdk\samples\multimedia\d3drm\src\Hier2

Description

This sample demonstrates a simple hierarchy of four meshes.

Required Libraries

  • Ddraw.lib
  • D3drm.lib

Required RMMain Code

  • Rmmain.cpp
  • Rmmain.rc

See Also

Hier1

Morph

Path

mssdk\samples\multimedia\d3drm\src\Morph

Description

This sample demonstrates how to use interpolators.

Required Libraries

  • Ddraw.lib
  • D3drm.lib

Required RMMain Code

  • Rmmain.cpp
  • Rmmain.rc

See Also

IDirect3DRMInterpolator

Quat

Path

mssdk\samples\multimedia\d3drm\src\Quat

Description

This sample uses quaternions to interpolate between two vectors in space.

Required Libraries

  • Ddraw.lib
  • D3drm.lib

Required RMMain Code

  • Rmmain.cpp
  • Rmmain.rc

RMBegin1

Path

mssdk\samples\multimedia\d3drm\src\RMBegin1

Description

This is a "bare-bones" sample that creates a default Direct3D Retained Mode device, loads a mesh from a DirectX file, adds lights, and rotates the mesh object. Extensive comments throughout the sample code introduce and explain its purpose.

Unlike most of the Direct3D Retained Mode samples, it does not use the RMMain helper file, Rmmain.cpp, or the extensive menus provided by Rmmain.rc.

For a detailed code walkthrough of the RMBegin1 sample, see Rotating an Object: The RMBegin1 Sample.

For a sample that builds upon the RMBegin1 sample code, see RMBegin2.

Required Libraries

  • Ddraw.lib
  • D3drm.lib

RMBegin2

Path

mssdk\samples\multimedia\d3drm\src\RMBegin2

Description

This is a "bare-bones" sample that demonstrates a hierarchy of frames. It loads, scales, lights, and colors three objects from DirectX files. The objects mimic a sun, planet, and moon scenario with the moon revolving around the planet and both the moon and planet revolving around the sun. This sample builds upon the code introduced in the RMBegin1 sample. In addition to building a more complex scene than RMBegin1, this sample handles resizing of the window and handles the WM_ACTIVATE and WM_PAINT messages. Extensive comments throughout the sample code introduce and explain its purpose.

Unlike most of the Direct3D Retained Mode samples, it does not use the RMMain helper file, Rmmain.cpp, or the extensive menus provided by Rmmain.rc.

For a detailed code walkthrough of the RMBegin2 sample, see Frame Hierarchies: The RMBegin2 Sample.

Required Libraries

  • Ddraw.lib
  • D3drm.lib

RMEnum

Path

mssdk\samples\multimedia\d3drm\src\Rmenum

Description

This is a "bare-bones" sample that enumerates devices, intelligently selects one, and creates the Direct3D Retained Mode device. This sample does not perform any rendering. It focuses on device enumeration for clarity and simplicity of code. It enables the user to select the device through a menu choice.

Unlike most of the Direct3D Retained Mode samples, it does not use the RMMain helper file, Rmmain.cpp, or the extensive menus provided by Rmmain.rc. It does use the error reporting functions from its Rmerror.c file.

For a detailed code walkthrough of the RMEnum sample, see Enumerating Devices.

Required Libraries

  • Ddraw.lib
  • D3drm.lib

RMMain

Path

mssdk\samples\multimedia\d3drm\src\Misc

Description

The RMMain helper code handles common tasks, such as creating, enumerating, and managing Microsoft DirectDraw® and Direct3D Retained Mode objects and providing a common resource for menus. It uses Direct3D Retained Mode to set up a window for rendering, calls the BuildScene function the sample provides to have the sample build its scene, and uses Direct3D Retained Mode to render the scene. Most of the Direct3D Retained Mode samples link to this common code, which allows the application-specific code to be much simpler. The samples that use RMMain only work in windowed mode.

RMMain also provides a number of menu items, allowing the user to see the effect of different rendering options. You can single step through the animation, select the device to use for rendering, select shading (flat or Gouraud), turn lighting and dithering on and off, and choose fill options (point, wireframe, or solid).

The RMMain helper code consists of the following files.
Rmmain.cpp | Main source file that includes WinMain and message handler. Creates Direct3D Retained Mode, uses it to set up the window for rendering, and then calls the sample to have it build its scene.
Resource.h | Header file for Rmmain.rc.
Rmmain.rc | Resource file for Rmmain.cpp, providing menus, keyboard accelerators, and the About dialog box.

Shadow

Path

mssdk\samples\multimedia\d3drm\src\Shadow

Description

This sample creates a shadow of a mesh object.

Required Libraries

  • Ddraw.lib
  • D3drm.lib

Required RMMain Code

  • Rmmain.cpp
  • Rmmain.rc

Tex1

Path

mssdk\samples\multimedia\d3drm\src\Tex1

Description

This sample loads a simple, texture-mapped mesh object, using a cylindrical mapping.

Required Libraries

  • Ddraw.lib
  • D3drm.lib

Required RMMain Code

  • Rmmain.cpp
  • Rmmain.rc

See Also

Tex3, Tex4, and Tex5

Tex3

Path

mssdk\samples\multimedia\d3drm\src\Tex3

Description

This sample uses texture wraps for special effects, using a spherical mapping relative to a frame.

Required Libraries

  • Ddraw.lib
  • D3drm.lib

Required RMMain Code

  • Rmmain.cpp
  • Rmmain.rc

See Also

Tex1, Tex4, and Tex5

Tex4

Path

mssdk\samples\multimedia\d3drm\src\Tex4

Description

This sample uses texture wraps for special effects, using a spherical mapping relative to the camera. The texture is also used as a background for the scene.

Required Libraries

  • Ddraw.lib
  • D3drm.lib

Required RMMain Code

  • Rmmain.cpp
  • Rmmain.rc

See Also

Tex1, Tex3, and Tex5

Tex5

Path

mssdk\samples\multimedia\d3drm\src\Tex5

Description

This sample uses a wrap for chrome mapping and a texture map as decal.

Required Libraries

  • Ddraw.lib
  • D3drm.lib

Required RMMain Code

  • Rmmain.cpp
  • Rmmain.rc

See Also

Tex1, Tex3, and Tex4

Trans

Path

mssdk\samples\multimedia\d3drm\src\Trans

Description

This sample demonstrates the use of transparent texture maps. It rotates a solid sphere and independently rotates two partially transparent checkered cubes that intersect with the sphere. The sample creates frames, lights, meshbuilders, meshes, textures, and materials. It calls IDirect3DRMTexture3::SetDecalTransparency to make decals transparent.

Required Libraries

  • Ddraw.lib
  • D3drm.lib

Required RMMain Code

  • Rmmain.cpp
  • Rmmain.rc

Uvis

Path

mssdk\samples\multimedia\d3drm\src\Uvis

Description

This sample demonstrates how Direct3D can be used with Direct3D Retained Mode. It demonstrates how to use a Direct3D Immediate Mode execute buffer as a visual in a Direct3D Retained Mode scene.

Required Libraries

  • Ddraw.lib
  • D3drm.lib

Required RMMain Code

  • Rmmain.cpp
  • Rmmain.rc

Viewer

Path

mssdk\samples\multimedia\d3drm\src\Viewer

Description

Viewer (Direct3D Retained Mode Object Viewer) is a stand-alone Retained Mode application that enables you to load and view 3-D objects.

The initial scene has a light source in the upper-right corner. To see this, the view can be moved backward and forward using the T and R keys. Additional objects can be loaded from the File menu, and new light sources can be added from the Lights menu. Objects can be rotated with the left mouse button and dragged with the right.

The last object that was rotated or dragged remains the current selection.

The device quality can be altered using the Renderer menu. Using this menu, the type of device used can also be switched from ramp to RGB. When using the RGB device, the color of lights in the scene can be changed in the same way as you change the color of objects. In 256-color mode, it is advisable to dither an RGB device for best results.

Additional keyboard controls:
T | Forward
R | Back
Z | Move current selection forwards
X | Move current selection back
Ctrl+G | Gouraud shade
Ctrl+F | Flat Shade
Ctrl+D | Dither toggle
Arrow Keys | Move left/right/up/down
Delete | Delete the current selection

Required Libraries

  • Ddraw.lib
  • D3drm.lib
  • Comdlg32.lib
  • Winmm.lib
  • Msvcrt.lib


DirectX File Format

Microsoft® DirectX® version 6.0 introduced interfaces and methods that enable reading from and writing to DirectX (.x) files. For more information, see the DirectX File Reference.

This section specifies the file format introduced with DirectX 2.0. A binary version of this format was subsequently released with DirectX 3.0, which is also detailed in this reference.

The DirectX file format provides a rich, template-driven format that enables the storage of meshes, textures, animations, and user-definable objects. Support for animation sets enables you to store predefined paths for playback in real time. Instancing and hierarchies are also supported. Instancing enables multiple references to an object, such as a mesh, while storing its data only once per file. Hierarchies are used to express relationships between data records. The DirectX file format is used natively by the Microsoft Direct3D® Retained Mode API, providing support for reading predefined objects into an application or for writing mesh information constructed by the application in real time.

The DirectX file format provides low-level data primitives upon which applications define higher-level primitives through templates. This is the method by which Direct3D Retained Mode defines higher-level primitives such as vectors, meshes, matrices, and colors.

The following sections detail the API-independent features of the file format and also the method by which Direct3D Retained Mode uses the file format.

  • DirectX File Format Architecture
  • DirectX File Templates
  • DirectX File Cube Example
  • DirectX File Binary Format
  • DirectX File Conv3ds.exe Utility
  • DirectX File Samples
  • DirectX File Reference


DirectX File Format Architecture

The Microsoft® DirectX® file format is an architecture- and context-free file format. It is template-driven and is free of any usage knowledge. The file format may be used by any client application and currently is used by Microsoft Direct3D® Retained Mode to describe geometry data, frame hierarchies, and animations.

This following sections deal with the content and syntax of the file format. The file format uses the extension .x when used with the DirectX Software Development Kit (SDK).

  • Reserved Words
  • Header
  • Comments
  • Templates
  • Data
  • Use of Commas and Semicolons

Reserved Words

The following words are reserved and must not be used:

  • ARRAY
  • BINARY
  • BINARY_RESOURCE
  • CHAR
  • CSTRING
  • DOUBLE
  • DWORD
  • FLOAT
  • SDWORD
  • STRING
  • SWORD
  • TEMPLATE
  • UCHAR
  • ULONGLONG
  • UNICODE
  • WORD

Header

The variable length header is compulsory and must be at the beginning of the data stream. The header contains the following:
Type | Subtype | Size | Contents | Content meaning
Magic Number (required) |  | 4 bytes | "xof " |
Version Number (required) | Major Number | 2 bytes | 03 | Major version 3
 | Minor Number | 2 bytes | 02 | Minor version 2
Format Type (required) |  | 4 bytes | "txt " | Text File
 |  |  | "bin " | Binary File
 |  |  | "tzip" | MSZip Compressed Text File
 |  |  | "bzip" | MSZip Compressed Binary File
Float size (required) |  | 4 bytes | 0064 | 64-bit floats
 |  |  | 0032 | 32-bit floats

Example

xof 0302txt 0064

Comments

Comments are only applicable in text files. Comments can occur anywhere in the data stream. A comment begins with either C++ style double-slashes "//", or a number sign "#". The comment runs to the next new line.

# This is a comment.
// This is another comment.

Templates

Templates define how the data stream is interpreted—the data is modulated by the template definition. This section discusses the following aspects of a template:

  • Template form
  • Template name
  • UUID
  • Members
  • Restrictions

Example templates are presented in Examples.

Template form

A template has the following form.

template <template-name> {
<UUID>
<member 1>;
...
<member n>;
[restrictions]
}

Template name

This is an alphanumeric name that may include the underscore character "_". It must not begin with a digit.

UUID

A universally unique identifier (UUID) formatted to the Open Software Foundation's Distributed Computing Environment standard and surrounded by angle brackets "<" and ">". For example: <3D82AB43-62DA-11cf-AB39-0020AF71E433>.

Members

Template members consist of a named data type followed by an optional name or an array of a named data type. Valid primitive data types are as follows:

Type | Size
WORD | 16 bits
DWORD | 32 bits
FLOAT | IEEE float
DOUBLE | 64 bits
CHAR | 8 bits
UCHAR | 8 bits
BYTE | 8 bits
STRING | NULL-terminated string
CSTRING | Formatted C-string (currently unsupported)
UNICODE | Unicode™ string (currently unsupported)

Additional data types defined by templates encountered earlier in the data stream can also be referenced within a template definition. No forward references are allowed.

Any valid data type can be expressed as an array in the template definition. The basic syntax is as follows:

array <data-type> <name>[<dimension-size>];

<dimension-size> can either be an integer or a named reference to another template member whose value is then substituted.

Arrays may be n-dimensional, where n is determined by the number of paired square brackets trailing the statement. For example:

array DWORD FixedHerd[24];
array DWORD Herd[nCows];
array FLOAT Matrix4x4[4][4];

Restrictions

Templates may be open, closed, or restricted. These restrictions determine which data types may appear in the immediate hierarchy of a data object defined by the template. An open template has no restrictions, a closed template rejects all data types, and a restricted template allows a named list of data types.

The syntax for indicating an open template is three periods enclosed by square brackets.

[ ... ]

A comma-separated list of named data types followed optionally by their UUIDs enclosed by square brackets indicates a restricted template.

[ { data-type [ UUID ] , }... ]

The absence of either of the above indicates a closed template.

Examples

template Mesh {
<3D82AB44-62DA-11cf-AB39-0020AF71E433>
DWORD nVertices;
array Vector vertices[nVertices];
DWORD nFaces;
array MeshFace faces[nFaces];
 [ ... ]                // An open template
}
template Vector {
<3D82AB5E-62DA-11cf-AB39-0020AF71E433>
FLOAT x;
FLOAT y;
FLOAT z;
}                        // A closed template
template FileSystem {
<UUID>
STRING name;
[ Directory <UUID>, File <UUID> ]    // A restricted template
}

There is one special template—the Header template. It is recommended that each application define such a template and use it to define application-specific information, such as version information. If present, this header will be read by the DirectX file format API. If a flags member is available, it will be used to determine how the following data is interpreted. The flags member, if defined, should be a DWORD. One bit is currently defined—bit 0. If this bit is clear, the following data in the file is binary. If set, the following data is text. Multiple header data objects can be used to switch between binary and text within the file.

Data

Data objects contain the actual data or a reference to that data. Each has a corresponding template that specifies the data type.

Data objects have the following form.

<Identifier> [name] { [<UUID>]
<member 1>;
...
<member n>;
}

This section discusses the following parts of data objects:

  • Identifier
  • Name
  • Members

Example templates are presented in Examples.

Identifier

This part is compulsory and must match a previously defined data type or primitive.

Name

Name is optional. (See earlier for the syntax definition.)

Members

Data members can be one of the following: data object, data reference, integer list, float list, or string list.

Data object

A nested data object. This allows the hierarchical nature of the file format to be expressed. The types of nested data objects allowed in the hierarchy may be restricted. See Templates for more information.

Data reference

A reference to a previously encountered data object. The syntax is as follows:

{
  name |
  UUID |
  name UUID
}

Integer list

A semicolon-separated list of integers. For example:

1; 2; 3;

Float list

A semicolon-separated list of floats. For example:

1.0; 2.0; 3.0;

String List

A semicolon-separated list of strings. For example:

"Moose"; "Goats"; "Sheep";

Use of Commas and Semicolons

This topic is perhaps the most complex syntax issue in the file format, and it is very strict. Commas are used to separate array members; semicolons terminate each data item.

For example, if a template is defined as:

template mytemp {
DWORD myvar;
}

Then an instance of this template would look like:

mytemp dataTemp {
1;
}

A template containing another template is defined as:

template mytemp {
DWORD myvar;
DWORD myvar2;
}
template container {
FLOAT aFloat;
mytemp aTemp;
}

Then an instance of this template would look like:

container dataContainer {
1.1;
2; 3;;
}

Note that the second line that represents the mytemp inside container has two semicolons at the end of the line. The first semicolon indicates the end of the data item, aTemp (inside container), and the second semicolon indicates the end of the container.

If an array is defined as:

Template mytemp {
array DWORD myvar[3];
}

Then an instance of this would look like:

mytemp aTemp {
1, 2, 3;
}

In the array case, there is no need for the data items to be separated by semicolons because they are delineated by commas. The semicolon at the end marks the end of the array.

Consider a template that contains an array of data items defined by a template.

template mytemp {
DWORD myvar;
DWORD myvar2;
}
template container {
DWORD count;
array mytemp tempArray[count];
}

Then an instance of this would look like:

container aContainer {
3;
1;2;,3;4;,5;6;;
}


DirectX File Templates

This appendix lists the templates used by Microsoft® Direct3D® Retained Mode. A familiarity with Direct3D Retained Mode data types is assumed.

  • Template Name: Header
  • Template Name: Vector
  • Template Name: Coords2d
  • Template Name: Quaternion
  • Template Name: Matrix4x4
  • Template Name: ColorRGBA
  • Template Name: ColorRGB
  • Template Name: Indexed Color
  • Template Name: Boolean
  • Template Name: Boolean2d
  • Template Name: Material
  • Template Name: TextureFilename
  • Template Name: MeshFace
  • Template Name: MeshFaceWraps
  • Template Name: MeshTextureCoords
  • Template Name: MeshNormals
  • Template Name: MeshVertexColors
  • Template Name: MeshMaterialList
  • Template Name: Mesh
  • Template Name: FrameTransformMatrix
  • Template Name: Frame
  • Template Name: FloatKeys
  • Template Name: TimedFloatKeys
  • Template Name: AnimationKey
  • Template Name: AnimationOptions
  • Template Name: Animation
  • Template Name: AnimationSet

Template Name: Header

UUID

<3D82AB43-62DA-11cf-AB39-0020AF71E433>

Member name | Type | Optional array size | Optional data objects
major | WORD |  | None
minor | WORD |  |
flags | DWORD |  |

Description

This template defines the application-specific header for the Direct3D Retained Mode usage of the DirectX file format. The Retained Mode uses the major and minor flags to specify the current major and minor versions for the Retained Mode file format.

Template Name: Vector

UUID

<3D82AB5E-62DA-11cf-AB39-0020AF71E433>

Member name | Type | Optional array size | Optional data objects
x | FLOAT |  | None
y | FLOAT |  |
z | FLOAT |  |

Description

This template defines a vector.

Template Name: Coords2d

UUID

<F6F23F44-7686-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
u | FLOAT |  | None
v | FLOAT |  |

Description

A two dimensional vector used to define a mesh's texture coordinates.

Template Name: Quaternion

UUID

<10DD46A3-775B-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
s | FLOAT |  | None
v | Vector |  |

Description

Currently unused.

Template Name: Matrix4x4

UUID

<F6F23F45-7686-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
matrix | array FLOAT | 16 | None

Description

This template defines a 4×4 matrix. This is used as a frame transformation matrix.

Template Name: ColorRGBA

UUID

<35FF44E0-6C7C-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
red | FLOAT |  | None
green | FLOAT |  |
blue | FLOAT |  |
alpha | FLOAT |  |

Description

This template defines a color object with an alpha component. This is used for the face color in the material template definition.

Template Name: ColorRGB

UUID

<D3E16E81-7835-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
red | FLOAT |  | None
green | FLOAT |  |
blue | FLOAT |  |

Description

This template defines the basic RGB color object.

Template Name: Indexed Color

UUID

<1630B820-7842-11cf-8F52-0040333594A3>

Member name | Type | Optional array size
index | DWORD |
indexColor | ColorRGBA |

Description

This template consists of an index parameter and an RGBA color and is used for defining mesh vertex colors. The index defines the vertex to which the color is applied.

Template Name: Boolean

UUID

<4885AE61-78E8-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
DWORD | truefalse |  | None

Description

Defines a simple Boolean type. This template should be set to 0 or 1.

Template Name: Boolean2d

UUID

<4885AE63-78E8-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
u | Boolean |  | None
v | Boolean |  |

Description

This template defines a set of two Boolean values used in the MeshFaceWraps template to define the texture topology of an individual face.

Template Name: Material

UUID

<3D82AB4D-62DA-11cf-AB39-0020AF71E433>

Member name | Type | Optional array size | Optional data objects
faceColor | ColorRGBA |  | Any
power | FLOAT |  |
specularColor | ColorRGB |  |
emissiveColor | ColorRGB |  |

Description

This template defines a basic material color that can be applied to either a complete mesh or a mesh's individual faces. The power is the specular exponent of the material. Note that the ambient color requires an alpha component.

TextureFilename is an optional data object used by Direct3D Retained Mode. If this object is not present, the face is untextured.

Template Name: TextureFilename

UUID

<A42790E1-7810-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
filename | STRING |  | None

Description

This template enables you to specify the file name of a texture to apply to a mesh or a face. This template should appear within a material object.

Template Name: MeshFace

UUID

<3D82AB5F-62DA-11cf-AB39-0020AF71E433>

Member name | Type | Optional array size | Optional data objects
nFaceVertexIndices | DWORD |  | None
faceVertexIndices | array DWORD | nFaceVertexIndicies |

Description

This template is used by the Mesh template to define a mesh's faces. Each element of the nFaceVertexIndices array references a mesh vertex used to build the face.

Template Name: MeshFaceWraps

UUID

<4885AE62-78E8-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
nFaceWrapValues | DWORD |  | None
faceWrapValues | Boolean2d |  |

Description

This template is used to define the texture topology of each face in a wrap. The value of the nFaceWrapValues member should be equal to the number of faces in a mesh.

Template Name: MeshTextureCoords

UUID

<F6F23F40-7686-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
nTextureCoords | DWORD |  | None
textureCoords | array Coords2d | nTextureCoords |

Description

This template defines a mesh's texture coordinates.

Template Name: MeshNormals

UUID

<F6F23F43-7686-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
nNormals | DWORD |  | None
normals | array Vector | nNormals |
nFaceNormals | DWORD |  |
faceNormals | array MeshFace | nFaceNormals |

Description

This template defines normals for a mesh. The first array of vectors is the normal vectors themselves, and the second array is an array of indexes specifying which normals should be applied to a given face. The value of the nFaceNormals member should be equal to the number of faces in a mesh.

Template Name: MeshVertexColors

UUID

<1630B821-7842-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
nVertexColors | DWORD |  | None
vertexColors | array IndexedColor | nVertexColors |

Description

This template specifies vertex colors for a mesh, instead of applying a material per face or per mesh.

Template Name: MeshMaterialList

UUID

<F6F23F42-7686-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
nMaterials | DWORD |  | Material
nFaceIndexes | DWORD |  |
FaceIndexes | array DWORD | nFaceIndexes |

Description

This template is used in a mesh object to specify which material applies to which faces. The nMaterials member specifies how many materials are present, and materials specify which material to apply.

Template Name: Mesh

UUID

<3D82AB44-62DA-11cf-AB39-0020AF71E433>

Member name | Type | Optional array size | Optional data objects
nVertices | DWORD |  | Any
vertices | array Vector | nVertices |
nFaces | DWORD |  |
faces | array MeshFace | nFaces |

Description

This template defines a simple mesh. The first array is a list of vertices, and the second array defines the faces of the mesh by indexing into the vertex array.

Optional Data Elements

The following optional data elements are used by Direct3D Retained Mode.

MeshFaceWraps | If this is not present, wrapping for both u and v defaults to false.
MeshTextureCoords | If this is not present, there are no texture coordinates.
MeshNormals | If this is not present, normals are generated using the GenerateNormals method of the API.
MeshVertexColors | If this is not present, the colors default to white.
MeshMaterialList | If this is not present, the material defaults to white.

Template Name: FrameTransformMatrix

UUID

<F6F23F41-7686-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
frameMatrix | Matrix4x4 |  | None

Description

This template defines a local transform for a frame (and all its child objects).

Template Name: Frame

UUID

<3D82AB46-62DA-11cf-AB39-0020AF71E433>

Member name | Type | Optional array size | Optional data objects
None |  |  | Any

Description

This template defines a frame. Currently, the frame can contain objects of the type Mesh and a FrameTransformMatrix.

Optional Data Elements

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 Name: FloatKeys

UUID

<10DD46A9-775B-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
nValues | DWORD |  | None
values | array FLOAT | nValues |

Description

This template defines an array of floating-point numbers (floats) and the number of floats in that array. This is used for defining sets of animation keys.

Template Name: TimedFloatKeys

UUID

<F406B180-7B3B-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
time | DWORD |  | None
tfkeys | FloatKeys |  |

Description

This template defines a set of floats and a positive time used in animations.

Template Name: AnimationKey

UUID

<10DD46A8-775B-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
keyType | DWORD |  | None
nKeys | DWORD |  |
keys | array TimedFloatKeys | nKeys |

Description

This template defines a set of animation keys. The keyType member specifies whether the keys are rotation, scale or position keys (using the integers 0, 1, or 2 respectively).

Template Name: AnimationOptions

UUID

<E2BF56C0-840F-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
openclosed | DWORD |  | None
positionquality | DWORD |  |

Description

This template enables you to set the Direct3D Retained Mode Animation options. The openclosed member can be either 0 for a closed or 1 for an open animation. The positionquality member is used to set the position quality for any position keys specified and can either be 0 for spline positions or 1 for linear positions. By default, an animation is closed.

Template Name: Animation

UUID

<3D82AB4F-62DA-11cf-AB39-0020AF71E433>

Member name | Type | Optional array size | Optional data objects
None |  |  | Any

Description

This template 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 Elements

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 Name: AnimationSet

UUID

<3D82AB50-62DA-11cf-AB39-0020AF71E433>

Member name | Type | Optional array size | Optional data objects
none |  |  | Animation

Description

An AnimationSet template 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.


DirectX File Cube Example

This section describes a simple cube and then shows how to add textures, frames, and animations to it.

  • A Simple Cube
  • Adding Textures
  • Frames and Animations

A Simple Cube

This file defines a simple cube that has four red sides and two green sides. Notice in this file that optional information is being used to add information to the data object defined by the Mesh template.

Material RedMaterial {
1.000000;0.000000;0.000000;1.000000;;    // R = 1.0, G = 0.0, B = 0.0
0.000000;
0.000000;0.000000;0.000000;;
0.000000;0.000000;0.000000;;
}
Material GreenMaterial {
0.000000;1.000000;0.000000;1.000000;;     // R = 0.0, G = 1.0, B = 0.0
0.000000;
0.000000;0.000000;0.000000;;
0.000000;0.000000;0.000000;;
}
// Define a mesh with 8 vertices and 12 faces (triangles). Use
// optional data objects in the mesh to specify materials, normals,
// and texture coordinates.
Mesh CubeMesh {
8;                                // 8 vertices
1.000000;1.000000;-1.000000;,     // vertex 0
-1.000000;1.000000;-1.000000;,    // vertex 1
-1.000000;1.000000;1.000000;,     // etc...
1.000000;1.000000;1.000000;,
1.000000;-1.000000;-1.000000;,
-1.000000;-1.000000;-1.000000;,
-1.000000;-1.000000;1.000000;,
1.000000;-1.000000;1.000000;;

12;                      // 12 faces
3;0,1,2;,                // face 0 has 3 vertices
3;0,2,3;,                // etc...
3;0,4,5;,
3;0,5,1;,
3;1,5,6;,
3;1,6,2;,
3;2,6,7;,
3;2,7,3;,
3;3,7,4;,
3;3,4,0;,
3;4,7,6;,
3;4,6,5;;

// All required data has been defined. Now define optional data
// using the hierarchical nature of the file format.
MeshMaterialList {
2;                    // Number of materials used
12;                   // A material for each face
0,                    // face 0 uses the first
0,                    // material
0,
0,
0,
0,
0,
0,
1,                    // face 8 uses the second
1,                    // material
1,
1;;
{RedMaterial}         // References to the definitions
{GreenMaterial}       // of material 0 and 1
}
MeshNormals {
8;                    // define 8 normals
0.333333;0.666667;-0.666667;,
-0.816497;0.408248;-0.408248;,
-0.333333;0.666667;0.666667;,
0.816497;0.408248;0.408248;,
0.666667;-0.666667;-0.333333;,
-0.408248;-0.408248;-0.816497;,
-0.666667;-0.666667;0.333333;,
0.408248;-0.408248;0.816497;;
12;                   // For the 12 faces,
3;0,1,2;,             // define the normals
3;0,2,3;,
3;0,4,5;,
3;0,5,1;,
3;1,5,6;,
3;1,6,2;,
3;2,6,7;,
3;2,7,3;,
3;3,7,4;,
3;3,4,0;,
3;4,7,6;,
3;4,6,5;;
}
MeshTextureCoords {
8;                        // Define texture coords
0.000000;1.000000;        // for each of the vertices
1.000000;1.000000;
0.000000;1.000000;
1.000000;1.000000;
0.000000;0.000000;
1.000000;0.000000;
0.000000;0.000000;
1.000000;0.000000;;
}
}

Adding Textures

To add textures, use the hierarchical nature of the file format and add an optional TextureFilename data object to the Material data objects. So, the Material objects now read as follows:

Material RedMaterial {
1.000000;0.000000;0.000000;1.000000;;    // R = 1.0, G = 0.0, B = 0.0
0.000000;
0.000000;0.000000;0.000000;;
0.000000;0.000000;0.000000;;
TextureFilename {
"tex1.ppm";
}
}
Material GreenMaterial {
0.000000;1.000000;0.000000;1.000000;;     // R = 0.0, G = 1.0, B = 0.0
0.000000;
0.000000;0.000000;0.000000;;
0.000000;0.000000;0.000000;;
TextureFilename {
"win95.ppm";
}
}

Frames and Animations

This section shows how to add frames and animations to a simple cube.

  • Frames
  • AnimationSets and Animations

Frames

A frame is expected to take the following structure:

Frame Aframe {        // The frame name is chosen for convenience.
FrameTransformMatrix {
...transform data...
}
[ Meshes ] and/or [ More frames]
}

Place the previously defined cube mesh inside a frame with an identity transform. Then apply an animation to this frame.

Frame CubeFrame {
FrameTransformMatrix {
1.000000, 0.000000, 0.000000, 0.000000,
0.000000, 1.000000, 0.000000, 0.000000,
0.000000, 0.000000, 1.000000, 0.000000,
0.000000, 0.000000, 0.000000, 1.000000;;
}
{CubeMesh}        // You could have the mesh inline, but this
                 // uses an object reference instead.
}

AnimationSets and Animations

Animations and AnimationSets in the DirectX file format map directly to the Direct3D Retained Mode animation concepts.

Animation Animation0 {        // The name is chosen for convenience.
{ Frame that it applies to&em;normally a reference }
AnimationKey {
...animation key data...
}
{ ...more animation keys... }
}

Animations are then grouped into AnimationSets:
AnimationSet AnimationSet0 { // The name is chosen for convenience.
{ an animation—could be inline or a reference }
{ ... more animations ... }
}

Now take the cube through an animation.

AnimationSet AnimationSet0 {
Animation Animation0 {
{CubeFrame}    // Use the frame containing the cube
AnimationKey {
2;             // Position keys
9;             // 9 keys
10; 3; -100.000000, 0.000000, 0.000000;;,
20; 3; -75.000000, 0.000000, 0.000000;;,
30; 3; -50.000000, 0.000000, 0.000000;;,
40; 3; -25.500000, 0.000000, 0.000000;;,
50; 3; 0.000000, 0.000000, 0.000000;;,
60; 3; 25.500000, 0.000000, 0.000000;;,
70; 3; 50.000000, 0.000000, 0.000000;;,
80; 3; 75.500000, 0.000000, 0.000000;;,
90; 3; 100.000000, 0.000000, 0.000000;;;
}
}
}


DirectX File Binary Format

This section details the binary version of the Microsoft® DirectX® file format as introduced with the release of DirectX 3.0. This appendix should be read in conjunction with the DirectX File Format Architecture section.

The binary format is a tokenized representation of the text format. Tokens can be stand-alone or accompanied by primitive data records. Stand-alone tokens give grammatical structure and record-bearing tokens supply the necessary data.

Note that all data is stored in little endian format.

A valid binary data stream consists of a header followed by templates and/or data objects.

This section discusses the following components of the binary file format:

  • Header
  • Tokens
  • Token Records
  • Templates
  • Data

In addition, example templates are provided, in Example Templates. A binary data object is shown in Example Data.

Header

The following definitions should be used when directly reading and writing the binary header. Note that compressed data streams are not currently supported and are therefore not detailed here.

#define XOFFILE_FORMAT_MAGIC \
  ((long)'x' + ((long)'o' << 8) + ((long)'f' << 16) + ((long)' ' << 24))

#define XOFFILE_FORMAT_VERSION \
  ((long)'0' + ((long)'3' << 8) + ((long)'0' << 16) + ((long)'2' << 24))

#define XOFFILE_FORMAT_BINARY \
  ((long)'b' + ((long)'i' << 8) + ((long)'n' << 16) + ((long)' ' << 24))

#define XOFFILE_FORMAT_TEXT   \
  ((long)'t' + ((long)'x' << 8) + ((long)'t' << 16) + ((long)' ' << 24))

#define XOFFILE_FORMAT_COMPRESSED \
  ((long)'c' + ((long)'m' << 8) + ((long)'p' << 16) + ((long)' ' << 24))

#define XOFFILE_FORMAT_FLOAT_BITS_32 \
  ((long)'0' + ((long)'0' << 8) + ((long)'3' << 16) + ((long)'2' << 24))

#define XOFFILE_FORMAT_FLOAT_BITS_64 \
  ((long)'0' + ((long)'0' << 8) + ((long)'6' << 16) + ((long)'4' << 24))

Tokens

Tokens are written as little endian WORDs. A list of token values follows. The list is divided into record-bearing and stand-alone tokens.

Record-bearing

#define TOKEN_NAME 1
#define TOKEN_STRING 2
#define TOKEN_INTEGER 3
#define TOKEN_GUID 5
#define TOKEN_INTEGER_LIST 6
#define TOKEN_FLOAT_LIST 7

Stand-alone

#define TOKEN_OBRACE 10
#define TOKEN_CBRACE 11
#define TOKEN_OPAREN 12
#define TOKEN_CPAREN 13
#define TOKEN_OBRACKET 14
#define TOKEN_CBRACKET 15
#define TOKEN_OANGLE 16
#define TOKEN_CANGLE 17
#define TOKEN_DOT 18
#define TOKEN_COMMA 19
#define TOKEN_SEMICOLON 20
#define TOKEN_TEMPLATE 31
#define TOKEN_WORD 40
#define TOKEN_DWORD 41
#define TOKEN_FLOAT 42
#define TOKEN_DOUBLE 43
#define TOKEN_CHAR 44
#define TOKEN_UCHAR 45
#define TOKEN_SWORD 46
#define TOKEN_SDWORD 47
#define TOKEN_VOID 48
#define TOKEN_LPSTR 49
#define TOKEN_UNICODE 50
#define TOKEN_CSTRING 51
#define TOKEN_ARRAY 52

Token Records

This section describes the format of the records for each of the record-bearing tokens.

TOKEN_NAME

TOKEN_NAME is a variable length record. The token is followed by a count value that specifies the number of bytes that follow in the name field. An ASCII name of length count completes the record.
Field | Type | Size (bytes) | Contents
token | WORD | 2 | TOKEN_NAME
count | DWORD | 4 | Length of name field, in bytes
name | BYTE array | Count | ASCII name

TOKEN_STRING

TOKEN_STRING is a variable length record. The token is followed by a count value that specifies the number of bytes that follow in the string field. An ASCII string of length count continues the record, which is completed by a terminating token. The choice of terminator is determined by syntax issues discussed elsewhere.
Field | Type | Size (bytes) | Contents
token | WORD | 2 | TOKEN_STRING
count | DWORD | 4 | Length of string field in bytes
string | BYTE array | Count | ASCII string
terminator | DWORD | 4 | TOKEN_SEMICOLON or TOKEN_COMMA

TOKEN_INTEGER

TOKEN_INTEGER is a fixed length record. The token is followed by the integer value required.
Field | Type | Size (bytes) | Contents
token | WORD | 2 | TOKEN_INTEGER
value | DWORD | 4 | Single integer

TOKEN_GUID

TOKEN_GUID is a fixed-length record. The token is followed by the four data fields as defined by the OSF DCE standard.
Field | Type | Size (bytes) | Contents
token | WORD | 2 | TOKEN_GUID
data1 | DWORD | 4 | UUID data field 1
data2 | WORD | 2 | UUID data field 2
data3 | WORD | 2 | UUID data field 3
data4 | BYTE array | 8 | UUID data field 4

TOKEN_INTEGER_LIST

TOKEN_INTEGER_LIST is a variable length record. The token is followed by a count value that specifies the number of integers that follow in the list field. For efficiency, consecutive integer lists should be compounded into a single list.
Field | Type | Size (bytes) | Contents
token | WORD | 2 | TOKEN_INTEGER_LIST
count | DWORD | 4 | Number of integers in list field
list | DWORD array | 4 x count | Integer list

TOKEN_FLOAT_LIST

TOKEN_FLOAT_LIST is a variable-length record. The token is followed by a count value that specifies the number of floats or doubles that follow in the list field. The size of the floating point value (float or double) is determined by the value of float size specified in the file header. For efficiency, consecutive TOKEN_FLOAT_LISTs should be compounded into a single list.
Field | Type | Size (bytes) | Contents
token | WORD | 2 | TOKEN_FLOAT_LIST
count | DWORD | 4 | Number of floats or doubles in list field
list | float/double array | 4 or 8 x count | Float or double list

Templates

A template has the following syntax definition:

template              : TOKEN_TEMPLATE name TOKEN_OBRACE
                            class_id
                            template_parts
                            TOKEN_CBRACE

template_parts        : template_members_part TOKEN_OBRACKET
                        template_option_info
                        TOKEN_CBRACKET
                      | template_members_list

template_members_part : /* Empty */
                      | template_members_list

template_option_info  : ellipsis
                      | template_option_list

template_members_list :    template_members
                      | template_members_list template_members

template_members      : primitive
                      | array
                      | template_reference

primitive             : primitive_type optional_name TOKEN_SEMICOLON

array                 : TOKEN_ARRAY array_data_type name dimension_list
                        TOKEN_SEMICOLON

template_reference    : name optional_name YT_SEMICOLON

primitive_type        : TOKEN_WORD
                      | TOKEN_DWORD
                      | TOKEN_FLOAT
                      | TOKEN_DOUBLE
                      | TOKEN_CHAR
                      | TOKEN_UCHAR
                      | TOKEN_SWORD
                      | TOKEN_SDWORD
                      | TOKEN_LPSTR
                      | TOKEN_UNICODE
                      | TOKEN_CSTRING

array_data_type       : primitive_type
                      | name

dimension_list        : dimension
                      | dimension_list dimension

dimension             : TOKEN_OBRACKET dimension_size TOKEN_CBRACKET

dimension_size        : TOKEN_INTEGER
                      | name

template_option_list  : template_option_part
                      | template_option_list template_option_part

template_option_part  : name optional_class_id

name                  : TOKEN_NAME

optional_name         : /* Empty */
                      | name

class_id              : TOKEN_GUID

optional_class_id     : /* Empty */
                      | class_id

ellipsis              : TOKEN_DOT TOKEN_DOT TOKEN_DOT

Data

A data object has the following syntax definition.

Note that in number_list and float_list data in binary files, TOKEN_COMMA and TOKEN_SEMICOLON are not used. The comma and semicolon are used in string_list data. Also note that you can only use data_reference for optional data members.

object                : identifier optional_name TOKEN_OBRACE
                            optional_class_id
                            data_parts_list
                            TOKEN_CBRACE
data_parts_list       : data_part
                      | data_parts_list data_part

data_part             : data_reference
                      | object
                      | number_list
                      | float_list
                      | string_list

number_list           : TOKEN_INTEGER_LIST

float_list            : TOKEN_FLOAT_LIST

string_list           : string_list_1 list_separator

string_list_1         : string
                      | string_list_1 list_separator string

list_separator        : comma
                      | semicolon

string                : TOKEN_STRING

identifier            : name
                      | primitive_type

data_reference        : TOKEN_OBRACE name optional_class_id TOKEN_CBRACE

Example Templates

Two example binary template definitions follow. Note that data is stored in little endian format, which is not shown in these examples.

The closed template RGB is identified by the UUID {55b6d780-37ec-11d0-ab39-0020af71e433} and has three members r, g, and b each of type float.

TOKEN_TEMPLATE, TOKEN_NAME, 3, 'R', 'G', 'B', TOKEN_OBRACE,
TOKEN_GUID, 55b6d780, 37ec, 11d0, ab, 39, 00, 20, af, 71, e4, 33,
TOKEN_FLOAT, TOKEN_NAME, 1, 'r', TOKEN_SEMICOLON,
TOKEN_FLOAT, TOKEN_NAME, 1, 'g', TOKEN_SEMICOLON,
TOKEN_FLOAT, TOKEN_NAME, 1, 'b', TOKEN_SEMICOLON,
TOKEN_CBRACE

The closed template Matrix4x4 is identified by the UUID {55b6d781-37ec-11d0-ab39-0020af71e433} and has one member—a two-dimensional array named matrix of type float.

TOKEN_TEMPLATE, TOKEN_NAME, 9, 'M', 'a', 't', 'r', 'i', 'x', '4', 'x', '4', TOKEN_OBRACE,
TOKEN_GUID, 55b6d781, 37ec, 11d0, ab, 39, 00, 20, af, 71, e4, 33,
TOKEN_ARRAY, TOKEN_FLOAT, TOKEN_NAME, 6, 'm', 'a', 't', 'r', 'i', 'x',
TOKEN_OBRACKET, TOKEN_INTEGER, 4, TOKEN_CBRACKET,
TOKEN_OBRACKET, TOKEN_INTEGER, 4, TOKEN_CBRACKET,
TOKEN_CBRACE

Example Data

The binary data object that follows shows an instance of the RGB template defined earlier. The example object is named blue, and its three members r, g, and b have the values 0.0, 0.0 and 1.0, respectively. Note that data is stored in little endian format, which is not shown in this example.

TOKEN_NAME, 3, 'R', 'G', 'B', TOKEN_NAME, 4, 'b', 'l', 'u', 'e', TOKEN_OBRACE,
TOKEN_FLOAT_LIST, 3, 0.0, 0.0, 1.0, TOKEN_CBRACE


DirectX File Conv3ds.exe Utility

The Conv3ds.exe utility converts three-dimensional (3-D) models produced by Autodesk 3-D Studio and other modeling packages into the Microsoft® DirectX® file format. By default, the utility produces binary .x files with no templates.

This article contains the following sections.

  • Using Conv3ds.exe
  • Conv3ds.exe Optional Arguments
  • 3DS Files Produced from Lightwave Objects
  • Hints and Tips

Using Conv3ds.exe

You can run Conv3ds.exe with no options, and it will produce an .x file containing a hierarchy of frames. For example, consider the command:

conv3ds File.3ds

This command will produce an .x file called File.x from the .3ds file. You can use IDirect3DRMFrame3::Load to load the frame.

Conv3ds.exe Optional Arguments

Conv3ds.exe -A

If the .3ds file contains key frame data, you can use the -A option to produce an .x file that contains an animation set. The command for doing this would be:

conv3ds -A File.3ds

The File.3ds parameter is the name of the file to be converted. You can use IDirect3DRMAnimationSet2::Load to load the animation.

Conv3ds.exe -m

Use the -m option to make an .x file that contains a single mesh made from all the objects in the .3ds file.

conv3ds -m File.3ds

Use IDirect3DRMMeshBuilder3::Load to load the mesh.

Conv3ds.exe -T

Use the-T option to wrap all the objects and frame hierarchies in a single top-level frame. Using this option, all the frames and objects in the .3ds file can be loaded with a single call to IDirect3DRMFrame3::Load. The first top-level frame hierarchy in the .x file will be loaded. The frame containing all the other frames and meshes is called "x3ds_filename" (without the .3ds extension). The -T option will have no effect if it is used with the -m option.

Conv3ds.exe -s

The -s option allows you to specify a scale factor for all the objects converted in the .3ds file. For example, the following command makes all objects 10 times bigger:

conv3ds -s10 File.3ds

The following command makes all objects 10 times smaller:

conv3ds -s0.1 File.3ds

Conv3ds.exe -r

The -r option reverses the winding order of the faces when the .3ds file is converted. If, after converting the .3ds file and viewing it in Direct3D, the object appears inside-out, try converting it with the -r option. All Lightwave models exported as .3ds files need this option. See 3DS Files Produced from Lightwave Objects for details.

Conv3ds.exe -v

The -v option turns on verbose output mode. Specify an integer with it. The following table shows the currently supported integers.
Option | Meaning
-v0 | Default. Verbose mode off.
-v1 | Prints warnings about bad objects, and prints general information about what the converter is doing.
-v2 | Prints basic key frame information, the objects being included in the conversion process, and information about the objects being saved.
-v3 | Very verbose. Mostly useful for the debugging information it provides.

Conv3ds.exe -e

The -e option allows you to change the extension for texture map files. For example, consider the command:

conv3ds -e"ppm" File.3ds

If File.3ds contains objects that reference the texture map file Brick.gif, the .x file will reference the texture map file Brick.ppm. The converter does not convert the texture map file. The texture map files must be in the D3DPATH when the resulting .x file is loaded. The D3DPath is an environment variable that sets the default search path.

Conv3ds.exe -x

The -x option forces the Conv3ds.exe utility to produce a text .x file, instead of a binary .x file. Text files are larger but can be hand-edited easily.

Conv3ds.exe -X

The -X option forces the Conv3ds.exe utility to include the Direct3D Retained Mode .x file templates in the file. By default, the templates are not included.

Conv3ds.exe -t

The -t option specifies that the .x file produced will not contain texture information.

Conv3ds.exe -N

The -N option specifies that the .x file produced will not contain normal vector information. All the Direct3D Retained Mode load calls will generate normal vectors for objects with no normal vectors in the .x file.

Conv3ds.exe -c

The -c option specifies that the .x file produced should not contain texture coordinates. By default, if you use the -m option, the mesh that is output will contain (0,0) uv texture coordinates if the .3ds object had no texture coordinates.

Conv3ds.exe -f

The -f option specifies that the .x file produced should not contain a frame transformation matrix.

Conv3ds.exe - z and Conv3ds.exe -Z

The -z and -Z options allow you to adjust the alpha face color value of all the materials referenced by objects in the .x file. For example, the following command causes Conv3ds.exe to add 0.1 to all alpha values under 0.2:

conv3ds -z0.1 -Z0.2 File.3ds

The following command causes Conv3ds.exe to subtract 0.2 from the alpha values for all alphas:

conv3ds-z"-0.2" -z1 File.3ds

Conv3ds.exe -o

The -o option allows you to specify the file name for the .x file produced.

Conv3ds.exe -h

The -h option tells the converter not to try to resolve any hierarchy information in the .3ds file (usually produced by the key framer). Instead, all the objects are output in top-level frames if the -m option is not used.

3DS Files Produced from Lightwave Objects

There are several issues with .3ds files exported by the Trans3d plug-in for Lightwave. These are best handled using the following Conv3ds.exe command:

conv3ds -r -N -f -h -T|m trans3dfile.3ds

All the .3ds objects produced by Trans3d and the Lightwave object editor need their winding order reversed. Otherwise, they appear inside-out when displayed. They contain no surface normal vector information.

Hints and Tips

If you cannot see objects produced by Conv3ds.exe after loading them into the Direct3D Retained Mode viewer, use the scale option -s with a scale factor of approximately 100. This will increase the scale of the objects in the .x file.

If, after loading the object into the viewer and switching from flat shading into Gouraud shading, the object turns dark gray, try converting with the -N option.

If the textures are not loaded after the object is converted, check whether the object is referencing either .ppm or .bmp files by using the -e option. Also check whether the textures' widths and heights are a power of 2. Make sure the textures are stored in one of the directories in your D3DPATH.

Currently, Conv3ds.exe cannot handle dummy frames used in .3ds animations. It ignores them. However, it will convert any child objects.


DirectX File Samples

The following samples demonstrate loading from, converting to, and saving to the Microsoft® DirectX® file format. These samples come with the DirectX Foundation 6.x Software Development Kit (SDK) and can be found in folders beneath the Mssdk\Samples\Multimedia\D3drm\Src subdirectory.

  • CONVXFMT
  • XOFLOAD
  • XOFSAVE
  • XOFUSER

CONVXFMT

Path

Mssdk\Samples\Multimedia\D3drm\Src\Convxfmt

Description

Converts from one DirectX file format to another.

XOFLOAD

Path

Mssdk\Samples\Multimedia\D3drm\Src\Xofload

Description

Loads a file using the Direct3D Retained Mode templates.

XOFSAVE

Path

Mssdk\Samples\Multimedia\D3drm\Src\Xofsave

Description

Saves a file using the Direct3D Retained Mode templates.

XOFUSER

Path

Mssdk\Samples\Multimedia\D3drm\Src\Xofuser

Description

Saves a file using user-defined templates.


DirectX File Reference

This section discusses the function, interfaces, objects, and data types introduced with DirectX version 6.0 that are used to write to and read from Microsoft® DirectX® (.x) files. This section also briefly introduces the relationship between the interfaces and provides a hierarchy chart that shows interface inheritance. The DirectX file methods allow reading from and writing to both text and binary files.

You should be familiar with the format of DirectX files as outlined in DirectX File Format Architecture before using these interfaces. Understanding the file format will help you better understand the purpose of the interfaces and their methods.

This section contains the following topics.

  • Introduction
  • Hierarchy Chart
  • Function and Interfaces
  • Data Types
  • Return Values

Introduction

The following summary discusses how to load data from a DirectX (.x) file and how to save data to a DirectX file. The DirectX file methods work with both text and binary DirectX files and support loading from various sources, such as files, memory, resources, or URLs.

To use the DirectX file interfaces, you must first use the DirectXFileCreate function to create an IDirectXFile object.

Loading a File

Use the following procedure to load a DirectX file.

  1. Use the DirectXFileCreate function to create an IDirectXFile object.
  2. If templates are not present in the DirectX file that you are going to load, use the IDirectXFile::RegisterTemplates method to register those templates.
  3. Use the IDirectXFile::CreateEnumObject method to create an IDirectXFileEnumObject enumerator object.
  4. Loop through the objects in the file. For each object, perform the following steps.
    1. Use the IDirectXFileEnumObject::GetNextDataObject method to retrieve each IDirectXFileData object.
    2. Use the IDirectXFileData::GetType method to retrieve the data's type.
    3. Load the data using the IDirectXFileData::GetData method.
    4. If the object has optional members, retrieve the optional members by calling the IDirectXFileData::GetNextObject method.
  5. Release the IDirectXFileData object.
  6. Release the IDirectXFileEnumObject object.
  7. Release the IDirectXFile object.

Saving a File

Use the following procedure to save DirectX file templates and data to a DirectX file.

  1. Use the DirectXFileCreate function to create an IDirectXFile object.
  2. Use the IDirectXFile::RegisterTemplates method to inform the DirectX file system about any templates that you are going to use.
  3. Use the IDirectXFile::CreateSaveObject method to create an IDirectXFileSaveObject object.
  4. Use the IDirectXFileSaveObject::SaveTemplates method to save templates, if desired.
  5. Loop through the objects to save. For each top-level object, perform the following steps.
    1. Use the IDirectXFileSaveObject::CreateDataObject method to create an IDirectXFileData object as a top-level object in the file. If the top-level data object has optional child objects, add them to the object by using the appropriate method from the "How to Add" column in the next step.
    2. Each IDirectXFileData object can have optional child objects if its template allows it. The child objects can be any one of the three types of objects: IDirectXFileData, IDirectXFileDataReference, or IDirectXFileBinary. Loop through the objects you need to save, adding each optional child member to the object list in the manner appropriate to its type, as shown in the following table.
      Object Type | How to Add
      Data | Call the IDirectXFileSaveObject::CreateDataObject method to create an IDirectXFileData object, and then call the IDirectXFileData::AddDataObject method to add it as a child of the object.
      Data Reference | Call the IDirectXFileData::AddDataReference method to create and add the data reference object as a child of the object.
      Binary | Call the IDirectXFileData::AddBinaryObject method to create and add the binary object as a child of the object.
    3. Call the IDirectXFileSaveObject::SaveData method to save the data object and all of its children.
    4. Release the IDirectXFileData object.
  6. Release the IDirectXFileSaveObject object.
  7. Release the IDirectXFile object.

Hierarchy Chart

The following diagram shows the relationship between the DirectX file interfaces.

 IUnknown
 |
 +--IDirectXFile
 |
 +--IDirectXFileEnumObject
 |
 +--IDirectXFileObject
 |  |
 |  +--IDirectXFileBinary
 |  |
 |  +--IDirectXFileData
 |  |
 |  +--IDirectXFileDataReference
 |
 +--IDirectXFileSaveObject

Function and Interfaces

DirectX supplies the following DirectX file function and interfaces.

  • DirectXFileCreate function
  • IDirectXFile
  • IDirectXFileBinary
  • IDirectXFileData
  • IDirectXFileDataReference
  • IDirectXFileEnumObject
  • IDirectXFileObject
  • IDirectXFileSaveObject

The following table provides the Globally Unique Identifier (GUID) that corresponds with each DirectX File interface. For information about using a GUID with the QueryInterface method to determine a child object's type, see the introduction to the IDirectXFileData interface.
Interface | GUID
IDirectXFile | IID_IDirectXFile
IDirectXFileBinary | IID_IDirectXFileBinary
IDirectXFileData | IID_IDirectXFileData
IDirectXFileDataReference | IID_IDirectXFileDataReference
IDirectXFileEnumObject | IID_IDirectXFileEnumObject
IDirectXFileObject | IID_IDirectXFileObject
IDirectXFileSaveObject | IID_IDirectXFileSaveObject

DirectXFileCreate Function

The DirectXFileCreate function creates the IDirectXFile interface.

Syntax

STDAPI DirectXFileCreate(LPDIRECTXFILE *ppDirectXFile);

Parameters

ppDirectXFile
Address of a pointer to receive the created IDirectXFile interface.

Return Value

Returns one of the following values:
DXFILE_OK
DXFILEERR_BADALLOC
DXFILEERR_BADVALUE

Remarks

After using this function, use the IDirectXFile methods to: register templates (RegisterTemplates), create an enumerator object (CreateEnumObject), or create a save object (CreateSaveObject).

IDirectXFile

This interface enables you to create the IDirectXFileEnumObject and IDirectXFileSaveObject objects and to register templates.

Use the DirectXFileCreate function to create an instance of this object.

The IDirectXFile interface provides the following methods.

  • CreateEnumObject
  • CreateSaveObject
  • RegisterTemplates

IDirectXFile::CreateEnumObject

IDirectXFile

Creates an enumerator object.

Syntax

HRESULT CreateEnumObject(
  LPVOID pvSource,
  DXFILELOADOPTIONS dwLoadOptions,
  LPDIRECTXFILEENUMOBJECT * ppEnumObj);

Parameters

pvSource
Pointer to data whose contents depend on the value of dwLoadOptions as outlined in the following table.
dwLoadOptions value | Contents of pvSource
DXFILELOAD_FROMFILE | Name of the file
DXFILELOAD_FROMRESOURCE | DXFILELOADRESOURCE structure
DXFILELOAD_FROMMEMORY | DXFILELOADMEMORY structure
DXFILELOAD_FROMURL | Name of the Uniform Resource Locator (URL)
dwLoadOptions
Value that specifies the source of the data. One of the DXFILELOADOPTIONS values.
ppEnumObj
Address of a pointer to receive the created IDirectXFileEnumObject interface.

Return Value

Returns one of the following values:
DXFILE_OK
DXFILEERR_BADALLOC
DXFILEERR_BADFILEFLOATSIZE
DXFILEERR_BADFILETYPE
DXFILEERR_BADFILEVERSION
DXFILEERR_BADRESOURCE
DXFILEERR_BADVALUE
DXFILEERR_FILENOTFOUND
DXFILEERR_RESOURCENOTFOUND
DXFILEERR_URLNOTFOUND

Remarks

After using this method, use one of the IDirectXFileEnumObject methods to retrieve a data object.

IDirectXFile::CreateSaveObject

IDirectXFile

Creates an instance of an IDirectXFileSaveObject object.

Syntax

HRESULT CreateSaveObject(
  LPCSTR szFileName,
  DXFILEFORMAT dwFileFormat,
  LPDIRECTXFILESAVEOBJECT * ppSaveObj);

Parameters

szFileName
Pointer to the name of the file to use for saving data.
dwFileFormat
File format. One of the DXFILEFORMAT constants.
ppSaveObj
Address of a pointer to receive the created IDirectXFileSaveObject object.

Return Value

Returns one of the following values:
DXFILE_OK
DXFILEERR_BADALLOC
DXFILEERR_BADFILE
DXFILEERR_BADVALUE

Remarks

After using this method, use methods of the IDirectXFileSaveObject interface to create data objects and to save templates or data.

IDirectXFile::RegisterTemplates

IDirectXFile

Registers custom templates.

Syntax

HRESULT RegisterTemplates(
  LPVOID pvData,
  DWORD cbSize);

Parameters

pvData
Pointer to a buffer consisting of a DirectX file in text or binary format that contains templates.
cbSize
Size of the buffer pointed to by pvData, in bytes.

Return Value

Returns one of the following values:
DXFILE_OK
DXFILEERR_BADFILEFLOATSIZE
DXFILEERR_BADFILETYPE
DXFILEERR_BADFILEVERSION
DXFILEERR_BADVALUE
DXFILEERR_PARSEERROR

Remarks

The following code fragment provides an example call to RegisterTemplates and example contents for the buffer to which pvData points.

IDirectXFile * pDXFile;

char *szTemplates = "xof 0303txt 0032\
    template SimpleData { \
        <2b934580-9e9a-11cf-ab39-0020af71e433> \
        DWORD item1;DWORD item2;DWORD item3;} \
    template ArrayData { \
        <2b934581-9e9a-11cf-ab39-0020af71e433> \
        DWORD cItems; array DWORD aItem[2][cItems]; [...] } \
    template RestrictedData { \
        <2b934582-9e9a-11cf-ab39-0020af71e433> \
        DWORD item; [SimpleData]}";

hr = pDXFile->RegisterTemplates(szTemplates, strlen(szTemplates));

All templates must specify a name and a UUID (Universally Unique Identifier).

IDirectXFileBinary

This interface enables you to read binary data and to retrieve information about it.

The IDirectXFileBinary interface provides the following methods.

  • GetMimeType
  • GetSize
  • Read

In addition, IDirectXFileBinary inherits the IDirectXFileObject::GetId and IDirectXFileObject::GetName methods.

IDirectXFileBinary::GetMimeType

IDirectXFileBinary

Retrieves the mime type for the binary data.

Syntax

HRESULT GetMimeType(LPCSTR * pszMimeType);

Parameters

pszMimeType
Address of a pointer to receive the mime type string.

Return Value

Returns one of the following values:
DXFILE_OK
DXFILEERR_BADVALUE

When there is no Mime type specified in a specified .X file for a binary object, the function will set *pszMimeType to NULL.

IDirectXFileBinary::GetSize

IDirectXFileBinary

Retrieves the size of the binary data.

Syntax

HRESULT GetSize(DWORD * pcbSize);

Parameters

pcbSize
Pointer to receive the size of the binary data, in bytes.

Return Value

Returns one of the following values:
DXFILE_OK
DXFILEERR_BADVALUE

IDirectXFileBinary::Read

IDirectXFileBinary

Reads binary data.

Syntax

HRESULT Read(
  LPVOID pvData,
  DWORD cbSize,
  LPDWORD pcbRead);

Parameters

pvData
Pointer to the buffer that receives the data that has been read.
cbSize
Size of the buffer pointed to by pvData, in bytes.
pcbRead
Pointer to the number of bytes read.

Return Value

Returns one of the following values:
DXFILE_OK
DXFILEERR_BADVALUE
DXFILEERR_NOMOREDATA

IDirectXFileData

The IDirectXFileData interface provides methods that enable you to build or to access the immediate hierarchy of the data object. Template restrictions determine the hierarchy. Data types allowed by the template are called optional members. The optional members are not required, but an object might miss important information without them. These optional members are saved as children of the data object. The children can be another data object, a reference to an earlier data object, or a binary object.

When saving objects to a DirectX file, use AddBinaryObject, AddDataObject, or AddDataReference to add binary objects, data objects, or data reference objects, respectively, to the file. For more information, see Saving a File.

When enumerating objects in an existing DirectX file, use the GetData, GetNextObject, and GetType methods as follows:

  1. Use GetType to retrieve the object's template's GUID. For example, for a mesh object GetType retrieves the GUID for the mesh template.
  2. Use GetData to retrieve required members of the object in a contiguous chunk of memory.
  3. For each child object, perform the following steps.
    1. Use GetNextObject to retrieve a child object.
    2. Use QueryInterface to determine the child object's type (data, data reference, or binary) by querying for support of the IDirectXFileData, IDirectXFileDataReference, and IDirectXFileBinary interfaces, in turn. The interface supported indicates the object's type. The following code fragment determines whether an object is a binary object by determining if it supports IDirectXFileBinary.
      IDirectXFileObject *DXFileObj;
IDirectXFileBinary *DXFileBinary;

if (FAILED(DXFileObj->QueryInterface(IID_IDirectXFileBinary,
                                     (LPVOID *)&DXFileBinary))
{
    // Object does not support IDirectXFileBinary and therefore
    // is not a binary object.
}
else
{
    // Object is binary.
}
    3. After you have determined the child object's type, use methods of the appropriate interface (IDirectXFileData, IDirectXFileDataReference, or IDirectXFileBinary) to act upon the child object.

The IDirectXFileData interface provides the following methods.

  • AddBinaryObject
  • AddDataObject
  • AddDataReference
  • GetData
  • GetNextObject
  • GetType

In addition, IDirectXFileData inherits the IDirectXFileObject::GetId and IDirectXFileObject::GetName methods.

IDirectXFileData::AddBinaryObject

IDirectXFileData

Creates and adds a binary object as a child object.

Syntax

HRESULT AddBinaryObject(
  LPCSTR szName,
  const GUID * pguid,
  LPCSTR szMimeType,
  LPVOID pvData,
  DWORD cbSize);

Parameters

szName
Pointer to the name of the object. Optional, specify NULL if the object does not need a name.
pguid
Pointer to the GUID representing the object. Optional, specify NULL if the object does not need a GUID.
szMimeType
Pointer to the object's mime type.
pvData
Pointer to the object's data.
cbSize
Size of the buffer pointed to by pvData, in bytes.

Return Value

Returns one of the following values:
DXFILE_OK
DXFILEERR_BADALLOC
DXFILEERR_BADVALUE

Remarks

For more information about saving child objects, see the introduction to this interface, IDirectXFileData.

IDirectXFileData::AddDataObject

IDirectXFileData

Adds a data object as a child object.

Syntax

HRESULT AddDataObject(LPDIRECTXFILEDATA pDataObj);

Parameters

pDataObj
Pointer to the IDirectXFileData object to add as a child object.

Return Value

Returns one of the following values:
DXFILE_OK
DXFILEERR_BADALLOC
DXFILEERR_BADVALUE

Remarks

Use the IDirectXFileSaveObject::CreateDataObject method to create the IDirectXFileData object before calling this method.

For more information about saving objects, see the introduction to this interface, IDirectXFileData.

IDirectXFileData::AddDataReference

IDirectXFileData

Creates and adds a data reference object as a child object.

Syntax

HRESULT AddDataReference(
  LPCSTR szRef,
  const GUID * pguidRef);

Parameters

szRef
Pointer to the name of the referenced data object. Can be NULL if pguidRef provides a reference to the GUID.
pguidRef
Pointer to the GUID representing the data. Can be NULL if szRef provides a reference to the name.

Return Value

Returns one of the following values:
DXFILE_OK
DXFILEERR_BADALLOC
DXFILEERR_BADVALUE

Remarks

At least one of the szRef or pguidRef parameters must be non-NULL.

For more information about saving objects, see the introduction to this interface, IDirectXFileData.

IDirectXFileData::GetData

IDirectXFileData

Retrieves the data for one of the object's members or the data for all members.

Syntax

HRESULT GetData(
  LPCSTR szMember,
  DWORD * pcbSize,
  void ** ppvData);

Parameters

szMember
Name of the member for which to retrieve data. Specify NULL to retrieve all required members' data.
pcbSize
Pointer to receive the ppvData buffer size, in bytes.
ppvData
Address of a pointer to receive the data associated with szMember. If szMember is NULL, *ppvData is set to point to a buffer containing all required members' data in a contiguous block of memory.

Return Value

Returns one of the following values:
DXFILE_OK
DXFILEERR_BADARRAYSIZE
DXFILEERR_BADDATAREFERENCE
DXFILEERR_BADVALUE

Remarks

This method retrieves the data for required members of a data object but no data for optional (child) members. Use GetNextObject to retrieve child objects.

For more information about enumerating objects, see the introduction to this interface, IDirectXFileData.

IDirectXFileData::GetNextObject

IDirectXFileData

Retrieves the next child data object, data reference object, or binary object in the DirectX file.

Syntax

HRESULT GetNextObject(LPDIRECTXFILEOBJECT * ppChildObj);

Parameters

ppChildObj
Address to receive a pointer to the child object's IDirectXFileObject interface.

Return Value

Returns one of the following values:
DXFILE_OK
DXFILEERR_BADVALUE
DXFILEERR_NOMOREOBJECTS

Remarks

To determine the type of object retrieved, use QueryInterface to query the retrieved object for support of IDirectXFileData, IDirectXFileDataReference, or IDirectXFileBinary interfaces. The interface supported indicates the type of object (data, data reference, or binary).

For more information about child objects, enumerating objects and determining the type of object, see the introduction to this interface, IDirectXFileData.

IDirectXFileData::GetType

IDirectXFileData

Retrieves the GUID of the object's template.

Syntax

HRESULT GetType(const GUID ** ppguid);

Parameters

ppguid
Address of a pointer to receive the GUID of the object's template.

Return Value

Returns one of the following values:
DXFILE_OK
DXFILEERR_BADVALUE

IDirectXFileDataReference

The IDirectXFileDataReference interface provides support for data reference objects. A data reference object refers to a data object that is defined earlier in the file. This allows you to use the same object multiple times without repeating it in the file.

After you have determined that an object is a data reference object, use this interface's Resolve method to get the real object that is defined earlier in the file. For information about how to determine that you have a data reference object, see the IDirectXFileData interface.

In addition, IDirectXFileDataReference inherits the IDirectXFileObject::GetId and IDirectXFileObject::GetName methods.

IDirectXFileDataReference::Resolve

IDirectXFileDataReference

Resolves data references.

Syntax

HRESULT Resolve(LPDIRECTXFILEDATA * ppDataObj);

Parameters

ppDataObj
Address of a pointer to receive the IDirectXFileData object.

Return Value

Returns one of the following values:
DXFILE_OK
DXFILEERR_BADVALUE
DXFILEERR_NOTFOUND

IDirectXFileEnumObject

This interface enables you to loop through to retrieve all data objects in the file and to retrieve a data object by GUID or by name.

The IDirectXFileEnumObject interface provides the following methods.

  • GetDataObjectById
  • GetDataObjectByName
  • GetNextDataObject

IDirectXFileEnumObject::GetDataObjectById

IDirectXFileEnumObject

Retrieves the data object that has the specified GUID.

Syntax

HRESULT GetDataObjectById(
  REFGUID rguid,
  LPDIRECTXFILEDATA * ppDataObj);

Parameters

rguid
Reference to the desired GUID.
ppDataObj
Pointer to receive the retrieved IDirectXFileData object.

Return Value

Returns one of the following values:
DXFILE_OK
DXFILEERR_BADVALUE
DXFILEERR_NOTFOUND

IDirectXFileEnumObject::GetDataObjectByName

IDirectXFileEnumObject

Retrieves the data object that has the specified name.

Syntax

HRESULT GetDataObjectByName(
  LPCSTR szName,
  LPDIRECTXFILEDATA * ppDataObj);

Parameters

szName
Pointer to the desired name.
ppDataObj
Pointer to receive the retrieved IDirectXFileData object.

Return Value

Returns one of the following values:
DXFILE_OK
DXFILEERR_BADVALUE
DXFILEERR_NOTFOUND

IDirectXFileEnumObject::GetNextDataObject

IDirectXFileEnumObject

Retrieves the next top-level object in the DirectX file. Top-level objects are always data objects. Data reference objects and binary objects can only be children of data objects.

Syntax

HRESULT GetNextDataObject(
  LPDIRECTXFILEDATA * ppDataObj);

Parameters

ppDataObj
Pointer to receive the retrieved IDirectXFileData object.

Return Value

Returns one of the following values:
DXFILE_OK
DXFILEERR_BADVALUE
DXFILEERR_NOMOREOBJECTS

IDirectXFileObject

IDirectXFileObject is the base interface for DirectX file objects. IDirectXFileData, IDirectXFileDataReference and IDirectXFileBinary interfaces all inherit from this interface.

The IDirectXFileObject interface provides the following methods.

  • GetId
  • GetName

IDirectXFileObject::GetId

IDirectXFileObject

Retrieves a pointer to the GUID that identifies a DirectX file object.

Syntax

HRESULT GetId (LPGUID pGuid)

Parameters

pGuid
Pointer to a GUID to receive the object's ID. The function will set the GUID to a NULL GUID if the object does not have an ID.

Return Value

Returns one of the following values.
DXFILE_OK
DXFILEERR_BADVALUE

IDirectXFileObject::GetName

IDirectXFileObject

Retrieves a pointer to a DirectX file object's name.

Syntax

HRESULT GetName (LPSTR pstrNameBuf, LPDWORD pdwBufLen)

Parameters

pstrNameBuf
Pointer to the buffer in which the DirectX file object's name will be copied. Set to NULL if only the buffer length is needed.
pdwBufLen
Pointer to a DWORD specifying the length of the buffer pointed to by pstrNameBuf. pdwBufLen will be modified to the buffer length needed to hold the object's name even if pstrNameBuf is NULL. In either case, the function will return DXFILEERR_BADVALUE if the original value of pdwBufLen is not as large as or larger than the length needed to hold the object's name.

Return Value

Returns one of the following values.
DXFILE_OK
DXFILEERR_BADALLOC

IDirectXFileSaveObject

This interface enables you to create data objects and to save templates and data objects. Use IDirectXFile::CreateSaveObject to create an instance of this object. Then use SaveTemplates to save the templates. Use CreateDataObject to create a data object, and use SaveData to save the data.

Note that templates are not required in every file. For example, you could put all templates in one DirectX file rather than duplicating them in every DirectX file.

The IDirectXFileSaveObject interface provides the following methods.

  • CreateDataObject
  • SaveData
  • SaveTemplates

IDirectXFileSaveObject::CreateDataObject

IDirectXFileSaveObject

Creates a data object.

Syntax

HRESULT CreateDataObject(
  REFGUID rguidTemplate,
  LPCSTR szName,
  const GUID * pguid,
  DWORD cbSize,
  LPVOID pvData,
  LPDIRECTXFILEDATA * ppDataObj);

Parameters

rguidTemplate
GUID representing the data object's template.
szName
Pointer to the name of the data object. Optional, specify NULL if the object does not have a name. If the object is going to be referenced by a data reference object, at least one of the szName or pguid parameters must be non-NULL.
pguid
Pointer to a GUID representing the data object. Optional, specify NULL if the object does not have a GUID. If the object is going to be referenced by a data reference object, at least one of the szName or pguid parameters must be non-NULL.
cbSize
Size of the data object, in bytes.
pvData
Pointer to a buffer containing all required member's data.
ppDataObj
Address of a pointer to receive the created IDirectXFileData object.

Return Value

Returns one of the following values:
DXFILE_OK
DXFILEERR_BADALLOC
DXFILEERR_BADVALUE

Remarks

Save any templates by using the SaveTemplates method before saving the data created by this method. Save the created data by using the SaveData method. If you need to save optional data, use the IDirectXFileData::AddDataObject method after using this method and before using SaveData. If the object has child objects, add them before calling SaveData.

IDirectXFileSaveObject::SaveData

IDirectXFileSaveObject

Saves a data object and its children to a DirectX file.

Syntax

HRESULT SaveData(
  LPDIRECTXFILEDATA pDataObj);

Parameters

pDataObj
Pointer to the IDirectXFileData object to save.

Return Value

Returns one of the following values:
DXFILE_OK
DXFILEERR_BADARRAYSIZE
DXFILEERR_BADVALUE

IDirectXFileSaveObject::SaveTemplates

IDirectXFileSaveObject

Saves templates to a DirectX file.

Syntax

HRESULT SaveTemplates(
  DWORD cTemplates,
  const GUID ** ppguidTemplates);

Parameters

cTemplates
Total number of templates to save.
ppguidTemplates
Address of a pointer to an array of the GUIDs for all templates to save.

Return Value

Returns one of the following values:
DXFILE_OK
DXFILEERR_BADVALUE

Remarks

The following code fragment provides an example call to SaveTemplates and example contents for the array to which ppuuid points.

IDirectXFileSaveObject * pDXFileSaveObject;

const GUID *aIds[] = {
    &DXFILEOBJ_SimpleData,
    &DXFILEOBJ_ArrayData,
    &DXFILEOBJ_RestrictedData};

hr = pDXFileSaveObject->SaveTemplates(3, aIds);

After using this method to save the templates, use the IDirectXFileSaveObject::CreateDataObject method to create a data object.

Data Types

The DirectX file interfaces use the following constants and structures.

  • DXFILEFORMAT Constants
  • DXFILELOADMEMORY Structure
  • DXFILELOADOPTIONS Constants
  • DXFILELOADRESOURCE Structure

DXFILEFORMAT Constants

Specifies values used by the IDirectXFile::CreateSaveObject method to indicate the format to use when saving the DirectX file.

Syntax

typedef DWORD DXFILEFORMAT;
#define DXFILEFORMAT_BINARY     0
#define DXFILEFORMAT_TEXT       1
#define DXFILEFORMAT_COMPRESSED 2

Values

DXFILEFORMAT_BINARY
Indicates a binary file.
DXFILEFORMAT_TEXT
Indicates a text file.
DXFILEFORMAT_COMPRESSED
Indicates a compressed file.
The default value for the file format is DXFILEFORMAT_BINARY. The file format values can be combined together in a logical OR to create compressed text or compressed binary files. If a file is specified as both binary (0) and text (1), it will be saved as a text file because the value will be indistinguishable from the text file format value (0 + 1 = 1). If you indicate that the file format should be text and compressed, the file will first be written out as text and then compressed. However, compressed text files are not as efficient as binary text files, so in most cases you will want to indicate binary and compressed. Setting a file to be compressed without specifying a format will result in a binary, compressed file.

DXFILELOADMEMORY Structure

Identifies a resource to be loaded when an application uses the IDirectXFile::CreateEnumObject method and specifies DXFILELOAD_FROMMEMORY.

Syntax

typedef struct _DXFILELOADMEMORY {
    LPVOID lpMemory;
    DWORD dSize;
}DXFILELOADMEMORY, *LPDXFILELOADMEMORY;

Members

lpMemory
Pointer to a block of memory to be loaded.
dSize
Size, in bytes, of the block of memory to be loaded.

DXFILELOADOPTIONS Constants

Specifies values used by the IDirectXFile::CreateEnumObject method to indicate the source of the file data.

Syntax

typedef DWORD DXFILELOADOPTIONS;
#define DXFILELOAD_FROMFILE  0x00L
#define DXFILELOAD_FROMRESOURCE 0x01L
#define DXFILELOAD_FROMMEMORY 0x02L
#define DXFILELOAD_FROMSTREAM 0x04L
#define DXFILELOAD_FROMURL 0x08L

Values

DXFILELOAD_FROMFILE
Indicates data read from a file.
DXFILELOAD_FROMRESOURCE
Indicates data read from a resource.
DXFILELOAD_FROMMEMORY
Indicates data read from memory.
DXFILELOAD_FROMSTREAM
Indicates data read from a stream. Not currently supported.
DXFILELOAD_FROMURL
Indicates data read from a URL (Uniform Resource Locator).

DXFILELOADRESOURCE Structure

Identifies a resource to be loaded when an application uses the IDirectXFile::CreateEnumObject method and specifies DXFILELOAD_FROMRESOURCE.

Syntax

typedef struct _DXFILELOADRESOURCE {
    HMODULE hModule;
    LPCTSTR lpName;
    LPCTSTR lpType;
}DXFILELOADRESOURCE, *LPDXFILELOADRESOURCE;

Members

hModule
Handle of the module containing the resource to be loaded. If this member is NULL, the resource must be attached to the executable file that will use it.
lpName
Name of the resource to be loaded. For example, if the resource is a mesh, this member should specify the name of the mesh file.
lpType
User-defined type identifying the resource.

Return Values

The methods of the DirectX file Component Object Model (COM) interfaces can return the following values in addition to standard COM return values.

DXFILE_OK
Command completed successfully. Equivalent to DD_OK.
DXFILEERR_BADALLOC
Memory allocation failed.
DXFILEERR_BADARRAYSIZE
Array size is invalid.
DXFILEERR_BADCACHEFILE
The cache file containing the X file date is invalid. A cache file contains data retrieved from the network, cached on the hard disk, and retrieved in subsequent requests.
DXFILEERR_BADDATAREFERENCE
Data reference is invalid.
DXFILEERR_BADFILE
File is invalid.
DXFILEERR_BADFILEFLOATSIZE
Floating-point size is invalid.
DXFILEERR_BADFILETYPE
File is not a DirectX file.
DXFILEERR_BADFILEVERSION
File version is not valid.
DXFILEERR_BADRESOURCE
Resource is invalid.
DXFILEERR_BADTYPE
Object type is invalid.
DXFILEERR_BADVALUE
Parameter is invalid.
DXFILEERR_FILENOTFOUND
File could not be found.
DXFILEERR_NOMOREDATA
No further data is available.
DXFILEERR_NOMOREOBJECTS
All objects have been enumerated.
DXFILEERR_NOTFOUND
Object could not be found.
DXFILEERR_PARSEERROR
File could not be parsed.
DXFILEERR_RESOURCENOTFOUND
Resource could not be found.
DXFILEERR_URLNOTFOUND
URL could not be found.


Requirements

Many topics that introduce the syntax of an API element contain information about the build and run-time requirements for using the element. The format is as follows:

Windows NT/2000: Requires Windows NT 3.1 or later.
Windows 95/98: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

The first line indicates the versions of Windows NT on which an element is supported. This information may include required service packs, option packs, or components such as Internet Explorer. If an element is not supported, the line reads "Windows NT/2000: Unsupported."

The second line indicates whether an element is supported on Windows 95 or Windows 98. This information may include required OEM service releases, redistributables, or components such as Internet Explorer. If an element is not supported, the line reads "Windows 95/98: Unsupported."

The third line indicates the versions of Windows CE on which an element is supported. If an element is not supported, the line reads "Windows CE: Unsupported."

The fourth line indicates the file that defines an element. This value can be an .h file, .idl file, or .odl file. If the header file is supplied by the user, the line reads "Header: User-defined."

The fifth line indicates the file used to resolve calls to a function or member. This value can be a .lib file, .dll file, or .tlb file. If the import library is supplied by the user, the line reads "Import Library: User-defined." For element types that do not require an import library, this line is omitted.

The sixth line indicates whether an element exists as both a Unicode (W) version and an ANSI (A) version. If Unicode support is not available, this line is omitted.


Copyright

NOTICE SPECIFIC TO SOFTWARE AVAILABLE ON THIS SITE

Any software that is made available on this site ("Software") is the copyrighted work of Microsoft® Corporation and/or its suppliers. Use of the Software is governed by the terms of the end user license agreement, if any, which accompanies or is included with the Software ("License Agreement") . An end user will be unable to install any Software that is accompanied by or includes a License Agreement unless he or she first agrees to the License Agreement terms.

The Software is made available for installation solely for use by end users according to the License Agreement. Any reproduction or redistribution of the Software not in accordance with the License Agreement is expressly prohibited by law and may result in severe civil and criminal penalties. Violators will be prosecuted to the maximum extent possible.

WITHOUT LIMITING THE FOREGOING, COPYING OR REPRODUCTION OF THE SOFTWARE TO ANY OTHER SERVER OR LOCATION FOR FURTHER REPRODUCTION OR REDISTRIBUTION IS EXPRESSLY PROHIBITED.

THE SOFTWARE IS WARRANTED, IF AT ALL, ONLY ACCORDING TO THE TERMS OF THE LICENSE AGREEMENT. EXCEPT AS WARRANTED IN THE LICENSE AGREEMENT, MICROSOFT CORPORATION HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS WITH REGARD TO THE SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND NON-INFRINGEMENT.

RESTRICTED RIGHTS LEGEND. Any Software which is accessed through this site for or on behalf of the United States of America, its agencies and/or instrumentalities ("U.S. Government"), is provided with Restricted Rights. Use, duplication, or disclosure by the U.S. Government is subject to restrictions as set forth in subparagraph (c)(1)(ii) of the Rights in Technical Data and Computer Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and (2) of the Commercial Computer Software—Restricted Rights at 48 CFR 52.227-19, as applicable. Manufacturer is Microsoft Corporation, One Microsoft Way, Redmond, WA 98052-6399.

NOTICE SPECIFIC TO DOCUMENTS AVAILABLE ON THIS SITE

Permission to use Documents (such as white papers, press releases, datasheets and FAQs) from this site ("Site") is granted, provided that (1) the below copyright notice appears in all copies and that both the copyright notice and this permission notice appear, (2) use of such Documents from this Site is for informational and non-commercial or personal use only and will not be copied or posted on any network computer or broadcast in any media, and (3) no modifications of any Documents are made. Use for any other purpose is expressly prohibited by law and may result in severe civil and criminal penalties. Violators will be prosecuted to the maximum extent possible.

Documents specified above do not include the design or layout of the Microsoft .com Web site or any other Microsoft-owned, operated, licensed, or controlled site. Elements of Microsoft Web sites are protected by trade dress and other laws and may not be copied or imitated in whole or in part. No logo, graphic, sound, or image from any Microsoft Web site may be copied or retransmitted unless expressly permitted by Microsoft.

MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS MAKE NO REPRESENTATIONS ABOUT THE SUITABILITY OF THE INFORMATION CONTAINED IN THE DOCUMENTS AND RELATED GRAPHICS PUBLISHED ON THIS SITE FOR ANY PURPOSE. ALL SUCH DOCUMENTS AND RELATED GRAPHICS ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS HEREBY DISCLAIM ALL WARRANTIES AND CONDITIONS WITH REGARD TO THIS INFORMATION, INCLUDING ALL IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS BE LIABLE FOR ANY SPECIAL, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA, OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF INFORMATION AVAILABLE FROM THIS SITE.

THE DOCUMENTS AND RELATED GRAPHICS PUBLISHED ON THIS SITE COULD INCLUDE TECHNICAL INACCURACIES OR TYPOGRAPHICAL ERRORS. CHANGES ARE PERIODICALLY ADDED TO THE INFORMATION HEREIN. MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS MAY MAKE IMPROVEMENTS AND/OR CHANGES IN THE PRODUCT(S) AND/OR THE PROGRAM(S) DESCRIBED HEREIN AT ANY TIME.

NOTICES REGARDING SOFTWARE, DOCUMENTS AND SERVICES AVAILABLE ON THIS SITE.

IN NO EVENT SHALL MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS BE LIABLE FOR ANY SPECIAL, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA, OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF SOFTWARE, DOCUMENTS, PROVISION OF, OR FAILURE TO PROVIDE, SERVICES OR INFORMATION AVAILABLE FROM THIS SITE.

LINKS TO THIRD-PARTY SITES

THE LINKS IN THIS AREA WILL LET YOU LEAVE MICROSOFT'S SITE. THE LINKED SITES ARE NOT UNDER THE CONTROL OF MICROSOFT, AND MICROSOFT IS NOT RESPONSIBLE FOR THE CONTENTS OF ANY LINKED SITE OR ANY LINK CONTAINED IN A LINKED SITE. MICROSOFT IS PROVIDING THESE LINKS TO YOU ONLY AS A CONVENIENCE, AND THE INCLUSION OF ANY LINK DOES NOT IMPLY ENDORSEMENT BY MICROSOFT OF THE SITE.

COPYRIGHT NOTICE. Copyright © 1999 Microsoft and/or its suppliers, One Microsoft Way, Redmond, Washington 98052-6399 U.S.A. All rights reserved.

TRADEMARKS. Microsoft, Windows, Windows NT, MSN, The Microsoft Network and/or other Microsoft products referenced herein are either trademarks or registered trademarks of Microsoft. Other product and company names mentioned herein may be the trademarks of their respective owners.

The names of companies, products, people, characters, and/or data mentioned herein are fictitious and are in no way intended to represent any real individual, company, product, or event, unless otherwise noted.

Any rights not expressly granted herein are reserved.

Contact Microsoft with questions or problems with this service.
**

** ** © 1999 Microsoft Corporation. All rights reserved. Terms of Use.


A

ambient
A light source that illuminates everything in a scene, regardless of the orientation, position, and surface characteristics of the objects in the scene. Because this illuminates a scene with equal strength everywhere, the position and orientation of the frame it is attached to are inconsequential. Multiple ambient light sources are combined within a scene.
array object
A group of objects organized into an array. Array objects make it simpler to apply operations to the entire group. The Component Object Model (COM) interfaces that enable you to work with array objects contain the GetElement and GetSize methods. These methods retrieve a pointer to an element in the array and the size of the array, respectively.


B

back buffer
A nonvisible surface that bitmaps and other images can be drawn to while the primary surface displays the currently visible image.
back clipping plane
The far boundary of a viewing frustum beyond which objects are not rendered. See also front clipping plane.


C

camera
A Direct3DRMFrame object used by the viewport to define the viewing position and direction. The viewport renders only what is visible along the positive z-axis of the camera frame, with the up direction being in the direction of the positive y-axis.


D

decal
A texture that is rendered directly as a visual. Decals are rendered into a viewport-aligned rectangle.
directional
A light source that is attached to a frame but appears to illuminate all objects with equal intensity, as if it were at an infinite distance from the objects. Directional light has orientation but no position, and it is commonly used to simulate distant light sources, such as the sun.


E

emissive property
The material property that determines whether a material emits light. The emissive property of a material is one of two properties that determines how the material reflects light. See also specular property.
enable frame
The frame to which a light applies.


F

front clipping plane
The near boundary of a viewing frustum. Any object closer to the camera than the front clipping plane is not rendered. The height of the front clipping plane defines the field of view. See also back clipping plane.


M

mipmap
A sequence of textures, each of which is a progressively lower-resolution, prefiltered representation of the same image. A higher-resolution image is used when a visible object is close to the viewer. As the object moves farther away (and gets smaller), lower-resolution images are used.
model coordinates
Coordinates that are relative to a child frame. See also world coordinates.


N

normal vector
An imaginary ray extending perpendicularly from a surface that defines the face's orientation.


P

parallel point
A light source that illuminates objects with parallel light. The light's orientation is taken from the position of the parallel-point light source. For example, two meshes on both sides of a parallel point light source are lit on the side that faces the position of the source.
penumbra
The outer, dimly lit section of a spotlight's cone of light. The penumbra surrounds the umbra and merges with the surrounding deep shadow. See also umbra and spotlight.
point
A light source that radiates equally in all directions from its origin.
power
In the specular property of a material, the value that determines the sharpness of specular highlights. A value of five gives a metallic appearance, and higher values give a more plastic appearance.


R

reference count
The manner in which a Component Object Model (COM) object controls its lifetime. When an object is created, its reference count is set to 1. When a pointer is assigned to point to one of the object's interfaces, the object's reference count is incremented. When the interface connection is destroyed, the reference count is decremented. The object is destroyed when the reference count reaches 0. All pointers to interfaces on that object are then invalid. For more information, see IUnknown Interface.
root frame
A frame in Direct3D that has no parent frame. A frame at the top of a hierarchy of frames. The root frame contains the entire set of objects that make up a scene.


S

specular property
The material property that determines how a point of light on a shiny object corresponds to the reflected light source. The specular property of a material is one of two properties that determines how a material reflects light. See also emissive property.
spotlight
A light source that emits a cone of light. Only objects within the cone are illuminated. The cone produces light of two degrees of intensity with a central brightly lit section (the umbra) that acts as a point source, and a surrounding dimly lit section (the penumbra) that merges with the surrounding deep shadow.


T

texture blending
The technique of combining the colors of a texture with the colors of the surface to which the texture is applied.


U

umbra
The central brightly lit section of a cone of light. The umbra can act as a point source. See also penumbra and spotlight.


V

vertex split
A vertex split adds a new vertex near an existing vertex and adds two new faces. Thus, a complex mesh can be built from a simple mesh and a sequence of vertex split records that increasingly refine the mesh. This allows meshes to be progressively downloaded from remote sites.
viewing frustum
A 3-D volume in a scene positioned relative to the viewport's camera. Objects within the frustum are visible. For perspective viewing, the viewing frustum is the volume of an imaginary pyramid that is between the front clipping plane and the back clipping plane. For orthographic viewing, the viewing frustum is cuboid.


W

world coordinates
Coordinates that are relative to the root frame. See also model coordinates.


GLOSSARY HEAD

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z


IDirect3DRMFrame3 Methods A to M

This section contains the reference pages for the methods of the IDirect3DRMFrame3 interface that begin with the letters A through M.

IDirect3DRMFrame3::AddChild

IDirect3DRMFrame3

Adds a child frame to a frame hierarchy.

Syntax

HRESULT AddChild(
  LPDIRECT3DRMFRAME3 lpD3DRMFrameChild
  );

Parameters

lpD3DRMFrameChild
Address of the Direct3DRMFrame object that will be added as a child.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

If the frame being added as a child already has a parent, this method removes it from its previous parent before adding it to the new parent. The child frame is added to the end of the Direct3DRMFrameArray object. You can obtain the Direct3DRMFrameArray object with IDirect3DRMFrame3::GetChildren.

To preserve an object's transformation, use the IDirect3DRMFrame3::GetTransform method to retrieve the object's transformation before using the AddChild method. Then reapply the transformation after the frame is added.

See Also

Hierarchies

IDirect3DRMFrame3::AddLight

IDirect3DRMFrame3

Adds a light to a frame.

Syntax

HRESULT AddLight(
  LPDIRECT3DRMLIGHT lpD3DRMLight
  );

Parameters

lpD3DRMLight
Address of a variable that represents the Direct3DRMLight object to be added to the frame.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

The light is added to the end of the Direct3DRMLightArray object. You can obtain the Direct3DRMLightArray object with IDirect3DRMFrame3::GetLights.

IDirect3DRMFrame3::AddMoveCallback

IDirect3DRMFrame3

Adds a callback function for special movement processing. The callback is called when the frame is moved or updated.

Syntax

HRESULT AddMoveCallback(
  D3DRMFRAME3MOVECALLBACK d3drmFMC,
  VOID *lpArg,
  DWORD dwFlags
  );

Parameters

d3drmFMC
Application-defined D3DRMFRAME3MOVECALLBACK callback function.
lpArg
Application-defined data to be passed to the callback function.
dwFlags
One of the following values:
D3DRMCALLBACK_PREORDER — The default value. When IDirect3DRMFrame3::Move traverses the hierarchy, callbacks for a frame are used before any child frames are traversed.
D3DRMCALLBACK_POSTORDER — When IDirect3DRMFrame3::Move traverses the hierarchy, callbacks for a frame are used after the child frames are traversed.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

This method replaces IDirect3DRMFrame2::AddMoveCallback2. Multiple callbacks on an individual frame are used in the order that the callbacks were created.

See Also

IDirect3DRMFrame3::Move, IDirect3DRMFrame3::DeleteMoveCallback

IDirect3DRMFrame3::AddRotation

IDirect3DRMFrame3

Adds a rotation about (rvX, rvY, rvZ) by the number of radians specified in rvTheta.

Syntax

HRESULT AddRotation(
  D3DRMCOMBINETYPE rctCombine,
  D3DVALUE rvX,
  D3DVALUE rvY,
  D3DVALUE rvZ,
  D3DVALUE rvTheta
  );

Parameters

rctCombine
A member of the D3DRMCOMBINETYPE enumerated type that specifies how to combine the new rotation with any current frame transformation.
rvX, rvY, and rvZ
Axis about which to rotate.
rvTheta
Angle of rotation, in radians.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

The specified rotation changes the matrix only for the frame identified by this IDirect3DRMFrame3 interface. This method changes the objects in the frame only once, unlike IDirect3DRMFrame3::SetRotation, which changes the matrix with every render tick.

See Also

3-D Transformations, IDirect3DRMFrame3::SetRotation

IDirect3DRMFrame3::AddScale

IDirect3DRMFrame3

Scales a frame's local transformation by (rvX, rvY, rvZ).

Syntax

HRESULT AddScale(
  D3DRMCOMBINETYPE rctCombine,
  D3DVALUE rvX,
  D3DVALUE rvY,
  D3DVALUE rvZ
  );

Parameters

rctCombine
Member of the D3DRMCOMBINETYPE enumerated type that specifies how to combine the new scale with any current frame transformation.
rvX, rvY, and rvZ
Scale factors in the x-, y-, and z-directions.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

The specified transformation only changes the matrix for the frame identified by the IDirect3DRMFrame3 interface.

See Also

3-D Transformations

IDirect3DRMFrame3::AddTransform

IDirect3DRMFrame3

Transforms the local coordinates of the frame by the affine transformation specified by rctCombine and rmMatrix.

Syntax

HRESULT AddTransform(
  D3DRMCOMBINETYPE rctCombine,
  D3DRMMATRIX4D rmMatrix
  );

Parameters

rctCombine
Member of the D3DRMCOMBINETYPE enumerated type that specifies how to combine the new transformation with any current transformation.
rmMatrix
Member of the D3DRMMATRIX4D array that defines the transformation matrix to be combined.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

Although a 4×4 matrix is given, the last column must be the transpose of [0 0 0 1] for the transformation to be affine.

The specified transformation changes the matrix only for the frame identified by this IDirect3DRMFrame3 interface.

See Also

3-D Transformations

IDirect3DRMFrame3::AddTranslation

IDirect3DRMFrame3

Adds a translation by (rvX, rvY, rvZ) to a frame's local coordinate system.

Syntax

HRESULT AddTranslation(
  D3DRMCOMBINETYPE rctCombine,
  D3DVALUE rvX,
  D3DVALUE rvY,
  D3DVALUE rvZ
  );

Parameters

rctCombine
Member of the D3DRMCOMBINETYPE enumerated type that specifies how to combine the new translation with any current translation.
rvX, rvY, and rvZ
Definitions of the position changes in the x-, y-, and z-directions.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

The specified translation changes the matrix only for the frame identified by this IDirect3DRMFrame3 interface.

See Also

3-D Transformations

IDirect3DRMFrame3::AddVisual

IDirect3DRMFrame3

Adds a visual object to a frame.

Syntax

HRESULT AddVisual(
  LPUNKNOWN lpD3DRMVisual
  );

Parameters

lpD3DRMVisual
Pointer to a variable that represents the visual object to be added to the frame.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

Visual objects include meshes, progressive meshes, textures, shadows, user visuals, and 3-D DirectX Transform objects. When a visual object is added to a frame, it becomes visible if the frame is in view. The frame references the visual object.

IDirect3DRMFrame3::DeleteChild

IDirect3DRMFrame3

Removes a frame from the hierarchy. If the frame is not referenced, it is destroyed along with any child frames, lights, and meshes.

Syntax

HRESULT DeleteChild(
  LPDIRECT3DRMFRAME3 lpChild
  );

Parameters

lpChild
Address of the Direct3DRMFrame object to be used as the child.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

Hierarchies

IDirect3DRMFrame3::DeleteLight

IDirect3DRMFrame3

Removes a light from a frame, destroying the light if it is no longer referenced. When a light is removed from a frame, the light no longer affects meshes in the scene its frame was in.

Syntax

HRESULT DeleteLight(
  LPDIRECT3DRMLIGHT lpD3DRMLight
  );

Parameters

lpD3DRMLight
Address of a variable that represents the Direct3DRMLight object to be removed.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMFrame3::DeleteMoveCallback

IDirect3DRMFrame3

Removes a frame-move callback function previously added with AddMoveCallback.

Syntax

HRESULT DeleteMoveCallback(
  D3DRMFRAME3MOVECALLBACK d3drmFMC,
  VOID *lpArg
  );

Parameters

d3drmFMC
Application-defined D3DRMFRAME3MOVECALLBACK callback function.
lpArg
Application-defined data that was passed to the callback function.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMFrame3::AddMoveCallback, IDirect3DRMFrame3::Move

IDirect3DRMFrame3::DeleteVisual

IDirect3DRMFrame3

Removes a visual object from a frame, destroying it if it is no longer referenced.

Syntax

HRESULT DeleteVisual(
  LPUNKNOWN lpD3DRMVisual
  );

Parameters

lpD3DRMVisual
Address of a variable that represents the Direct3DRMVisual object to be removed.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMFrame3::GetAxes

IDirect3DRMFrame3

Retrieves the vectors that are aligned with the direction (rvDx, rvDy, rvDz) and up (rvUx, rvUy, rvUz) vectors supplied to the IDirect3DRMFrame3::SetOrientation method.

Syntax

HRESULT GetAxes(
  LPD3DVECTOR dir,
  LPD3DVECTOR up
  );

Parameters

dir
The z-axis for the frame. Default is (0,0,1).
up
The y-axis for the frame. Default is (0,1,0).

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

This method along with IDirect3DRMFrame3::SetAxes helps support both left-handed and right-handed coordinate systems. SetAxes allows you to specify that the negative z-axis represents the front of the object.

See Also

IDirect3DRMFrame3::SetAxes, IDirect3DRMFrame3::GetInheritAxes, IDirect3DRMFrame3::SetInheritAxes

IDirect3DRMFrame3::GetBox

IDirect3DRMFrame3

Retrieves the bounding box containing a DIRECT3DRMFRAME2 object. The bounding box gives the minimum and maximum model coordinates in each dimension.

Syntax

HRESULT GetBox(
  D3DRMBOX  *lpD3DRMBox
  );

Parameters

lpD3DRMBox
Address of a D3DRMBOX structure that will be filled with the bounding box coordinates.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. Returns D3DRMERR_BOXNOTSET unless a valid bounding box has already been set on the frame. For a list of other possible return codes, see Direct3D Retained Mode Return Values.

Remarks

This method supports a bounding box on a frame for hierarchical culling. A valid bounding box must be set on the frame with IDirect3DRMFrame3::SetBox. For a bounding box to be enabled, the IDirect3DRMFrame3::SetBoxEnable method must be used to set the enable flag to TRUE. By default, the box-enable flag is FALSE. There is no default bounding box.

See Also

IDirect3DRMFrame3::SetBox, IDirect3DRMFrame3::SetBoxEnable, IDirect3DRMFrame3::GetBoxEnable

IDirect3DRMFrame3::GetBoxEnable

IDirect3DRMFrame3

Retrieves the flag that determines whether a bounding box is enabled for this Direct3DRMFrame3 object.

Syntax

BOOL GetBoxEnable( );

Return Value

Returns TRUE if a bounding box is enabled, or FALSE if it is not enabled.

Remarks

For a bounding box to be enabled, the IDirect3DRMFrame3::SetBoxEnable flag must be used to set the enable flag to TRUE. By default, the box enable flag is FALSE.

See Also

IDirect3DRMFrame3::SetBoxEnable IDirect3DRMFrame3::GetBox, IDirect3DRMFrame3::SetBox

IDirect3DRMFrame3::GetChildren

IDirect3DRMFrame3

Retrieves a list of child frames in the form of a Direct3DRMFrameArray object.

Syntax

HRESULT GetChildren(
  LPDIRECT3DRMFRAMEARRAY *lplpChildren
  );

Parameters

lplpChildren
Address of a pointer to be initialized with a valid Direct3DRMFrameArray pointer if the call succeeds.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

DIRECT3DRMFRAMEARRAY, Hierarchies

IDirect3DRMFrame3::GetColor

IDirect3DRMFrame3

Retrieves the color of the frame.

Syntax

D3DCOLOR GetColor( );

Return Value

Returns the color of the Direct3DRMFrame2 object. By default, the color is white.

See Also

IDirect3DRMFrame3::SetColor

IDirect3DRMFrame3::GetHierarchyBox

IDirect3DRMFrame3

Calculates a bounding box to contain all the geometry in the hierarchy rooted in this Direct3DRMFrame3 object.

Syntax

HRESULT GetHierarchyBox(
  D3DRMBOX *lpD3DRMBox
  );

Parameters

lpD3DRMBox
Address of a D3DRMBOX structure that will be filled with the bounding box coordinates.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMFrame3::GetBox, IDirect3DRMFrame3::SetBox, IDirect3DRMFrame3::SetBoxEnable, IDirect3DRMFrame3::GetBoxEnable

IDirect3DRMFrame3::GetInheritAxes

IDirect3DRMFrame3

Retrieves the flag that indicates whether the axes for the frame are inherited from the parent frame.

Syntax

BOOL GetInheritAxes( );

Return Value

Returns TRUE if the frame inherits axes (the default) and FALSE if the frame does not inherit axes.

Remarks

By default, the axes are inherited from the parent. If a frame is set to inherit from a parent and there is no parent, the frame acts as if it inherits from a parent with the default axes (direction=(0,0,1) and up=(0,1,0)).

This method and the IDirect3DRMFrame3::SetInheritAxes method allow a single policy for axes to be set at the root of the hierarchy.

See Also

IDirect3DRMFrame3::SetInheritAxes, IDirect3DRMFrame3::GetAxes, IDirect3DRMFrame3::SetAxes

IDirect3DRMFrame3::GetLights

IDirect3DRMFrame3

Retrieves a list of lights in the frame in the form of a Direct3DRMLightArray object.

Syntax

HRESULT GetLights(
  LPDIRECT3DRMLIGHTARRAY *lplpLights
  );

Parameters

lplpLights
Address of a pointer to be initialized with a valid Direct3DRMLightArray pointer if the call succeeds.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMLightArray

IDirect3DRMFrame3::GetMaterial

IDirect3DRMFrame3

Retrieves the material of the Direct3DRMFrame2 object.

Syntax

HRESULT GetMaterial(
  LPDIRECT3DRMMATERIAL2 *lplpMaterial
  );

Parameters

lplpMaterial
Address of a variable that will be filled with a pointer to the Direct3DRMMaterial object that is applied to the frame. By default, the material is NULL.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMFrame3::SetMaterial

IDirect3DRMFrame3::GetMaterialMode

IDirect3DRMFrame3

Retrieves the material mode of the frame.

Syntax

D3DRMMATERIALMODE GetMaterialMode( );

Return Value

Returns a member of the D3DRMMATERIALMODE enumerated type that specifies the current material mode. By default, the mode is D3DRMMATERIAL_FROMMESH.

See Also

IDirect3DRMFrame3::SetMaterialMode

IDirect3DRMFrame3::GetMaterialOverride

IDirect3DRMFrame3

Retrieves the current per-attribute override settings for material attributes.

Syntax

HRESULT GetMaterialOverride(
  LPD3DRMMATERIALOVERRIDE lpdmOverride);

Parameters

lpdmOverride
Pointer to a D3DRMMATERIALOVERRIDE structure that describes the properties to be overridden.

Return Value

Returns one of the following values:
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

If a texture exists in the override, its reference count has been incremented (with AddRef) before being passed back, and you need to release the texture when you exit. Therefore, if you apply a texture override, remember to release it.

See Also

SetMaterialOverride

IDirect3DRMFrame3::GetOrientation

IDirect3DRMFrame3

Retrieves the orientation of a frame relative to the given reference frame.

Syntax

HRESULT GetOrientation(
  LPDIRECT3DRMFRAME lpRef,
  LPD3DVECTOR lprvDir,
  LPD3DVECTOR lprvUp
  );

Parameters

lpRef
Address of a variable that represents the Direct3DRMFrame object to be used as the reference. This can be NULL. If NULL, the method uses its own local transform matrix instead of using the reference frame's transform matrix.
lprvDir and lprvUp
Addresses of D3DVECTOR structures that will be filled with the normalized directions of the frame's z-axis and y-axis, respectively. The default orientation of a frame has a direction vector of [0, 0, 1] and an up vector of [0, 1, 0].

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMFrame3::SetOrientation

IDirect3DRMFrame3::GetParent

IDirect3DRMFrame3

Retrieves the parent frame of the current frame.

Syntax

HRESULT GetParent(
  LPDIRECT3DRMRAME3 *lplpParent
  );

Parameters

lplpParent
Address of a pointer that will be filled with the pointer to the Direct3DRMFrame object representing the frame's parent. If the current frame is the root, this pointer will be NULL when the method returns.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMFrame3::GetPosition

IDirect3DRMFrame3

Retrieves the position of a frame relative to the given reference frame, that is, it retrieves the distance of the frame from the reference. The distance is stored in the lprvPos parameter as a vector rather than as a linear measure.

Syntax

HRESULT GetPosition(
  LPDIRECT3DRMFRAME3 lpRef,
  LPD3DVECTOR lprvPos
  );

Parameters

lpRef
Address of a variable that represents the Direct3DRMFrame object to be used as the reference. This can be NULL. If NULL, the method uses its own local transform matrix instead of using the reference frame's transform matrix.
lprvPos
Address of a D3DVECTOR structure that will be filled with the frame's position.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMFrame3::SetPosition

IDirect3DRMFrame3::GetRotation

IDirect3DRMFrame3

Retrieves the rotation of the frame relative to the given reference frame.

Syntax

HRESULT GetRotation(
  LPDIRECT3DRMFRAME3 lpRef,
  LPD3DVECTOR lprvAxis,
  LPD3DVALUE lprvTheta
  );

Parameters

lpRef
Address of a variable that represents the Direct3DRMFrame object to be used as the reference. This can be NULL. If NULL, the method uses its own local transform matrix instead of using the reference frame's transform matrix.
lprvAxis
Address of a D3DVECTOR structure that will be filled with the frame's axis of rotation.
lprvTheta
Address of a variable that will be the frame's rotation, in radians.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMFrame3::SetRotation, Transformations

IDirect3DRMFrame3::GetScene

IDirect3DRMFrame3

Retrieves the root frame of the hierarchy containing the given frame.

Syntax

HRESULT GetScene(
  LPDIRECT3DRMFRAME3 lplpRoot
  );

Parameters

lplpRoot
Address of the pointer that will be filled with the pointer to the Direct3DRMFrame object representing the scene's root frame.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMFrame3::GetSceneBackground

IDirect3DRMFrame3

Retrieves the background color of a scene.

Syntax

D3DCOLOR GetSceneBackground( );

Return Value

Returns the color.

IDirect3DRMFrame3::GetSceneBackgroundDepth

IDirect3DRMFrame3

Retrieves the current background-depth buffer for the scene.

Syntax

HRESULT GetSceneBackgroundDepth(
  LPDIRECTDRAWSURFACE  *lplpDDSurface
  );

Parameters

lplpDDSurface
Address of a pointer that will be initialized with the address of a DirectDraw surface representing the current background-depth buffer.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMFrame3::SetSceneBackgroundDepth

IDirect3DRMFrame3::GetSceneFogColor

IDirect3DRMFrame3

Retrieves the fog color of a scene.

Syntax

D3DCOLOR GetSceneFogColor( );

Return Value

Returns the fog color. By default, the color is white.

IDirect3DRMFrame3::GetSceneFogEnable

IDirect3DRMFrame3

Retrieves whether fog is currently enabled for this scene.

Syntax

BOOL GetSceneFogEnable( );

Return Value

Returns TRUE if fog is enabled, and FALSE otherwise. By default, this flag is FALSE.

IDirect3DRMFrame3::GetSceneFogMethod

IDirect3DRMFrame3

Retrieves the current fogging method.

Syntax

HRESULT GetSceneFogMethod(
  LPDWORD lpdwFlags);

Parameters

lpdwFlags
Pointer to a DWORD that receives the current fog method. Note that these flags are mutually exclusive. The currently defined flags are:
D3DRMFOGMETHOD_ANY
Indicates that Direct3DRM should choose an applicable method.
D3DRMFOGMETHOD_VERTEX
Use vertex fog.
D3DRMFOGMETHOD_TABLE
Use table fog.

Return Value

Returns one of the following values:
D3DRMERR_BADVALUE
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

The default behavior for Direct3DRMFrame objects created by the IDirect3DRM3 interface is D3DRMFOGMETHOD_ANY and the fog method will be chosen based on the capabilities of the device. If the device supports both vertex- and table-based fog then vertex fogging will be used. If the application requests table fog, but table fog is not available, vertex fog will be used. The default behavior for Direct3DRMFrame objects created with an IDirect3DRM or IDirect3DRM2 interface is D3DRMFOGMETHOD_VERTEX.

This method was introduced with DirectX version 6.0.

IDirect3DRMFrame3::GetSceneFogMode

IDirect3DRMFrame3

Retrieves the current fog mode for this scene.

Syntax

D3DRMFOGMODE GetSceneFogMode( );

Return Value

Returns a member of the D3DRMFOGMODE enumerated type that specifies the current fog mode.

IDirect3DRMFrame3::GetSceneFogParams

IDirect3DRMFrame3

Retrieves the current fog parameters for this scene.

Syntax

HRESULT GetSceneFogParams(
  D3DVALUE *lprvStart,
  D3DVALUE  *lprvEnd,
  D3DVALUE  *lprvDensity
  );

Parameters

lprvStart, lprvEnd, and lprvDensity
Addresses of variables that will be the fog start, end, and density values.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMFrame3::GetSortMode

IDirect3DRMFrame3

Retrieves the sorting mode used to process child frames.

Syntax

D3DRMSORTMODE GetSortMode( );

Return Value

Returns the member of the D3DRMSORTMODE enumerated type that specifies the sorting mode. The default value is D3DRMSORT_FROMPARENT.

See Also

IDirect3DRMFrame3::SetSortMode

IDirect3DRMFrame3::GetTexture

IDirect3DRMFrame3

Retrieves the texture of the given frame.

Syntax

HRESULT GetTexture(
  LPDIRECT3DRMTEXTURE3 *lplpTexture
  );

Parameters

lplpTexture
Address of the pointer that will be filled with the address of the Direct3DRMTexture object representing the frame's texture. By default, the texture is NULL.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMFrame3::SetTexture

IDirect3DRMFrame3::GetTransform

IDirect3DRMFrame3

Retrieves the current-world transformation of the frame as a 4×4 affine matrix.

Syntax

HRESULT GetTransform(
  LPDIRECT3DRMFRAME lpRefFrame,
  D3DRMMATRIX4D rmMatrix);

Parameters

lpRefFrame
Frame that serves as the root of the scene for the purposes of this call. If this argument is NULL, the current root frame (as returned by GetScene) is used.
rmMatrix
D3DRMMATRIX4D array that receives the frame's transformation. Because this is an array, this value is an address.

Return Value

Returns one of the following values:
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0. This method extends IDirect3DRMFrame::GetTransform by adding the lpRefFrame parameter.

See Also

3-D Transformations

IDirect3DRMFrame3::GetTraversalOptions

IDirect3DRMFrame3

Retrieves the traversal status of the current frame.

Syntax

HRESULT GetTraversalOptions(
  LPDWORD lpdwFlags);

Parameters

lpdwFlags
Pointer to a DWORD that will be filled in with the current enable status. The currently defined flags are:
D3DRMFRAME_RENDERENABLE
Indicates render this frame or any children of this frame.
D3DRMFRAME_PICKENABLE
Indicates pick any visuals in this frame or any children of this frame.
By default, dwFlags is D3DRMFRAME_RENDERENABLE | D3DRMFRAME_PICKENABLE, and the frame is enabled for both rendering and picking.

Return Value

Returns one of the following values:
D3DRMERR_BADVALUE
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMFrame3::GetVelocity

IDirect3DRMFrame3

Retrieves the velocity of the frame relative to the given reference frame. Velocity is specified as units per tick. See IDirect3DRM3::Tick for more information.

Syntax

HRESULT GetVelocity(
  LPDIRECT3DRMFRAME3 lpRef,
  LPD3DVECTOR lprvVel,
  BOOL fRotVel
  );

Parameters

lpRef
Address of a variable that represents the Direct3DRMFrame object to be used as the reference. This can be NULL. If NULL, the method uses its own local transform matrix instead of using the reference frame's transform matrix.
lprvVel
Address of a D3DVECTOR structure that will be filled with the frame's velocity.
fRotVel
Flag specifying whether the rotational velocity of the object is taken into account when retrieving the linear velocity. If this parameter is TRUE, the object's rotational velocity is included in the calculation.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMFrame3::SetVelocity

IDirect3DRMFrame3::GetVisuals

IDirect3DRMFrame3

Retrieves a list of visuals in the frame.

Syntax

HRESULT GetVisuals(
  LPDWORD pdwNumVisuals, LPUNKNOWN *ppUnk
  );

Parameters

pdwNumVisuals
Pointer to a DWORD value containing the number of vectors expected to be returned. If ppUnk is NULL, GetVisuals returns the number of visuals contained by the frame. If ppUnk is not NULL, the DWORD value receives the number of visuals actually retrieved.
ppUnk
Pointer to a Direct3DRMVisualArray object containing the array of visuals that will be initialized. Setting this to NULL causes GetVisuals to return the number of visuals contained by the frame. Otherwise, this is a user-allocated array with space for pdwNumVisuals.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMFrame3::GetZbufferMode

IDirect3DRMFrame3

Retrieves the z-buffer mode; that is, whether z-buffering is enabled or disabled.

Syntax

D3DRMZBUFFERMODE GetZbufferMode( );

Return Value

Returns one of the members of the D3DRMZBUFFERMODE enumerated type. The default value is D3DRMZBUFFER_FROMPARENT.

See Also

IDirect3DRMFrame3::SetZbufferMode

IDirect3DRMFrame3::InverseTransform

IDirect3DRMFrame3

Transforms the vector in the lprvSrc parameter in world coordinates to model coordinates, and returns the result in the lprvDst parameter.

Syntax

HRESULT InverseTransform(
  D3DVECTOR *lprvDst,
  D3DVECTOR *lprvSrc
  );

Parameters

lprvDst
Address of a D3DVECTOR structure that will be filled with the result of the transformation.
lprvSrc
Address of a D3DVECTOR structure that is the source of the transformation.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMFrame3::Transform, 3-D Transformations

IDirect3DRMFrame3::InverseTransformVectors

IDirect3DRMFrame3

This transforms an array of vectors from world- to model-space.

Syntax

HRESULT InverseTransformVectors
(LPDIRECT3DRMFRAME3 lpRefFrame,
DWORD dwNumVectors,
LPD3DVECTOR	lpDstVectors,
LPD3DVECTOR	lpSrcVectors);

Parameters

lpRefFrame
Frame that is to be used as the root of the scene for the purposes of this call. If this argument is NULL, the current root frame (as would be returned by GetScene) will be used.
dwNumVectors
The number of vectors whose coordinates are to be transformed.
lpDstVectors
Destination of the transformation.
lpSrcVectors
Array of vectors to transform.

Return Value

Returns one of the following values:
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMFrame3::Load

IDirect3DRMFrame3

Loads a Direct3DRMFrame2 object.

Syntax

HRESULT Load(
  LPVOID lpvObjSource,
  LPVOID lpvObjID,
  D3DRMLOADOPTIONS d3drmLOFlags,
  D3DRMLOADTEXTURE3CALLBACK d3drmLoadTextureProc,
  LPVOID lpArgLTP
  );

Parameters

lpvObjSource
Source for the object to be loaded. This source can be a file, resource, memory block, or stream, depending on the source flags specified in the d3drmLOFlags parameter.
lpvObjID
Object name or position to be loaded. The use of this parameter depends on the identifier flags specified in the d3drmLOFlags parameter. If the D3DRMLOAD_BYPOSITION flag is specified, this parameter is a pointer to a DWORD value that gives the object's order in the file. This parameter can be NULL.
d3drmLOFlags
Value of the D3DRMLOADOPTIONS type describing the load options.
d3drmLoadTextureProc
D3DRMLOADTEXTURE3CALLBACK callback function used to load any textures used by the object that require special formatting. This parameter can be NULL.
lpArgLTP
Pointer to application-defined data passed to the D3DRMLOADTEXTURE3CALLBACK callback function.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

By default, this method loads the first frame hierarchy in the file specified by the lpvObjSource parameter. The frame that uses this method is used as the parent of the new frame hierarchy. By default, perspective correction is on.

IDirect3DRMFrame3::LookAt

IDirect3DRMFrame3

Faces the frame toward the target frame, relative to the given reference frame, locking the rotation by the given constraints.

Syntax

HRESULT LookAt(
  LPDIRECT3DRMFRAME3 lpTarget,
  LPDIRECT3DRMFRAME3 lpRef,
  D3DRMFRAMECONSTRAINT rfcConstraint
  );

Parameters

lpTarget
Address of the variable that represents the Direct3DRMFrame object to be used as the target.
lpRef
Address of the variable that represents the Direct3DRMFrame object to be used as the reference. This can be NULL. If NULL, the method uses its own local transform matrix instead of using the reference frame's transform matrix.
rfcConstraint
Member of the D3DRMFRAMECONSTRAINT enumerated type that specifies the axis of rotation to constrain.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMFrame3::Move

IDirect3DRMFrame3

Applies the linear and rotational velocities for all frames in the given hierarchy.

Syntax

HRESULT Move(
  D3DVALUE delta
  );

Parameters

delta
Amount to change the linear and rotational velocity. The change in each component is equal to the velocity of that component multiplied by delta. Although either or both of these velocities can be set relative to any frame, the system automatically converts them to velocities relative to the parent frame for the purpose of applying time deltas.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.


IDirect3DRMFrame3 Methods N to Z

This section contains the reference pages for the methods of the IDirect3DRMFrame3 interface that begin with the letters N through Z.

IDirect3DRMFrame3::RayPick

IDirect3DRMFrame3

Searches the hierarchy starting at this Direct3DRMFrame3 object and calculates the intersections between any visuals and the ray specified by the dvPosition and dvDirection parameters in the coordinate space specified by the lpRefFrame parameter.

Syntax

HRESULT RayPick(
  LPDIRECT3DRMFRAME3 lpRefFrame,
  LPD3DRMRAY ray,
  DWORD dwFlags,
  LPD3DRMPICKED2ARRAY *lplpPicked2Array
  );

Parameters

lpRefFrame
Address of the Direct3DRMFrame3 object that contains the ray.
ray
Pointer to a D3DRMRAY structure that contains two D3DVECTOR structures. The first D3DVECTOR structure is the vector direction of the ray. The second D3DVECTOR structure is the position of the origin of the ray.
dwFlags
Can be one of the following values:
D3DRMRAYPICK_ONLYBOUNDINGBOXES – Only intersections with bounding boxes of the visuals in the hierarchy are returned. Does not check for exact face intersections.
D3DRMRAYPICK_IGNOREFURTHERPRIMITIVES – Only the closest visual that intersects the ray is returned. Ignores visuals farther away than the closest one found so far in a search.
D3DRMRAYPICK_INTERPOLATEUV – Interpolate texture coordinates.
D3DRMRAYPICK_INTERPOLATECOLOR – Interpolate color.
D3DRMRAYPICK_INTERPOLATENORMAL – Interpolate normal.
lplpPicked2Array
The address of a pointer to be initialized with a valid pointer to the IDirect3DRMPicked2Array interface. You then use the IDirect3DRMPicked2Array::GetPick method to retrieve a visual object, an IDirect3DRMFrameArray interface, and a D3DRMPICKDESC2 structure. The array of frames is the path through the hierarchy leading to the visual object that intersected the ray. The D3DRMPICKDESC2 structure contains the face and group identifiers, pick position, horizontal and vertical texture coordinates for the vertex, vertex normal, and color of the intersected objects.

If you specify D3DRMRAYPICK_ONLYBOUNDINGBOXES, the texture, normal, and color data in the D3DRMPICKDESC2 structure will be invalid.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

There are two kinds of flags: optimization flags and interpolation flags. Optimization flags allow you to limit the search and therefore make it faster. Interpolation flags specify what to interpolate if a primitive is hit. The three interpolation choices are color, normal, and texture coordinates.

The ray is specified in the reference frame coordinate space (pointed to by lpRefFrame). If the reference frame is NULL, the ray is specified in world coordinates.

IDirect3DRMFrame3::Save

IDirect3DRMFrame3

Saves a Direct3DRMFrame3 object to the specified file.

Syntax

HRESULT Save(
  LPCSTR lpFilename,
  D3DRMXOFFORMAT d3dFormat,
  D3DRMSAVEOPTIONS d3dSaveFlags
  );

Parameters

lpFilename
Address specifying the name of the created file. This file must have a .x file name extension.
d3dFormat
D3DRMXOF_TEXT value from the D3DRMXOFFORMAT enumerated type.
d3dSaveFlags
Value of the D3DRMSAVEOPTIONS type describing the save options.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMFrame3::SetAxes

IDirect3DRMFrame3

Sets the vectors that define a coordinate space by which the IDirect3DRMFrame3::SetOrientation vectors are transformed.

Syntax

HRESULT SetAxes(
  D3DVALUE dx,
  D3DVALUE dy,
  D3DVALUE dz,
  D3DVALUE ux,
  D3DVALUE uy,
  D3DVALUE uz
  );

Parameters

dx, dy, dz
The z-axis for the frame. Default is (0,0,1).
ux, uy, uz
The y-axis for the frame. Default is (0,1,0).

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

This method helps support both left-handed and right-handed coordinate systems. This method also allows you to specify that the negative z-axis represents the front of the object.

The IDirect3DRMFrame3::SetOrientation direction (rvDx, rvDy, rvDz) and up (rvUx, rvUy, rvUz) vectors are transformed according to the value of the SetAxes vectors.

The axes are inherited by child frames as specified in IDirect3DRMFrame3::SetInheritAxes.

See Also

IDirect3DRMFrame3::GetAxes, IDirect3DRMFrame3::GetInheritAxes, IDirect3DRMFrame3::SetInheritAxes

IDirect3DRMFrame3::SetBox

IDirect3DRMFrame3

Sets the box to be used in bounding-box testing. In order for the bounding box to be valid, its minimum x must be less than or equal to its maximum x, minimum y must be less than or equal to its maximum y, and minimum z must be less than or equal to its maximum z.

Syntax

HRESULT SetBox(
  D3DRMBOX  *lpD3DRMBox
  );

Parameters

lpD3DRMBox
Address of a D3DRMBOX structure that contains the bounding-box coordinates.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

This method supports a bounding box on a frame for hierarchical culling. For a bounding box to be enabled, the IDirect3DRMFrame3::SetBoxEnable method must be used to set the enable flag to TRUE. By default, the box-enable flag is FALSE.

See Also

IDirect3DRMFrame3::GetBox, IDirect3DRMFrame3::SetBoxEnable, IDirect3DRMFrame3::GetBoxEnable

IDirect3DRMFrame3::SetBoxEnable

IDirect3DRMFrame3

Enables or disables bounding-box testing for this Direct3DRMFrame3 object. Bounding-box testing cannot be enabled unless a valid bounding box has already been set on the frame.

Syntax

HRESULT SetBoxEnable(
  BOOL bEnableFlag
  );

Parameters

bEnableFlag
Flag specifying whether bounding boxes are enabled or not. TRUE to enable a bounding box. FALSE if a bounding box is not enabled. Default is FALSE.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

For a bounding box to be enabled, this method must be used to set the enable flag to TRUE. By default, the box-enable flag is FALSE.

Bounding-box testing is performed as follows: At render time, the bounding box is transformed into model space and checked for intersection with the viewing frustum. If the entire box is outside of the viewing frustum, none of the visuals in the frame, or in any child frame, are rendered. Otherwise, rendering continues as normal.

Enabling bounding-box testing with a box of {0,0,0,0} completely prevents a frame from being rendered.

See Also

IDirect3DRMFrame3::GetBoxEnable, IDirect3DRMFrame3::GetBox, IDirect3DRMFrame3::SetBox

IDirect3DRMFrame3::SetColor

IDirect3DRMFrame3

Sets the color of the frame. This color is used for meshes in the frame when the D3DRMMATERIALMODE enumerated type is D3DRMMATERIAL_FROMFRAME.

Syntax

HRESULT SetColor(
  D3DCOLOR rcColor
  );

Parameters

rcColor
New color for the frame. Be sure to set the alpha component as well as the red, green, and blue color components or your objects might not be visible. The RGBA_MAKE DirectX macro allows you to specify these values.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

This method is also used to add a color key to a DIRECT3DRMFRAMEINTERPOLATOR object. By default, the color is white.

See Also

IDirect3DRMFrame3::GetColor, IDirect3DRMFrame3::SetMaterialMode

IDirect3DRMFrame3::SetColorRGB

IDirect3DRMFrame3

Sets the color of the frame. This color is used for meshes in the frame when the D3DRMMATERIALMODE enumerated type is D3DRMMATERIAL_FROMFRAME.

Syntax

HRESULT SetColorRGB(
  D3DVALUE rvRed,
  D3DVALUE rvGreen,
  D3DVALUE rvBlue
  );

Parameters

rvRed, rvGreen, and rvBlue
New color for the frame. Each component of the color should be in the range 0.0 to 1.0.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

This method is also used to add an RGB color key to a DIRECT3DRMFRAMEINTERPOLATOR object.

See Also

IDirect3DRMFrame3::SetMaterialMode

IDirect3DRMFrame3::SetInheritAxes

IDirect3DRMFrame3

Specifies whether the axes for the frame are inherited from the parent frame.

Syntax

HRESULT SetInheritAxes(
  BOOL inherit_from_parent
  );

Parameters

inherit_from_parent
Flag indicating whether the frame should inherit axes from its parent. If TRUE, the frame inherits axes (the default). If FALSE, the frame does not inherit axes.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

By default, the axes are inherited from the parent. If a frame is set to inherit from the parent, and there is no parent, the frame acts as if it inherits from a parent with the default axes (direction=(0,0,1) and up=(0,1,0)). This method allows a single policy for axes to be set at the root of the hierarchy.

See Also

IDirect3DRMFrame3::GetInheritAxes, IDirect3DRMFrame3::GetAxes, IDirect3DRMFrame3::SetAxes

IDirect3DRMFrame3::SetMaterial

IDirect3DRMFrame3

Sets the material of the Direct3DRMFrame2 object.

Syntax

HRESULT SetMaterial(
  LPDIRECT3DRMMATERIAL2 *lplpMaterial
  );

Parameters

lplpMaterial
Address of the Direct3DRMMaterial object that will be applied to the frame.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMFrame3::GetMaterial

IDirect3DRMFrame3::SetMaterialMode

IDirect3DRMFrame3

Sets the material mode for a frame. The material mode determines the source of material information for visuals rendered with the frame.

Syntax

HRESULT SetMaterialMode(
  D3DRMMATERIALMODE rmmMode
  );

Parameters

rmmMode
One of the members of the D3DRMMATERIALMODE enumerated type. By default, the mode is D3DRMMATERIAL_FROMMESH.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMFrame3::GetMaterialMode

IDirect3DRMFrame3::SetMaterialOverride

IDirect3DRMFrame3

Enables you to set specific material attributes. For example, this method enables you to override only the emissive property of materials.

Syntax

HRESULT SetMaterialOverride(
  LPD3DRMMATERIALOVERRIDE lpdmOverride);

Parameters

lpdmOverride
Pointer to a D3DRMMATERIALOVERRIDE structure that describes the properties to be overridden.

Return Value

Returns one of the following values:
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

The override always overrides everything down the hierarchy. If you override the emissive property in one frame, any attempts to override the same property farther down the hierarchy will be ignored. This override also takes precedence over standard frame overrides, as well as material properties on specific meshes. Overrides such as SetMaterial and SetTexture have no effect on the behavior of this method.

This method was introduced with DirectX version 6.0.

See Also

GetMaterialOverride

IDirect3DRMFrame3::SetOrientation

IDirect3DRMFrame3

Aligns a frame so that its z-direction points along the direction vector [rvDx, rvDy, rvDz] and its y-direction aligns with the vector [rvUx, rvUy, rvUz].

Syntax

HRESULT SetOrientation(
  LPDIRECT3DRMFRAME3 lpRef,
  D3DVALUE rvDx,
  D3DVALUE rvDy,
  D3DVALUE rvDz,
  D3DVALUE rvUx,
  D3DVALUE rvUy,
  D3DVALUE rvUz
  );

Parameters

lpRef
Address of a variable that represents the Direct3DRMFrame object to be used as the reference. This can be NULL. If NULL, the method uses its own local transform matrix instead of using the reference frame's transform matrix.
rvDx, rvDy, and rvDz
New z-axis for the frame. Each component of the vector should be in the range -1.0 to 1.0.
rvUx, rvUy, and rvUz
New y-axis for the frame. Each component of the vector should be in the range -1.0 to 1.0.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

The default orientation of a frame has a direction vector of [0, 0, 1] and an up vector of [0, 1, 0].

If [rvUx, rvUy, rvUz] is parallel to [rvDx, rvDy, rvDz], the D3DRMERR_BADVALUE error value is returned; otherwise, the [rvUx, rvUy, rvUz] vector passed is projected onto the plane that is perpendicular to [rvDx, rvDy, rvDz].

This method is also used to add an orientation key to a Direct3DRMFrameInterpolator object.

Prior to DirectX version 6.0, SetOrientation did not respect scale and shear. This was fixed in DirectX version 6.0.

The following code fragment calls SetOrientation to set the default orientation. It assumes the camera and scene frames have already been created using the IDirect3DRM3::CreateFrame method.

LPDIRECT3DRMFRAME3 camera;
LPDIRECT3DRMFRAME3 scene;

if (FAILED(camera->SetOrientation(scene, D3DVAL(0), D3DVAL(0), D3DVAL(1),
                                  D3DVAL(0), D3DVAL(1), D3DVAL(0)))
{
    // error
}

See Also

IDirect3DRMFrame3::GetOrientation

IDirect3DRMFrame3::SetPosition

IDirect3DRMFrame3

Sets the position of a frame relative to the frame of reference. It places the frame a distance of [rvX, rvY, rvZ] from the reference. When a child frame is created within a parent, it is placed at [0, 0, 0] in the parent frame.

Syntax

HRESULT SetPosition(
  LPDIRECT3DRMFRAME3 lpRef,
  D3DVALUE rvX,
  D3DVALUE rvY,
  D3DVALUE rvZ
  );

Parameters

lpRef
Address of a variable that represents the Direct3DRMFrame object to be used as the reference. This can be NULL. If NULL, the method uses its own local transform matrix instead of using the reference frame's transform matrix.
rvX, rvY, and rvZ
New position for the frame. Position has no units. Use the viewing frustrum to choose reasonable numbers. For more information, see Viewports.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

This method is also used to add a position key to a Direct3DRMFrameInterpolator object.

The following code fragment calls SetPosition. It assumes the camera and scene frames have already been created using the IDirect3DRM3::CreateFrame method.

LPDIRECT3DRMFRAME3 camera;
LPDIRECT3DRMFRAME3 scene;

if (FAILED(camera->SetPosition(scene, D3DVAL(0), D3DVAL(0), -D3DVAL(10)))
{
    // error
}

See Also

IDirect3DRMFrame3::GetPosition

IDirect3DRMFrame3::SetQuaternion

IDirect3DRMFrame3

Sets a frame's orientation relative to a reference frame using a unit quaternion.

Syntax

HRESULT SetQuaternion(
  LPDIRECT3DRMFRAME3 lpRef,
  D3DRMQUATERNION *quat
  )

Parameters

lpRef
Address of a variable that represents the Direct3DRMFrame2 object to be used as the reference. This can be NULL. If NULL, the method uses its own local transform matrix instead of using the reference frame's transform matrix.
quat
A D3DRMQUATERNION structure that holds the unit quaternion.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

A quaternion is a four-valued vector that can be used to represent any rotation and that has properties that are useful when interpolating between orientations. A quaternion is a unit quaternion if s**2 + x**2 + y**2 + z**2 = 1.

The function D3DRMQuaternionFromRotation can be used to generate unit quaternions from arbitrary rotation values.

The SetQuaternion method is supported by FrameInterpolators. See Interpolators for more information about interpolators.

IDirect3DRMFrame3::SetRotation

IDirect3DRMFrame3

Sets a frame rotating by the given angle around the given vector at each call to the IDirect3DRM3::Tick or IDirect3DRMFrame3::Move method. The direction vector [rvX, rvY, rvZ] is defined in the reference frame.

Syntax

HRESULT SetRotation(
  LPDIRECT3DRMFRAME3 lpRef,
  D3DVALUE rvX,
  D3DVALUE rvY,
  D3DVALUE rvZ,
  D3DVALUE rvTheta
  );

Parameters

lpRef
Address of a variable that represents the Direct3DRMFrame object to be used as the reference. This can be NULL. If NULL, the method uses its own local transform matrix instead of using the reference frame's transform matrix.
rvX, rvY, and rvZ
Vector about which rotation occurs. Valid values are in the range -1.0 to 1.0.
rvTheta
Rotation angle, in radians. The larger the angle, the faster an object rotates. The IDirect3DRMFrame3::Move and IDirect3DRM3::Tick methods scale this value.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

The specified rotation changes the matrix with every render tick, unlike the IDirect3DRMFrame3::AddRotation method, which changes the objects in the frame only once.

The following code fragment calls SetRotation. It assumes the child and scene frames have already been created using the IDirect3DRM3::CreateFrame method.

LPDIRECT3DRMFRAME3 child;
LPDIRECT3DRMFRAME3 scene;

if (FAILED(child->SetRotation(scene, D3DVAL(0), D3DVAL(1), D3DVAL(1), D3DVAL(0.02)))
{
    // error
}

See Also

IDirect3DRMFrame3::AddRotation, IDirect3DRMFrame3::GetRotation

IDirect3DRMFrame3::SetSceneBackground

IDirect3DRMFrame3

Sets the background color of a scene.

Syntax

HRESULT SetSceneBackground(
  D3DCOLOR rcColor
  );

Parameters

rcColor
New color for the background.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

This method is also used to add a background color key to a Direct3DRMFrameInterpolator object.

IDirect3DRMFrame3::SetSceneBackgroundDepth

IDirect3DRMFrame3

Specifies a background-depth buffer for a scene.

Syntax

HRESULT SetSceneBackgroundDepth(
  LPDIRECTDRAWSURFACE lpImage
  );

Parameters

lpImage
Address of a DirectDraw surface that will store the new background depth for the scene.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

The image must have a depth of 16 bits per pixel. If the image and viewport sizes are different, the image is scaled first. For best performance when animating the background-depth buffer, the image should be the same size as the viewport. This enables the depth buffer to be updated directly from the image memory without incurring extra overhead.

See Also

IDirect3DRMFrame3::GetSceneBackgroundDepth

IDirect3DRMFrame3::SetSceneBackgroundImage

IDirect3DRMFrame3

This method is obsolete and should not be used. It does not have the same behavior it did in DirectX version 5 because of changes in rasterizers. Rather than use this method you should do a blit (bit block transfer) to the screen for your background.

Syntax

HRESULT SetSceneBackgroundImage(
  LPDIRECT3DRMTEXTURE3 lpTexture
  );

Parameters

lpTexture
Address of a Direct3DRMTexture object that will contain the new background scene.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

This method is obsolete. It does not have the same behavior it did in DirectX version 5.

IDirect3DRMFrame3::SetSceneBackgroundRGB

IDirect3DRMFrame3

Sets the background color of a scene.

Syntax

HRESULT SetSceneBackgroundRGB(
  D3DVALUE rvRed,
  D3DVALUE rvGreen,
  D3DVALUE rvBlue
  );

Parameters

rvRed, rvGreen, and rvBlue
New color for the background. Each component of the color should be in the range 0.0 to 1.0.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

This method is also used to add a background RGB color key to a Direct3DRMFrameInterpolator object.

IDirect3DRMFrame3::SetSceneFogColor

IDirect3DRMFrame3

Sets the fog color of a scene.

Syntax

HRESULT SetSceneFogColor(
  D3DCOLOR rcColor
  );

Parameters

rcColor
New color for the fog.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

This method is also used to add a fog color key to a Direct3DRMRFrameInterpolator object. By default, the color is white.

IDirect3DRMFrame3::SetSceneFogEnable

IDirect3DRMFrame3

Sets the fog-enable state.

Syntax

HRESULT SetSceneFogEnable(
  BOOL bEnable
  );

Parameters

bEnable
New fog-enable state.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

By default, fog is not enabled.

IDirect3DRMFrame3::SetSceneFogMethod

IDirect3DRMFrame3

Specifies whether fogging is to be performed via vertex fog or table fog.

Syntax

HRESULT SetSceneFogMethod(
  DWORD dwFlags);

Parameters

dwFlags
The currently defined flags are:
D3DRMFOGMETHOD_ANY
Indicates that Direct3D Retained Mode should choose an applicable method.
D3DRMFOGMETHOD_VERTEX
Use vertex fog.
D3DRMFOGMETHOD_TABLE
Use table fog.

Return Value

Returns one of the following values:
D3DRMERR_BADVALUE
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

The default behavior for Direct3DRMFrame objects created by the IDirect3DRM3 interface is D3DRMFOGMETHOD_ANY and the fog method will be chosen based on the capabilities of the device. If the device supports both vertex- and table-based fog then vertex fogging will be used. If the application requests table fog, but table fog is not available, vertex fog will be used. The default behavior for Direct3DRMFrame objects created with an IDirect3DRM or IDirect3DRM2 interface is D3DRMFOGMETHOD_VERTEX.

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMFrame3::SetSceneFogMode

IDirect3DRMFrame3

Sets the fog mode.

Syntax

HRESULT SetSceneFogMode(
  D3DRMFOGMODE rfMode
  );

Parameters

rfMode
One of the members of the D3DRMFOGMODE enumerated type, specifying the new fog mode.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMFrame3::SetSceneFogParams

IDirect3DRMFrame3::SetSceneFogParams

IDirect3DRMFrame3

Sets the current fog parameters for this scene.

Syntax

HRESULT SetSceneFogParams(
  D3DVALUE rvStart,
  D3DVALUE rvEnd,
  D3DVALUE rvDensity
  );

Parameters

rvStart and rvEnd
Fog start and end points for linear fog mode. These settings determine the distance from the camera at which fog effects first become visible, and the distance at which fog reaches its maximum density.
rvDensity
Fog density for the exponential fog modes. This value should be in the range 0 through 1.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

This method is also used to add a fog parameters key to a Direct3DRMRFrameInterpolator object.

See Also

D3DRMFOGMODE, IDirect3DRMFrame3::SetSceneFogMode

IDirect3DRMFrame3::SetSortMode

IDirect3DRMFrame3

Sets the sorting mode used to process child frames. You can use this method to change the properties of hidden-surface-removal algorithms.

Syntax

HRESULT SetSortMode(
  D3DRMSORTMODE d3drmSM
  );

Parameters

d3drmSM
One of the members of the D3DRMSORTMODE enumerated type, specifying the sorting mode. The default value is D3DRMSORT_FROMPARENT.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMFrame3::GetSortMode

IDirect3DRMFrame3::SetTexture

IDirect3DRMFrame3

Sets the texture of the frame.

Syntax

HRESULT SetTexture(
  LPDIRECT3DRMTEXTURE3 lpD3DRMTexture
  );

Parameters

lpD3DRMTexture
Address of a variable that represents the Direct3DRMTexture object to be used.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

The texture is used for meshes in the frame when the D3DRMMATERIALMODE enumerated type is D3DRMMATERIAL_FROMFRAME. To disable the frame's texture, use a NULL texture.

See Also

IDirect3DRMFrame3::GetTexture, IDirect3DRMFrame3::SetMaterialMode

IDirect3DRMFrame3::SetTraversalOptions

IDirect3DRMFrame3

Specifies whether this frame is traversed during rendering and picking. In other words, using this API without a value of D3DRMFRAME_RENDERENABLE effectively switches the frame off for rendering. By default, the frame is enabled for rendering and picking.

Syntax

HRESULT SetTraversalOptions
(DWORD dwFlags);

Parameters

dwFlags
The currently defined flags are:
D3DRMFRAME_RENDERENABLE
Indicates render this frame or any children of this frame.
D3DRMFRAME_PICKENABLE
Indicates pick any visuals in this frame or any children of this frame.

Return Value

Returns one of the following values:
D3DRMERR_BADVALUE
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMFrame3::SetVelocity

IDirect3DRMFrame3

Sets the velocity of the given frame relative to the reference frame. The frame will be moved by the vector [rvX, rvY, rvZ] with respect to the reference frame at each successive call to the IDirect3DRM3::Tick or IDirect3DRMFrame3::Move method.

Syntax

HRESULT SetVelocity(
  LPDIRECT3DRMFRAME3 lpRef,
  D3DVALUE rvX,
  D3DVALUE rvY,
  D3DVALUE rvZ,
  BOOL fRotVel
  );

Parameters

lpRef
Address of a variable that represents the Direct3DRMFrame object to be used as the reference. This can be NULL. If NULL, the method uses its own local transform matrix instead of using the reference frame's transform matrix.
rvX, rvY, and rvZ
New velocity for the frame. Rotational velocity has no units and can be any value. The IDirect3DRMFrame3::Move and IDirect3DRM3::Tick methods scale this value.
fRotVel
Flag specifying whether the rotational velocity of the object is taken into account when setting the linear velocity. If TRUE, the object's rotational velocity is included in the calculation.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMFrame3::GetVelocity

IDirect3DRMFrame3::SetZbufferMode

IDirect3DRMFrame3

Sets the z-buffer mode; that is, whether z-buffering is enabled or disabled.

Syntax

HRESULT SetZbufferMode(
  D3DRMZBUFFERMODE d3drmZBM
  );

Parameters

d3drmZBM
One of the members of the D3DRMZBUFFERMODE enumerated type, specifying the z-buffer mode. The default value is D3DRMZBUFFER_FROMPARENT.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMFrame3::GetZbufferMode

IDirect3DRMFrame3::Transform

IDirect3DRMFrame3

Transforms the vector in the lpd3dVSrc parameter in model coordinates to world coordinates, returning the result in the lpd3dVDst parameter.

Syntax

HRESULT Transform(
  D3DVECTOR *lpd3dVDst,
  D3DVECTOR *lpd3dVSrc
  );

Parameters

lpd3dVDst
Address of a D3DVECTOR structure that will be filled with the result of the transformation operation.
lpd3dVSrc
Address of a D3DVECTOR structure that is the source of the transformation operation.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMFrame3::InverseTransform, 3-D Transformations

IDirect3DRMFrame3::TransformVectors

IDirect3DRMFrame3

Transforms an array of vectors from model- to world-space.

Syntax

HRESULT TransformVectors(
  LPDIRECT3DRMFRAME3 lpRefFrame,
  DWORD dwNumVectors,
  LPD3DVECTOR lpDstVectors,
  LPD3DVECTOR lpSrcVectors);

Parameters

lpRefFrame
Frame that is to be used as the root of the scene for the purposes of this call. If this argument is NULL, the current root frame (as would be returned by GetScene) will be used.
dwNumVectors
The number of vectors to be transformed.
lpDstVectors
Destination of the transformation.
lpSrcVectors
Array of vectors to transform.

Return Value

Returns one of the following values:
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.


IDirect3DRMMeshBuilder3

IDirect3DRMMeshBuilder3 Methods A to M

This section contains the reference pages for the methods of the IDirect3DRMMeshBuilder3 interface that begin with the letters A through M.

IDirect3DRMMeshBuilder3::AddFace

IDirect3DRMMeshBuilder3

Adds a face to a Direct3DRMMeshBuilder3 object.

Syntax

HRESULT AddFace(
  LPDIRECT3DRMFACE2 lpD3DRMFace
  );

Parameters

lpD3DRMFace
Address of a pointer to the face being added.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

Any one face can exist in only one mesh at a time.

IDirect3DRMMeshBuilder3::AddFaces

IDirect3DRMMeshBuilder3

Adds faces to a Direct3DRMMeshBuilder3 object.

Syntax

HRESULT AddFaces(
  DWORD dwVertexCount,
  D3DVECTOR  *lpD3DVertices,
  DWORD normalCount,
  D3DVECTOR *lpNormals,
  DWORD *lpFaceData,
  LPDIRECT3DRMFACEARRAY *lplpD3DRMFaceArray
  );

Parameters

dwVertexCount
Number of vertices.
lpD3DVertices
Base address of an array of D3DVECTOR structures that store the vertex positions.
normalCount
Number of normals.
lpNormals
Base address of an array of D3DVECTOR structures that store the normal positions.
lpFaceData
For each face, this parameter should contain a vertex count followed by the indexes into the vertices array. If normalCount is not zero, this parameter should contain a vertex count followed by pairs of indexes, with the first index of each pair indexing into the array of vertices, and the second indexing into the array of normals. The list of indexes must terminate with a zero.
lplpD3DRMFaceArray
Address of a pointer to an IDirect3DRMFaceArray interface that will be filled with a pointer to the newly created faces.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMMeshBuilder3::AddFacesIndexed

IDirect3DRMMeshBuilder3

Enables a number of faces to be created on the meshbuilder that use pre-existing vertices and normals (optional).

Syntax

IDirect3DRMMeshBuilder3::AddFacesIndexed(
  DWORD dwFlags,
  DWORD *lpdwvIndices,
  DWORD *lpdwIndexFirst,
  DWORD *lpdwCount);

Parameters

dwFlags
Flag value that specifies how normal indexes should be handled. Must be either 0 or D3DRMADDFACES_VERTICESONLY. If the value is 0, indexes of pre-existing normals must be specified in the lpdwvIndices parameter. Otherwise, the normal with the corresponding index will be used automatically for each vertex.
lpdwvIndices
Pointer to a contiguous array of unsigned integer tuples that specify the following for each face.
  • Number of vertices n, where n is greater than or equal to 3
  • Vertex indexes
  • Normal indexes (optional)

The following table shows the relationship between the value for the dwFlags parameter and the required face tuple format for the lpdwvIndices parameter.
dwFlags | Required face tuple format
0 | {<n>, <vIndex0>, <nIndex0>,...,<vIndexn-1>, <nIndexn-1>}
D3DRMADDFACES_VERTICESONLY | {<n>, <vIndex0>,...,<vIndexn-1>}

The vIndex and nIndex values are required to index into previously existing vertices and normals within the meshbuilder. The array of tuples should be terminated with the value 0.

lpdwIndexFirst
Optional pointer to a DWORD that, if supplied, is filled with the index of the first new face added to the meshbuilder. Subsequent faces have contiguous indexes. Faces are added in the order in which they are specified in the lpdwvIndices parameter.
lpdwCount
Optional pointer to a DWORD that, if supplied, is filled with the number of faces added to the meshbuilder.

Return Value

Returns one of the following values:
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMMeshBuilder3::AddFrame

IDirect3DRMMeshBuilder3

Adds the contents of a frame to a Direct3DRMMeshBuilder3 object.

Syntax

HRESULT AddFrame(
  LPDIRECT3DRMFRAME3 lpD3DRMFrame
  );

Parameters

lpD3DRMFrame
Address of a pointer to the frame whose contents are being added.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

This method adds a copy of all the mesh and meshbuilder faces from the specified frame hierarchy (which may be a sub-branch of a larger frame hierarchy) to the Direct3DRMMeshBuilder3 object. The frame tree is specified by passing the root frame. Faces are added with the position and orientation of their containing frame factored in. Transforms of the specified root frame are ignored, even if the root frame has a parent.

The source frame is not modified or referenced by this operation.

IDirect3DRMMeshBuilder3::AddMesh

IDirect3DRMMeshBuilder3

Adds a mesh to a Direct3DRMMeshBuilder3 object.

Syntax

HRESULT AddMesh(
  LPDIRECT3DRMMESH lpD3DRMMesh
  );

Parameters

lpD3DRMMesh
Address of a pointer to the mesh being added.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMMeshBuilder3::AddMeshBuilder

IDirect3DRMMeshBuilder3

Adds the contents of a Direct3DRMMeshBuilder3 object to a Direct3DRMMeshBuilder3 object. All sub-meshbuilders underneath the source Direct3DRMMeshBuilder3 object and the faces they contain are duplicated beneath the target Direct3DRMMeshBuilder3 object.

Syntax

HRESULT
AddMeshBuilder(
  LPDIRECT3DRMMESHBUILDER3 lpD3DRMMeshBuild
  DWORD dwFlags);
  );

Parameters

lpD3DRMMeshBuild
Pointer to the Direct3DRMMeshBuilder3 object whose contents are being added.
dwFlags

One of the following defined flags:

D3DRMADDMESHBUILDER_FLATTENSUBMESHES
Causes the submesh objects to not be duplicated. Their faces are still copied, but only to the top-level of the destination meshbuilder.
D3DRMADDMESHBUILDER_NOSUBMESHES
Causes sub-meshbuilders to be ignored.
D3DRMADDMESHBUILDER_DONTCOPYAPPDATA
By default, AddMeshBuilder3 copies the application data of source meshbuilders to the destination. Specifying D3DRMADDMESHBUILDER_DONTCOPYAPPDATA prevents this from occurring.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

The source Direct3DRMMeshBuilder3 object is not modified or referenced by this operation.

IDirect3DRMMeshBuilder3::AddNormal

IDirect3DRMMeshBuilder3

Adds a normal to a Direct3DRMMeshBuilder3 object.

Syntax

int AddNormal(
  D3DVALUE x,
  D3DVALUE y,
  D3DVALUE z
  );

Parameters

x, y, and z
The x-, y-, and z-components of the direction of the new normal.

Return Value

Returns the index of the normal.

IDirect3DRMMeshBuilder3::AddTriangles

IDirect3DRMMeshBuilder3

Enables the application to add new triangles (as opposed to general polygons) to the IDirect3DRMMeshBuilder3 object, and in the process, to implicitly create new faces. This method provides flexibility to the application in describing the triangles. The triangles are described by a set of vertices. Each vertex must have a position, but may optionally have none or any of the following: normal, texture coordinates, or color. The vertex also has a type that describes whether this new vertex describes a list, strip, or fan. A flag also indicates whether this triangle is to be added to the face of the previous triangle, or whether a new face is to be created.

Syntax

HRESULT AddTriangles(
  DWORD dwFlags,
  DWORD dwFormat,
  DWORD dwVertexCount,
  LPVOID lpData);

Parameters

dwFlags
Must be zero.
dwFormat
Logical combination of values describing the format of the vertex data. If all valid values are included, the vertex data is described by the following Element structure.
struct Element
{
    DWORD     dwType;
    D3DVECTOR dvPosition;
    D3DVECTOR dvNormal;
    D3DCOLOR  dcColor;
    D3DVALUE  tu;
    D3DVALUE  tv;
};

Valid values include a logical combination of any of the following values, which indicate which members of the Element structure to include in the description for each element. The dvPosition member is always present.

D3DRMFVF_TYPE
Include the dwType structure member. If the dwType structure member is present, it must include one of the following:
D3DRMVERTEX_LIST
Starts a new list or is a member of a previously started list. If the previous vertex (or the vertex previous to that) was not marked with this flag, the following vertices must be marked with this flag until at least one triangle is formed.
D3DRMVERTEX_STRIP
Forms a new triangle in strip format with the previous two vertices.
D3DRMVERTEX_FAN
Forms a new triangle with the previous vertex and the first vertex in the fan.
D3DRMFVF_NORMAL
Include the dvNormal structure member.
D3DRMFVF_COLOR
Include the dcColor structure member.
D3DRMFVF_TEXTURECOORDS
Include the tu and tv structure members.
dwVertexCount
Vertex number.
lpvData
Pointer to the data described by dwFormat.

Return Value

Returns one of the following values:
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

The following example shows the appropriate dwType flag for each vertex in the diagram.
Vertex Number | dwType Flag
0 | D3DRMVERTEX_STRIP
1 | D3DRMVERTEX_STRIP
2 | D3DRMVERTEX_STRIP
3 | D3DRMVERTEX_STRIP
4 | D3DRMVERTEX_STRIP
5 | D3DRMVERTEX_FAN
6 | D3DRMVERTEX_FAN
7 | D3DRMVERTEX_FAN
8 | D3DRMVERTEX_FAN
9 | D3DRMVERTEX_LIST
10 | D3DRMVERTEX_LIST
11 | D3DRMVERTEX_LIST
12 | D3DRMVERTEX_LIST
13 | D3DRMVERTEX_LIST
14 | D3DRMVERTEX_LIST

IDirect3DRMMeshBuilder3::AddVertex

IDirect3DRMMeshBuilder3

Adds a vertex to a Direct3DRMMeshBuilder3 object.

Syntax

int AddVertex(
  D3DVALUE x,
  D3DVALUE y,
  D3DVALUE z
  );

Parameters

x, y, and z
X-, y-, and z-components of the position of the new vertex.

Return Value

Returns the index of the vertex.

IDirect3DRMMeshBuilder3::CreateFace

IDirect3DRMMeshBuilder3

Creates a new face with no vertices and adds it to a Direct3DRMMeshBuilder3 object.

Syntax

HRESULT CreateFace(
  LPDIRECT3DRMFACE2 *lplpD3DRMFace2
  );

Parameters

lplpD3DRMFace2
Address of a pointer to an IDirect3DRMFace2 interface that will be filled with a pointer to the face that was created.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMMeshBuilder3::CreateMesh

IDirect3DRMMeshBuilder3

Creates a new mesh from a Direct3DRMMeshBuilder3 object.

Syntax

HRESULT CreateMesh(
  LPDIRECT3DRMMESH *lplpD3DRMMesh
  );

Parameters

lplpD3DRMMesh
Address that will be filled with a pointer to an IDirect3DRMMesh interface.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMMeshBuilder3::CreateSubMesh

IDirect3DRMMeshBuilder3

Creates a new submesh for the current Direct3DRMMeshBuilder3 object. A submesh is similar to a meshbuilder object in that it supports the IDirect3DRMMeshBuilder3 interface, and can itself have submeshes. The difference between submeshes and meshbuilders is that all submeshes share the vertices and normals with the greatest ancestor in the chain of submeshes. Meshbuilders do not share vertices and normals.

Syntax

HRESULT CreateSubMesh(
  LPUNKNOWN  *lplpUnk);

Parameters

lplpUnk
Address to receive a pointer to the IUnknown interface of the new submesh. You can use QueryInterface on the IUnknown interface to query for IDirect3DRMMeshBuilder3 support.

Return Value

Returns one of the following values:
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

See Also

DeleteSubMesh, GetSubMeshes, GetParentMesh

IDirect3DRMMeshBuilder3::DeleteFace

IDirect3DRMMeshBuilder3

Deletes a face from the IDirect3DRMMeshBuilder3 object.

Syntax

HRESULT DeleteFace
(LPDIRECT3DRMFACE2 lpFace);

Parameters

lpFace
Pointer to the interface of a Direct3DRMFace2 object to remove from the Direct3DRMMeshBuilder3 object.

Return Value

Returns one of the following values:
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMMeshBuilder3::DeleteNormals

IDirect3DRMMeshBuilder3

Deletes an inclusive range of normals. Note that if any of the normals are currently in use by a face, an error is returned.

Syntax

HRESULT DeleteNormals
(DWORD dwFirstIndex,
DWORD dwCount);

Parameters

dwFirstIndex
Index of the first normal to delete.
dwCount
Count of vertices to delete.

Return Value

Returns one of the following values:
D3DRMERR_ENTRYINUSE
D3DRMERR_OUTOFRANGE
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMMeshBuilder3::DeleteSubMesh

IDirect3DRMMeshBuilder3

Deletes a submesh. The submesh must be an immediate child of the current Direct3DRMMeshBuilder3 object.

Syntax

HRESULT DeleteSubMesh(
  LPUNKNOWN lplpUnk);

Parameters

lplpUnk
Pointer to the IUnknown interface of the submesh to delete.

Return Value

Returns one of the following values:
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

See Also

CreateSubMesh, GetSubMeshes and GetParentMesh

IDirect3DRMMeshBuilder3::DeleteVertices

IDirect3DRMMeshBuilder3

Deletes an inclusive range of vertices. Note that if any of the vertices are currently in use by a face, an error is returned.

Syntax

HRESULT DeleteVertices
(DWORD dwFirstIndex,
DWORD dwCount);

Parameters

dwFirstIndex
Index of the first vertex to delete.
dwCount
Count of the vertices to delete.

Return Value

Returns one of the following values:
D3DRMERR_ENTRYINUSE
D3DRMERR_OUTOFRANGE
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMMeshBuilder3::Empty

IDirect3DRMMeshBuilder3

Removes all faces, vertices, and normals from the Direct3DRMMeshBuilder3 object.

Syntax

HRESULT Empty
(DWORD dwFlags);

Parameters

dwFlags
Flags; must be zero.

Return Value

Returns one of the following values:
D3DRMERR_OUTOFRANGE
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMMeshBuilder3::Enable

IDirect3DRMMeshBuilder3

Specifies whether this Direct3DRMMeshBuilder3 object should be enabled or disabled for rendering and picking.

Syntax

HRESULT Enable(
  DWORD dwFlags);

Parameters

dwFlags

The currently defined flags are:

D3DRMADDMESHBUILDER_RENDERENABLE
Rendering is enabled on this Direct3DRMMeshBuilder3 object. This setting is the default.
D3DRMADDMESHBUILDER_PICKENABLE
Picking is enabled on this Direct3DRMMeshBuilder3 object. This setting is the default.

Return Value

Returns one of the following values:
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

See Also

GetEnable

IDirect3DRMMeshBuilder3::GenerateNormals

IDirect3DRMMeshBuilder3

Processes the Direct3DRMMeshBuilder3 object and generates normals for each vertex in a mesh by averaging the face normals for each face that shares the vertex. New normals are generated if the faces sharing a vertex have an angle between them greater than the crease angle.

Syntax

HRESULT GenerateNormals(
  D3DVALUE dvCreaseAngle,
  DWORD dwFlags
  );

Parameters

dvCreaseAngle
The least angle in radians that faces can have between them and have a new normal generated.
dwFlags
One of the following values.
D3DRMGENERATENORMALS_PRECOMPACT (dwFlags = 1)
Specifies that the algorithm should attempt to compact mesh vertices before it generates normals. See comments below.
D3DRMGENERATENORMALS_USECREASEANGLE (dwFlags = 2)
Specifies that the dvCreaseAngle parameter should be used. Otherwise, the crease angle is ignored.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

This method replaces IDirect3DRMMeshBuilder2::GenerateNormals2. If you specify the D3DRMGENERATENORMALS_PRECOMPACT flag, the precompact pass searches all the vertices in the mesh and merges any that are the same. This is a good way of compacting a mesh that has been loaded. Some meshes have multiple vertices if they have multiple normals at that vertex. This is not necessary in Direct3D Retained Mode. Specifying this flag is the way to get rid of the multiple vertices.

After compacting, the normals are generated. The edges between faces are examined, and if the angle the faces make at the edge is less than the crease angle, the face normals are averaged to generate the vertex normal. If the angle is greater than the crease angle, a new normal is generated. Note that a new vertex is not generated.

IDirect3DRMMeshBuilder3::GetBox

IDirect3DRMMeshBuilder3

Retrieves the bounding box containing a Direct3DRMMeshBuilder3 object. The bounding box gives the minimum and maximum model coordinates in each dimension.

Syntax

HRESULT GetBox(
  D3DRMBOX *lpD3DRMBox
  );

Parameters

lpD3DRMBox
Address of a D3DRMBOX structure that will be filled with the bounding box coordinates.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMMeshBuilder3::GetColorSource

IDirect3DRMMeshBuilder3

Retrieves the color source of a Direct3DRMMeshBuilder3 object. The color source can be either a face or a vertex.

Syntax

D3DRMCOLORSOURCE GetColorSource( );

Return Value

Returns a member of the D3DRMCOLORSOURCE enumerated type.

See Also

IDirect3DRMMeshBuilder3::SetColorSource

IDirect3DRMMeshBuilder3::GetEnable

IDirect3DRMMeshBuilder3

Retrieves a value that indicates whether this Direct3DRMMeshBuilder3 object should be enabled or disabled.

Syntax

HRESULT GetEnable(
  LPDWORD lpdwFlags);

Parameters

lpdwFlags
Pointer to receive a flag indicating the current enable status of this Direct3DRMMeshBuilder3 object. The currently defined flags are:
D3DRMADDMESHBUILDER_PICKENABLE
Picking is enabled on this Direct3DRMMeshBuilder3 object. This flag is set by default.
D3DRMADDMESHBUILDER_RENDERENABLE
Rendering is enabled on this Direct3DRMMeshBuilder3 object. This flag is set by default.

Return Value

Returns one of the following values:
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

See Also

Enable

IDirect3DRMMeshBuilder3::GetFace

IDirect3DRMMeshBuilder3

Retrieves a single face of a Direct3DRMMeshBuilder3 object.

Syntax

HRESULT GetFace(
  DWORD dwIndex,
  LPDIRECT3DRMFACE2 *lplpD3DRMFace2
  );

Parameters

dwIndex
The index of the mesh face to be retrieved. The face must already be part of a Direct3DRMMeshBuilder3 object.
lplpD3DRMFace2
Address of a pointer to an IDirect3DRMFace2 interface that is filled with an address of the face.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMMeshBuilder3::GetFaceCount

IDirect3DRMMeshBuilder3

Retrieves the number of faces in a Direct3DRMMeshBuilder3 object.

Syntax

int GetFaceCount( );

Return Value

Returns the number of faces.

IDirect3DRMMeshBuilder3::GetFaces

IDirect3DRMMeshBuilder3

Retrieves the faces of a Direct3DRMMeshBuilder3 object.

Syntax

HRESULT GetFaces(
  LPDIRECT3DRMFACEARRAY *lplpD3DRMFaceArray
  );

Parameters

lplpD3DRMFaceArray
Address of a pointer to an IDirect3DRMFaceArray interface that is filled with an address of the faces.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMMeshBuilder3::GetGeometry

IDirect3DRMMeshBuilder3

Retrieves the vertices, normals, and face data for a Direct3DRMMeshBuilder3 object.

Syntax

HRESULT GetGeometry(
  DWORD *vcount,
  D3DVECTOR *vertices,
  DWORD *ncount,
  D3DVECTOR *normals,
  DWORD *face_data_size,
  DWORD *face_data
  );

Parameters

vcount
Address of a variable that will contain the number of vertices.
vertices
Address of an array of D3DVECTOR structures that will contain the vertices for the Direct3DRMMeshBuilder3 object. If this parameter is NULL, the method returns the number of vertices in the vcount parameter.
ncount
Address of a variable that will contain the number of normals.
normals
Address of an array of D3DVECTOR structures that will contain the normals for the Direct3DRMMeshBuilder3 object. If this parameter is NULL, the method returns the number of normals in the ncount parameter.
face_data_size
Address of a variable that specifies the size of the buffer pointed to by the face_data parameter. The size is given in units of DWORD values. This parameter cannot be NULL.
face_data
Address of the face data for the Direct3DRMMeshBuilder3 object. This data is in the same format as specified in the IDirect3DRMMeshBuilder3::AddFaces method except that it is null-terminated. If this parameter is NULL, the method returns the required size of the face-data buffer in the face_data_size parameter.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

This method was introduced with DirectX version 6.0. The IDirect3DRMMeshBuilder and IDirect3DRMMeshBuilder2 interfaces provided this functionality through the GetVertices method. The old method was renamed to GetGeometry with the IDirect3DRMMeshBuilder3 interface to better describe what this method does and to avoid conflicts with the new GetVertices method.

IDirect3DRMMeshBuilder3::GetNormal

IDirect3DRMMeshBuilder3

Retrieves a normal vector.

Syntax

HRESULT GetNormal
(DWORD dwIndex,
LPD3DVECTOR lpVector);

Parameters

dwIndex
Index of the normal to return.
lpVector
Pointer to a D3DVECTOR structure that will be filled in with the x-, y-, and z-coordinates of the normal.

Return Value

Returns one of the following values:
D3DRMERR_OUTOFRANGE
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMMeshBuilder3::GetNormalCount

IDirect3DRMMeshBuilder3

Returns the number of normals in the Direct3DRMMeshBuilder3 object.

Syntax

DWORD GetNormalCount(void);

Return Value

Returns one of the following values:
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

See Also

GetNormals and SetNormals

IDirect3DRMMeshBuilder3::GetNormals

IDirect3DRMMeshBuilder3

Retrieves an array of normals that have previously been defined in the Direct3DRMMeshBuilder3 object.

Syntax

HRESULT GetNormals(
  DWORD dwFirst,
  LPDWORD lpdwCount,
  LPD3DVECTOR lpdvVector);

Parameters

dwFirst
Index of the first normal to be returned.
lpdwCount
Pointer to a DWORD containing the number of normals expected to be returned. If lpdvVector is NULL, this parameter receives the number of normals available, starting from the index given in dwFirst. If lpdvVector is not NULL, this parameter contains the number of normals actually retrieved. To ensure that you receive all the available normals, starting from dwFirst, call this method with lpdvVector set to NULL, then use the value returned in lpdwCount to size the array in lpdvVector, and call the method again.
lpdvVector
Pointer to an array of vectors to receive the normal data.

Return Value

Returns one of the following values:
D3DRMERR_OUTOFRANGE
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

See Also

GetNormalCount and SetNormals

IDirect3DRMMeshBuilder3::GetParentMesh

IDirect3DRMMeshBuilder3

Retrieves a parent mesh of this Direct3DRMMeshBuilder3 object. If the current mesh is not a submesh, this method retrieves a pointer to its own IUnknown interface.

Syntax

HRESULT GetParentMesh(
  DWORD dwFlags,
  LPUNKNOWN  *lplpUnk);

Parameters

dwFlags
Flag value that defines which Direct3DRMMeshBuilder3 object to retrieve. The currently defined flags are:
D3DRMMESHBUILDER_DIRECTPARENT
This Direct3DRMMeshBuilder3 object's direct parent.
D3DRMMESHBUILDER_ROOTMESH
The final parent of this Direct3DRMMeshBuilder3 object that has no parent.
lplpUnk
Address of a pointer to receive the parent's IUnknown interface.

Return Value

Returns one of the following values:
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

See Also

GetSubMeshes

IDirect3DRMMeshBuilder3::GetPerspective

IDirect3DRMMeshBuilder3

Determines whether perspective correction is on for a Direct3DRMMeshBuilder3 object.

Syntax

BOOL GetPerspective( );

Return Value

Returns TRUE if perspective correction is on, or FALSE otherwise.

IDirect3DRMMeshBuilder3::GetQuality

IDirect3DRMMeshBuilder3

Retrieves the rendering quality of a Direct3DRMMeshBuilder3 object.

Syntax

D3DRMRENDERQUALITY GetQuality( );

Return Value

Returns a member of the D3DRMRENDERQUALITY enumerated type that specifies the rendering quality of the mesh.

See Also

IDirect3DRMMeshBuilder3::SetQuality

IDirect3DRMMeshBuilder3::GetSubMeshes

IDirect3DRMMeshBuilder3

Retrieves a list of the submeshes that this Direct3DRMMeshBuilder3 object contains.

Syntax

HRESULT GetSubMeshes(
  LPDWCOUNT lpdwCount,
  LPUNKNOWN lpUnk);

Parameters

lpdwCount
Pointer to a DWORD value containing the number of IUnknown interface pointers expected to be returned. If lpUnk is NULL, the value pointed to by lpdwCount receives the number of pointers available. Otherwise, the value pointed to by lpdwCount receives the number of IUnknown pointers actually retrieved.
lpUnk
Array of IUnknown pointers to child submeshes

Return Value

Returns one of the following values:
D3DRMERR_OUTOFRANGE
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

See Also

GetParentMesh

IDirect3DRMMeshBuilder3::GetTextureCoordinates

IDirect3DRMMeshBuilder3

Retrieves the texture coordinates of a specified vertex in a Direct3DRMMeshBuilder3 object.

Syntax

HRESULT GetTextureCoordinates(
  DWORD index,
  D3DVALUE *lpU,
  D3DVALUE *lpV
  );

Parameters

index
Index of the vertex.
lpU and lpV
Addresses of variables that will be filled with the texture coordinates of the vertex when the method returns.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMMeshBuilder3::SetTextureCoordinates

IDirect3DRMMeshBuilder3::GetVertex

IDirect3DRMMeshBuilder3

Retrieves a vertex vector.

Syntax

HRESULT GetVertex
(DWORD dwIndex,
LPD3DVECTOR lpVector);

Parameters

dwIndex
Index of the vertex to return.
lpVector
Pointer to a D3DVECTOR structure that will be filled in with the x-, y-, and z-coordinates of the vertex.

Return Value

Returns one of the following values:
D3DRMERR_OUTOFRANGE
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMMeshBuilder3::GetVertexColor

IDirect3DRMMeshBuilder3

Retrieves the color of a specified vertex in a Direct3DRMMeshBuilder3 object.

Syntax

D3DCOLOR GetVertexColor(
  DWORD index
  );

Parameters

index
Index of the vertex.

Return Value

Returns the color.

See Also

IDirect3DRMMeshBuilder3::SetVertexColor

IDirect3DRMMeshBuilder3::GetVertexCount

IDirect3DRMMeshBuilder3

Retrieves the number of vertices in a Direct3DRMMeshBuilder3 object.

Syntax

int GetVertexCount( );

Return Value

Returns the number of vertices.

IDirect3DRMMeshBuilder3::GetVertices

IDirect3DRMMeshBuilder3

Retrieves an array of vertices that previously have been defined in the Direct3DRMMeshBuilder3 object.

Syntax

HRESULT GetVertices(
  DWORD dwFirst,
  LPDWORD lpdwCount,
  LPD3DVECTOR lpdvVector);

Parameters

dwFirst
Index of the first vertex to be returned.
lpdwCount
Pointer to a DWORD value containing the number of vectors expected to be returned. If lpdvVector is NULL, the DWORD value receives the number of vertices available from the given offset. Otherwise, the DWORD value receives the number of vectors actually retrieved.
lpdvVector
Pointer to an array of vectors that will be initialized with the vertex data.

Return Value

Returns one of the following values:
D3DRMERR_OUTOFRANGE
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0 and is different from the GetVertices method that the old IDirect3DRMMeshBuilder and IDirect3DRMMeshBuilder2 interfaces provide. For IDirect3DRMMeshBuilder3, the older method has been renamed to GetGeometry, which better describes its function.

See Also

SetVertices and GetGeometry

IDirect3DRMMeshBuilder3::Load

IDirect3DRMMeshBuilder3

Loads a Direct3DRMMeshBuilder3 object.

Syntax

HRESULT Load(
  LPVOID lpvObjSource,
  LPVOID lpvObjID,
  D3DRMLOADOPTIONS d3drmLOFlags,
  D3DRMLOADTEXTURE3CALLBACK d3drmLoadTextureProc,
  LPVOID lpvArg
  );

Parameters

lpvObjSource
Source for the object to be loaded. This source can be a file, resource, memory block, or stream, depending on the source flags specified in the d3drmLOFlags parameter.
lpvObjID
Object name or position to be loaded. The use of this parameter depends on the identifier flags specified in the d3drmLOFlags parameter. If the D3DRMLOAD_BYPOSITION flag is specified, this parameter is a pointer to a DWORD value that gives the object's order in the file. This parameter can be NULL.
d3drmLOFlags
Value of the D3DRMLOADOPTIONS type describing the load options.
d3drmLoadTextureProc
A D3DRMLOADTEXTURE3CALLBACK callback function used to load any textures used by an object that require special formatting. This parameter can be NULL.
lpvArg
Address of application-defined data passed to the D3DRMLOADTEXTURE3CALLBACK callback function.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

By default, this method loads the first mesh from the source specified in the lpvObjSource parameter.

This method respects the right-handed and left-handed geometry options as set by IDirect3DRM3::SetOptions.

You can load more than one object into a MeshBuilder by calling its load method multiple times.


IDirect3DRMMeshBuilder3

IDirect3DRMMeshBuilder3 Methods N to Z

This section contains the reference pages for the methods of the IDirect3DRMMeshBuilder3 interface that begin with the letters N through Z.

IDirect3DRMMeshBuilder3::Optimize

IDirect3DRMMeshBuilder3

Optimizes the MeshBuilder object for the current device. Note that this may be an expensive operation.

Syntax

HRESULT Optimize
(DWORD dwFlags);

Parameters

dwFlags
Must be zero.

Return Value

Returns one of the following values:
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

IDirect3DRMMeshBuilder3::ReserveSpace

IDirect3DRMMeshBuilder3

Reserves space within a Direct3DRMMeshBuilder3 object for the specified number of vertices, normals, and faces. This allows the system to use memory more efficiently.

Syntax

HRESULT ReserveSpace(
  DWORD vertexCount,
  DWORD normalCount,
  DWORD faceCount
  );

Parameters

vertexCount, normalCount, and faceCount
Number of vertices, normals, and faces to allocate space for.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMMeshBuilder3::Save

IDirect3DRMMeshBuilder3

Saves a Direct3DRMMeshBuilder3 object.

Syntax

HRESULT Save(
  const char * lpFilename,
  D3DRMXOFFORMAT d3drmXOFFormat,
  D3DRMSAVEOPTIONS d3drmSOContents
  );

Parameters

lpFilename
Address specifying the name of the created file. This file must have a .x file name extension.
d3drmXOFFormat
The D3DRMXOF_TEXT value from the D3DRMXOFFORMAT enumerated type.
d3drmSOContents
Value of the D3DRMSAVEOPTIONS type describing the save options.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMMeshBuilder3::Scale

IDirect3DRMMeshBuilder3

Scales a Direct3DRMMeshBuilder3 object by the given scaling factors, parallel to the x-, y-, and z-axes in model coordinates.

Syntax

HRESULT Scale(
  D3DVALUE sx,
  D3DVALUE sy,
  D3DVALUE sz
  );

Parameters

sx, sy, and sz
Scaling factors that are applied along the x-, y-, and z-axes.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMMeshBuilder3::SetColor

IDirect3DRMMeshBuilder3

Sets all the faces of a Direct3DRMMeshBuilder3 object to a given color.

Syntax

HRESULT SetColor(
  D3DCOLOR color
  );

Parameters

color
Color of the faces. Be sure to set the alpha component as well as the red, green, and blue color components or your objects might not be visible. The RGBA_MAKE DirectX macro allows you to specify these values.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMMeshBuilder3::SetColorRGB

IDirect3DRMMeshBuilder3

Sets all the faces of a Direct3DRMMeshBuilder3 object to a given color.

Syntax

HRESULT SetColorRGB(
  D3DVALUE red,
  D3DVALUE green,
  D3DVALUE blue
  );

Parameters

red, green, and blue
Red, green, and blue components of the color.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMMeshBuilder3::SetColorSource

IDirect3DRMMeshBuilder3

Sets the color source of a Direct3DRMMeshBuilder3 object.

Syntax

HRESULT SetColorSource(
  D3DRMCOLORSOURCE source
  );

Parameters

source
Member of the D3DRMCOLORSOURCE enumerated type that specifies the new color source to use.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMMeshBuilder3::GetColorSource

IDirect3DRMMeshBuilder3::SetMaterial

IDirect3DRMMeshBuilder3

Sets the material of all the faces of a Direct3DRMMeshBuilder3 object.

Syntax

HRESULT SetMaterial(
  LPDIRECT3DRMMATERIAL2 lpIDirect3DRMmaterial
  );

Parameters

lpIDirect3DRMmaterial
Address of IDirect3DRMMaterial2 interface for the Direct3DRMMeshBuilder3 object.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMMeshBuilder3::SetNormal

IDirect3DRMMeshBuilder3

Sets the normal vector of a specified vertex in a Direct3DRMMeshBuilder3 object.

Syntax

HRESULT SetNormal(
  DWORD index,
  D3DVALUE x,
  D3DVALUE y,
  D3DVALUE z
  );

Parameters

index
Index of the normal to be set.
x, y, and z
The x-, y-, and z-components of the vector to assign to the specified normal.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMMeshBuilder3::SetNormals

IDirect3DRMMeshBuilder3

Sets the normals that previously have been defined in the Direct3DRMMeshBuilder3 object.

Syntax

HRESULT SetNormals(
  DWORD dwFirst,
  DWORD dwCount,
  LPD3DVECTOR lpdvVector);

Parameters

dwFirst
Index of the first normal to be modified.
dwCount
Number of normals to be modified.
lpdvVector
Array of vectors describing the new normal data.

Return Value

Returns one of the following values:
D3DRMERR_OUTOFRANGE
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

See Also

GetNormals

IDirect3DRMMeshBuilder3::SetPerspective

IDirect3DRMMeshBuilder3

Enables or disables perspective-correct texture-mapping for a Direct3DRMMeshBuilder3 object.

Syntax

HRESULT SetPerspective(
  BOOL perspective
  );

Parameters

perspective
Specify TRUE if the mesh should be texture-mapped with perspective correction, or FALSE otherwise.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMMeshBuilder3::SetQuality

IDirect3DRMMeshBuilder3

Sets the rendering quality of a Direct3DRMMeshBuilder3 object.

Syntax

HRESULT SetQuality(
  D3DRMRENDERQUALITY quality
  );

Parameters

quality
Member of the D3DRMRENDERQUALITY enumerated type that specifies the new rendering quality to use.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

An object's quality has three components: shade mode (flat or Gouraud; Phong shading is not yet implemented and will default to Gouraud shading), lighting type (on or off), and fill mode (point, wireframe, or solid).

You can set the quality of a device with IDirect3DRMDevice3::SetQuality. By default it is D3DRMRENDER_FLAT (flat shading, lights on, and solid fill).

You can set the quality of a Direct3DRMMeshBuilder3 object with the SetQuality method. By default, a Direct3DRMMeshBuilder3 object's quality is D3DRMRENDER_GOURAUD (Gouraud shading, lights on, and solid fill).

Tip: Gouraud shading performs better than Phong shading on progressive mesh objects that change their level of detail often or quickly.

Direct3D Retained Mode renders an object at the lowest quality setting based on the device and object's current setting for each individual component. For example, if the object's current quality setting is D3DRMRENDER_GOURAUD, and the device is D3DRMRENDER_FLAT then the object will be rendered with flat shading, solid fill and lights on.

If the object's current quality setting is D3DRMSHADE_GOURAUD|D3DRMLIGHT_OFF|D3DRMFILL_WIREFRAME and the device's quality setting is D3DRMSHADE_FLAT|D3DRMLIGHT_ON|D3DRMFILL_POINT, then the object will be rendered with flat shading, lights off, and point fill mode.

These rules apply to Direct3DRMMeshBuilder3 objects and Direct3DRMProgressiveMesh objects. However, Direct3DRMMesh objects do not follow these rules. Mesh objects ignore the device's quality settings and use the group quality setting (which defaults to D3DRMRENDER_GOURAUD).

See Also

IDirect3DRMMeshBuilder3::GetQuality

IDirect3DRMMeshBuilder3::SetTexture

IDirect3DRMMeshBuilder3

Sets the texture of all the faces of a Direct3DRMMeshBuilder3 object.

Syntax

HRESULT SetTexture(
  LPDIRECT3DRMTEXTURE3 lpD3DRMTexture
  );

Parameters

lpD3DRMTexture
Address of the required Direct3DRMTexture object.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMMeshBuilder3::SetTextureCoordinates

IDirect3DRMMeshBuilder3

Sets the texture coordinates of a specified vertex in a Direct3DRMMeshBuilder3 object.

Syntax

HRESULT SetTextureCoordinates(
  DWORD index,
  D3DVALUE u,
  D3DVALUE v
  );

Parameters

index
Index of the vertex to be set.
u and v
Texture coordinates to assign to the specified mesh vertex.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMMeshBuilder3::GetTextureCoordinates

IDirect3DRMMeshBuilder3::SetTextureTopology

IDirect3DRMMeshBuilder3

Sets the texture topology of a Direct3DRMMeshBuilder3 object.

Syntax

HRESULT SetTextureTopology(
  BOOL cylU,
  BOOL cylV
  );

Parameters

cylU and cylV
Specify TRUE for either or both of these parameters if you want the texture to have a cylindrical topology in the u- and v-dimensions, respectively; otherwise, specify FALSE.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

Remarks

The texture topology flags, cylU and cylV, control the settings of the Direct3D Immediate Mode render states D3DRENDERSTATE_WRAPU and D3DRENDERSTATE_WRAPV. When a wrap flag is TRUE, the rasterizer will cross from one edge of the texture to the opposite edge (toroidal mapping) if it is the shorter path between two texture coordinates. Consider a triangle that has v coordinates ranging from 0.1 and 0.9 along one edge. If WRAPV is FALSE, nearly the full length of the texture will be rendered along the triangle. If WRAPV is TRUE, a sliver from the top of the texture and one from the bottom will be rendered. Additionally, when a wrap flag is TRUE, only the fractional part of a texture coordinate is considered for values greater than 1.0, which means textures will not be tiled across a face when wrap is TRUE.

Controlling the wrapping behavior is necessary for proper interpretation of texture coordinates. If you have a single texture wrapped across many faces, set the cylU and cylV parameters to TRUE. If a model has one texture per face or you want multiple copies of the texture to be tiled across a single face by using texture coordinates greater than 1, set cylU and cylV to FALSE.

Several interfaces expose a SetTextureTopology method. IDirect3DRMMeshBuilder3::SetTextureTopology updates the topology on all component faces, overriding any settings made by IDirect3DRMFace2::SetTextureTopology. By default, IDirect3DRMFrame3::SetTexture reads from the mesh because the default material mode is D3DRMMATERIAL_FROMMESH. If the material mode is not D3DRMMATERIAL_FROMMESH, IDirect3DRMFrame3::SetTexture overrides settings made by IDirect3DRMMeshBuilder3::SetTextureTopology.

IDirect3DRMMeshBuilder3::SetVertex

IDirect3DRMMeshBuilder3

Sets the position of a specified vertex in a Direct3DRMMeshBuilder3 object.

Syntax

HRESULT SetVertex(
  DWORD index,
  D3DVALUE x,
  D3DVALUE y,
  D3DVALUE z
  );

Parameters

index
Index of the vertex to be set.
x, y, and z
The x-, y-, and z-components of the position to assign to the specified vertex.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMMeshBuilder3::SetVertexColor

IDirect3DRMMeshBuilder3

Sets the color of a specified vertex in a Direct3DRMMeshBuilder3 object.

Syntax

HRESULT SetVertexColor(
  DWORD index,
  D3DCOLOR color
  );

Parameters

index
Index of the vertex to be set.
color
Color to assign to the specified vertex.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

See Also

IDirect3DRMMeshBuilder3::GetVertexColor

IDirect3DRMMeshBuilder3::SetVertexColorRGB

IDirect3DRMMeshBuilder3

Sets the color of a specified vertex in a Direct3DRMMeshBuilder3 object.

Syntax

HRESULT SetVertexColorRGB(
  DWORD index,
  D3DVALUE red,
  D3DVALUE green,
  D3DVALUE blue
  );

Parameters

index
Index of the vertex to be set.
red, green, and blue
Red, green, and blue components of the color to assign to the specified vertex.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.

IDirect3DRMMeshBuilder3::SetVertices

IDirect3DRMMeshBuilder3

Sets the vertices that previously have been defined in the Direct3DRMMeshBuilder3 object.

Syntax

HRESULT SetVertices(
  DWORD dwFirst,
  DWORD dwCount,
  LPD3DVECTOR lpdvVector);

Parameters

dwFirst
Index of the first vertex to be modified.
dwCount
Number of vertices to modify.
lpdvVector
Array of vectors describing the new vertex data.

Return Value

Returns one of the following values:
D3DRMERR_OUTOFRANGE
DDERR_INVALIDOBJECT
DDERR_INVALIDPARAMS
DD_OK

Remarks

This method was introduced with DirectX version 6.0.

See Also

GetVertices

IDirect3DRMMeshBuilder3::Translate

IDirect3DRMMeshBuilder3

Adds the specified offsets to the vertex positions of a Direct3DRMMeshBuilder3 object.

Syntax

HRESULT Translate(
  D3DVALUE tx,
  D3DVALUE ty,
  D3DVALUE tz
  );

Parameters

tx, ty, and tz
Offsets that are added to the x-, y-, and z-coordinates, respectively, of each vertex position.

Return Value

Returns D3DRM_OK if successful, or an error otherwise. For a list of possible errors, see Direct3D Retained Mode Return Values.


Direct3DRMFrame3 Methods A to M

This section contains the reference material for the methods of the Direct3DRMFrame3 interface that begin with the letters A through M.

Direct3DRMFrame3.AddChild

Direct3DRMFrame3

Adds a child frame to a frame hierarchy.

Syntax

object.AddChild(child As Direct3DRMFrame3)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
child
Direct3DRMFrame3 object that will be added as a child.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

If the frame being added as a child already has a parent, this method removes it from its previous parent before adding it to the new parent.

To preserve an object's transformation, use the Direct3DRMFrame3.GetTransform method to retrieve the object's transformation before using the AddChild method. Then reapply the transformation after the frame is added.

Direct3DRMFrame3.AddLight

Direct3DRMFrame3

Adds a light to a frame.

Syntax

object.AddLight(val As Direct3DRMLight)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
val
Variable that represents the Direct3DRMLight object to be added to the frame.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFrame3.AddMoveCallback

Direct3DRMFrame3

Adds a callback for special movement processing. The callback is called when the frame is moved or updated.

Syntax

object.AddMoveCallback(frameMoveImplementation As Direct3DRMFrameCallback3
  userArgument As object,
  flags As CONST_D3DRMCALLBACKORDERFLAGS)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
frameMoveImplementation
Direct3DRMFrameCallback3 interface implemented by the application.
userArgument
Application-defined data passed to the callback.
flags
One or more values from the CONST_D3DRMCALLBACKORDERFLAGS enumerated type.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method replaces Direct3DRMFrame2.AddMoveCallback2. Multiple callbacks on an individual frame are used in the order that the callbacks were created.

See Also

Direct3DRMFrame3.DeleteMoveCallback

Direct3DRMFrame3.AddRotation

Direct3DRMFrame3

Adds a rotation about the given coordinates by the specified number of radians.

Syntax

object.AddRotation(combineType As CONST_D3DRMCOMBINETYPE,
  x As Single,
  y As Single,
  z As Single,
  theta As Single)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
combineType
Member of the CONST_D3DRMCOMBINETYPE enumerated type that specifies how to combine the new rotation with any current frame transformation.
x, y, and z
Axis about which to rotate.
theta
Angle of rotation, in radians.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

The specified rotation changes the matrix only for the frame identified by this Direct3DRMFrame3 interface. This method changes the objects in the frame only once, unlike Direct3DRMFrame3.SetRotation, which changes the matrix with every render tick.

Direct3DRMFrame3.AddScale

Direct3DRMFrame3

Scales a frame's local transformation by the given coordinate scale factors.

Syntax

object.AddScale(combineType As CONST_D3DRMCOMBINETYPE,
  sx As Single,
  sy As Single,
  sz As Single)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
combineType
Member of the CONST_D3DRMCOMBINETYPE enumerated type that specifies how to combine the new scale with any current frame transformation.
sx, sy, and sz
Scale factors in the in the x-, y-, and z-axis directions.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

The specified transformation changes the matrix only for the frame identified by the Direct3DRMFrame3 interface.

Direct3DRMFrame3.AddTransform

Direct3DRMFrame3

Transforms the local coordinates of the frame by the specified affine transformation.

Syntax

object.AddTransform(t As CONST_D3DRMCOMBINETYPE,
  val() As Single)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
t
Member of the CONST_D3DRMCOMBINETYPE enumerated type that specifies how to combine the new transformation with any current transformation.
val
Row-ordered array representing a 4×4 matrix.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Although a 4×4 matrix is given, the last column must be the transpose of [0 0 0 1] for the transformation to be affine. The specified transformation changes the matrix only for the frame identified by this Direct3DRMFrame3 interface.

Direct3DRMFrame3.AddTranslation

Direct3DRMFrame3

Adds a translation by the given position changes to a frame's local coordinate system.

Syntax

object.AddTranslation(t As CONST_D3DRMCOMBINETYPE,
  x As Single,
  y As Single,
  z As Single)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
t
Member of the CONST_D3DRMCOMBINETYPE enumerated type that specifies how to combine the new translation with any current translation.
x, y, and z
Definitions of the position changes in the x-, y-, and z-axis directions.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

The specified translation changes the matrix only for the frame identified by this Direct3DRMFrame3 interface.

Direct3DRMFrame3.AddVisual

Direct3DRMFrame3

Adds a visual object to a frame.

Syntax

object.AddVisual(v As Direct3DRMVisual)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
v
Variable that represents the Direct3DRMVisual object to be added to the frame.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Visual objects include meshes, progressive meshes, textures, shadows, user visuals, and 3-D Microsoft® DirectX® Transform objects. When a visual object is added to a frame, it becomes visible if the frame is in view. The frame references the visual object.

Direct3DRMFrame3.DeleteChild

Direct3DRMFrame3

Removes a frame from the hierarchy. If the frame is not referenced, it is destroyed along with any child frames, lights, and meshes.

Syntax

object.DeleteChild(c As Direct3DRMFrame3)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
c
Direct3DRMFrame3 object to be removed from the hierarchy.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFrame3.DeleteLight

Direct3DRMFrame3

Removes a light from a frame, destroying the light if it is no longer referenced. When a light is removed from a frame, the light no longer affects meshes in the scene its frame was in.

Syntax

object.DeleteLight(l As Direct3DRMLight)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
l
Variable that represents the Direct3DRMLight object to be removed.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFrame3.DeleteMoveCallback

Direct3DRMFrame3

Removes a frame-move callback previously added with AddMoveCallback.

Syntax

object.DeleteMoveCallback(frameMoveImplementation As Direct3DRMFrameCallback3,
  userArgument As object)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
frameMoveImplementation
Direct3DRMFrameCallback3 interface implemented by the application.
userArgument
Application-defined data that was passed to the callback.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMFrame3.Move

Direct3DRMFrame3.DeleteVisual

Direct3DRMFrame3

Removes a visual object from a frame, destroying it if it is no longer referenced.

Syntax

object.DeleteVisual(v As Direct3DRMVisual)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
v
Variable that represents the Direct3DRMVisual object to be removed.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Visual objects include meshes, progressive meshes, textures, shadows, user visuals, and 3-D DirectX Transform objects. When a visual object is added to a frame, it becomes visible if the frame is in view. The frame references the visual object.

Direct3DRMFrame3.GetAxes

Direct3DRMFrame3

Retrieves the vectors that are aligned with the direction (dx, dy, dz) and up (ux, uy, uz) vectors supplied to the Direct3DRMFrame3.SetOrientation method.

Syntax

object.GetAxes(dir As D3DVECTOR,
  up As D3DVECTOR)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
dir
The z-axis for the frame. Default is (0, 0, 1).
up
The y-axis for the frame. Default is (0, 1, 0).

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method, along with Direct3DRMFrame3.SetAxes, helps support both left-handed and right-handed coordinate systems. SetAxes enables you to specify that the negative z-axis represents the front of the object.

See Also

Direct3DRMFrame3.GetInheritAxes, Direct3DRMFrame3.SetInheritAxes, D3DVECTOR

Direct3DRMFrame3.GetBox

Direct3DRMFrame3

Retrieves the bounding box containing a Direct3DRMFrame3 object. The bounding box gives the minimum and maximum model coordinates in each dimension.

Syntax

object.GetBox(box As D3DRMBOX)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
box
D3DRMBOX type that will be filled with the bounding box coordinates.

Error Values

Returns D3DRMERR_BOXNOTSET unless a valid bounding box has already been set on the frame. For a list of other possible return codes, see Direct3D Retained Mode Error Values.

Remarks

This method supports a bounding box on a frame for hierarchical culling. A valid bounding box must be set on the frame with the Direct3DRMFrame3.SetBox method. For a bounding box to be enabled, the Direct3DRMFrame3.SetBoxEnable method must be used to set the enable flag to D_TRUE. By default, the box-enable flag is D_FALSE. There is no default bounding box.

See Also

Direct3DRMFrame3.GetBoxEnable

Direct3DRMFrame3.GetBoxEnable

Direct3DRMFrame3

Retrieves the flag that determines whether a bounding box is enabled for this Direct3DRMFrame3 object.

Syntax

object.GetBoxEnable( ) As CONST_DBOOLFLAGS

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.

Return Value

Returns –1 if a bounding box is enabled, or zero if it is not enabled.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

For a bounding box to be enabled, the Direct3DRMFrame3.SetBoxEnable method must be used to set the enable flag to D_TRUE. By default, the box-enable flag is D_FALSE.

See Also

Direct3DRMFrame3.GetBox, Direct3DRMFrame3.SetBox

Direct3DRMFrame3.GetChildren

Direct3DRMFrame3

Retrieves a list of child frames in the form of a Direct3DRMFrameArray object.

Syntax

object.GetChildren( ) As Direct3DRMFrameArray

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.

Return Value

Returns a Direct3DRMFrameArray object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFrame3.GetColor

Direct3DRMFrame3

Retrieves the color of the frame.

Syntax

object.GetColor( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.

Return Value

Returns the color of the Direct3DRMFrame3 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMFrame3.SetColor

Direct3DRMFrame3.GetHierarchyBox

Direct3DRMFrame3

Calculates a bounding box to contain all the geometry in the hierarchy rooted in this Direct3DRMFrame3 object.

Syntax

object.GetHierarchyBox(box As D3DRMBOX)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
box
D3DRMBOX type that will be filled with the bounding box coordinates.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMFrame3.GetBox, Direct3DRMFrame3.SetBox, Direct3DRMFrame3.SetBoxEnable, Direct3DRMFrame3.GetBoxEnable

Direct3DRMFrame3.GetInheritAxes

Direct3DRMFrame3

Retrieves the flag that indicates whether the axes for the frame are inherited from the parent frame.

Syntax

object.GetInheritAxes( ) As CONST_DBOOLFLAGS

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.

Return Value

Returns –1 if the frame inherits axes (the default) or zero if the frame does not inherit axes.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

By default, the axes are inherited from the parent. If a frame is set to inherit from a parent and there is no parent, the frame acts as if it inherits from a parent with the default axes: direction = (0, 0, 1) and up = (0, 1, 0).

This method and the Direct3DRMFrame3.SetInheritAxes method enable a single policy for axes to be set at the root of the hierarchy.

See Also

Direct3DRMFrame3.GetAxes, Direct3DRMFrame3.SetAxes

Direct3DRMFrame3.GetLights

Direct3DRMFrame3

Retrieves a list of lights in the frame in the form of a Direct3DRMLightArray object.

Syntax

object.GetLights( ) As Direct3DRMLightArray

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.

Return Value

Returns a Direct3DRMLightArray object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFrame3.GetMaterial

Direct3DRMFrame3

Retrieves the material of the Direct3DRMFrame3 object.

Syntax

object.GetMaterial(ret As Direct3DRMMaterial2)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
ret
Direct3DRMMaterial2 object that is applied to the frame.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMFrame3.SetMaterial

Direct3DRMFrame3.GetMaterialMode

Direct3DRMFrame3

Retrieves the material mode of the frame.

Syntax

object.GetMaterialMode( ) As CONST_D3DRMMATERIALMODE

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.

Return Value

Returns a member of the CONST_D3DRMMATERIALMODE enumerated type that specifies the current material mode.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMFrame3.SetMaterialMode

Direct3DRMFrame3.GetMaterialOverride

Direct3DRMFrame3

Retrieves the current per-attribute override settings for material attributes.

Syntax

object.GetMaterialOverride(override As D3DRMMATERIALOVERRIDE)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
override
D3DRMMATERIALOVERRIDE type that holds the override information.

Error Values

If the method fails, it can return DDERR_INVALIDOBJECT or DDERR_INVALIDPARAMS.

For a complete list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMFrame3.SetMaterialOverride

Direct3DRMFrame3.GetMaterialOverrideTexture

Direct3DRMFrame3

Retrieves the override texture.

Syntax

object.GetMaterialOverrideTexture( ) As Direct3DRMTexture3

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.

Return Value

Returns a Direct3DRMTexture3 object if there is an override texture; otherwise, returns NOTHING.

Error Values

If the method fails, it can return DDERR_INVALIDOBJECT or DDERR_INVALIDPARAMS.

For a complete list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMFrame3.SetMaterialOverrideTexture

Direct3DRMFrame3.GetOrientation

Direct3DRMFrame3

Retrieves the orientation of a frame relative to the given reference frame.

Syntax

object.GetOrientation(ref As Direct3DRMFrame3,
  dir As D3DVECTOR,
  up As D3DVECTOR)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
ref
Variable that represents the Direct3DRMFrame3 object to be used as the reference.
dir and up
D3DVECTOR types that will hold the normalized directions of the frame's z-axis and y-axis, respectively.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMFrame3.SetOrientation

Direct3DRMFrame3.GetParent

Direct3DRMFrame3

Retrieves the parent frame of the current frame.

Syntax

object.GetParent( ) As Direct3DRMFrame3

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.

Return Value

Returns a Direct3DRMFrame3 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFrame3.GetPosition

Direct3DRMFrame3

Retrieves the position of a frame relative to the given reference frame; that is, it retrieves the distance of the frame from the reference. The distance is stored in the position parameter as a vector rather than as a linear measure.

Syntax

object.GetPosition(ref As Direct3DRMFrame3,
  position As D3DVECTOR)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
ref
Variable that holds the Direct3DRMFrame object to be used as the reference.
position
D3DVECTOR type that will hold the frame's position.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMFrame3.SetPosition

Direct3DRMFrame3.GetRotation

Direct3DRMFrame3

Retrieves the rotation of the frame relative to the given reference frame.

Syntax

object.GetRotation(ref As Direct3DRMFrame3,
  axis As D3DVECTOR,
  theta As Single)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
ref
Variable that represents the Direct3DRMFrame3 object to be used as the reference.
axis
D3DVECTOR type that will hold the frame's axis of rotation.
theta
Variable that will be the frame's rotation, in radians.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMFrame3.SetRotation

Direct3DRMFrame3.GetScene

Direct3DRMFrame3

Retrieves the root frame of the hierarchy containing the given frame.

Syntax

object.GetScene( ) As Direct3DRMFrame3

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.

Return Value

Returns a Direct3DRMFrame3 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFrame3.GetSceneBackground

Direct3DRMFrame3

Retrieves the background color of a scene.

Syntax

object.GetSceneBackground( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.

Return Value

Returns the color.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFrame3.GetSceneBackgroundDepth

Direct3DRMFrame3

Retrieves the current background-depth buffer for the scene.

Syntax

object.GetSceneBackgroundDepth( ) As DirectDrawSurface4

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.

Return Value

Returns a DirectDrawSurface4 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMFrame3.SetSceneBackgroundDepth

Direct3DRMFrame3.GetSceneFogColor

Direct3DRMFrame3

Retrieves the fog color of a scene.

Syntax

object.GetSceneFogColor( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.

Return Value

Returns the fog color.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFrame3.GetSceneFogEnable

Direct3DRMFrame3

Retrieves whether fog is enabled for this scene.

Syntax

object.GetSceneFogEnable( ) As CONST_DBOOLFLAGS

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.

Return Value

Returns –1 if fog is enabled, or zero otherwise.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFrame3.GetSceneFogMethod

Direct3DRMFrame3

Retrieves the current fogging method.

Syntax

object.GetSceneFogMethod( ) As CONST_D3DRMFOGMETHOD

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.

Return Value

Returns one of the values from the CONST_D3DRMFOGMETHOD enumerated type.

Error Values

If an error occurs, this method returns one of the following values.

  • D3DRMERR_BADVALUE
  • DDERR_INVALIDOBJECT
  • DDERR_INVALIDPARAMS

Direct3DRMFrame3.GetSceneFogMode

Direct3DRMFrame3

Retrieves the current fog mode for this scene.

Syntax

object.GetSceneFogMode( ) As CONST_D3DRMFOGMODE

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.

Return Value

Returns a member of the CONST_D3DRMFOGMODE enumerated type that specifies the current fog mode.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFrame3.GetSceneFogParams

Direct3DRMFrame3

Retrieves the current fog parameters for this scene.

Syntax

object.GetSceneFogParams(start As Single,
  end As Single,
  density As Single)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
start, end, and density
Variables that will be the fog start, end, and density values.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFrame3.GetSortMode

Direct3DRMFrame3

Retrieves the sorting mode used to process child frames.

Syntax

object.GetSortMode( ) As CONST_D3DRMSORTMODE

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.

Return Value

Returns the member of the CONST_D3DRMSORTMODE enumerated type that specifies the sorting mode.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMFrame3.SetSortMode

Direct3DRMFrame3.GetTexture

Direct3DRMFrame3

Retrieves the texture of the given frame.

Syntax

object.GetTexture( ) As Direct3DRMTexture3

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.

Return Value

Returns a Direct3DRMTexture3 object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMFrame3.SetTexture

Direct3DRMFrame3.GetTransform

Direct3DRMFrame3

Retrieves the current-world transformation of the frame as a 4 × 4 affine matrix.

Syntax

object.GetTransform(referenceFrame As Direct3DRMFrame3
  val() As Single)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
referenceFrame
Direct3DRMFrame3 object used as the reference frame.
val
Row-ordered array representing a 4 × 4 matrix.

Error Values

If an error occurs, this method can return DDERR_INVALIDOBJECT or DDERR_INVALIDPARAMS.

For a complete list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFrame3.GetTraversalOptions

Direct3DRMFrame3

Retrieves the traversal status of the current frame.

Syntax

object.GetTraversalOptions( ) As CONST_D3DRMTRAVERALFLAGS

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.

Return Value

Returns one of the values from the CONST_D3DRMTRAVERALFLAGS enumerated type.

Error Values

If an error occurs, this method returns one of the following values.

  • D3DRMERR_BADVALUE
  • DDERR_INVALIDOBJECT
  • DDERR_INVALIDPARAMS

Direct3DRMFrame3.GetVelocity

Direct3DRMFrame3

Retrieves the velocity of the frame relative to the given reference frame. Velocity is specified as units per tick. See IDirect3DRM3.Tick for more information.

Syntax

object.GetVelocity(ref As Direct3DRMFrame3,
  vel As D3DVECTOR,
  includeRotationalVelocity As CONST_DBOOLFLAGS)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
ref
Variable that represents the Direct3DRMFrame3 object to be used as the reference.
vel
D3DVECTOR type that will be filled with the frame's velocity.
includeRotationalVelocity
D_FALSE or D_TRUE; if set to D_TRUE the object's rotational velocity is included in the calculation.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMFrame3.SetVelocity

Direct3DRMFrame3.GetVisual

Direct3DRMFrame3

Retrieves a single visual in the frame.

Syntax

object.GetVisual(index As Long) As Direct3DRMVisual

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
index
Variable indicating the index of the single Direct3DRMVisual object to be retrieved. Possible values range from 0 to N1 for an array of size N.

Return Value

Returns a Direct3DRMVisual object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFrame3.GetVisualCount

Direct3DRMFrame3

Retrieves the number of visuals in the frame.

Syntax

object.GetVisualCount( ) As Long

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.

Return Value

Returns the number of visuals, Direct3DRMVisual objects, contained by the frame.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFrame3.GetVisuals

Direct3DRMFrame3

Retrieves a list of visuals, Direct3DRMVisual objects, in the frame.

Syntax

object.GetVisuals( ) As Direct3DRMVisualArray

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.

Return Value

Returns a Direct3DRMVisualArray object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFrame3.GetZbufferMode

Direct3DRMFrame3

Retrieves the z-buffer mode; that is, whether z-buffering is enabled or disabled.

Syntax

object.GetZbufferMode( ) As CONST_D3DRMZBUFFERMODE

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.

Return Value

Returns one of the members of the CONST_D3DRMZBUFFERMODE enumerated type.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMFrame3.SetZbufferMode

Direct3DRMFrame3.InverseTransform

Direct3DRMFrame3

Transforms a given vector in world coordinates to model coordinates, and returns the result.

Syntax

object.InverseTransform(d As D3DVECTOR,
  s As D3DVECTOR)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
d
D3DVECTOR type that will be filled with the result of the transformation.
s
D3DVECTOR type that is the source of the transformation.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMFrame3.Transform

Direct3DRMFrame3.InverseTransformVectors

Direct3DRMFrame3

Transforms an array of vectors from world coordinates to model coordinates.

Syntax

object.GetVelocity(reference As Direct3DRMFrame3,
  num As Long,
  DstVectors() As D3DVECTOR,
  SrcVectors() As D3DVECTOR)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
reference
Frame that is to be used as the root of the scene for the purposes of this call. If this argument is NOTHING, the current root frame (as would be returned by the Direct3DRMFrame3.GetScene method) will be used.
num
Number of vectors whose coordinates are to be transformed.
DstVectors()
Destination of the transformation.
SrcVectors()
Array of vectors to transform.

Error Values

If an error occurs, this method returns DDERR_INVALIDOBJECT or DDERR_INVALIDPARAMS.

See Also

D3DVECTOR

Direct3DRMFrame3.LoadFromFile

Direct3DRMFrame3

Loads a Direct3DRMFrame3 object.

Syntax

object.LoadFromFile(filename As String,
  id As String,
  options As CONST_D3DRMLOADFLAGS,
  loadTextureImplementation As Direct3DRMLoadTextureCallback3,
  userArgument As Object)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
filename
Source for the object to be loaded. This source can be a file, resource, memory block, or stream, depending on the source flags specified in the flags parameter.
id
Object name or position to be loaded. If id is "", you must set the options parameter to D3DRMLOAD_FIRST. Note that Microsoft Visual Basic® will accept an Integer in the id parameter, indicating the position of the item to be loaded, even though a String data type is specified. For example, placing 1 in the id parameter will load the object in the first position.
options
One or more values from the CONST_D3DRMLOADFLAGS enumerated type describing the load options.
loadTextureImplementation
Direct3DRMLoadTextureCallback3 interface used to load any textures used by the object that require special formatting. Textures must have a width and length divisible by two. This parameter can be NOTHING.
userArgument
Application-defined data passed to the callback.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

By default, this method loads the first frame hierarchy in the file specified by the filename parameter. The frame that uses this method is used as the parent of the new frame hierarchy. By default, perspective correction is on.

The instance flags do not change the interpretation of any of the members. By using the D3DRMLOAD_INSTANCEBYREFERENCE flag, an application can load the same file twice without creating any new objects. If an object does not have a name, setting the D3DRMLOAD_INSTANCEBYREFERENCE flag has the same effect as setting the D3DRMLOAD_INSTANCEBYCOPYING flag—the loader creates each unnamed object as a new one, even if some of the objects are identical.

Direct3DRMFrame3.LookAt

Direct3DRMFrame3

Faces the frame toward the target frame, relative to the given reference frame, locking the rotation by the given constraints.

Syntax

object.LookAt(tgt As Direct3DRMFrame3,
  reference As Direct3DRMFrame3,
  contraint As CONST_D3DRMFRAMECONSTRAINT)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
tgt and reference
Variables that represent the Direct3DRMFrame3 objects to be used as the target and reference, respectively.
contraint
Member of the CONST_D3DRMFRAMECONSTRAINT enumerated type that specifies the axis of rotation to constrain.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFrame3.Move

Direct3DRMFrame3

Applies the linear and rotational velocities for all frames in the given hierarchy.

Syntax

object.Move(delta As Single)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
delta
Amount to change the linear and rotational velocity. The change in each component is equal to the velocity of that component multiplied by delta. Although either or both of these velocities can be set relative to any frame, the system automatically converts them to velocities relative to the parent frame for the purpose of applying time changes.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.


Direct3DRMFrame3 Methods N to Z

This section contains the reference material for the methods of the Direct3DRMFrame3 interface that begin with the letters N through Z.

Direct3DRMFrame3.RayPick

Direct3DRMFrame3

Searches the hierarchy starting at this Direct3DRMFrame3 object and calculates the intersections between any visuals and the ray specified by the Direct3DRMFrame3 interface referenced by the refer parameter.

Syntax

object.RayPick(refer As Direct3DRMFrame3,
  ray As D3DRMRAY,
  flags As CONST_D3DRMRAYPICKFLAGS) As Direct3DRMPick2Array

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
refer
Direct3DRMFrame3 object that contains the ray.
ray
D3DRMRAY type that contains two D3DVECTOR types. The first D3DVECTOR type is the vector direction of the ray. The second D3DVECTOR type is the position of the ray's origin.
flags
One or more values from the CONST_D3DRMRAYPICKFLAGS enumerated type, indicating type of intersection calculated or interpolation options.

Return Value

Returns a Direct3DRMPick2Array object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

There are two kinds of flags: optimization flags and interpolation flags. Optimization flags enable you to limit the search and therefore make it faster. Interpolation flags specify what to interpolate if a primitive is hit. The three interpolation choices are color, normal, and texture coordinates.

The ray is specified in the reference frame coordinate space (pointed to by refer). If the reference frame is NOTHING, the ray is specified in world coordinates.

Direct3DRMFrame3.Save

Direct3DRMFrame3

Saves a Direct3DRMFrame3 object to the specified file.

Syntax

object.Save(name As String,
  format As CONST_D3DRMXOFFORMAT,
  flags As CONST_D3DRMSAVEFLAGS)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
name
Name of the created file. This file must have the .x file name extension.
format
D3DRMXOF_TEXT value from the CONST_D3DRMXOFFORMAT enumerated type, indicating that the file is in text format.
flags
One or more values from the CONST_D3DRMSAVEFLAGS enumerated type describing the save options.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFrame3.SetAxes

Direct3DRMFrame3

Sets the vectors that define a coordinate space by which the Direct3DRMFrame3.SetOrientation vectors are transformed.

Syntax

object.SetAxes(dx As Single,
  dy As Single,
  dz As Single,
  ux As Single,
  uy As Single,
  uz As Single)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
dx, dy, dz
The z-axis for the frame. Default is (0, 0, 1).
ux, uy, uz
The y-axis for the frame. Default is (0, 1, 0).

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method helps support both left-handed and right-handed coordinate systems. This method also enables you to specify that the negative z-axis represents the front of the object.

The Direct3DRMFrame3.SetOrientation direction (dx, dy, dz) and up (ux, uy, uz) vectors are transformed according to the value of the SetAxes vectors.

The axes are inherited by child frames as specified in Direct3DRMFrame3.SetInheritAxes.

See Also

Direct3DRMFrame3.GetAxes, Direct3DRMFrame3.GetInheritAxes

Direct3DRMFrame3.SetBox

Direct3DRMFrame3

Sets the box to be used in bounding-box testing. For the bounding box to be valid, its minimum x-coordinate must be less than or equal to its maximum x-coordinate, its minimum y-coordinate must be less than or equal to its maximum y-coordinate, and its minimum z-coordinate must be less than or equal to its maximum z-coordinate.

Syntax

object.SetBox(box As D3DRMBOX)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
box
D3DRMBOX type that contains the bounding-box coordinates.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method supports a bounding box on a frame for hierarchical culling. For a bounding box to be enabled, the Direct3DRMFrame3.SetBoxEnable method must be used to set the enable flag to D_TRUE. By default, the box-enable flag is D_FALSE.

See Also

Direct3DRMFrame3.GetBox, Direct3DRMFrame3.GetBoxEnable

Direct3DRMFrame3.SetBoxEnable

Direct3DRMFrame3

Enables or disables bounding-box testing for this Direct3DRMFrame3 object. Bounding-box testing cannot be enabled unless a valid bounding box has already been set on the frame.

Syntax

object.SetBoxEnable(boxEnable As CONST_DBOOLFLAGS)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
boxEnable
Flag specifying whether bounding boxes are enabled. Specify D_TRUE to enable a bounding box or D_FALSE to disable a bounding box. Default is D_FALSE.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

Bounding-box testing is performed as follows: at render time, the bounding box is transformed into model space and checked for intersection with the viewing frustum. If the entire box is outside the viewing frustum, none of the visuals in the frame, or in any child frame, are rendered. Otherwise, rendering continues as usual.

Enabling bounding-box testing with a box of {0, 0, 0, 0} completely prevents a frame from being rendered.

See Also

Direct3DRMFrame3.GetBoxEnable, Direct3DRMFrame3.GetBox, Direct3DRMFrame3.SetBox

Direct3DRMFrame3.SetColor

Direct3DRMFrame3

Sets the color of the frame. This color is used for meshes in the frame when the CONST_D3DRMMATERIALMODE enumerated type is set to D3DRMMATERIAL_FROMFRAME.

Syntax

object.SetColor(c As Long)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
c
New color for the frame. Be sure to set the alpha component as well as the red, green, and blue color components or your objects might not be visible. To specify an object's color, including the alpha component, call the CreateColorRGBA method from the DirectX7 interface on the object.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMFrame3.GetColor, Direct3DRMFrame3.SetMaterialMode

Direct3DRMFrame3.SetColorRGB

Direct3DRMFrame3

Sets the color of the frame. This color is used for meshes in the frame when the CONST_D3DRMMATERIALMODE enumerated type is set to D3DRMMATERIAL_FROMFRAME.

Syntax

object.SetColorRGB(r As Single,
  g As Single,
  b As Single)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
r, g, b
New color for the frame. Each component of the color should be in the range 0.0 to 1.0.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMFrame3.SetMaterialMode

Direct3DRMFrame3.SetInheritAxes

Direct3DRMFrame3

Specifies whether the axes for the frame are inherited from the parent frame.

Syntax

object.SetInheritAxes(inheritFromParent As CONST_DBOOLFLAGS)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
inheritFromParent
Indicates whether the frame should inherit axes from its parent. If set to D_TRUE, the frame inherits axes (the default). If set to D_FALSE, the frame does not inherit axes.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

By default, the axes are inherited from the parent. If a frame is set to inherit from the parent, and there is no parent, the frame acts as if it inherits from a parent with the default axes (direction = (0, 0, 1) and up = (0, 1, 0)). This method allows a single policy for axes to be set at the root of the hierarchy.

See Also

Direct3DRMFrame3.GetInheritAxes, Direct3DRMFrame3.GetAxes, Direct3DRMFrame3.SetAxes

Direct3DRMFrame3.SetMaterial

Direct3DRMFrame3

Sets the material of the Direct3DRMFrame3 object.

Syntax

object.SetMaterial(mat As Direct3DRMMaterial2)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
mat
Direct3DRMMaterial object that will be applied to the frame.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMFrame3.GetMaterial

Direct3DRMFrame3.SetMaterialMode

Direct3DRMFrame3

Sets the material mode for a frame. The material mode determines the source of material information for visuals rendered with the frame.

Syntax

object.SetMaterialMode(val As CONST_D3DRMMATERIALMODE)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
val
One of the members of the CONST_D3DRMMATERIALMODE enumerated type, describing the source of material information for visuals rendered with a frame.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMFrame3.GetMaterialMode

Direct3DRMFrame3.SetMaterialOverride

Direct3DRMFrame3

Enables you to set specific material attributes. For example, this method enables you to override only the emissive property of materials.

Syntax

object.SetMaterialOverride(override As D3DRMMATERIALOVERRIDE)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
override
D3DRMMATERIALOVERRIDE type that describes the properties to override.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

The override always overrides everything down the hierarchy. If you override the emissive property in one frame, any attempts to override the same property farther down the hierarchy will be ignored. This override also takes precedence over standard frame overrides, as well as material properties on specific meshes. Overrides such as SetMaterial and SetTexture have no effect on the behavior of this method.

See Also

Direct3DRMFrame3.GetMaterialOverride

Direct3DRMFrame3.SetMaterialOverrideTexture

Direct3DRMFrame3

Sets the current per-attribute override settings for material attributes.

Syntax

object.SetMaterialOverrideTexture(tex As Direct3DRMTexture3)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
tex
Direct3DRMTexture3 interface to be set as the override texture.

Error Values

If this method fails, it can return DDERR_INVALIDOBJECT or DDERR_INVALIDPARAMS.

For a complete list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMFrame3.GetMaterialOverrideTexture

Direct3DRMFrame3.SetOrientation

Direct3DRMFrame3

Aligns a frame so that its z-direction points along the direction vector [dx, dy, dz] and its y-direction aligns with the vector [ux, uy, uz].

Syntax

object.SetOrientation(reference As Direct3DRMFrame3,
  dx As Single,
  dy As Single,
  dz As Single,
  ux As Single,
  uy As Single,
  uz As Single)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
reference
Variable that represents the Direct3DRMFrame object to be used as the reference.
dx, dy, dz
New z-axis for the frame. Each component of the vector should be in the range 1.0 to 1.0.
ux, uy, uz
New y-axis for the frame. Each component of the vector should be in the range 1.0 to 1.0.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

The default orientation of a frame has a direction vector of [0, 0, 1] and an up vector of [0, 1, 0].

If [ux, uy, uz] is parallel to [dx, dy, dz], the D3DRMERR_BADVALUE error value is returned; otherwise, the [ux, uy, uz] vector passed is projected onto the plane that is perpendicular to [dx, dy, dz].

This method is also used to add an orientation key to a Direct3DRMFrameInterpolator object.

See Also

Direct3DRMFrame3.GetOrientation

Direct3DRMFrame3.SetPosition

Direct3DRMFrame3

Sets the position of a frame relative to the frame of reference. It places the frame a distance of [x, y, z] from the reference. When a child frame is created within a parent, it is placed at [0, 0, 0] in the parent frame.

Syntax

object.SetPosition(reference As Direct3DRMFrame3,
  x As Single,
  y As Single,
  z As Single)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
reference
Variable that represents the Direct3DRMFrame object to be used as the reference.
x, y, z
New position for the frame. Position has no units. Use the viewing frustum to choose reasonable numbers.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method is also used to add a position key to a Direct3DRMFrameInterpolator object.

See Also

Direct3DRMFrame3.GetPosition

Direct3DRMFrame3.SetQuaternion

Direct3DRMFrame3

Sets a frame's orientation relative to a reference frame using a unit quaternion.

Syntax

object.SetQuaternion(reference As Direct3DRMFrame3,
  quat As D3DRMQUATERNION)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
reference
Variable that represents the Direct3DRMFrame object to be used as the reference.
quat
D3DRMQUATERNION type used to set the frame's orientation.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

A quaternion is a four-valued vector that can be used to represent any rotation and has properties that are useful when interpolating between orientations. A quaternion is a unit quaternion if s**2 + x**2 + y**2 + z**2 = 1.

The SetQuaternion method is supported by interpolators.

Direct3DRMFrame3.SetRotation

Direct3DRMFrame3

Sets a frame rotating by the given angle around the given vector at each call to the Direct3DRM3.Tick or Direct3DRMFrame3.Move method. The direction vector [x, y, z] is defined in the reference frame.

Syntax

object.SetRotation(reference As Direct3DRMFrame3,
  x As Single,
  y As Single,
  z As Single,
  theta As Single)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
reference
Variable that represents the Direct3DRMFrame object to be used as the reference.
x, y, z
Vector about which rotation occurs. Valid values are in the range 1.0 to 1.0.
theta
Rotation angle, in radians. The larger the angle, the faster an object rotates. The Move and Tick methods scale this value.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

The specified rotation changes the matrix with every render tick, unlike the Direct3DRMFrame3.AddRotation method, which changes the objects in the frame only once.

See Also

Direct3DRMFrame3.GetRotation

Direct3DRMFrame3.SetSceneBackground

Direct3DRMFrame3

Sets the background color of a scene.

Syntax

object.SetSceneBackground(c As Long)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
c
New color for the background.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method is also used to add a background color key to a Direct3DRMFrameInterpolator object.

Direct3DRMFrame3.SetSceneBackgroundDepth

Direct3DRMFrame3

Specifies a background-depth buffer for a scene.

Syntax

object.SetSceneBackgroundDepth(s As DirectDrawSurface4)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
s
Microsoft DirectDraw® surface that will store the new background depth for the scene.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

The image must have a depth of 16 bits per pixel. If the image and viewport sizes are different, the image is scaled first. For best performance when animating the background-depth buffer, the image should be the same size as the viewport. This enables the depth buffer to be updated directly from the image memory without incurring extra overhead.

See Also

Direct3DRMFrame3.GetSceneBackgroundDepth

Direct3DRMFrame3.SetSceneBackgroundImage

Direct3DRMFrame3

Specifies a background image for a scene.

Syntax

object.SetSceneBackgroundImage(i As Direct3DRMTexture3)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
i
Direct3DRMTexture3 object that will contain the new background scene.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

If the image is a different size or color depth than the viewport, the image will first be scaled or converted to the correct depth. For best performance when animating the background, the image should be the same size and color depth. This enables the background to be rendered directly from the image memory without incurring any extra overhead.

Direct3DRMFrame3.SetSceneBackgroundRGB

Direct3DRMFrame3

Sets the background color of a scene.

Syntax

object.SetSceneBackgroundRGB(r As Single,
  g As Single,
  b As Single)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
r, g, b
New color for the background. Each component of the color should be in the range 0.0 to 1.0.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method is also used to add a background RGB color key to a Direct3DRMFrameInterpolator object.

Direct3DRMFrame3.SetSceneFogColor

Direct3DRMFrame3

Sets the fog color of a scene.

Syntax

object.SetSceneFogColor(c As Long)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
c
New color for the fog.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method is also used to add a fog color key to a Direct3DRMRFrameInterpolator object.

Direct3DRMFrame3.SetSceneFogEnable

Direct3DRMFrame3

Sets the fog-enable state.

Syntax

object.SetSceneFogEnable(enable As CONST_DBOOLFLAGS)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
enable
New fog-enable state. Set this parameter to D_FALSE to disable fog-enable state and to D_TRUE to enable fog-enable state.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFrame3.SetSceneFogMethod

Direct3DRMFrame3

Specifies whether fogging will be performed by means of vertex fog or table fog.

Syntax

object.SetSceneFogMethod(enable As CONST_D3DRMFOGMETHOD)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
enable
Value indicating how fogging will be implemented. A value from the CONST_D3DRMFOGMETHOD enumerated type.

Error Values

If an error occurs, this method can return one of the following values.

  • D3DRMERR_BADVALUE
  • DDERR_INVALIDOBJECT
  • DDERR_INVALIDPARAMS

For a complete list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

The default behavior for Direct3DRMFrame3 objects created by the Direct3DRM3 interface is D3DRMFOGMETHOD_ANY and the fog method will be chosen based on the capabilities of the device. If the device supports both vertex- and table-based fog, then vertex fogging will be used. If the application requests table fog, but table fog is not available, vertex fog will be used.

Direct3DRMFrame3.SetSceneFogMode

Direct3DRMFrame3

Sets the fog mode.

Syntax

object.SetSceneFogMode(c As CONST_D3DRMFOGMODE)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
c
One of the members of the CONST_D3DRMFOGMODE enumerated type, specifying the new fog mode.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMFrame3.SetSceneFogParams

Direct3DRMFrame3.SetSceneFogParams

Direct3DRMFrame3

Sets the fog start point, end point, and density for the scene.

Syntax

object.SetSceneFogParams(start As Single,
  End As Single,
  density As Single)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
start, End
Fog start and end points for linear fog mode. These settings determine the distance from the camera at which fog effects first become visible, and the distance at which fog reaches its maximum density.
density
Fog density for the exponential fog modes. This value should be in the range 0 through 1.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

This method is also used to add a fog parameters key to a Direct3DRMRFrameInterpolator object.

See Also

CONST_D3DRMFOGMODE, Direct3DRMFrame3.SetSceneFogMode

Direct3DRMFrame3.SetSortMode

Direct3DRMFrame3

Sets the sorting mode used to process child frames. You can use this method to change the properties of hidden-surface-removal algorithms.

Syntax

object.SetSortMode(val As CONST_D3DRMSORTMODE)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
val
One of the members of the CONST_D3DRMSORTMODE enumerated type, specifying the sorting mode. The default value is D3DRMSORT_FROMPARENT.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMFrame3.GetSortMode

Direct3DRMFrame3.SetTexture

Direct3DRMFrame3

Sets the texture of the frame.

Syntax

object.SetTexture(t As Direct3DRMTexture3)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
t
Direct3DRMTexture3 object to be used.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Remarks

The texture is used for meshes in the frame when the CONST_D3DRMMATERIALMODE enumerated type is D3DRMMATERIAL_FROMFRAME. To disable the frame's texture, use a NOTHING texture.

See Also

Direct3DRMFrame3.GetTexture, Direct3DRMFrame3.SetMaterialMode

Direct3DRMFrame3.SetTraversalOptions

Direct3DRMFrame3

Specifies whether this frame is traversed during rendering and picking.

Syntax

object.SetTraversalOptions(flags As CONST_D3DRMTRAVERALFLAGS)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
flags
One or more values from the CONST_D3DRMTRAVERALFLAGS enumerated type, indicating whether this frame is renderable and pickable. Using this method without a value of D3DRMFRAME_RENDERENABLE effectively switches the frame off for rendering. By default, the frame is enabled for rendering and picking.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

Direct3DRMFrame3.SetVelocity

Direct3DRMFrame3

Sets the velocity of the given frame relative to the reference frame. The frame will be moved by the vector [x, y, z] with respect to the reference frame at each successive call to the Direct3DRM3.Tick or Direct3DRMFrame3.Move method.

Syntax

object.SetVelocity(reference As Direct3DRMFrame3,
  x As Single,
  y As Single,
  z As Single,
  with_rotation As CONST_DBOOLFLAGS)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
reference
Direct3DRMFrame object to be used as the reference.
x, y, z
New velocity for the frame. Rotational velocity has no units and can be any value. The Move and Tick methods scale this value.
with_rotation
Flag specifying whether the rotational velocity of the object is taken into account when setting the linear velocity. If set to D_TRUE, the object's rotational velocity is included in the calculation; otherwise, set to D_FALSE.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMFrame3.GetVelocity

Direct3DRMFrame3.SetZbufferMode

Direct3DRMFrame3

Sets whether z-buffering is enabled or disabled.

Syntax

object.SetZbufferMode(val As CONST_D3DRMZBUFFERMODE)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
val
One of the members of the CONST_D3DRMZBUFFERMODE enumerated type, specifying the z-buffer mode. The default value is D3DRMZBUFFER_FROMPARENT.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMFrame3.GetZbufferMode

Direct3DRMFrame3.Transform

Direct3DRMFrame3

Transforms the given vector and returns the result.

Syntax

object.Transform(d As D3DVECTOR,
  s As D3DVECTOR)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
d
D3DVECTOR type that will be filled with the result of the transformation operation.
s
D3DVECTOR type that is the source of the transformation operation.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

Direct3DRMFrame3.InverseTransform

Direct3DRMFrame3.TransformVectors

Direct3DRMFrame3

Transforms an array of vectors from model- to world-space.

Syntax

object.TransformVectors(reference As DIRECT3DRMFrame3,
  num As Long,
  DstVectors() As D3DVECTOR,
  SrcVectors() As D3DVECTOR)

Parts

object
Object expression that resolves to a Direct3DRMFrame3 object.
reference
Frame that will be used as the root of the scene for the purposes of this call. If this argument is NOTHING, the current root frame (as would be returned by the Direct3DRMFrame3.GetScene method) will be used.
num
Number of vectors to be transformed.
DstVectors()
Destination of the transformation.
SrcVectors()
Array of vectors to transform.

Error Values

For a list of possible errors, see Direct3D Retained Mode Error Values.

See Also

D3DVECTOR